萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux SonarQube 客戶端 API 獲取違規數與程式碼行數實戰

SonarQube 提供 REST API 讓外部系統整合程式碼品質指標。本文示範使用官方 sonar-ws-client Java 客戶端,透過 ResourceQuery 獲取專案的 violations(違規數)與 lines(程式碼行數)指標,並給出 Maven 依賴配置與完整程式碼範例。

一、Maven 依賴配置

SonarQube 架構

<dependencies>
    <!-- SonarQube Web Service Client -->
    <dependency>
        <groupId>org.codehaus.sonar</groupId>
        <artifactId>sonar-ws-client</artifactId>
        <version>4.3</version> <!-- 建議與 Server 版本一致 -->
    </dependency>

    <!-- HTTP Client (Client 4.x 相容) -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
</dependencies>

二、核心程式碼範例

import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.connectors.HttpClient4Connector;
import org.sonar.wsclient.host.Host;
import org.sonar.wsclient.services.Resource;
import org.sonar.wsclient.services.ResourceQuery;
import org.sonar.wsclient.services.Measure;
import java.text.DecimalFormat;
import java.util.List;

public class SonarMetricsFetcher {
    private static final String HOST = "https://your-sonarqube:9000";
    private static final String USER = "admin";
    private static final String PASS = "admin";
    private static final String PROJECT_KEY = "com.example:my-project";
    private static final String[] METRICS = {"violations", "lines", "ncloc", "functions", "classes", "files"};

    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("#.##");

        // 1. 建立連接器
        Sonar sonar = new Sonar(
            new HttpClient4Connector(
                new Host(HOST, USER, PASS)
            )
        );

        // 2. 建立查詢:指定專案鍵與指標
        ResourceQuery query = ResourceQuery.createForMetrics(PROJECT_KEY, METRICS);
        query.setIncludeTrends(true);  // 包含趨勢資料

        // 3. 執行查詢
        Resource resource = sonar.find(query);
        if (resource == null) {
            System.err.println("Project not found: " + PROJECT_KEY);
            return;
        }

        // 4. 解析指標
        List measures = resource.getMeasures();
        for (Measure measure : measures) {
            String key = measure.getMetricKey();
            double val = measure.getValue();
            System.out.printf("%s: %s%n", key, df.format(val));
        }

        // 5. 額外:取得特定指標的歷史趨勢
        for (Measure measure : measures) {
            if (measure.getTrend() != null) {
                System.out.printf("%s trend: %s%n", measure.getMetricKey(), measure.getTrend());
            }
        }
    }
}

三、關鍵指標說明

四、REST API 直接呼叫(無 Java 客戶端)

# 取得專案指標 (需 Basic Auth)
curl -u admin:admin "https://sonarqube:9000/api/measures/component?componentKey=com.example:my-project&metricKeys=violations,lines,ncloc,coverage"

# 回應範例
{
  "component": {
    "measures": [
      {"metric": "violations", "value": "127", "bestValue": false},
      {"metric": "lines", "value": "15432", "bestValue": false},
      {"metric": "ncloc", "value": "8921", "bestValue": true},
      {"metric": "coverage", "value": "78.5", "bestValue": true}
    ]
  }
}

五、整合到 CI/CD 流水線

# Jenkins Pipeline 片段
stage('SonarQube Quality Gate') {
    steps {
        script {
            def metrics = sh(
                script: '''
                curl -s -u $SONAR_USER:$SONAR_PASS \
                "$SONAR_URL/api/measures/component?componentKey=$PROJECT_KEY&metricKeys=violations,ncloc,coverage"
                ''',
                returnStdout: true
            ).trim()

            def json = readJSON text: metrics
            def violations = json.component.measures.find { it.metric == 'violations' }.value as int
            def coverage = json.component.measures.find { it.metric == 'coverage' }.value as float

            if (violations > 0) {
                error "Quality Gate Failed: ${violations} violations found"
            }
            if (coverage < 80.0) {
                error "Quality Gate Failed: Coverage ${coverage}% < 80%"
            }
            echo "Quality Gate Passed"
        }
    }
}

六、常見問題排查

指標鍵中文名稱含義典型用途
violations違規總數所有規則違反項目計數(含 Blocker/Critical/Major/Minor/Info)品質紅燈門檻
lines總行數包含空白行、註解行的物理行數專案規模估算
ncloc非註解程式碼行數實際邏輯行數 (Non-Commenting Lines of Code)生產力/技術債密度分母
functions函數/方法數複雜度參考
classes類別數架構規模參考
files檔案數
duplicated_lines_density重複程式碼密度重複行數 / ncloc重構優先級
coverage測試覆蓋率Line coverage %品質門檻核心指標
問題原因解決
401 UnauthorizedToken 過期/權限不足使用 User Token (SonarQube 7.8+) 替代密碼
找不到專案Project Key 錯誤確認專案設定頁面的 Project Key,區分大小寫
指標值為空尚未掃描/掃描失敗檢查 Scanner 執行日誌,確認分析成功
版本不相容Client 版本與 Server API 不符Client 版本鎖定為 Server 主版本號 (如 9.9.x → client 9.9)

透過 SonarQube Web API 程式化獲取品質指標,能將程式碼品質納入自動化治理體系:阻擋不合格合併請求、觸發技術債務警示、生成管理儀表板,讓品質可視、可控、可改善。

copyright © 萬盛學電腦網 all rights reserved