Skip to content
Snippets Groups Projects
javaproject.gradle 9.84 KiB
Newer Older
  • Learn to ignore specific revisions
  • apply plugin: 'java'
    
    apply plugin: 'project-report'
    
    evaluationDependsOnChildren()
    
    configurations {
        tests  { 
             extendsFrom testRuntime 
    
        resolutionStrategy.cacheDynamicVersionsFor 0, 'hours'
    
        resolutionStrategy.cacheChangingModulesFor 0, 'hours'
    }
    
    
    task wrapper(type: Wrapper) {
    
        gradleVersion = '1.8'
        distributionUrl = "http://svncisd.ethz.ch/repos/cisd/ivy-repository/trunk/gradle/distribution/1.8/gradle-1.8-all.zip"
    
    ext.addSource = (sourceCompatibility == org.gradle.api.JavaVersion.VERSION_1_6)
    
    sourceCompatibility='1.6'
    targetCompatibility='1.6'
    
    sourceSets { 
    
        main {
            java {
                srcDirs = ['source/java']
            }
        }
        test {
            java {
                srcDirs = ['sourceTest/java']
            }
            resources {
                srcDirs = ['sourceTest/java']
            }
        }
    
        examples {
            java {
                srcDirs = ['sourceExamples/java']
            }
        }
    
    buildDir = 'targets/gradle'
    
        apply from: '../gradle/repository.gradle'
    
        
        repositories repositoryConfig
        
        dependencies {
            classpath 'cisd:cisd-ant-tasks:+'
    
    repositories repositoryConfig
    
    
    def execute(command, arguments) {
        new ByteArrayOutputStream().withStream { os ->
            print "execute: ${command}"
            arguments.collect({print " ${it}"})
            println ''
            def result = exec {
                executable = command
                args = arguments
                standardOutput = os
            }
            return os.toString().split('\n')
        }
    
    def execute_working_dir(command, arguments, working_dir) {
        new ByteArrayOutputStream().withStream { os ->
            print "execute: ${command}"
            arguments.collect({print " ${it}"})
            println ''
            def result = exec {
                executable = command
                args = arguments
                standardOutput = os
            }
            return os.toString().split('\n')
        }
    }
    
    
    def isSvnProject() {
       def result = exec {
    
                executable = svnCommand
                args = ['--non-interactive', "info"]
                standardOutput = new ByteArrayOutputStream()
    
                ignoreExitValue = true
            }
        return result["exitValue"] == 0
    }
    
    
    def executeSVN(arguments) {
        arguments.add(0, '--non-interactive')
    
        return execute(svnCommand, arguments)
    
    }
    
    def calculateCleanFlag() {
        for (childProject in project.childProjects.values()) {
            if (childProject.cleanFlag == 'dirty') {
                return 'dirty'
            }
        }
    
        def isSvn = isSvnProject()
        if (isSvn) {
            def output = executeSVN(['status', '../' + project.name])
            def lines = output.findAll({ (it.startsWith('?') || it.trim().isEmpty()) == false})
            return lines.isEmpty() ? 'clean' : 'dirty'
        } else {
            def output = execute_working_dir('git', ['status', '--porcelain'], '../' + project.name)
            return output.length == 0 ? 'clean' : 'dirty'
        }
    
    }
    
    def findMaximum(lines, key) {
        return lines.findAll({ it.startsWith(key)}).collect({element -> element.split(':')[1].toInteger()}).max()
    }
    
    
    def findGitSvnVersion(lines) {
        for (a in lines) {
            if (a.contains("git-svn-id")) {
                return a.split("@")[1].split()[0].toInteger()
            }
    
        throw new Exception("Couldn't get svn version from git")
    }
    
    def calculateBuildInfo() {
        if (isSvnProject()) {
            def output = executeSVN(['info', '-R', '../' + project.name])
            def maxRevisionNumber = findMaximum(output, 'Revision:')
            project.ext.revisionNumber = findMaximum(output, 'Last Changed Rev:')
            if (maxRevisionNumber < project.ext.revisionNumber) {
                throw new GradleException("Maximum revision ($maxRevisionNumber) is less than the maximum "
                          + "last changed revision ($project.ext.revisionNumber).")
            }
            project.ext.versionNumber = 'SNAPSHOT'
            def url = output.findAll({ it.startsWith('URL:')})[0].split('URL:')[1].trim()
            if (url.contains('/trunk') == false) {
                pathElements = url.split('/')
                project.ext.versionNumber = 'libraries' == pathElements[-2] ? pathElements[-3] : pathElements[-2]
            }
        } else {
            def gitlogoutput = execute_working_dir('git', ['log', '-1'], '../' + project.name)
            project.ext.revisionNumber = findGitSvnVersion(gitlogoutput)
            project.ext.versionNumber = 'GIT-SNAPSHOT'
    
        for (childProject in project.childProjects.values()) {
            project.ext.revisionNumber = Math.max(project.ext.revisionNumber, childProject.revisionNumber)
            if (project.ext.versionNumber != childProject.versionNumber) {
                throw new GradleException("Inconsistent version numbers: "
                            + "${project.name} at version ${project.ext.versionNumber} but "
                            + "${childProject.name} at version ${childProject.versionNumber}.") 
            } 
        }
        version = "${project.ext.versionNumber}-r${project.ext.revisionNumber}"
    
        project.ext.revisionForPublication = project.ext.versionNumber.startsWith('SNAPSHOT') ? "r${project.ext.revisionNumber}" : project.ext.versionNumber
    
        project.ext.cleanFlag = calculateCleanFlag()
        def buildInfo = "${project.ext.versionNumber}:${project.ext.revisionNumber}:${project.ext.cleanFlag}"
        println "BUILD INFO for $project: $buildInfo"
    
        def targetsDist = 'targets/dist'
    
        def distFolder = new File("${project.projectDir}/$targetsDist")
    
        distFolder.deleteDir()
        distFolder.mkdirs()
    
        file("${project.projectDir}/$targetsDist/BUILD-${project.name}.INFO") << buildInfo
    
    task checkRestrictions(type: Exec, dependsOn: [classes, testClasses]) {
        doFirst {
    
            def cp = configurations.testCompile.filter({ f -> f.name.startsWith('restrictionchecker') || f.name.startsWith('bcel')}).asPath
            def cmd = ['java', '-cp', cp, 'ch.rinn.restrictions.RestrictionChecker', '-r', sourceSets.main.output.classesDir]
    
            if (sourceSets.test.output.classesDir.exists()) {
                cmd.add(sourceSets.test.output.classesDir)
            }
            cmd.add('-cp')
            cmd.add(sourceSets.main.output.classesDir)
            if (sourceSets.test.output.classesDir.exists()) {
                cmd.add(sourceSets.test.output.classesDir)
            }
            cmd.add(configurations.testCompile.asPath)
            commandLine cmd
    
        useTestNG()
        options.suites('sourceTest/java/tests.xml')    
    
        jvmArgs '-Xmx2048m', '-XX:MaxPermSize=256m', '-Duser.timezone=Europe/Zurich'
    
        
        testLogging.showStandardStreams = true
    
        ignoreFailures = true
    
        options.encoding = 'utf-8'
        options.fork = true
        doFirst {
            options.forkOptions.with {
                executable = 'java'
    
                if (addSource) {
    	            jvmArgs = ['-cp', configurations.ecj.asPath, 'org.eclipse.jdt.internal.compiler.batch.Main', 
    	                       '-nowarn', '-source', '1.6']
    	        } else {
    	            jvmArgs = ['-cp', configurations.ecj.asPath, 'org.eclipse.jdt.internal.compiler.batch.Main', 
    	                       '-nowarn']
    	        }
    
        options.encoding = 'utf-8'
        options.fork = true
        doFirst {
            options.forkOptions.with {
                executable = 'java'
    
                if (addSource) {
    	            jvmArgs = ['-cp', configurations.ecj.asPath, 'org.eclipse.jdt.internal.compiler.batch.Main', 
    	                       '-nowarn', '-source', '1.6']
    	        } else {
    	            jvmArgs = ['-cp', configurations.ecj.asPath, 'org.eclipse.jdt.internal.compiler.batch.Main', 
    	                       '-nowarn']
    	        }
    
    processTestResources {
    
        fileMode=0666
    
    apply plugin: 'eclipse'
    
    eclipse {
    
        classpath {
            downloadSources=true
    
            defaultOutputDir = file('targets/classes')
    
        whenMerged{ classpath ->
            def projectRefs = classpath.entries.findAll{entry -> entry.kind =='src' && entry.path.startsWith('/')}
            classpath.entries.removeAll(projectRefs)
            classpath.entries.addAll(projectRefs)   
        }   
    
    }
    
    task testJar(type: Jar, dependsOn: testClasses) {
        baseName = "test-${project.archivesBaseName}"
        from sourceSets.test.output
    }
    
    
    task sourcesJar(type: Jar) {
    
        from sourceSets.main.allSource
    
    compileJava.dependsOn sourcesJar
    
    }
    
    task compileDependencies(type: Copy) {
        into "$buildDir/output/compile-dependencies"
        from configurations.compile
    }
    
    task runtimeDependencies(type: Copy) {
        into "$buildDir/output/runtime-dependencies"
        from configurations.runtime
    }
    
    task testCompileDependencies(type: Copy) {
        into "$buildDir/output/testCompile-dependencies"
        from configurations.testCompile
    }
    
    task testRuntimeDependencies(type: Copy) {
        into "$buildDir/output/testRuntime-dependencies"
        from configurations.testRuntime
    
    }
    
    task checkDependencies(dependsOn: classes) << {
    	ant.taskdef(name: 'dependencychecker', classname: 'classycle.ant.DependencyCheckingTask', classpath: configurations.testRuntime.asPath)
        ant.dependencychecker(
    
                    definitionFile: 'resource/dependency-structure.ddf', 
                    failOnUnwantedDependencies: 'true',
                    mergeInnerClasses: 'true') {
            fileset(dir: "${buildDir}", includes: "**/*.class")
        }
    }
    
    apply plugin: 'ivy-publish'
    
    if (hasProperty('ivyRepository') == false || ''.equals(project.ivyRepository))
    {
        project.ext.ivyRepository = "${project.projectDir}/../ivy-repository"
    }
    
    publishing {
    
        repositories {
            ivy {
    
                ivyPattern "file://${project.ivyRepository}/[organisation]/[module]/[revision]/ivy.xml"
                artifactPattern "file://${project.ivyRepository}/[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
    
            }
        }
    }
    
    publish {
        dependsOn build