You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求指导:通过YML流水线生成Clang-tidy报告并附加到AzureDevOps拉取请求

在Azure DevOps中实现Clang-Tidy扫描并强制PR无错误才可合并

1. 配置Clang-Tidy扫描Pipeline任务

首先确保你的Azure DevOps代理(或容器)已安装Clang-Tidy工具,然后在Pipeline中添加扫描任务:

扫描脚本(Bash示例)

# 切换到源码根目录
cd $(Build.SourcesDirectory)

# 获取PR中变更的代码文件(仅扫描修改内容,提升效率)
changed_files=$(git diff --name-only origin/master HEAD | grep -E "\.(cpp|hpp|c|h)$")

if [ -n "$changed_files" ]; then
    # 基于编译数据库执行扫描(需提前通过CMake生成:cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..)
    clang-tidy -p build/ $changed_files -export-fixes clang-tidy-fixes.json --format-style=file
    
    # 生成HTML格式的可读报告(借助clang-tidy-html工具转换JSON结果)
    clang-tidy-html clang-tidy-fixes.json -o clang-tidy-report.html
else
    echo "PR无代码文件变更,跳过Clang-Tidy扫描"
fi

上传报告作为构建产物

添加Publish Build Artifacts任务,将clang-tidy-report.html和clang-tidy-fixes.json上传到构建产物中,方便后续查看。

2. 将扫描报告附加到PR评论

通过Azure DevOps REST API,在Pipeline中添加脚本将报告内容作为评论插入PR:

PowerShell脚本示例

$orgUrl = "$(System.TeamFoundationCollectionUri)"
$project = "$(System.TeamProject)"
$prId = "$(System.PullRequest.PullRequestId)"
$pat = "$(System.AccessToken)"

# 读取报告内容,无报告则显示默认文本
$reportContent = if (Test-Path "clang-tidy-report.html") { Get-Content -Path "clang-tidy-report.html" -Raw } else { "无扫描结果" }

# 构造PR评论内容
$body = @{
    content = "### Clang-Tidy代码扫描报告`n$reportContent"
    commentType = "text"
} | ConvertTo-Json

# 调用API添加评论
Invoke-RestMethod -Uri "$orgUrl/$project/_apis/git/repositories/$(Build.Repository.ID)/pullRequests/$prId/comments?api-version=7.1-preview.1" `
    -Method Post `
    -Headers @{ Authorization = "Bearer $pat"; "Content-Type" = "application/json" } `
    -Body $body

注意:需要在Pipeline的Agent Job中启用“允许脚本访问OAuth令牌”,确保System.AccessToken有权限操作PR评论。

3. 设置PR合并强制规则

配置分支策略

  1. 进入Azure DevOps项目的Repos > Branches,找到master分支,点击... > Branch policies。
  2. 添加Build validation规则,选择你创建的Clang-Tidy扫描Pipeline,设置:
    • 触发条件:When a pull request is created or updated
    • 要求:Required(必须成功才能合并)

脚本中强制错误拦截

在Clang-Tidy扫描脚本末尾添加判断逻辑,若检测到错误则让任务失败:

# 检查扫描结果是否存在错误
if [ -s clang-tidy-fixes.json ]; then
    echo "Clang-Tidy检测到代码不符合规范,任务失败"
    exit 1
fi

这样只要扫描出错误,Pipeline就会失败,PR将无法满足合并条件。

4. 额外优化

  • 在代码根目录添加.clang-tidy配置文件,自定义扫描规则、忽略文件等,示例:
    Checks: '*,llvm-header-guard,-readability-identifier-naming'
    HeaderFilterRegex: '.*'
    FormatStyle: file
    
  • 若使用容器代理,可在Dockerfile中预先安装Clang-Tidy,避免每次安装耗时。

内容的提问来源于stack exchange,提问作者faiqali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:22:47