Post

Sonar 代码质量管理

Sonar 代码质量管理

快速上手 SonarQube

安装、配置项目

使用 SonarQube Community 版本,具体安装过程、如何配置项目看最新文档

运行分析

安装 SonarScanner:

1
npm install -g sonar-scanner

配置sonar-project.properties到项目的根目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# SonarQube 服务器地址
sonar.host.url=http://localhost:9000

# SonarQube 用户令牌 (强烈建议使用此方式)
sonar.token=sqp_***************************

# 项目的唯一标识符 (在 SonarQube 实例中必须是唯一的)
sonar.projectKey=my-project

# 项目在 SonarQube UI 上显示的名称
sonar.projectName=My Project

# 项目版本号
sonar.projectVersion=1.0

# 需要分析的源代码根目录 (相对路径, '.' 代表当前目录)
sonar.sources=.

# 源代码的编码格式 (推荐使用 UTF-8)
sonar.sourceEncoding=UTF-8

然后执行:

1
sonar-scanner

分析完成后,访问 SonarQube 仪表盘查看结果。

示例:分析一个 React 项目

假设 React 项目,使用 Jest 生成测试覆盖率报告。我们将 SonarQube 集成到工作流中。

  1. 生成覆盖率报告
    package.json 中配置 Jest:

    1
    2
    3
    
    "scripts": {
      "test": "jest --coverage"
    }
    

    运行 npm test 后,覆盖率报告会生成在 coverage/lcov.info

  2. 自定义规则
    在 SonarQube UI 中,调整 JavaScript 规则。例如,启用“函数复杂度不超过 10”的检查,或禁用某些过于严格的规则。

  3. 查看结果
    运行 sonar-scanner 后,仪表盘会展示:

    • Bug:如未处理的 Promise rejection。
    • 代码异味:如过长的函数。
    • 覆盖率:显示哪些代码未被测试覆盖。

高级用法

  1. 质量门(Quality Gates)
    设置通过条件(例如,覆盖率低于 80% 则失败),并在 CI 中检查:

    1
    
    sonar-scanner -Dsonar.qualitygate.wait=true
    
  2. 与 CI/CD 集成
    在 GitHub Actions 中添加 SonarQube 步骤:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    name: Build and Analyze
    on: [push]
    jobs:
      sonar:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v2
          - run: npm install
          - run: npm test
          - uses: sonarsource/sonarcloud-github-action@master
            env:
              SONAR_TOKEN: $
    
  3. 分支分析
    SonarQube 支持多分支分析,适合 monorepo 或长期维护的项目。

This post is licensed under CC BY 4.0 by the author.