apply plugin: 'jacoco'

jacoco {
  toolVersion = "0.8.8"
}

configurations {
  jacocoAnt
  jacocoRuntime
}


tasks.withType(Test) {
  jacoco.includeNoLocationClasses true
  jacoco.excludes = ['jdk.internal.*']
}

// Globals

// Add files that should not be listed in the report (e.g. generated Files from dagger)
def fileFilter = [] // ['**/*Dagger.*']
def kotlinDebugTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/debug/com", excludes: fileFilter)
def mainSrc = "$projectDir/src/main/java"
def srcDirectories = files([mainSrc])
def clsDirectories = files([kotlinDebugTree])

// Make sure the path is correct (if not run the unit tests and try find the .exec file that is generated after the unit tests are finished should be similar to that one)
def execData = fileTree(dir: "$buildDir", includes: ["jacoco/testDebugUnitTest.exec"])

task jacocoUnitTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
  reports {
    xml.required = true
    html.required = true
    csv.required = true
  }

  sourceDirectories.from = srcDirectories
  classDirectories.from = clsDirectories
  executionData.from = execData
}

task jacocoTestCoverageVerification(type: JacocoCoverageVerification, dependsOn: ['jacocoUnitTestReport']) {
  sourceDirectories.from = srcDirectories
  classDirectories.from = clsDirectories
  executionData.from = execData

  violationRules {
    failOnViolation = true
    rule {
      limit {
        minimum = 0.7 // Lower threshold to not block MRs because we have 72% coverage. Rise it to 0.8 after adding more tests
      }
    }
  }
}


configurations {
  antJUnit
}

dependencies {
  antJUnit 'org.apache.ant:ant-junit:1.10.14'
}

task mergeUnitAndJacocoTestReport(dependsOn: ["jacocoTestCoverageVerification"]) {
  ext {
    resultsDir = file("build/test-results/testDebugUnitTest")
  }

  doLast {
    ant.taskdef(name: 'junitreport',
      classname: 'org.apache.tools.ant.taskdefs.optional.junit.XMLResultAggregator',
      classpath: configurations.antJUnit.asPath)

    ant.junitreport(todir: resultsDir) {
      fileset(dir: resultsDir, includes: 'TEST-*.xml')
    }
  }
}
