view init.gradle @ 129:bef2bfc61f6e

CM-133: fix bamboo plan parsing. enable showEnv to display sytem properties and env variables in -info mode
author smith@nwoca.org
date Wed, 05 Jun 2013 02:29:48 +0100
parents c93df17513f1
children 9ce07c211984
line wrap: on
line source

gradle.ext.ssdtDevelkitLocation = gradle.ext.has('ssdtDevelkitLocation') ? gradle.ssdtDevelkitLocation : 'http://hg.ssdt-ohio.org/browse/public/develkit'

ant.property(file: System.getProperty('user.home') + "/.ssdt/private.properties")
gradle.ext.ivyUserDir = ant.properties['ivy.default.ivy.user.dir'] ?: System.getProperty('user.home') + "/.ivy2"

loadEnvironments()


gradle.addListener(new ArtifactoryGradleSettings())

def hostname 
try { hostname = "hostname".execute().text.toLowerCase().readLines().first() } catch (e) { hostname = 'unknown'}

gradle.ext.bambooBuild = System.getenv().any { it.key.startsWith('BAMBOO')} || hostname?.startsWith('ssdt-')

gradle.ext.bambooPlan = (System.getenv('BAMBOO_PLAN') ?: 'UNKNOWN-UNKNOWN-JOB1').split('-')[0..1].join('-')
logger.info "Bamboo plan: ${gradle.bambooPlan}"

gradle.ext.hgRepositoryUrl = ""
try {
   gradle.ext.hgRepositoryUrl = "hg path".execute().text.split('=')[1].trim()
} catch (e) {}

rootProject.ext.indyCapable = {
    boolean capable = true
    try {
        Class.forName('java.lang.invoke.MethodHandle')
    } catch (e) {
        capable = false
    }
    capable && !rootProject.hasProperty('skipIndy')
}

rootProject.ext.useIndy = {
    boolean indy = false
    // first, check if a system property activates indy support
    indy |= System.hasProperty('indy') && Boolean.valueOf(System.getProperty('indy'))

    // check ssdt environment for indy property.
    indy |= (gradle.environment.indy) ? gradle.environment.indy.toBoolean() : false

    // check if the main project has an extension property setting indy (-Pindy).
    if (rootProject.hasProperty('indy')) { indy =  (Boolean.valueOf(rootProject.indy)) }

    // set the groovy runtime system property to ensure forked junit test will get the indy flag properly
    if (indy && rootProject.indyCapable()) System.setProperty("groovy.target.indy","true")

    indy && rootProject.indyCapable()
}

println "Indy available: ${rootProject.indyCapable()} enabled: ${rootProject.useIndy()}"
        
if (gradle.bambooBuild) {
   gradle.ext.ssdtGradlekitLocation = gradle.ext.has('ssdtGradlekitLocation') ? gradle.ssdtGradlekitLocation : 'http://hg.ssdt-ohio.org/ssdt/gradlekit/raw-file/tip'
   logger.info "applying SSDT artifactory Gradle Settings (bamboo: $gradle.bambooBuild host: $hostname)"
   apply from: "${gradle.ssdtGradlekitLocation}/artifactory.gradle" 
}


buildscript {
    repositories {
        maven { url 'http://repos.ssdt.nwoca.org/artifactory/gradle-plugins' }
        maven { url 'http://repos.ssdt.nwoca.org/artifactory/repository' }
        maven { url 'http://repos.ssdt.nwoca.org/artifactory/libs-snapshots' }
    }
}

apply from: "${gradle.ssdtDevelkitLocation}/metrics.gradle"   

task wrapper(type: Wrapper) {}

wrapper << {
    // patch wrapper path for 1.0-milestone-7 (http://issues.gradle.org/browse/GRADLE-1823)
    ant.replace(file: 'gradlew', token: '\\wrapper\\gradle-wrapper.jar',value:'/wrapper/gradle-wrapper.jar')
}

allprojects {

    task cleanLocal(description: "removes all artifacts from developer's local repository") << {

        def local = project.repositories.find { it.name == 'local' } 
        if ( local ) {                  
            logger.info "removing local repo: $it"
            new File(System.properties['user.home'] + "/.ssdt/local-repo").deleteDir() 
            def localDir = new File(gradle.ivyUserDir + "/local")
            localDir.deleteDir()
            logger.info "verifying removal of local repo"
            if (localDir.exists()) {
                throw new org.gradle.api.GradleException("Unable to clean ${localDir}. Files may be locked by another process.")
            }
        }
    }    
    
    cleanLocal.onlyIf { 
        project.repositories.any { it.name == 'local' }
    }    
    
}


class ArtifactoryGradleSettings extends BuildAdapter implements BuildListener {
    
