comparison init70-git.gradle @ 311:69ef3d16fb19

add git specific versions of init20, init50, init70
author Marc Davis <davis@ssdt-ohio.org>
date Wed, 01 Feb 2023 11:01:56 -0500
parents
children 7ca1fbf8636a
comparison
equal deleted inserted replaced
310:7bf282e58ce7 311:69ef3d16fb19
1 import groovy.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 = 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: resources.text.fromInsecureUri("${gradle.ssdtGradlekitLocation}/artifactory70.gradle")
145 }
146
147 if (!rootProject.hasProperty('disableMetrics')) {
148 apply from: resources.text.fromInsecureUri("${gradle.ssdtDevelkitLocation}/metrics70.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 = 'https://docker.ssdt.io/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 patternLayout() {
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 patternLayout() {
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 patternLayout() {
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 /*
489 * Add a new task for local repos that declare an Ivy publish configuration
490 * This is a workaround for how the older versions handled the publishLocal
491 * task and the updateArchive option that was removed in gradle 7.0
492 */
493 if (thisProject.repositories.find { it.name == 'local' } && thisProject.getTasksByName('publishIvyPublicationToLocalRepository', false)) {
494 thisProject.tasks.create("publishLocal") {
495 description = "Publishes this projects artifacts to developer's local repository"
496 dependsOn = ["publishIvyPublicationToLocalRepository"]
497 }
498 }
499
500 }
501
502 root.subprojects { p ->
503 if (root.useIndy()) {
504 println "enabling indy compilation on $p"
505 [compileGroovy.groovyOptions, compileTestGroovy.groovyOptions]*.with {
506 optimizationOptions = [indy: true]
507 }
508 }
509 }
510 }
511 }
512
513
514 task showEnvironments {
515
516 doLast {
517 println "Defined environments: $gradle.environments"
518 gradle.environments.each { e ->
519 println "\n $e:"
520 gradle.getProperty(e).flatten().sort { it.key }.each { k, v ->
521 println String.format(' %25s = %s', k, k.contains('password') ? "********" : v)
522 }
523 }
524 if (logger.isInfoEnabled()) {
525 println "System properties:"
526 System.properties.each { println " $it" }
527 println "env variables:"
528 System.getenv().each { println " $it" }
529 }
530 }
531 }
532
533 def loadEnvironments() {
534 def developerPrivate = new Properties()
535 if (file('private.properties').exists()) {
536 developerPrivate.load(file('private.properties').newReader())
537 }
538 def envOverrides = [:]
539
540 if (!hasProperty('env')) {
541 gradle.ext.env = developerPrivate.env ?: 'dev'
542 } else {
543 def values = getProperty('env').split(',')
544 gradle.ext.env = values.first()
545 values.tail().each {
546 def (k, v) = it.split('=')
547 envOverrides.put(k, v)
548 }
549 }
550
551 println "Environment is: $gradle.env ($envOverrides)"
552 def slurper = new ConfigSlurper(gradle.env)
553 slurper.setBinding(['gradle': gradle])
554
555 def environment = slurper.parse(
556 '''deploy.mode="production"
557 environments {
558 test { deploy.mode="test" }
559 dev { deploy.mode="development"}
560 }''')
561 if (developerPrivate['deploy.mode']) {
562 environment.put('deploy.mode', developerPrivate['deploy.mode'])
563 }
564
565 environment.put('branchInfo',gradle.branch)
566 environment.put('branchVersion',gradle.branch.version.toString())
567 def environments = []
568 gradle.ext.environment = environment
569 file('.').listFiles().findAll { it.name ==~ /^environment.*\.groovy$/ }.sort { it.name }.each { envFile ->
570 def envName = envFile.name - '.groovy'
571 def privateFile = file("private" + envName - "environment" + ".groovy")
572 logger.info("loading environment $envFile.name")
573
574 def envCfg = slurper.parse(envFile.toURL())
575 envCfg.merge(slurper.parse(developerPrivate))
576 envCfg.put('ssdt.projectid', gradle.ssdtProjectId)
577 envCfg.put('ssdt.environment', gradle.env)
578 if (privateFile.exists()) {
579 logger.info("loading private environment $privateFile")
580 envCfg.merge(slurper.parse(privateFile.toURL()))
581 }
582
583 gradle.rootProject.getProperties().find { it.key.startsWith('environment') }.each {
584 it.value.split(',').each { p ->
585 def (k, v) = p.split('=')
586 logger.info("$envName: overriding " + k + "=" + v + " in $it")
587 envCfg.put(k, v)
588 }
589 }
590
591 envOverrides.each { k, v ->
592 logger.info("$envName: overriding " + k + "=" + v)
593 envCfg.put(k, v)
594 }
595 environment.merge(envCfg)
596 if (envName != 'environment') {
597 gradle.ext[envName] = envCfg
598 environments << envName
599 }
600 }
601 environment.merge(slurper.parse(developerPrivate))
602 def deployMode = environment.deploy.mode ?: 'development'
603 environments.each { gradle.ext[it].put('ssdt.deployment.mode', deployMode) }
604 environments << 'environment'
605 gradle.ext.environments = environments
606
607 }
608
609 def updateCopyrightProfile(Project r) {
610 r.file('.idea/copyright').mkdirs()
611 r.file('.idea/copyright/ODE.xml').text =
612 '''<component name="CopyrightManager">
613 <copyright>
614 <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;" />
615 <option name="myName" value="ODE" />
616 </copyright>
617 </component>'''
618
619 r.file('.idea/copyright/profiles_settings.xml').text =
620 '''<component name="CopyrightManager">
621 <settings default="ODE" />
622 </component>'''
623
624 }
625
626 @ToString(includeNames=true)
627 class RuntimeInfo {
628 // OS memory in megabytes, zero if unknown
629 int systemMemory = 0
630 int systemFreeMemory = 0
631 String javaVersion = System.getProperty('java.version')
632
633 RuntimeInfo() {
634 try {
635 new File('/proc/meminfo').readLines().findAll { it.startsWith 'Mem' }.collect { it.split(/\s+/) }.each {
636 int value = (it[1] as Long) / 1024
637 if (it[0].startsWith('MemTotal')) { systemMemory = value }
638 if (it[0].startsWith('MemFree')) { systemFreeMemory = value }
639 }
640
641 } catch (e) { }
642
643 }
644
645 void requireMemory(int megabytes) {
646 if (systemFreeMemory > 0 && systemFreeMemory < megabytes) {
647 println "WARNING: potentially insufficent OS memory for this build"
648 // throw new GradleException("insufficent free OS memory for this build (available: ${systemFreeMemory}m, required: ${megabytes}m)")
649 }
650 }
651 /**
652 * Returns maximum memory available upto the value specified.
653 */
654 int maxMemory(int megabytes) {
655 if (systemFreeMemory) {
656 [systemFreeMemory,megabytes].min()
657 } else { megabytes }
658
659 }
660
661 void requireJava(String version) {
662
663 if ( version && !javaVersion.startsWith(version)) {
664 throw new GradleException("Requires java version $version but running under $javaVersion")
665 }
666 }
667
668 }
669
670
671 @TupleConstructor
672 @Sortable
673 class Version {
674
675 Integer major = 0
676 Integer minor = 0
677 Integer patch = 0
678 Boolean snapshot = true
679
680 Integer previousMinor = 0
681 Integer previousPatch = 0
682
683 Version nextMajor() {
684 new Version(major + 1, 0, 0, false)
685 }
686
687 Version nextMinor() {
688 if (snapshot) {
689 new Version(major, minor , 0,false)
690 } else {
691 new Version(major, minor + 1, 0,false)
692 }
693 }
694
695 Version nextPatch() {
696 if (snapshot) {
697 new Version(major, previousMinor, previousPatch + 1,false)
698 }
699 }
700
701 Version nextSnapshot() {
702 new Version(major, minor + 1, 0,true,minor,patch)
703 }
704
705 boolean isHotfix() {
706 !snapshot && patch > 0
707 }
708
709 String toString() {
710 "${major}.${minor}.${patch}${snapshot ? '.SNAPSHOT' : ''}"
711 }
712
713 }
714
715 void setBranchInfo() {
716 gradle.ext.branch = new BranchInfo(System.getenv('bamboo_planRepository_branch'))
717 gradle.ext.branchName = gradle.branch.name
718 gradle.ext.branchStream = gradle.branch.stream
719 gradle.ext.branchHash = gradle.branch.hash
720 println "${gradle.hgRepositoryUrl} ${gradle.branch} ${gradle.branch.version}"
721 }
722
723
724 @ToString(includes=['name','shortName','buildVersion','imageId','deployName'],includeNames= true)
725 class BranchInfo {
726 def name
727 def stream = "none"
728 def buildNumber = ""
729 def changeset = ""
730 def version
731
732 BranchInfo(name) {
733 this.name = name
734 if (!name) {
735 this.name = determineName() ?: ''
736 }
737 this.name = this.name.replace('@', '-')
738 determineStream()
739 buildNumber = System.getenv('bamboo_buildNumber') ?: ""
740 changeset = System.getenv('bamboo_planRepository_revision') ?: ""
741 }
742
743 String getDefaultDependencyStatus() {
744 return isRelease() ? 'release' : 'integration'
745 }
746
747 private boolean isRelease() {
748 return stream in ['release', 'hotfix']
749 }
750
751 def getShortName() {
752 def result = name.contains('/') ? name.split('/')[1] : name
753 }
754
755 String getBuildVersion() {
756 def v = isRelease() ? shortName - "v": ""
757 return v
758 }
759
760 def Version getVersion() {
761 if (!version) {
762 if (isRelease()) {
763 version = new Version(*getBuildVersion().split('\\.')*.toInteger(), false)
764 } else {
765 version = findSnapshotVersion()
766 }
767 }
768 return version
769 }
770
771 def getImageId() {
772 (buildVersion ?: shortName.take(25)) + (buildNumber ? "-${buildNumber}" : "-0")
773 }
774
775 def getDeployName() {
776 (buildVersion ?: shortName.take(25)).toLowerCase().collectReplacements {
777 ('a'..'z').contains(it) || ('0'..'9').contains(it) || it == "-" ? null : '-'
778 }
779 }
780
781 def getHash() {
782 generateMD5(name)
783 }
784 def generateMD5(String s) {
785 def digest = java.security.MessageDigest.getInstance("MD5")
786 digest.update(s.bytes);
787 new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
788 }
789
790 private Version findSnapshotVersion() {
791 println "findSnapshotVersion()"
792 try {
793 def repositoryUrl = System.getenv('bamboo_planRepository_repositoryUrl')
794 if (repositoryUrl) {
795 println "git pull $repositoryUrl".execute().text
796 }
797 def versions = "git tag".execute().text.split("\n")
798 .findAll { it != null || it != "" }
799 .collect { it.replace("v", "") }
800 .collect { new Version(*it.split('\\.')*.toInteger()) }
801 .sort { v1, v2 -> v2 <=> v1 }
802 return versions ? versions.first().nextSnapshot() : new Version().nextSnapshot()
803 } catch (ex) {
804 println ex
805 return new Version().nextSnapshot()
806 }
807 }
808
809 def determineName() {
810 try {
811 def branch = "git branch --show-current".execute().text.trim()
812 return branch
813 } catch (ignored) {
814 return null
815 }
816 }
817
818 /**
819 * Try to determine the stream based on hgflow configs
820 * git-flow doesn't have a local config, so we may need to keep this
821 * file around just for the comparison.
822 *
823 * A new name for the file could help as well?
824 */
825 void determineStream() {
826 def flowConfig = new File('.hgflow').exists() ? new File('.hgflow') : new File('../.hgflow')
827 if (flowConfig.exists()) {
828 def flows = new Properties()
829 flows.load(flowConfig.newReader())
830 flows.stringPropertyNames().each {
831 if (!it.startsWith("[") && name.startsWith(flows.getProperty(it))) {
832 stream = it
833 }
834 }
835 }
836 }
837
838 }
839
840
841