comparison init20.gradle @ 175:c3b7af90d1e4

start init script for gradle version 2.*
author smith@nwoca.org
date Fri, 12 Dec 2014 20:59:40 +0000
parents init.gradle@e949e86b570e
children e0865f323a60
comparison
equal deleted inserted replaced
174:e949e86b570e 175:c3b7af90d1e4
1 import groovy.sql.Sql
2
3 final GradleVersion gradleCurrent = GradleVersion.current()
4 final GradleVersion gradleV20 = GradleVersion.version('2.0')
5 println "Gradle Version: $gradleCurrent"
6 if (gradleCurrent < gradleV20) {
7 throw new RuntimeException("this init script requires Gradle version 2.0 or higher")
8 }
9
10 gradle.ext.ssdtDevelkitLocation = gradle.ext.has('ssdtDevelkitLocation') ? gradle.ssdtDevelkitLocation : 'http://hg.ssdt-ohio.org/browse/public/develkit'
11
12 ant.property(file: System.getProperty('user.home') + "/.ssdt/private.properties")
13 gradle.ext.ivyUserDir = ant.properties['ivy.default.ivy.user.dir'] ?: System.getProperty('user.home') + "/.ivy2"
14
15 gradle.ext.ssdtProjectId = System.getenv('bamboo_project_id') ?: rootProject.name
16
17 gradle.addListener(new ArtifactoryGradleSettings())
18
19 def hostname
20 try {
21 hostname = "hostname".execute().text.toLowerCase().readLines().first()
22 } catch (e) {
23 hostname = 'unknown'
24 }
25
26 gradle.ext.bambooBuild = System.getenv().any {
27 it.key.toLowerCase().contains('bamboo')
28 } || hostname?.startsWith('ssdt-')
29
30 gradle.ext.bambooPlan = (System.getenv('BAMBOO_PLAN') ?: 'UNKNOWN-UNKNOWN-JOB1').split('-')[0..1].join('-')
31 logger.info "Bamboo plan: ${gradle.bambooPlan}"
32
33 gradle.ext.buildTimestamp = System.currentTimeMillis().toString().padLeft(14, '0')
34
35 gradle.ext.hgRepositoryUrl = ""
36 try {
37 gradle.ext.hgRepositoryUrl = ("hg path".execute().text.split('=') ?: ['', ''])[1].trim()
38 } catch (e) {
39 }
40
41 def springModuleTranslator = [
42 'spring-transaction': 'spring-tx',
43 'spring-web-servlet': 'spring-webmvc',
44 ].withDefault { it }
45
46 gradle.ext.normalizeSpring = { DependencyResolveDetails details ->
47 if (details.requested.group == 'org.springframework' && details.requested.name.startsWith('org.springframework.')) {
48 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
49 details.useTarget(group: 'org.springframework', name: shortName, version: details.requested.version)
50 }
51 if (details.requested.group == 'org.springframework.security' && details.requested.name.startsWith('org.springframework.')) {
52 def shortName = springModuleTranslator[details.requested.name.replace('org.springframework.', 'spring-').replace('.', '-')]
53 details.useTarget("${details.requested.group}:$shortName:${details.requested.version}")
54 }
55 }
56
57
58 gradle.ext.branchName = System.getenv('bamboo_planRepository_branch')
59 gradle.ext.branchStream = ""
60
61 if (!gradle.branchName) {
62 gradle.ext.branchName = "hg branch".execute().text.trim()
63 def rawParents = 'hg parents'.execute().text
64 def parent = rawParents.split('\n').find { it.startsWith("branch") }?.split(":")?.getAt(1)?.trim()
65 gradle.ext.branchName = parent ?: gradle.branchName
66 }
67
68 if (file('.hgflow').exists()) {
69 def flows = new Properties()
70 flows.load(file('.hgflow').newReader())
71 flows.stringPropertyNames().each {
72 if (!it.startsWith("[") && gradle.branchName.startsWith(flows.getProperty(it))) {
73 gradle.ext.branchStream = it
74 }
75 }
76 }
77
78 gradle.branchName = gradle.branchName.replace('@', '-')
79 gradle.ext.branchHash = generateMD5(gradle.branchName)
80 loadEnvironments()
81
82 gradle.environment.put('hgRepositoryUrl', gradle.hgRepositoryUrl)
83 gradle.environment.put('branchName', gradle.branchName)
84 gradle.environment.put('branchStream', gradle.branchStream)
85 gradle.environment.put('branchHash', gradle.branchHash)
86
87
88 rootProject.ext.indyCapable = {
89 boolean capable = true
90 try {
91 Class.forName('java.lang.invoke.MethodHandle')
92 } catch (e) {
93 capable = false
94 }
95 capable && !rootProject.hasProperty('skipIndy')
96 }
97
98 rootProject.ext.useIndy = {
99 boolean indy = false
100 // first, check if a system property activates indy support
101 indy |= System.hasProperty('indy') && Boolean.valueOf(System.getProperty('indy'))
102
103 // check ssdt environment for indy property.
104 indy |= (gradle.environment.indy) ? gradle.environment.indy.toBoolean() : false
105
106 // check if the main project has an extension property setting indy (-Pindy).
107 if (rootProject.hasProperty('indy')) {
108 indy = (Boolean.valueOf(rootProject.indy))
109 }
110
111 // set the groovy runtime system property to ensure forked junit test will get the indy flag properly
112 if (indy && rootProject.indyCapable()) System.setProperty("groovy.target.indy", "true")
113
114 indy && rootProject.indyCapable()
115 }
116
117 println "Indy available: ${rootProject.indyCapable()} enabled: ${rootProject.useIndy()}"
118
119 if (gradle.bambooBuild) {
120 gradle.ext.ssdtGradlekitLocation = gradle.ext.has('ssdtGradlekitLocation') ? gradle.ssdtGradlekitLocation : 'http://hg.ssdt-ohio.org/ssdt/gradlekit/raw-file/tip'
121 logger.info "applying SSDT artifactory Gradle Settings (bamboo: $gradle.bambooBuild host: $hostname)"
122 apply from: "${gradle.ssdtGradlekitLocation}/artifactory.gradle"
123 }
124
125
126 buildscript {
127 repositories {
128 maven { url 'http://repos.ssdt.nwoca.org/artifactory/ssdt-repo' }
129 }
130 }
131
132 apply from: "${gradle.ssdtDevelkitLocation}/metrics.gradle"
133
134 task wrapper(type: Wrapper) {}
135
136 rootProject.afterEvaluate { r ->
137
138 if (r.plugins.hasPlugin(org.gradle.plugins.ide.idea.IdeaPlugin)) {
139
140 r.idea.project.ipr.withXml { xml ->
141 if (file('.hg').exists()) {
142 println 'enabling HG on project'
143 def vcs = findComponent(xml.asNode(), 'VcsDirectoryMappings')
144 vcs.mapping.@vcs = 'hg4idea'
145 }
146
147 def codeStyle = findComponent(xml.asNode(), 'ProjectCodeStyleSettingsManager')
148 if (codeStyle) {
149 xml.asNode().remove(codeStyle)
150 }
151
152 def styleManager = xml.asNode().appendNode('component', [name: 'ProjectCodeStyleSettingsManager'])
153 styleManager.appendNode 'option', [name: 'USE_PER_PROJECT_SETTINGS', value: true]
154
155 def styleOptions = new NodeBuilder().option(name: 'PER_PROJECT_SETTINGS') {
156 value {
157 GroovyCodeStyleSettings {
158 option(name: 'CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND', value: '10')
159 option(name: 'PACKAGES_TO_USE_IMPORT_ON_DEMAND') {
160 value {
161 'package'(name: "java.awt", withSubpackages: false, static: false)
162 'package'(name: "javax.swing", withSubpackages: false, static: false)
163 'package'(name: "javax.persistence", withSubpackages: false, static: false)
164 'package'(name: "javax.validation", withSubpackages: true, static: false)
165 }
166 }
167 }
168 XML {
169 option(name: 'XML_LEGACY_SETTINGS_IMPORTED', value: true)
170 }
171
172 }
173 }
174
175 styleManager.append styleOptions
176
177 if (r.group.contains('org.ssdt')) {
178
179 def copyRight = findComponent(xml.asNode(), 'CopyrightManager')
180 if (copyRight) {
181 xml.asNode().remove(copyRight)
182 }
183
184 copyRight = new NodeBuilder().component(name: 'CopyrightManager', default: 'ODE') {
185
186 copyright {
187 option(name: 'notice', value: 'Copyright (c) $today.year. Ohio Department of Education. - All Rights Reserved.\nUnauthorized copying of this file, in any medium, is strictly prohibited.\nWritten by State Software Development Team (http://ssdt.oecn.k12.oh.us/)')
188 option(name: 'keyword', value: 'Copyright')
189 option(name: 'allowReplaceKeyword', value: 'South Front')
190 option(name: 'myName', value: 'ODE')
191 option(name: 'myLocal', value: true)
192 }
193 LanguageOptions(name: 'CSS') {
194 option(name: 'fileTypeOverride', value: 1)
195 }
196 LanguageOptions(name: 'JSP') {
197 option(name: 'fileTypeOverride', value: 1)
198 option(name: 'prefixLines', value: false)
199 }
200 LanguageOptions(name: 'JSPX') {
201 option(name: 'fileTypeOverride', value: 1)
202 option(name: 'prefixLines', value: false)
203 }
204 LanguageOptions(name: 'JavaScript') {
205 option(name: 'fileTypeOverride', value: 1)
206 }
207 LanguageOptions(name: 'Properties') {
208 option(name: 'fileTypeOverride', value: 1)
209 }
210 }
211
212 xml.asNode().append copyRight
213
214 }
215 }
216 }
217
218 }
219
220 def findComponent(project, name) {
221 project.component.find { it.@name == name }
222 }
223
224 allprojects {
225
226 task cleanLocal(description: "removes all artifacts from developer's local repository") << {
227
228 def local = project.repositories.find { it.name == 'local' }
229 if (local) {
230 logger.info "removing local repo: $it"
231 new File(System.properties['user.home'] + "/.ssdt/local-repo").deleteDir()
232 def localDir = new File(gradle.ivyUserDir + "/local")
233 localDir.deleteDir()
234 logger.info "verifying removal of local repo"
235 if (localDir.exists()) {
236 throw new org.gradle.api.GradleException("Unable to clean ${localDir}. Files may be locked by another process.")
237 }
238 }
239 }
240
241 cleanLocal.onlyIf {
242 project.repositories.any { it.name == 'local' }
243 }
244
245 tasks.addRule("Pattern: <environment>As[Test]Properties: Generates <environment>.properties as resource or Test resource") { String taskName ->
246 if ((taskName - 'Test').endsWith("AsProperties") && !taskName.startsWith('clean')) {
247 def t = taskName.contains('Test') ? processTestResources.destinationDir : processResources.destinationDir
248 def e = (taskName - 'Test' - 'AsProperties').capitalize()
249 task(taskName) {
250 ext.propertyFile = new File(t, "${e.toLowerCase()}.properties")
251 inputs.files "../environment${e}.groovy", "../private${e}.groovy", '../private.properties'
252 doLast {
253 t.mkdirs()
254 def ps = gradle."environment${e}".toProperties()
255 ps['ssdt.project'] = project.name
256 ps.store(propertyFile.newOutputStream(), "by $taskName of $this")
257 def l = propertyFile.readLines().sort()
258 propertyFile.text = l.join('\n')
259 }
260 }
261 }
262 }
263
264 if (gradle.hasProperty('environmentDatabase')) {
265 tasks.addRule("Pattern: database{Drop|Create}...: drops or creates the environment's database") { String taskName ->
266 if (taskName.startsWith('database') && (taskName.contains('Drop') || taskName.contains('Create'))) {
267 task(taskName) {
268 doLast {
269 def dropIt = taskName.contains("Drop")
270 def createIt = taskName.contains("Create")
271 def driverName = gradle.environmentDatabase.jdbc.driverClassName
272 def databaseUrl = gradle.environmentDatabase.jdbc.url
273 if (driverName != "org.postgresql.Driver") {
274 logger.info "skipping database operation for non-postgresql driver"
275 throw new StopActionException("driver $driverName not supported by $taskName")
276 }
277 if (!configurations.hasProperty('jdbcdriver')) {
278 throw new GradleException("databaseDrop requires a 'jdbcdriver' configuration with a postgresql (or other) driver")
279 }
280 configurations.jdbcdriver.each { File file ->
281 GroovyObject.class.classLoader.addURL(file.toURL())
282 }
283 Class.forName(driverName)
284 def url = new URI(databaseUrl.substring(5))
285 def jdbcBaseUrl = databaseUrl - url.path
286 def databaseName = url.path - "/"
287 def adminUrl = jdbcBaseUrl + "/postgres"
288 def sql = Sql.newInstance(adminUrl,
289 gradle.environmentDatabase.jdbc.username,
290 gradle.environmentDatabase.jdbc.password,
291 driverName)
292 if (dropIt) {
293 logger.info "dropping $databaseName (if exists) from $adminUrl"
294 sql.execute 'DROP DATABASE IF EXISTS "' + databaseName + '";'
295 }
296
297 if (createIt) {
298 logger.info "Creating database $databaseName at $adminUrl"
299 sql.execute 'CREATE DATABASE "' + databaseName + '";'
300 }
301 }
302 }
303
304 }
305 }
306 }
307
308 }
309
310
311 class ArtifactoryGradleSettings extends BuildAdapter implements BuildListener {
312
313 def void projectsEvaluated(Gradle gradle) {
314 def ssdtArtifactory = 'http://repos.ssdt.nwoca.org/artifactory'
315 Project root = gradle.getRootProject()
316 root.allprojects {
317
318
319 def thisProject = delegate
320 thisProject.status = 'integration'
321 if (gradle.branchStream) {
322 thisProject.status = 'integration'
323 def fixupVersion = thisProject.version - ".SNAPSHOT"
324 if (gradle.branchStream == 'feature') {
325 fixupVersion = fixupVersion + ".SNAPSHOT"
326 }
327 if (gradle.branchStream == 'develop') {
328 fixupVersion = fixupVersion + ".SNAPSHOT"
329 }
330 if (gradle.branchStream in ['production', 'release']) {
331 thisProject.
332 status = 'release'
333 }
334 thisProject
335 .version = fixupVersion
336 }
337
338 configurations.all {
339 resolutionStrategy.cacheChangingModulesFor 60 * 60 * 8, 'seconds'
340 resolutionStrategy.cacheDynamicVersionsFor 60 * 60 * 8, 'seconds'
341 }
342 repositories {
343
344 if (!gradle.bambooBuild) {
345 ivy {
346 name = 'local'
347 artifactPattern gradle.ivyUserDir + '/local/[artifact]-[revision](-[classifier]).[ext]'
348 ivyPattern gradle.ivyUserDir + "/local/[module]-ivy-[revision].xml"
349 }
350 }
351
352 if (gradle.branchStream == 'feature') {
353 ivy {
354 name = 'ssdt-branches'
355 def url = "${ssdtArtifactory}/ssdt-branches"
356 artifactPattern "${url}/${gradle.branchHash}/[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
357 ivyPattern "${url}/${gradle.branchHash}/[organization]/[module]/ivy-[revision].xml"
358 // m2compatible = false
359 // def filter1 = ";ssdt-branch.branchName+=${gradle.branchName.replaceAll('/', '-')}"
360 // def filter2 = ";ssdt-branch.branchName=${gradle.branchName.replaceAll('/', '-')}"
361 // checkmodified = true
362 // changingMatcher = 'regexp'
363 // changingPattern = '.*SNAPSHOT'
364 }
365 }
366
367 ivy {
368 name = 'ssdt-snapshots'
369 def url = "${ssdtArtifactory}/ssdt-snapshots"
370 artifactPattern "${url}/[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
371 artifactPattern "${url}/[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
372 ivyPattern "${url}/[organization]/[module]/ivy-[revision].xml"
373 // checkmodified = true
374 // m2compatible = true
375 // changingMatcher = 'regexp'
376 // changingPattern = '.*SNAPSHOT'
377 }
378
379 ivy {
380 name = 'ssdt-releases'
381 // m2compatible = false
382 def url = "${ssdtArtifactory}/ssdt-releases"
383 artifactPattern "${url}/[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]"
384 artifactPattern "${url}/[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
385 ivyPattern("${url}/[organization]/[module]/ivy-[revision].xml")
386 }
387
388 maven {
389 name = 'ssdt-repository'
390 url = "${ssdtArtifactory}/repository"
391 }
392
393
394 }
395
396 if (thisProject.repositories.find {
397 it.name == 'local'
398 } && thisProject.getTasksByName('uploadArchives', false)) {
399 uploadArchives {
400 repositories {
401 add thisProject.repositories.local
402 }
403 }
404
405 thisProject.tasks.create("publishLocal") {
406 description = "Publishes this projects artifacts to developer's local repository"
407 dependsOn = ["uploadArchives"]
408 }
409 }
410
411 }
412
413 root.subprojects { p ->
414 if (root.useIndy()) {
415 def groovyIndy = p.configurations.compile.files.find { f -> f.name.startsWith('groovy-all') && f.name.contains('-indy') }
416 if (groovyIndy) {
417 logger.info "enabling indy on $p"
418 [compileGroovy.groovyOptions, compileTestGroovy.groovyOptions]*.with {
419 optimizationOptions = [indy: true]
420 }
421 }
422 }
423 }
424 }
425 }
426
427
428 task showEnvironments << {
429 println "Defined environments: $gradle.environments"
430 gradle.environments.each { e ->
431 println "\n $e:"
432 gradle.getProperty(e).flatten().sort { it.key }.each { k, v ->
433 println String.format(' %25s = %s', k, k.contains('password') ? "********" : v)
434 }
435 }
436 if (logger.isInfoEnabled()) {
437 println "System properties:"
438 System.properties.each { println " $it" }
439 println "env variables:"
440 System.getenv().each { println " $it" }
441 }
442 }
443
444 def loadEnvironments() {
445 def developerPrivate = new Properties()
446 if (file('private.properties').exists()) {
447 developerPrivate.load(file('private.properties').newReader())
448 }
449 def envOverrides = [:]
450
451 if (!hasProperty('env')) {
452 gradle.ext.env = developerPrivate.env ?: 'dev'
453 } else {
454 def values = getProperty('env').split(',')
455 gradle.ext.env = values.first()
456 values.tail().each {
457 def (k, v) = it.split('=')
458 envOverrides.put(k, v)
459 }
460 }
461
462 println "Environment is: $gradle.env ($envOverrides)"
463 def slurper = new ConfigSlurper(gradle.env)
464 slurper.setBinding(['gradle': gradle])
465
466 def environment = slurper.parse(
467 '''deploy.mode="production"
468 environments {
469 test { deploy.mode="test" }
470 dev { deploy.mode="development"}
471 }''')
472 if (developerPrivate['deploy.mode']) {
473 environment.put('deploy.mode', developerPrivate['deploy.mode'])
474 }
475
476 def environments = []
477 gradle.ext.environment = environment
478 file('.').listFiles().findAll { it.name ==~ /^environment.*\.groovy$/ }.sort { it.name }.each { envFile ->
479 def envName = envFile.name - '.groovy'
480 def privateFile = file("private" + envName - "environment" + ".groovy")
481 logger.info("loading environment $envFile.name")
482
483 def envCfg = slurper.parse(envFile.toURL())
484 envCfg.merge(slurper.parse(developerPrivate))
485 envCfg.put('ssdt.projectid', gradle.ssdtProjectId)
486 envCfg.put('ssdt.environment', gradle.env)
487 if (privateFile.exists()) {
488 logger.info("loading private environment $privateFile")
489 envCfg.merge(slurper.parse(privateFile.toURL()))
490 }
491
492 gradle.rootProject.getProperties().find { it.key.startsWith('environment') }.each {
493 it.value.split(',').each { p ->
494 def (k, v) = p.split('=')
495 logger.info("$envName: overriding " + k + "=" + v + " in $it")
496 envCfg.put(k, v)
497 }
498 }
499
500 envOverrides.each { k, v ->
501 logger.info("$envName: overriding " + k + "=" + v)
502 envCfg.put(k, v)
503 }
504 environment.merge(envCfg)
505 if (envName != 'environment') {
506 gradle.ext[envName] = envCfg
507 environments << envName
508 }
509 }
510 environment.merge(slurper.parse(developerPrivate))
511 def deployMode = environment.deploy.mode ?: 'development'
512 environments.each { gradle.ext[it].put('ssdt.deployment.mode', deployMode) }
513 environments << 'environment'
514 gradle.ext.environments = environments
515
516 }
517
518 def generateMD5(String s) {
519 def digest = java.security.MessageDigest.getInstance("MD5")
520 digest.update(s.bytes);
521 new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
522 }