    def void projectsEvaluated(Gradle gradle) {
        def ssdtArtifactory = 'http://repos.ssdt.nwoca.org/artifactory'
        Project root = gradle.getRootProject()       
        root.allprojects {
               
            def thisProject = delegate        
            configurations.all {
                resolutionStrategy.cacheChangingModulesFor 60 * 60 * 8, 'seconds'
                resolutionStrategy.cacheDynamicVersionsFor 60 * 60 * 8, 'seconds'
            }        
            repositories {
                if (!gradle.bambooBuild) {                         
                    add(new org.apache.ivy.plugins.resolver.FileSystemResolver()) {
                        name = 'local'
                        addIvyPattern gradle.ivyUserDir + "/local/[module]-ivy-[revision].xml"
                        addArtifactPattern gradle.ivyUserDir + '/local/[module]-[artifact]-[revision](-[classifier]).[ext]'
                        descriptor = 'optional'
                        checkmodified = true
                        changingMatcher = 'regexp'
                        changingPattern = '.*SNAPSHOT'   
                        force = true
                    }                       
                }                   

                add(new org.apache.ivy.plugins.resolver.URLResolver()) {
                    name = 'ssdt-snapshots'
                    m2compatible =  true
                    def url = "${ssdtArtifactory}/ssdt-snapshots"
                    addArtifactPattern("${url}/[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]")
                    addArtifactPattern("${url}/[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]")
                    addIvyPattern("${url}/[organization]/[module]/ivy-[revision].xml")
                    checkmodified = true
                    changingMatcher = 'regexp'
                    changingPattern = '.*SNAPSHOT'
                   }

                add(new org.apache.ivy.plugins.resolver.URLResolver()) {
                    name = 'ssdt-releases'
                    m2compatible = false
                    def url = "${ssdtArtifactory}/ssdt-releases"
                    addArtifactPattern("${url}/[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]")
                    addArtifactPattern("${url}/[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]")
                    addIvyPattern("${url}/[organization]/[module]/ivy-[revision].xml")
                }


                maven {
                    name = 'ssdt-repository'
                    url = "${ssdtArtifactory}/repository"
                }

                              
            }           
            
            if ( thisProject.repositories.find { it.name == 'local' } ) {
                uploadArchives {
                   repositories {                     
                         add thisProject.repositories.local
                    }
                }
                
                thisProject.tasks.create("publishLocal") {
                    description = "Publishes this projects artifacts to developer's local repository"
                    dependsOn = ["uploadArchives"]
                }
            }

        }

        root.subprojects { p ->     
            if (root.useIndy()) {
                def groovyIndy = p.configurations.compile.files.find { f -> f.name.startsWith('groovy-all') && f.name.contains('-indy') }
                if (groovyIndy) {
                    logger.info "enabling indy on $p"
                    [compileGroovy.groovyOptions,compileTestGroovy.groovyOptions]*.with {
                        optimizationOptions = [ indy: true ]
                    }
                }
            }       
        }
    }
}


task showEnvironments << {
    println "Defined environments: $gradle.environments"   
    gradle.environments.each { e -> 
        println "\n $e:"        
        gradle.getProperty(e).flatten().each { k, v -> 
            println String.format('  %25s = %s',k, k.contains('password') ? "********" : v )
        }
    }
    if (logger.isInfoEnabled() ) {
        println "System properties:"
        System.properties.each { println "    $it" }
        println "env variables:"
        System.getenv().each { println "    $it" }
    }
}

def loadEnvironments() {
    def developerPrivate = new Properties()
    if (file('private.properties').exists()) {
        developerPrivate.load(file('private.properties').newReader())
    }
    def envOverrides = [:]
    
    if ( !hasProperty('env') ) {
        gradle.ext.env = developerPrivate.env ?: 'dev'
    } else {
        def values = getProperty('env').split(',')
        gradle.ext.env = values.first()
        values.tail().each {
            def (k,v) = it.split('=')
            envOverrides.put(k,v)
        }
    }
    
    println "Environment is: $gradle.env ($envOverrides)"
    def slurper = new ConfigSlurper(gradle.env)
    def environment = new ConfigObject()
    def environments = []
    
    file('.').eachFileMatch(~/^environment.*\.groovy$/) { envFile ->
        def envName = envFile.name - '.groovy'
        def privateFile = file("private" + envName - "environment" + ".groovy")
        logger.info("loading environment $envFile.name")

        def envCfg = slurper.parse(envFile.toURL())
        envCfg.merge(slurper.parse(developerPrivate))
        if (privateFile.exists()) {
            logger.info("loading private environment $privateFile")
            envCfg.merge(slurper.parse(privateFile.toURL()))
        }
        
        gradle.rootProject.getProperties().find { it.key.startsWith('environment')  }.each {
            it.value.split(',').each { p ->
                def (k,v) = p.split('=')
                logger.info("$envName: overriding " + k + "=" + v  + " in $it")
                envCfg.put(k,v)
            }
        }
        
        envOverrides.each { k,v ->
            logger.info("$envName: overriding " + k + "=" + v)
            envCfg.put(k,v)
        }
        environment.merge(envCfg)
        if (envName != 'environment' ) {
           gradle.ext[envName] =envCfg 
           environments << envName
        }
    }    
    environment.merge(slurper.parse(developerPrivate))
    environments << 'environment'
    gradle.ext.environment = environment
    gradle.ext.environments = environments

}