comparison init20-git.gradle @ 311:69ef3d16fb19

add git specific versions of init20, init50, init70
author Marc Davis <davis@ssdt-ohio.org>
date Wed, 01 Feb 2023 11:01:56 -0500
parents
children 7ca1fbf8636a
comparison
equal deleted inserted replaced
310:7bf282e58ce7 311:69ef3d16fb19
1 import groovy.sql.Sql
2 import groovy.transform.Sortable
3 import groovy.transform.ToString
4 import groovy.transform.TupleConstructor
5
6 buildscript {
7 repositories {
8 maven { url 'https://docker.ssdt.io/artifactory/ssdt-repo' }
9 maven { url 'https://docker.ssdt.io/artifactory/gradle-plugins' }
10 }
11 dependencies {
12 classpath 'postgresql:postgresql:9.1-901.jdbc4'
13 classpath 'com.netflix.nebula:gradle-dependency-lock-plugin:5.0.6'
14 }
15 }
16
17 final GradleVersion gradleCurrent = GradleVersion.current()
18 final GradleVersion gradleV20 = GradleVersion.version('2.0')
19 final GradleVersion gradleV31 = GradleVersion.version('3.1')
20
21 println "Gradle Version: $gradleCurrent"
22
23 if (gradleCurrent < gradleV20) {
24 throw new RuntimeException("this init script requires Gradle version 2.0 or higher")
25 }
26
27 gradle.ext.ssdtDevelkitLocation = gradle.ext.has('ssdtDevelkitLocation') ? gradle.ssdtDevelkitLocation : 'http://hg.ssdt-ohio.org/browse/public/develkit'
28
29 ant.property(file: System.getProperty('user.home') + "/.ssdt/private.properties")
30 gradle.ext.ivyUserDir = ant.properties['ivy.default.ivy.user.dir'] ?: System.getProperty('user.home') + "/.ivy2"
31
32 gradle.ext.ssdtProjectId = System.getenv('bamboo_project_id') ?: rootProject.name
33
34 gradle.addListener(new ArtifactoryGradleSettings())
35
36 def hostname
37 try {
38 hostname = "hostname".execute().text.toLowerCase().readLines().first()
39 } catch (e) {
40 hostname = 'unknown'
41 }
42
43 gradle.ext.bambooBuild = System.getenv().any {
44 it.key.toLowerCase().contains('bamboo')
45 } || hostname?.startsWith('ssdt-ba')
46
47 gradle.ext.bambooPlan = (System.getenv('BAMBOO_PLAN') ?: 'UNKNOWN-UNKNOWN-JOB1').split('-')[0..1].join('-')
48 logger.info "Bamboo plan: ${gradle.bambooPlan}"
49
50 gradle.ext.buildTimestamp = System.currentTimeMillis().toString().padLeft(14, '0')
51
52 gradle.ext.hgRepositoryUrl = ""
53
54 try {
55 gradle.ext.hgRepositoryUrl = ("hg path".execute().text.split('=') ?: ['', ''])[1].trim()
56 } catch (e) {
57 }
58
59 def springModuleTranslator = [
60 'spring-transaction': 'spring-tx',
61 'spring-web-servlet': 'spring-webmvc',
62 ].withDefault { it }
63
64 gradle.ext.normalizeSpring = { DependencyResolveDetails details ->
65 if (details.requested.group == 'org.springframework' && details.requested.name.startsWith('org.springframework.')) {
66 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
67 details.useTarget(group: 'org.springframework', name: shortName, version: details.requested.version)
68 }
69 if (details.requested.group == 'org.springframework.security' && details.requested.name.startsWith('org.springframework.')) {
70 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
71 details.useTarget("${details.requested.group}:$shortName:${details.requested.version}")
72 }
73 }
74
75 gradle.ext.runtimeInfo = new RuntimeInfo()
76
77
78 if (System.env.DOCKER_HOST ) {
79 if (System.env.DOCKER_HOST.contains('tcp:')) {
80 gradle.ext.dockerEngineUrl = "https:${System.env.DOCKER_HOST?.minus('tcp:')}"
81 }
82 gradle.ext.dockerEngineUrl = System.env.DOCKER_HOST
83 }
84
85 setBranchInfo()
86
87 loadEnvironments()
88
89 gradle.environment.put('hgRepositoryUrl', gradle.hgRepositoryUrl)
90 gradle.environment.put('branchName', gradle.branch.name)
91 gradle.environment.put('branchStream', gradle.branch.stream)
92 gradle.environment.put('branchHash', gradle.branch.hash)
93
94
95 def cacheTimeout = 60 * 60 * 8
96 if (gradle.environment['dependencyTimeout']) {
97 cacheTimeout = gradle.environment['dependencyTimeout'] as Integer
98 println "setting changing dependency timeout to $cacheTimeout seconds"
99 }
100
101 gradle.ext.cacheTimeout = cacheTimeout
102
103 rootProject.ext.indyCapable = {
104 boolean capable = true
105 try {
106 Class.forName('java.lang.invoke.MethodHandle')
107 } catch (e) {
108 capable = false
109 }
110 capable && !rootProject.hasProperty('skipIndy')
111 }
112
113 rootProject.ext.useIndy = {
114 boolean indy = false
115 // first, check if a system property activates indy support
116 indy |= System.hasProperty('indy') && Boolean.valueOf(System.getProperty('indy'))
117
118 // check ssdt environment for indy property.
119 indy |= (gradle.environment.indy) ? gradle.environment.indy.toBoolean() : false
120
121 // check if the main project has an extension property setting indy (-Pindy).
122 if (rootProject.hasProperty('indy')) {
123 indy = (Boolean.valueOf(rootProject.indy))
124 }
125
126 // set the groovy runtime system property to ensure forked junit test will get the indy flag properly
127 if (indy && rootProject.indyCapable()) System.setProperty("groovy.target.indy", "true")
128
129 indy && rootProject.indyCapable()
130 }
131
132 println "Indy available: ${rootProject.indyCapable()} enabled: ${rootProject.useIndy()}"
133
134 if (gradle.bambooBuild) {
135
136 file('build-number.txt').text = "build.number=${gradle.branch.buildNumber ?: -1 }\n"
137 gradle.ext.ssdtGradlekitLocation = gradle.ext.has('ssdtGradlekitLocation') ? gradle.ssdtGradlekitLocation : 'http://hg.ssdt-ohio.org/ssdt/gradlekit/raw-file/tip'
138 logger.info "applying SSDT artifactory Gradle Settings (bamboo: $gradle.bambooBuild host: $hostname)"
139 apply from: "${gradle.ssdtGradlekitLocation}/artifactory20.gradle"
140 }
141
142 if (!rootProject.hasProperty('disableMetrics')) {
143 apply from: "${gradle.ssdtDevelkitLocation}/metrics.gradle"
144 }
145
146 rootProject.afterEvaluate { r ->
147 if (gradle.bambooBuild && r.hasProperty('requireJavaVersion')) {
148 gradle.runtimeInfo.requireJava( r.getProperty('requireJavaVersion') )
149 }
150 }
151
152 def findComponent(project, name) {
153 project.component.find { it.@name == name }
154 }
155
156 if (gradleCurrent >= gradleV31) {
157 wrapper {
158 distributionType = org.gradle.api.tasks.wrapper.Wrapper.DistributionType.ALL
159 }
160 }
161
162 allprojects {
163
164 apply plugin: nebula.plugin.dependencylock.DependencyLockPlugin
165
166 dependencyLock {
167 globalLockFile = gradle.branch.isRelease() ? 'release.lock' : 'global.lock'
168 includeTransitives = true
169 }
170
171 configurations.all {
172 resolutionStrategy.cacheChangingModulesFor gradle.cacheTimeout, 'seconds'
173 resolutionStrategy.cacheDynamicVersionsFor gradle.cacheTimeout, 'seconds'
174 }
175 configurations.all {
176 resolutionStrategy.eachDependency { DependencyResolveDetails details ->
177 if (details.requested.group == 'org.ssdt_ohio' && !details.requested.version ) {
178 details.useVersion( "latest.${gradle.branch.defaultDependencyStatus}" )
179 }
180 if (details.requested.version == 'default') {
181 details.useVersion("latest.${gradle.branch.defaultDependencyStatus}" )
182 }
183 if (project.hasProperty("overrideCommon")) {
184 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.contains('ssdt.common.')) {
185 details.useVersion(project.overrideCommon)
186 }
187 }
188 if (project.hasProperty("overrideVui")) {
189 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('vui.')) {
190 details.useVersion(project.overrideVui)
191 }
192 }
193 if (project.hasProperty("overrideUsasCore")) {
194 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('usas.') && !details.requested.name.startsWith('usas.vui')) {
195 details.useVersion(project.overrideUsasCore)
196 }
197 }
198 if (project.hasProperty("overrideUspsCore")) {
199 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('usps.') && !details.requested.name.startsWith('usps.vui')) {
200 details.useVersion(project.overrideUspsCore)
201 }
202 }
203
204 resolutionStrategy.force 'xml-apis:xml-apis:1.4.01'
205 }
206 }
207
208 task cleanLocal(description: "removes all artifacts from developer's local repository") {
209
210 doLast {
211 def local = project.repositories.find { it.name == 'local' }
212 if (local) {
213 logger.info "removing local repo: $it"
214 new File(System.properties['user.home'] + "/.ssdt/local-repo").deleteDir()
215 def localDir = new File(gradle.ivyUserDir + "/local")
216 localDir.deleteDir()
217 logger.info "verifying removal of local repo"
218 if (localDir.exists()) {
219 throw new org.gradle.api.GradleException("Unable to clean ${localDir}. Files may be locked by another process.")
220 }
221 }
222 }
223 }
224
225 cleanLocal.onlyIf {
226 project.repositories.any { it.name == 'local' }
227 }
228
229 project.ext.previousBuildenv = project.file('build/buildenv.txt').exists() ? project.file('build/buildenv.txt').text : 'none'
230
231 tasks.addRule("Pattern: <environment>As[Test]Properties: Generates <environment>.properties as resource or Test resource") { String taskName ->
232 if ((taskName - 'Test').endsWith("AsProperties") && !taskName.startsWith('clean')) {
233 // def t = taskName.contains('Test') ? processTestResources.destinationDir : processResources.destinationDir
234 def t = taskName.contains('Test') ? sourceSets.test.output.resourcesDir : sourceSets.main.output.resourcesDir
235 def e = (taskName - 'Test' - 'AsProperties').capitalize()
236 task(taskName) {
237 ext.outputDir = t
238 ext.propertyFile = "${e.toLowerCase()}.properties"
239 ext.buildenv = project.file('build/buildenv.txt')
240 inputs.files project.file("../environment${e}.groovy"), project.file("../private${e}.groovy"), project.file('../private.properties')
241 outputs.files new File(outputDir,propertyFile), buildenv
242 outputs.upToDateWhen {
243 gradle.env == project.previousBuildenv && outputs.getFiles().every { it.exists() }
244 }
245 doLast {
246 t.mkdirs()
247 outputDir.mkdirs()
248 buildenv.text = gradle.env
249 def ps = gradle."environment${e}".toProperties()
250 ps['ssdt.project'] = project.name
251 def pf = new File(outputDir,propertyFile)
252 ext.outputPropertyFile = pf
253 ps.store(pf.newOutputStream(), "by $taskName of $this")
254 def l = pf.readLines().sort()
255 pf.text = l.join('\n').replaceAll("\\.PARENT","")
256 }
257 }
258 }
259 }
260
261 if (gradle.hasProperty('environmentDatabase')) {
262 tasks.addRule("Pattern: database{Drop|Create}...: drops or creates the environment's database") { String taskName ->
263 if (taskName.startsWith('database') && (taskName.contains('Drop') || taskName.contains('Create'))) {
264 task(taskName) {
265 doLast {
266 def dropIt = taskName.contains("Drop")
267 def createIt = taskName.contains("Create")
268 def driverName = gradle.environmentDatabase.jdbc.driverClassName
269 def databaseUrl = gradle.environmentDatabase.jdbc.url
270 if (driverName != "org.postgresql.Driver") {
271 logger.info "skipping database operation for non-postgresql driver"
272 throw new StopActionException("driver $driverName not supported by $taskName")
273 }
274 if (!configurations.hasProperty('jdbcdriver')) {
275 throw new GradleException("databaseDrop requires a 'jdbcdriver' configuration with a postgresql (or other) driver")
276 }
277 configurations.jdbcdriver.each { File file ->
278 GroovyObject.class.classLoader.addURL(file.toURL())
279 }
280 Class.forName(driverName)
281 def url = new URI(databaseUrl.substring(5))
282 def jdbcBaseUrl = databaseUrl - url.path
283 def databaseName = url.path - "/"
284 def adminUrl = jdbcBaseUrl + "/postgres"
285 def sql = Sql.newInstance(adminUrl,
286 gradle.environmentDatabase.jdbc.username,
287 gradle.environmentDatabase.jdbc.password,
288 driverName)
289 if (dropIt) {
290 logger.info "disconnecting sessions from $databaseName"
291 sql.execute "REVOKE CONNECT ON DATABASE \"" + databaseName + "\" FROM public;"
292 sql.execute "REVOKE CONNECT ON DATABASE \"" + databaseName + "\" FROM " + gradle.environmentDatabase.jdbc.username + ";"
293 sql.execute "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '" + databaseName + "';"
294 logger.info "dropping $databaseName (if exists) from $adminUrl"
295 sql.execute 'DROP DATABASE IF EXISTS "' + databaseName + '";'
296 }
297
298 if (createIt) {
299 logger.info "Creating database $databaseName at $adminUrl"
300 sql.execute 'CREATE DATABASE "' + databaseName + '";'
301 }
302 }
303 }
304
305 }
306 }
307 }
308
309 }
310
311 rootProject.afterEvaluate {
312
313 tasks.addRule("release{Major|Minor|Patch|n.n.n|Lock}: create release branch or update release Lock file") { String taskName ->
314
315 if (taskName == 'releaseLock') {
316
317 if (!gradle.branch.isRelease()) {
318 throw new BuildCancelledException("releaseLock is only valid on release or hotfix branch.")
319 }
320
321 dependencyLock.globalLockFile = 'release.lock'
322
323 task('doCommitLock') {
324 doLast {
325 println 'hg status'.execute().text
326 println 'hg commit release.lock -A -m "lock dynamic dependencies for release"'.execute().text
327 }
328 }
329
330
331 task('doForceDeleteLock') {
332 doLast {
333 println "deleting $dependencyLock.globalLockFile"
334 rootProject.file(dependencyLock.globalLockFile).delete()
335 }
336 }
337
338
339 def branchTasks = ['deleteGlobalLock', 'doForceDeleteLock', 'generateGlobalLock', 'saveGlobalLock', 'doCommitLock']
340
341 task(taskName) {
342 dependsOn branchTasks
343 }
344
345 branchTasks.tail().inject(branchTasks.head()) { a, b ->
346 tasks[b].mustRunAfter a
347 b
348 }
349
350 }
351
352 def matcher = (taskName =~ /^release(Major|Minor|Patch|\d{1,3}\.\d{1,3}\.\d{1,3})$/)
353 if (matcher.matches()) {
354
355 dependencyLock.globalLockFile = 'release.lock'
356
357 task('doReleaseBranch') {
358 ext.requested = matcher[0][1].toLowerCase()
359 doLast {
360 def releaseVersion = determineReleaseVersion(requested)
361 def releaseStream = releaseVersion.isHotfix() ? 'hotfix' : 'release'
362
363 println "-" * 60
364 println "Preparing to create branch\n"
365 println "\tproject:\t${gradle.rootProject.name}"
366 println "\tcurrent:\t${gradle.branch} ($gradle.branch.version)"
367 println()
368 println "\ttype :\t${releaseStream.toUpperCase()}"
369 println "\tversion:\t${releaseVersion}"
370 println "\ttarget :\t${releaseStream}/v${releaseVersion}"
371 println()
372 println("-" * 60)
373 println "DRY RUN".center(60)
374 println("-" * 60)
375
376 println "hg flow ${releaseStream} start v${releaseVersion} --dirty --dry-run".execute().text
377
378 println "-" * 60
379
380 if (!confirmPrompt("Continue?")) {
381 throw new BuildCancelledException("release branching canceled by user request")
382 }
383
384 println "hg flow ${releaseStream} start v${releaseVersion} --dirty".execute().text
385 println "hg update ${releaseStream}/v${releaseVersion}".execute().text
386
387 setBranchInfo()
388
389 println "-" * 60
390 println " Be sure to execute 'releaseLock' task to update the release.lock file before proceeding."
391 println "-" * 60
392
393 }
394 }
395
396
397 def branchTasks = ['doReleaseBranch']
398
399 task(taskName) {
400 dependsOn branchTasks
401 }
402
403 branchTasks.tail().inject(branchTasks.head()) { a, b ->
404 tasks[b].mustRunAfter a
405 b
406 }
407
408 }
409 }
410
411 }
412
413 private static String readLine(String message, String defaultValue = null) {
414 String _message = "> $message" + (defaultValue ? " [$defaultValue] " : "")
415 if (System.console()) {
416 return System.console().readLine(_message) ?: defaultValue
417 }
418 println "$_message "
419
420 System.in.newReader().readLine() ?: defaultValue
421 }
422
423 private static boolean confirmPrompt(String message, boolean defaultValue = false) {
424 String defaultStr = defaultValue ? 'Y' : 'n'
425 String consoleVal = readLine("${message} (Y|n)", defaultStr)
426 if (consoleVal) {
427 return consoleVal.toLowerCase().startsWith('y')
428 }
429
430 defaultValue
431 }
432
433 private Version determineReleaseVersion(String requested) {
434 if (requested == 'major') {
435 return gradle.branch.version.nextMajor()
436 } else if (requested == 'minor') {
437 return gradle.branch.version.nextMinor()
438 } else if (requested == 'patch') {
439 return gradle.branch.version.nextPatch()
440 } else {
441 return new Version(*requested.split(/\./)*.toInteger(), false)
442 }
443 }
444
445 class ArtifactoryGradleSettings extends BuildAdapter implements BuildListener {
446
447 def void projectsEvaluated(Gradle gradle) {
448 def ssdtArtifactory = 'https://docker.ssdt.io/artifactory'
449 Project root = gradle.getRootProject()
450
451
452 def branchVersioning = gradle.rootProject.version == 'unspecified'
453
454 root.allprojects {
455
456 def thisProject = delegate
457 thisProject.status = 'integration'
458 if (gradle.branchStream) {
459 if (branchVersioning) {
460 thisProject.version = gradle.branch.version
461 thisProject.status = gradle.branch.defaultDependencyStatus
462 } else {
463
464 thisProject.status = 'integration'
465 def fixupVersion = thisProject.version - ".SNAPSHOT"
466 if (gradle.branchStream == 'feature') {
467 fixupVersion = fixupVersion + ".SNAPSHOT"
468 }
469 if (gradle.branchStream == 'develop') {
470 fixupVersion = fixupVersion + ".SNAPSHOT"
471 }
472 if (gradle.branchStream in ['production', 'release', 'hotfix']) {
473 thisProject.status = 'release'
474 }
475 thisProject.version = fixupVersion
476 }
477 }
478
479 repositories {
480
481 if (!gradle.bambooBuild) {
482 ivy {
483 name = 'local'
484 artifactPattern gradle.ivyUserDir + '/local/[artifact]-[revision](-[classifier]).[ext]'
485 ivyPattern gradle.ivyUserDir + "/local/[module]-ivy-[revision].xml"
486 }
487 mavenLocal()
488 }
489
490 if (gradle.branchStream == 'feature') {
491 ivy {
492 name = 'ssdt-branches'
493 url = "${ssdtArtifactory}/ssdt-branches/${gradle.branchHash}/"
494 layout "pattern", {
495 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
496 ivy "[organization]/[module]/ivy-[revision].xml"
497 }
498 }
499 }
500
501 ivy {
502 name = 'ssdt-releases'
503 url = "${ssdtArtifactory}/ssdt-releases"
504 layout "pattern", {
505 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
506 artifact "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
507 ivy "[organization]/[module]/ivy-[revision].xml"
508 m2compatible = true
509 }
510 }
511
512 ivy {
513 name = 'ssdt-snapshots'
514 url = "${ssdtArtifactory}/ssdt-snapshots"
515 layout "pattern", {
516 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
517 artifact "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
518 ivy "[organization]/[module]/ivy-[revision].xml"
519 m2compatible = true
520 }
521 }
522
523 maven {
524 name = 'ssdt-repository'
525 url = "${ssdtArtifactory}/repository"
526 }
527
528 }
529
530 def remoteRepos = thisProject.repositories.findAll { it.hasProperty('url') && !(it.name.toLowerCase().contains('local') || it.url.toString().contains('ssdt')) }
531 if (remoteRepos) {
532 logger.warn "WARNING: Remote repositories configured for $thisProject:\n" + remoteRepos.collect { "\t$it.name $it.url " }.join('\n') + "\n Moved to lowest priority..."
533 remoteRepos.each {
534 thisProject.repositories.remove(it)
535 thisProject.repositories.addLast(it)
536 }
537 }
538 logger.info "$thisProject configured repositories:\n" + thisProject.repositories.collect {"\t$it.name ${it.hasProperty('url') ? it.url : '' }" }.join('\n')
539
540
541 if (thisProject.repositories.find { it.name == 'local' } && thisProject.getTasksByName('uploadArchives', false)) {
542 uploadArchives {
543 repositories {
544 add thisProject.repositories.local
545 }
546 }
547
548 thisProject.tasks.create("publishLocal") {
549 description = "Publishes this projects artifacts to developer's local repository"
550 dependsOn = ["uploadArchives"]
551 }
552 }
553
554 }
555
556 root.subprojects { p ->
557 if (root.useIndy()) {
558 def groovyIndy = p.configurations.compile.files.find { f -> f.name.startsWith('groovy-all') && f.name.contains('-indy') }
559 if (groovyIndy) {
560 println "enabling indy compilation on $p"
561 [compileGroovy.groovyOptions, compileTestGroovy.groovyOptions]*.with {
562 optimizationOptions = [indy: true]
563 }
564 }
565 }
566 }
567 }
568 }
569
570
571 task showEnvironments {
572
573 doLast {
574 println "Defined environments: $gradle.environments"
575 gradle.environments.each { e ->
576 println "\n $e:"
577 gradle.getProperty(e).flatten().sort { it.key }.each { k, v ->
578 println String.format(' %25s = %s', k, k.contains('password') ? "********" : v)
579 }
580 }
581 if (logger.isInfoEnabled()) {
582 println "System properties:"
583 System.properties.each { println " $it" }
584 println "env variables:"
585 System.getenv().each { println " $it" }
586 }
587 }
588 }
589
590 def loadEnvironments() {
591 def developerPrivate = new Properties()
592 if (file('private.properties').exists()) {
593 developerPrivate.load(file('private.properties').newReader())
594 }
595 def envOverrides = [:]
596
597 if (!hasProperty('env')) {
598 gradle.ext.env = developerPrivate.env ?: 'dev'
599 } else {
600 def values = getProperty('env').split(',')
601 gradle.ext.env = values.first()
602 values.tail().each {
603 def (k, v) = it.split('=')
604 envOverrides.put(k, v)
605 }
606 }
607
608 println "Environment is: $gradle.env ($envOverrides)"
609 def slurper = new ConfigSlurper(gradle.env)
610 slurper.setBinding(['gradle': gradle])
611
612 def environment = slurper.parse(
613 '''deploy.mode="production"
614 environments {
615 test { deploy.mode="test" }
616 dev { deploy.mode="development"}
617 }''')
618 if (developerPrivate['deploy.mode']) {
619 environment.put('deploy.mode', developerPrivate['deploy.mode'])
620 }
621
622 environment.put('branchInfo',gradle.branch)
623 environment.put('branchVersion',gradle.branch.version.toString())
624 def environments = []
625 gradle.ext.environment = environment
626 file('.').listFiles().findAll { it.name ==~ /^environment.*\.groovy$/ }.sort { it.name }.each { envFile ->
627 def envName = envFile.name - '.groovy'
628 def privateFile = file("private" + envName - "environment" + ".groovy")
629 logger.info("loading environment $envFile.name")
630
631 def envCfg = slurper.parse(envFile.toURL())
632 envCfg.merge(slurper.parse(developerPrivate))
633 envCfg.put('ssdt.projectid', gradle.ssdtProjectId)
634 envCfg.put('ssdt.environment', gradle.env)
635 if (privateFile.exists()) {
636 logger.info("loading private environment $privateFile")
637 envCfg.merge(slurper.parse(privateFile.toURL()))
638 }
639
640 gradle.rootProject.getProperties().find { it.key.startsWith('environment') }.each {
641 it.value.split(',').each { p ->
642 def (k, v) = p.split('=')
643 logger.info("$envName: overriding " + k + "=" + v + " in $it")
644 envCfg.put(k, v)
645 }
646 }
647
648 envOverrides.each { k, v ->
649 logger.info("$envName: overriding " + k + "=" + v)
650 envCfg.put(k, v)
651 }
652 environment.merge(envCfg)
653 if (envName != 'environment') {
654 gradle.ext[envName] = envCfg
655 environments << envName
656 }
657 }
658 environment.merge(slurper.parse(developerPrivate))
659 def deployMode = environment.deploy.mode ?: 'development'
660 environments.each { gradle.ext[it].put('ssdt.deployment.mode', deployMode) }
661 environments << 'environment'
662 gradle.ext.environments = environments
663
664 }
665
666
667 @ToString(includeNames=true)
668 class RuntimeInfo {
669 // OS memory in megabytes, zero if unknown
670 int systemMemory = 0
671 int systemFreeMemory = 0
672 String javaVersion = System.getProperty('java.version')
673
674 RuntimeInfo() {
675 try {
676 new File('/proc/meminfo').readLines().findAll { it.startsWith 'Mem' }.collect { it.split(/\s+/) }.each {
677 int value = (it[1] as Long) / 1024
678 if (it[0].startsWith('MemTotal')) { systemMemory = value }
679 if (it[0].startsWith('MemFree')) { systemFreeMemory = value }
680 }
681
682 } catch (e) { }
683
684 }
685
686 void requireMemory(int megabytes) {
687 if (systemFreeMemory > 0 && systemFreeMemory < megabytes) {
688 println "WARNING: potentially insufficent OS memory for this build"
689 // throw new GradleException("insufficent free OS memory for this build (available: ${systemFreeMemory}m, required: ${megabytes}m)")
690 }
691 }
692 /**
693 * Returns maximum memory available upto the value specified.
694 */
695 int maxMemory(int megabytes) {
696 if (systemFreeMemory) {
697 [systemFreeMemory,megabytes].min()
698 } else { megabytes }
699
700 }
701
702 void requireJava(String version) {
703
704 if ( version && !javaVersion.startsWith(version)) {
705 throw new GradleException("Requires java version $version but running under $javaVersion")
706 }
707 }
708
709 }
710
711
712 @TupleConstructor
713 @Sortable
714 class Version {
715
716 Integer major = 0
717 Integer minor = 0
718 Integer patch = 0
719 Boolean snapshot = true
720
721 Version nextMajor() {
722 new Version(major + 1, 0, 0, false)
723 }
724
725 Version nextMinor() {
726 if (snapshot) {
727 new Version(major, minor , 0,false)
728 } else {
729 new Version(major, minor + 1, 0,false)
730 }
731 }
732
733 Version nextPatch() {
734 new Version(major, minor, patch + 1,false)
735 }
736
737 Version nextSnapshot() {
738 new Version(major, minor + 1, 0)
739 }
740
741 boolean isHotfix() {
742 !snapshot && patch > 0
743 }
744
745 String toString() {
746 "${major}.${minor}.${patch}${snapshot ? '.SNAPSHOT' : ''}"
747 }
748
749 }
750
751 void setBranchInfo() {
752 gradle.ext.branch = new BranchInfo(System.getenv('bamboo_planRepository_branch'))
753 gradle.ext.branchName = gradle.branch.name
754 gradle.ext.branchStream = gradle.branch.stream
755 gradle.ext.branchHash = gradle.branch.hash
756 println "${gradle.hgRepositoryUrl} ${gradle.branch} ${gradle.branch.version}"
757 }
758
759
760 @ToString(includes=['name','shortName','buildVersion','imageId','deployName'],includeNames= true)
761 class BranchInfo {
762 def name
763 def stream = "none"
764 def buildNumber = ""
765 def changeset = ""
766 def version
767
768 BranchInfo(name) {
769 this.name = name
770 if (!name) {
771 this.name = determineName() ?: ''
772 }
773 this.name = this.name.replace('@', '-')
774 determineStream()
775 buildNumber = System.getenv('bamboo_buildNumber') ?: ""
776 changeset = System.getenv('bamboo_planRepository_revision') ?: ""
777 }
778
779 String getDefaultDependencyStatus() {
780 return isRelease() ? 'release' : 'integration'
781 }
782
783 private boolean isRelease() {
784 return stream in ['release', 'hotfix']
785 }
786
787 def getShortName() {
788 def result = name.contains('/') ? name.split('/')[1] : name
789 }
790
791 String getBuildVersion() {
792 def v = isRelease() ? shortName - "v": ""
793 return v
794 }
795
796 def Version getVersion() {
797 if (!version) {
798 if (isRelease()) {
799 version = new Version(*getBuildVersion().split('\\.')*.toInteger(), false)
800 } else {
801 version = findSnapshotVersion()
802 }
803 }
804 return version
805 }
806
807 def getImageId() {
808 (buildVersion ?: shortName.take(25)) + (buildNumber ? "-${buildNumber}" : "-0")
809 }
810
811 def getDeployName() {
812 (buildVersion ?: shortName.take(25)).toLowerCase().collectReplacements {
813 ('a'..'z').contains(it) || ('0'..'9').contains(it) || it == "-" ? null : '-'
814 }
815 }
816
817 def getHash() {
818 generateMD5(name)
819 }
820 def generateMD5(String s) {
821 def digest = java.security.MessageDigest.getInstance("MD5")
822 digest.update(s.bytes);
823 new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
824 }
825
826 private findSnapshotVersion() {
827
828 try {
829 def repositoryUrl = System.getenv('bamboo_planRepository_repositoryUrl')
830 if (repositoryUrl) {
831 println "git pull $repositoryUrl".execute().text
832 }
833 def versions = "git tag".execute().text.split("\n")
834 .findAll { it != null || it != "" }
835 .collect { it.replace("v", "") }
836 .collect { new Version(*it.split('\\.')*.toInteger()) }
837 .sort { v1, v2 -> v2 <=> v1 }
838 return versions ? versions.first().nextSnapshot() : new Version().nextSnapshot()
839 } catch (ex) {
840 println ex
841 return new Version().nextSnapshot()
842 }
843 }
844
845
846 def determineName() {
847 try {
848 def branch = "git branch --show-current".execute().text.trim()
849 return branch
850 } catch (ignored) {
851 return null
852 }
853 }
854
855 /**
856 * Try to determine the stream based on hgflow configs
857 * git-flow doesn't have a local config, so we may need to keep this
858 * file around just for the comparison.
859 *
860 * A new name for the file could help as well?
861 */
862 void determineStream() {
863 def flowConfig = new File('.hgflow').exists() ? new File('.hgflow') : new File('../.hgflow')
864 if (flowConfig.exists()) {
865 def flows = new Properties()
866 flows.load(flowConfig.newReader())
867 flows.stringPropertyNames().each {
868 if (!it.startsWith("[") && name.startsWith(flows.getProperty(it))) {
869 stream = it
870 }
871 }
872 }
873 }
874
875 }
876