comparison init70-github.gradle @ 336:6258c89efe9e

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