sonar 插件和 gradle 引入

在項目的gradle 中

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.1" //sonar插件
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
plugins {
    id "org.sonarqube" version "3.1"
}
apply from: "sonar.gradle"
// 引入公共配置
apply from: "config.gradle"

config 文件

ext {
    sdkVersion = [
            compileSdk: 28,
            buildTools: "28.0.0",
            minSdk    : 25,
            targetSdk : 28
    ]

    supportLib = [
            "appcompat"       : "androidx.appcompat:appcompat:1.2.0",
            "constraint"      : "androidx.constraintlayout:constraintlayout:2.0.4",
            "asynclayout"     : "androidx.asynclayoutinflater:asynclayoutinflater:1.0.0"
    ]

    wtLib = [
            "wt-widget"     : "com.autopai.support:widget:R30-1.0.0.zn", // 公共控件
            "wt-statistic"  : "com.openos.sdk:statistic:1.0.0.+", // 埋點
            "wt-virtual-car": "com.openos.sdk:virtualcar-sdk:0.0.2-SNAPSHOT" ,// 虛擬車,末尾加-SNAPSHOT,每次都拉取最新版本
            "wt-theme"      : "com.autopai.support:skin:2.0.1.+" // 主題切換
    ]

    testLib = [
            "junit": "junit:junit:4.13.1"
    ]

    androidTestLib = [
            "test-core"    : 'androidx.test:core:1.3.0',
            "test-runner"  : 'androidx.test.ext:junit:1.1.2',
            "test-rules"   : 'androidx.test:rules:1.3.0',
            "espresso-core": 'androidx.test.espresso:espresso-core:3.3.0'
    ]
}

在app的 gradle 中 可以引入config文件的數組

dependencies {
    implementation 'com.openos.sdk:virtualcar-sdk:0.0.2-SNAPSHOT'
    testImplementation testLib["junit"]
    androidTestImplementation androidTestLib["test-runner"]
    androidTestImplementation androidTestLib["espresso-core"]
}

sonar.gradle

import groovy.json.JsonSlurper

/**
 * 更新日期 2021-03-16-18-20-26
 * 請注意todo註釋的地方
 */
ext {
    sonar = [
            //sonarqube 服務器地址
            host       : "http://10.1.120.7:9001",
            // todo 這裏寫上sonar後臺自己生成的token
            username   : "e2f2ed6dec45d7a985072f4502857a1bb8da7a61",
            // 密碼請保持爲空即可,不可刪除
            passwd     : "",
            projectkey : APK_PACKAGE_NAME + "_${getBranch()}",
            projectName: APK_PACKAGE_NAME + "_${getBranch()}(${getGitName()})"
    ]
}
//啓動遠程服務器一個sonar任務
sonarqube {
    properties {
        property "sonar.host.url", sonar.host
        property "sonar.verbose", "true"
        property "sonar.login", sonar.username
//        property "sonar.password", sonar.passwd
        property "sonar.sourceEncoding", "UTF-8"
        property "sonar.projectKey", sonar.projectkey
        property "sonar.projectName", sonar.projectName
        property "sonar.exclusions", "**/*Test.java"
        property "sonar.core.codeCoveragePlugin","jacoco"
        //覆蓋報告絕對路徑 需要保證路徑下有生成的報告report.html
        property "sonar.coverage.jacoco.xmlReportPaths","${project.projectDir}/core/build/reports/coverage/debug/report.xml"
    }
}

subprojects {
    sonarqube {
        //todo 如果項目有渠道,請手動指定打開下面註釋,設置對應的渠道(注意:如果渠道是s311ica,則下面需要寫上s311icaDebug),如果沒有渠道則不用做任何操作
//         androidVariant 'dev_Debug'
        println("flavor=" + name)
        properties {
            //這裏sources,binaries默認會去找對應渠道,不需去指定,否則會出現多渠道分析干擾的情況
        }
    }
}

//查詢sonar分析工程是否通過
task queryStatus() {
    try {
        //先創建出了一個URL對象,urlPath:是我們訪問接口地址
        String urlPath = sonar.host + "/api/qualitygates/project_status?projectKey=" + sonar.projectkey
        URL url = new URL(urlPath);
        //URL鏈接對象,通過URL對象打開一個connection鏈接對像
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        //設置urlConnection對象鏈接超時
        urlConnection.setConnectTimeout(5000);
        //設置urlConnection對象獲取數據超時
        urlConnection.setReadTimeout(5000);
        //設置本次urlConnection請求方式
        urlConnection.setRequestMethod("GET");
        // 認證登陸
        String base64Credentials = new String(Base64.encoder.encode((sonar.username + ":" + sonar.passwd).getBytes("UTF-8")));
        urlConnection.setRequestProperty("Authorization", "Basic " + base64Credentials);
        //調用urlConnection的鏈接方法,線程等待,等待的是服務器所給我們返回的結果集
        urlConnection.connect();
        //獲取本次網絡請求的狀態碼
        int code = urlConnection.getResponseCode();
        //如果本次返回的狀態嗎是200(成功)
        println("http code:" + code)
        if (code == 200) {
            //調用urlConnection.getInputStream得到本次請求所返回的結果流
            InputStream inputStream = urlConnection.getInputStream();
            //創建一個BufferedReader,去讀取結果流
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String readLine;
            StringBuffer buffer = new StringBuffer();
            while ((readLine = reader.readLine()) != null) {
                buffer.append(readLine);
            }
            //讀取完結果流之後所得到的結果
            String result = buffer.toString();
            inputStream.close();
            def parsedJson = new JsonSlurper().parseText(result)
            println(sonar.projectkey + " ---> status:" + parsedJson.projectStatus.status)
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

//需要有git環境
def static getBranch() {
    String cmd = "git rev-parse --abbrev-ref HEAD"
    return cmd.execute().text.trim().toString()
}
//需要有git環境
def static getGitName() {
    String cmd = "git config user.email"
    return cmd.execute().text.trim().toString()
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章