comparison init50.gradle @ 277:7352aab6847e

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