comparison init40-git.gradle @ 299:5e9e2ea82657

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