
configurations{
    emma
}

dependencies{
    emma "emma:emma:2.0.5312"
    emma "emma:emma_ant:2.0.5312"
}

def emmaMetaDataFile = "${rootProject.buildDir}/emma/emma.em"
def emmaCoverageFile = "${rootProject.buildDir}/emma/emma.ec"

task emmaInstrument {
    dependsOn classes
    doFirst {
        ant.taskdef(resource:"emma_ant.properties", classpath: configurations.emma.asPath)
        ant.path(id: "emmarun.classpath") {
            pathelement(location: sourceSets.main.classesDir.absolutePath)
        }
        ant.emma(verbosity: "quiet") { // use "info, verbose, trace1, trace2, trace3 for more info"
            instr(merge: "true", destdir: "$buildDir/emma/classes", instrpathref: "emmarun.classpath", metadatafile: "$emmaMetaDataFile") {
                instrpath {
                    fileset(dir: sourceSets.main.classesDir.absolutePath, includes: "*.class")
                }
            }
        }
    }
}

// Modify test tasks in the project to generate coverage data
afterEvaluate {
    if (project.hasProperty('coverage') && ['on','true'].contains(project.properties.coverage)) {
        tasks.withType(Test.class).each { task ->
            task.dependsOn emmaInstrument
            task.configure() {
                jvmArgs '-Dsec.log.level=DEBUG', "-Demma.coverage.out.file=$emmaCoverageFile"
                jvmArgs '-Demma.verbosity.level=quiet'
            }
            task.doFirst {
                classpath = files("$buildDir/emma/classes") + configurations.emma + classpath
            }
        }
    }
}

if (rootProject.getTasksByName('coverageReport', false).isEmpty()) {
    rootProject.task('coverageReport') << {
        ant.taskdef(resource:"emma_ant.properties", classpath: configurations.emma.asPath)
        ant.path(id: "src.path") {
            coreModuleProjects.each {module->
                module.sourceSets.main.java.srcDirs.each {
                    pathelement(location: it.absolutePath )
                }
            }
        }
        ant.emma(enabled: "true", verbosity: "info") {
            report(sourcepathref:"src.path") {
                fileset(dir: rootProject.buildDir) {
                    include: '*.ec'
                    include: '*.emma'
                }
                txt(outfile: "$rootProject.buildDir/emma/coverage.txt")
                html(outfile: "$rootProject.buildDir/emma/coverage.html")
//              xml(outfile: "$rootProject.buildDir/emma/coverage.xml")
            }
        }
    }
}
