comparison init50-github.gradle @ 350:b8d368020501

Add github version of init50
author Marc Davis <marc.davis@mcoecn.org>
date Wed, 26 Jul 2023 11:17:00 -0400
parents
children c57a1da032ec
comparison
equal deleted inserted replaced
349:45fc06cbb6b2 350:b8d368020501
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 gradleV50 = GradleVersion.version('5.0')
17
18 if (gradleCurrent < gradleV50) {
19 throw new RuntimeException("this init script requires Gradle version 5.0 or higher")
20 }
21
22 gradle.ext.ssdtDevelkitLocation = gradle.ext.has('ssdtDevelkitLocation') ? gradle.ssdtDevelkitLocation : 'http://hg.ssdt-ohio.org/browse/public/develkit'
23
24 ant.property(file: System.getProperty('user.home') + "/.ssdt/private.properties")
25 gradle.ext.ivyUserDir = ant.properties['ivy.default.ivy.user.dir'] ?: System.getProperty('user.home') + "/.ivy2"
26
27 gradle.ext.ssdtProjectId = System.getenv('bamboo_project_id') ?: rootProject.name
28
29 gradle.addListener(new ArtifactoryGradleSettings())
30
31 def hostname
32 try {
33 hostname = "hostname".execute().text.toLowerCase().readLines().first()
34 } catch (e) {
35 hostname = 'unknown'
36 }
37
38 gradle.ext.bambooBuild = System.getenv().any {
39 it.key.toLowerCase().contains('bamboo')
40 } || hostname?.startsWith('ssdt-ba')
41
42 if (!rootProject.hasProperty("bambooLocalBuild")) {
43 gradle.ext.bambooLocalBuild = false
44 } else {
45 gradle.ext.bambooLocalBuild = rootProject.bambooLocalBuild.toBoolean()
46 }
47
48 if (gradle.bambooLocalBuild) {
49 println "Bamboo local build active"
50 }
51
52 gradle.ext.bambooPlan = (System.getenv('BAMBOO_PLAN') ?: 'UNKNOWN-UNKNOWN-JOB1').split('-')[0..1].join('-')
53 logger.info "Bamboo plan: ${gradle.bambooPlan}"
54
55 gradle.ext.buildTimestamp = System.currentTimeMillis().toString().padLeft(14, '0')
56
57 gradle.ext.hgRepositoryUrl = ""
58
59 try {
60 gradle.ext.hgRepositoryUrl = ("hg path".execute().text.split('=') ?: ['', ''])[1].trim()
61 } catch (e) {
62 }
63
64 def springModuleTranslator = [
65 'spring-transaction': 'spring-tx',
66 'spring-web-servlet': 'spring-webmvc',
67 ].withDefault { it }
68
69 gradle.ext.normalizeSpring = { DependencyResolveDetails details ->
70 if (details.requested.group == 'org.springframework' && details.requested.name.startsWith('org.springframework.')) {
71 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
72 details.useTarget(group: 'org.springframework', name: shortName, version: details.requested.version)
73 }
74 if (details.requested.group == 'org.springframework.security' && details.requested.name.startsWith('org.springframework.')) {
75 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
76 details.useTarget("${details.requested.group}:$shortName:${details.requested.version}")
77 }
78 }
79
80 gradle.ext.runtimeInfo = new RuntimeInfo()
81
82
83 if (System.env.DOCKER_HOST ) {
84 if (System.env.DOCKER_HOST.contains('tcp:')) {
85 gradle.ext.dockerEngineUrl = "https:${System.env.DOCKER_HOST?.minus('tcp:')}"
86 }
87 gradle.ext.dockerEngineUrl = System.env.DOCKER_HOST
88 }
89
90 setBranchInfo()
91
92 loadEnvironments()
93
94 gradle.environment.put('hgRepositoryUrl', gradle.hgRepositoryUrl)
95 gradle.environment.put('branchName', gradle.branch.name)
96 gradle.environment.put('branchStream', gradle.branch.stream)
97 gradle.environment.put('branchHash', gradle.branch.hash)
98
99
100 def cacheTimeout = 60 * 60 * 8
101 if (gradle.environment['dependencyTimeout']) {
102 cacheTimeout = gradle.environment['dependencyTimeout'] as Integer
103 println "setting changing dependency timeout to $cacheTimeout seconds"
104 }
105
106 gradle.ext.cacheTimeout = cacheTimeout
107
108 rootProject.ext.indyCapable = {
109 boolean capable = true
110 try {
111 Class.forName('java.lang.invoke.MethodHandle')
112 } catch (e) {
113 capable = false
114 }
115 capable && !rootProject.hasProperty('skipIndy')
116 }
117
118 rootProject.ext.useIndy = {
119 boolean indy = false
120 // first, check if a system property activates indy support
121 indy |= System.hasProperty('indy') && Boolean.valueOf(System.getProperty('indy'))
122
123 // check ssdt environment for indy property.
124 indy |= (gradle.environment.indy) ? gradle.environment.indy.toBoolean() : false
125
126 // check if the main project has an extension property setting indy (-Pindy).
127 if (rootProject.hasProperty('indy')) {
128 indy = (Boolean.valueOf(rootProject.indy))
129 }
130
131 // set the groovy runtime system property to ensure forked junit test will get the indy flag properly
132 if (indy && rootProject.indyCapable()) System.setProperty("groovy.target.indy", "true")
133
134 indy && rootProject.indyCapable()
135 }
136
137 println "Indy available: ${rootProject.indyCapable()} enabled: ${rootProject.useIndy()}"
138
139 if (gradle.bambooBuild) {
140
141 file('build-number.txt').text = "build.number=${gradle.branch.buildNumber ?: -1 }\n"
142 logger.info "applying SSDT artifactory Gradle Settings (bamboo: $gradle.bambooBuild host: $hostname)"
143 apply from: "${gradle.ssdtDevelkitLocation}/artifactory40.gradle"
144 }
145
146 if (!rootProject.hasProperty('disableMetrics')) {
147 apply from: "${gradle.ssdtDevelkitLocation}/metrics50.gradle"
148 }
149
150 rootProject.afterEvaluate { r ->
151 if (gradle.bambooBuild && r.hasProperty('requireJavaVersion')) {
152 gradle.runtimeInfo.requireJava( r.getProperty('requireJavaVersion') )
153 }
154 if (!gradle.bambooBuild && !r.file('.idea/copyright/ODE.xml').exists() ) {
155 updateCopyrightProfile(r)
156 }
157 }
158
159 def findComponent(project, name) {
160 project.component.find { it.@name == name }
161 }
162
163 wrapper {
164 distributionType = org.gradle.api.tasks.wrapper.Wrapper.DistributionType.ALL
165 }
166
167 allprojects {
168
169 configurations.all {
170 resolutionStrategy.cacheChangingModulesFor gradle.cacheTimeout, 'seconds'
171 resolutionStrategy.cacheDynamicVersionsFor gradle.cacheTimeout, 'seconds'
172 }
173 configurations.all {
174 resolutionStrategy.eachDependency { DependencyResolveDetails details ->
175 if (details.requested.group == 'org.ssdt_ohio' && !details.requested.version ) {
176 details.useVersion( "latest.${gradle.branch.defaultDependencyStatus}" )
177 }
178 if (details.requested.version == 'default') {
179 details.useVersion("latest.${gradle.branch.defaultDependencyStatus}" )
180 }
181 if (project.hasProperty("overrideCommon")) {
182 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.contains('ssdt.common.')) {
183 details.useVersion(project.overrideCommon)
184 }
185 }
186 if (project.hasProperty("overrideVui")) {
187 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('vui.')) {
188 details.useVersion(project.overrideVui)
189 }
190 }
191 if (project.hasProperty("overrideUsasCore")) {
192 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('usas.') && !details.requested.name.startsWith('usas.vui')) {
193 details.useVersion(project.overrideUsasCore)
194 }
195 }
196 if (project.hasProperty("overrideUspsCore")) {
197 if (details.requested.group == 'org.ssdt_ohio' && details.requested.name.startsWith('usps.') && !details.requested.name.startsWith('usps.vui')) {
198 details.useVersion(project.overrideUspsCore)
199 }
200 }
201
202 }
203 }
204
205 task cleanLocal(description: "removes all artifacts from developer's local repository") {
206
207 doLast {
208 def local = project.repositories.find { it.name == 'local' }
209 if (local) {
210 logger.info "removing local repo: $it"
211 new File(System.properties['user.home'] + "/.ssdt/local-repo").deleteDir()
212 def localDir = new File(gradle.ivyUserDir + "/local")
213 localDir.deleteDir()
214 logger.info "verifying removal of local repo"
215 if (localDir.exists()) {
216 throw new org.gradle.api.GradleException("Unable to clean ${localDir}. Files may be locked by another process.")
217 }
218 }
219 }
220 }
221
222 cleanLocal.onlyIf {
223 project.repositories.any { it.name == 'local' }
224 }
225
226 project.ext.previousBuildenv = project.file('build/buildenv.txt').exists() ? project.file('build/buildenv.txt').text : 'none'
227
228 tasks.addRule("Pattern: <environment>As[Test]Properties: Generates <environment>.properties as resource or Test resource") { String taskName ->
229 if ((taskName - 'Test').endsWith("AsProperties") && !taskName.startsWith('clean')) {
230 // def t = taskName.contains('Test') ? processTestResources.destinationDir : processResources.destinationDir
231 def t = taskName.contains('Test') ? sourceSets.test.output.resourcesDir : sourceSets.main.output.resourcesDir
232 def e = (taskName - 'Test' - 'AsProperties').capitalize()
233 task(taskName) {
234 ext.outputDir = t
235 ext.propertyFile = "${e.toLowerCase()}.properties"
236 ext.buildenv = project.file('build/buildenv.txt')
237 inputs.files project.file("../environment${e}.groovy"), project.file("../private${e}.groovy"), project.file('../private.properties')
238 outputs.files new File(outputDir,propertyFile), buildenv
239 outputs.upToDateWhen {
240 gradle.env == project.previousBuildenv && outputs.getFiles().every { it.exists() }
241 }
242 doLast {
243 t.mkdirs()
244 outputDir.mkdirs()
245 buildenv.text = gradle.env
246 def ps = gradle."environment${e}".toProperties()
247 ps['ssdt.project'] = project.name
248 def pf = new File(outputDir,propertyFile)
249 ext.outputPropertyFile = pf
250 ps.store(pf.newOutputStream(), "by $taskName of $this")
251 def l = pf.readLines().sort()
252 pf.text = l.join('\n').replaceAll("\\.PARENT","")
253 }
254 }
255 }
256 }
257
258 }
259
260 subprojects {
261
262 it.ext.environment = gradle.environment
263
264 dependencyLocking {
265 if (gradle.branch.isRelease()) {
266 lockAllConfigurations()
267 }
268 }
269
270 task("releaseLock" ) {
271 description = "Create release dependencies Lock files"
272 doFirst {
273 assert gradle.startParameter.writeDependencyLocks : "must include --write-locks or --update-locks option when locking dependencies"
274 }
275 doLast {
276
277 if (!gradle.branch.isRelease()) {
278 throw new BuildCancelledException("releaseLock is only valid on release or hotfix branch.")
279 }
280
281 configurations.findAll {
282 it.canBeResolved
283 }.findAll { c ->
284 def n = c.name.toLowerCase()
285 ['compile','runtime','provided'].any { n.contains(it) }
286 }.each {
287 it.resolve()
288 }
289 }
290 }
291
292 }
293
294 rootProject.afterEvaluate {
295
296 tasks.addRule("release{Major|Minor|Patch|n.n.n}: create release branch or update release Lock file") { String taskName ->
297
298 def matcher = (taskName =~ /^release(Major|Minor|Patch|\d{1,3}\.\d{1,3}\.\d{1,3})$/)
299 if (matcher.matches()) {
300
301 task('doReleaseBranch') {
302 ext.requested = matcher[0][1].toLowerCase()
303 doLast {
304 def releaseVersion = determineReleaseVersion(requested)
305 def releaseStream = releaseVersion.isHotfix() ? 'hotfix' : 'release'
306
307 println "-" * 60
308 println "Preparing to create branch\n"
309 println "\tproject:\t${gradle.rootProject.name}"
310 println "\tcurrent:\t${gradle.branch} ($gradle.branch.version)"
311 println()
312 println "\ttype :\t${releaseStream.toUpperCase()}"
313 println "\tversion:\t${releaseVersion}"
314 println "\ttarget :\t${releaseStream}/v${releaseVersion}"
315 println()
316 println("-" * 60)
317 println "DRY RUN".center(60)
318 println("-" * 60)
319
320 println "hg flow ${releaseStream} start v${releaseVersion} --dirty --dry-run".execute().text
321
322 println "-" * 60
323
324 if (!confirmPrompt("Continue?")) {
325 throw new BuildCancelledException("release branching canceled by user request")
326 }
327
328 println "hg flow ${releaseStream} start v${releaseVersion} --dirty".execute().text
329 println "hg update ${releaseStream}/v${releaseVersion}".execute().text
330
331 setBranchInfo()
332
333 println "-" * 60
334 println " Be sure to execute 'releaseLock' task to update the release.lock file before proceeding."
335 println "-" * 60
336
337 }
338 }
339
340
341 def branchTasks = ['doReleaseBranch']
342
343 task(taskName) {
344 dependsOn branchTasks
345 }
346
347 branchTasks.tail().inject(branchTasks.head()) { a, b ->
348 tasks[b].mustRunAfter a
349 b
350 }
351
352 }
353 }
354
355 }
356
357 private static String readLine(String message, String defaultValue = null) {
358 String _message = "> $message" + (defaultValue ? " [$defaultValue] " : "")
359 if (System.console()) {
360 return System.console().readLine(_message) ?: defaultValue
361 }
362 println "$_message "
363
364 System.in.newReader().readLine() ?: defaultValue
365 }
366
367 private static boolean confirmPrompt(String message, boolean defaultValue = false) {
368 String defaultStr = defaultValue ? 'Y' : 'n'
369 String consoleVal = readLine("${message} (Y|n)", defaultStr)
370 if (consoleVal) {
371 return consoleVal.toLowerCase().startsWith('y')
372 }
373
374 defaultValue
375 }
376
377 private Version determineReleaseVersion(String requested) {
378 if (requested == 'major') {
379 return gradle.branch.version.nextMajor()
380 } else if (requested == 'minor') {
381 return gradle.branch.version.nextMinor()
382 } else if (requested == 'patch') {
383 return gradle.branch.version.nextPatch()
384 } else {
385 return new Version(*requested.split(/\./)*.toInteger(), false)
386 }
387 }
388
389 class ArtifactoryGradleSettings extends BuildAdapter implements BuildListener {
390
391 def void projectsEvaluated(Gradle gradle) {
392 def ssdtArtifactory = 'https://docker.ssdt.io/artifactory'
393 Project root = gradle.getRootProject()
394
395
396 def branchVersioning = gradle.rootProject.version == 'unspecified'
397
398 root.allprojects {
399
400 def thisProject = delegate
401 thisProject.status = 'integration'
402 if (gradle.branchStream) {
403 if (branchVersioning) {
404 thisProject.version = gradle.branch.version
405 thisProject.status = gradle.branch.defaultDependencyStatus
406 } else {
407
408 thisProject.status = 'integration'
409 def fixupVersion = thisProject.version - ".SNAPSHOT"
410 if (gradle.branchStream == 'feature') {
411 fixupVersion = fixupVersion + ".SNAPSHOT"
412 }
413 if (gradle.branchStream == 'develop') {
414 fixupVersion = fixupVersion + ".SNAPSHOT"
415 }
416 if (gradle.branchStream in ['production', 'release', 'hotfix']) {
417 thisProject.status = 'release'
418 }
419 thisProject.version = fixupVersion
420 }
421 }
422
423 repositories {
424
425 if (!gradle.bambooBuild || gradle.bambooLocalBuild) {
426 ivy {
427 name = 'local'
428 artifactPattern gradle.ivyUserDir + '/local/[artifact]-[revision](-[classifier]).[ext]'
429 ivyPattern gradle.ivyUserDir + "/local/[module]-ivy-[revision].xml"
430 }
431 }
432
433 if (!gradle.bambooBuild) {
434 mavenLocal()
435 }
436
437 if (gradle.branchStream == 'feature') {
438 ivy {
439 name = 'ssdt-branches'
440 url = "${ssdtArtifactory}/ssdt-branches/${gradle.branchHash}/"
441 patternLayout() {
442 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
443 ivy "[organization]/[module]/ivy-[revision].xml"
444 }
445 }
446 }
447
448 ivy {
449 name = 'ssdt-releases'
450 url = "${ssdtArtifactory}/ssdt-releases"
451 patternLayout() {
452 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
453 artifact "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
454 ivy "[organization]/[module]/ivy-[revision].xml"
455 m2compatible = true
456 }
457 }
458
459 ivy {
460 name = 'ssdt-snapshots'
461 url = "${ssdtArtifactory}/ssdt-snapshots"
462 patternLayout() {
463 artifact "[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
464 artifact "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
465 ivy "[organization]/[module]/ivy-[revision].xml"
466 m2compatible = true
467 }
468 }
469
470 maven {
471 name = 'ssdt-repository'
472 url = "${ssdtArtifactory}/repository"
473 }
474
475 }
476
477 def remoteRepos = thisProject.repositories.findAll { it.hasProperty('url') && !(it.name.toLowerCase().contains('local') || it.url.toString().contains('ssdt')) }
478 if (remoteRepos) {
479 logger.warn "WARNING: Remote repositories configured for $thisProject:\n" + remoteRepos.collect { "\t$it.name $it.url " }.join('\n') + "\n Moved to lowest priority..."
480 remoteRepos.each {
481 thisProject.repositories.remove(it)
482 thisProject.repositories.addLast(it)
483 }
484 }
485 logger.info "$thisProject configured repositories:\n" + thisProject.repositories.collect {"\t$it.name ${it.hasProperty('url') ? it.url : '' }" }.join('\n')
486
487 if (thisProject.repositories.find { it.name == 'local' } && thisProject.getTasksByName('uploadArchives', false)) {
488 uploadArchives {
489 repositories {
490 add thisProject.repositories.local
491 }
492 }
493
494 thisProject.tasks.create("publishLocal") {
495 description = "Publishes this projects artifacts to developer's local repository"
496 dependsOn = ["uploadArchives"]
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('ssdt_head_ref'))
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 class BranchInfo {
725 def name
726 def stream = "none"
727 def buildNumber = ""
728 def changeset = ""
729 def version
730
731 String toString() {
732 "{name:$name, stream:$stream, buildNumber:$buildNumber, changeSet:$changeset, version:$version}"
733 }
734
735 BranchInfo(name) {
736 this.name = name
737 if (!name) {
738 this.name = determineName() ?: ''
739 }
740 this.name = this.name.replace('@', '-')
741 determineStream()
742 buildNumber = System.getenv('ssdt_run_number') ?: ""
743 changeset = System.getenv('ssdt_sha') ?: ""
744 }
745
746 String getDefaultDependencyStatus() {
747 return isRelease() ? 'release' : 'integration'
748 }
749
750 private boolean isRelease() {
751 return stream in ['release', 'hotfix']
752 }
753
754 def getShortName() {
755 def result = name.contains('/') ? name.split('/')[1] : name
756 }
757
758 String getBuildVersion() {
759 def v = isRelease() ? shortName - "v": ""
760 return v
761 }
762
763 def Version getVersion() {
764 if (!version) {
765 if (isRelease()) {
766 version = new Version(*getBuildVersion().split('\\.')*.toInteger(), false)
767 } else {
768 version = findSnapshotVersion()
769 }
770 }
771 return version
772 }
773
774 def getImageId() {
775 (buildVersion ?: shortName.take(25)) + (buildNumber ? "-${buildNumber}" : "-0")
776 }
777
778 def getDeployName() {
779 (buildVersion ?: shortName.take(25)).toLowerCase().collectReplacements {
780 ('a'..'z').contains(it) || ('0'..'9').contains(it) || it == "-" ? null : '-'
781 }
782 }
783
784 def getHash() {
785 generateMD5(name)
786 }
787 def generateMD5(String s) {
788 def digest = java.security.MessageDigest.getInstance("MD5")
789 digest.update(s.bytes);
790 new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
791 }
792
793 private Version findSnapshotVersion() {
794 println "findSnapshotVersion()"
795 try {
796 def repositoryUrl = System.getenv('ssdt_repositoryUrl')
797 if (repositoryUrl) {
798 println "git pull $repositoryUrl".execute().text
799 }
800 def versions = "git tag".execute().text.split("\n")
801 .findAll { it != null || it != "" }
802 .collect { it.replace("v", "") }
803 .collect {
804 Version v = null
805 try {
806 v = new Version(*it.split('\\.')*.toInteger())
807 return v
808 } catch (ignored) {
809 //non semver tag found, ignoring
810 }
811 }
812 .findAll { it != null }
813 .sort { v1, v2 -> v2 <=> v1 }
814
815 def branches = "git branch --all".execute().text.split("\n")
816 .findAll {it.contains('release') || it.contains('hotfix') }
817 .collect { it.replaceAll('\\s+', ' ').split('/').last() - 'v' }
818 .collect { new Version(*it.split('\\.')*.toInteger()) }
819
820 def results = (branches + versions).sort { v1, v2 -> v2 <=> v1 }
821 if (results.isEmpty()) {
822 return new Version().nextSnapshot()
823 } else {
824 return results.first().nextSnapshot()
825 }
826 } catch (ex) {
827 println ex
828 return new Version().nextSnapshot()
829 }
830 }
831
832 def determineName() {
833 try {
834 def branch = "git branch --show-current".execute().text.trim()
835 return branch
836 } catch (ignored) {
837 return null
838 }
839 }
840
841 /**
842 * Try to determine the stream based on hgflow configs
843 * git-flow doesn't have a local config, so we may need to keep this
844 * file around just for the comparison.
845 *
846 * A new name for the file could help as well?
847 */
848 void determineStream() {
849 def flowConfig = new File('.hgflow').exists() ? new File('.hgflow') : new File('../.hgflow')
850 if (flowConfig.exists()) {
851 def flows = new Properties()
852 flows.load(flowConfig.newReader())
853 flows.stringPropertyNames().each {
854 if (!it.startsWith("[") && name.startsWith(flows.getProperty(it))) {
855 stream = it
856 }
857 }
858 }
859 }
860
861 }
862
863
864