comparison init40-github.gradle @ 342:9791f84cfc67

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