apply plugin: 'jacoco'

jacoco {
    // https://bintray.com/bintray/jcenter/org.jacoco:org.jacoco.core
    toolVersion = "0.8.10"
}

if (project.plugins.hasPlugin('com.android.application') || project.plugins.hasPlugin('com.android.library')) {
    android {
        buildTypes {
            debug {
                //we have customized coverage task
                testCoverageEnabled false
            }
        }

        testOptions {
            unitTests.all {
                jacoco {
                    //some weird Java9 issue (https://github.com/gradle/gradle/issues/5184)
                    includeNoLocationClasses = true
                    excludes = ['jdk.internal.*']
                }
            }
        }
    }
}

project.afterEvaluate {

    if (project.plugins.hasPlugin('com.android.application')) {
        android.applicationVariants.all { variant ->
            def name = variant.name
            def testTaskName = "test${name.capitalize()}UnitTest"

            createJacocoReportTask(testTaskName, name)
        }
    } else if (project.plugins.hasPlugin('com.android.library')) {
        android.libraryVariants.all { variant ->
            def name = variant.name
            def testTaskName = "test${name.capitalize()}UnitTest"

            createJacocoReportTask(testTaskName, name)
        }
    }
}

private void createJacocoReportTask(testTaskName, name) {
    tasks.register("${testTaskName}Coverage", JacocoReport) { JacocoReport task ->
        task.dependsOn tasks.named("$testTaskName")
        task.group = "Reporting"
        task.description = "Generate Jacoco coverage reports for the ${name.capitalize()} build."

        task.additionalClassDirs(fileTree(
                dir: "${project.buildDir}/intermediates/javac/${name}",
                excludes: ['**/R.class',
                           '**/R$*.class',
                           'android/**/*.class',
                           '**/*$ViewInjector*.*',
                           '**/*$ViewBinder*.*',
                           '**/BuildConfig.*',
                           '**/*$Lambda$*.*',
                           '**/*Dagger*.*',
                           'android/**/*.*',
                           '**/*$*$*.*',
                           '**/Manifest*.*']))

        task.additionalSourceDirs(files(["${project.projectDir}/src/main/java"]))
        task.executionData(files("${project.buildDir}/jacoco/${testTaskName}.exec"))

        task.reports {
            xml.required = true
            xml.outputLocation = file("${rootProject.buildDir}/jacoco/jacoco${task.path.replace(':', '-')}Coverage.xml")
            html.required = true
            html.outputLocation = file("${project.buildDir}/jacoco/report/html/${testTaskName}")
        }
    }
}
