Home > Net >  How to create a gradle task to run sonar locally
How to create a gradle task to run sonar locally

Time:01-18

I have configured Sonar for my project and it is working fine, but I would like to create a custom task in the Gradle file to generate reports and run sonar locally directly.

For that, I have tried to create this custom task:

    task sonarLocalReport(dependsOn: ['jacocoTestReport', 'lint']) {
    group = "Reporting"
    description = "Generate Sonar reports for local check"
    doLast {
        project.extensions.getByName("sonar").ext.extraProperties = [
                "sonar.host.url": "http://localhost:9000",
                "sonar.login": "KEY"
        ]
    }}

I tried to add extra properties to my sonar task:

    sonar {
    properties {
        property "sonar.projectKey", "App-Android"
        property "sonar.sourceEncoding", "UTF-8"
        property "sonar.projectName", "android"
        property "sonar.java.coveragePlugin", "jacoco"
        property "sonar.sources", "${project.projectDir}/src/main/java"
        property "sonar.tests", "${project.projectDir}/src/test/java"
        property "sonar.junit.reportPaths", "${project.buildDir}/test-results/testDebugUnitTest"
        property "sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/jacoco/jacocoTestReport/jacocoTestReport.xml"
        property "sonar.android.lint.reportPaths", "${project.buildDir}/reports/lint-results-debug.xml"
    }
}

When I run my custom task sonarLocalReport, I get nothing new locally.

I don´t know if this is not the way to add new properties to the sonar task or if I need to run sonar task after adding these new properties.

CodePudding user response:

I found the solution and it will be something like this:

sonar {
    properties {
        property "sonar.projectKey", "App-Android"
        property "sonar.sourceEncoding", "UTF-8"
        property "sonar.projectName", "android"
        ...
}

task sonarLocal(type: GradleBuild) {
    tasks = ['lint', 'jacocoTestReport']
    sonarLocal.finalizedBy('sonar')
    sonar {
        properties {
            property "sonar.host.url", "http://localhost:9000"
            property "sonar.login", "YOUR_KEY_GENERATED"
        }
    }
}

Then you can run your task like ./gradlew app:sonarLocal and it will run after lint, jacocoTestReport and sonar, adding some properties to be able to send data to your local sonar server.

  • Related