尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

.NET编码规范08-CICD集成-将编码规范嵌入流水线

.NET编码规范08-CICD集成-将编码规范嵌入流水线 .NET编码规范第 8 篇CI/CD 集成 —— 将编码规范嵌入流水线前言前面的 7 篇文章建立了一套完整的编码规范工具体系。但工具再强大如果没有在正确的时间被强制执行就只是建议而已。CI/CD 流水线是将编码规范从建议变为铁律的最后一道关卡。任何违反核心规范的代码都应该在 CI 阶段被拦截而不是靠 Code Review 的人肉检查。一、为什么必须在 CI/CD 中强制执行本地环境的不确定性开发者的 IDE 设置各异Git Hook 可能被跳过--no-verifydotnet format可能忘记运行分析器可能被#pragma局部禁用CI/CD 是唯一的统一执行环境开发 → 本地格式化 → 提交 PR → CI 自动检查 → 通过/拦截 ↓ 拒绝合并给出违规详情二、核心策略三级门禁Level 1: dotnet format --verify-no-changes ← 格式是否合规 ↓ 通过 Level 2: dotnet csharpier --check . ← 排版是否统一 ↓ 通过 Level 3: dotnet build --warnaserror ← 代码质量是否达标 ↓ 通过 ✅ 允许合并如果任何一级失败CI 构建中断PR 无法合并。三、GitHub Actions 完整配置3.1 最简版本name:Code Style Qualityon:push:branches:[main,develop]pull_request:branches:[main]jobs:check:runs-on:ubuntu-lateststeps:-uses:actions/checkoutv4-name:Setup .NETuses:actions/setup-dotnetv4with:dotnet-version:9.0.x-name:Restore toolsrun:dotnet tool restore-name:Format check (dotnet format)run:dotnet format style--verify-no-changes--severity info-name:Format check (CSharpier)run:dotnet csharpier--check .-name:Build with analysisrun:dotnet build--configuration Release--warnaserror3.2 完整生产版name:Code Quality Gateon:push:branches:[main,develop]pull_request:branches:[main]types:[opened,synchronize,reopened,ready_for_review]env:DOTNET_VERSION:9.0.xBUILD_CONFIGURATION:Releasejobs:format-check:name:Format Style Checkruns-on:ubuntu-lateststeps:-uses:actions/checkoutv4with:fetch-depth:0# 获取完整历史GitVersion 等工具可能需要-name:Setup .NETuses:actions/setup-dotnetv4with:dotnet-version:${{env.DOTNET_VERSION}}-name:Restore toolsrun:dotnet tool restore-name:CSharpier format checkrun:dotnet csharpier--check .-name:dotnet format checkrun:dotnet format style--verify-no-changes--severity info-name:Report format errorsif:failure()run:|echo ## ❌ Format Check Failed $GITHUB_STEP_SUMMARY echo Please run dotnet csharpier . and dotnet format style --severity info locally. echo See the log above for details. $GITHUB_STEP_SUMMARYquality-check:name:Code Quality Analysisruns-on:ubuntu-latestneeds:format-check# 格式检查通过后才做质量检查steps:-uses:actions/checkoutv4-name:Setup .NETuses:actions/setup-dotnetv4with:dotnet-version:${{env.DOTNET_VERSION}}-name:Restore dependenciesrun:dotnet restore-name:Build with strict analysisrun:dotnet build--configuration ${{env.BUILD_CONFIGURATION}}--no-restore--warnaserror-name:Report analysis errorsif:failure()run:|echo ## ❌ Code Quality Check Failed $GITHUB_STEP_SUMMARY echo Build with --warnaserror failed. Check the build log for CA/IDE violations. $GITHUB_STEP_SUMMARY-name:Run testsrun:dotnet test--configuration ${{env.BUILD_CONFIGURATION}}--no-build--verbosity normal# 注意上面的 quality-check 用 needs: format-check 是串行如果想并行删掉这行即可3.3 在 PR 评论中报告违规高级-name:Annotate PR with violationsif:failure()github.event_name pull_requestuses:actions/github-scriptv7with:script:|const output ## ⚠️ Code Quality Gate FailedYour PR has violations that must be fixed before merging:-Run \dotnet csharpier .\ to fix formatting-Run \dotnet format style--severity info\ to fix code style-Check the build log at[Actions](${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}) for CA/IDE violations After fixing,push your changes and re-run the checks.; github.rest.issues.createComment({issue_number:context.issue.number,owner:context.repo.owner,repo:context.repo.repo,body:output});四、Azure DevOps Pipeline 配置# azure-pipelines.ymltrigger:branches:include:-main-developpool:vmImage:ubuntu-latestvariables:buildConfiguration:ReleasedotnetVersion:9.0.xsteps:-task:UseDotNet2displayName:Install .NET SDKinputs:version:$(dotnetVersion)-script:dotnet tool restoredisplayName:Restore .NET tools-script:dotnet csharpier--check .displayName:Check CSharpier formattingcontinueOnError:false-script:dotnet format style--verify-no-changes--severity infodisplayName:Check code stylecontinueOnError:false-script:dotnet build--configuration $(buildConfiguration)--warnaserrordisplayName:Build with strict analysis-script:dotnet test--configuration $(buildConfiguration)--no-build--verbosity normaldisplayName:Run tests五、TreatWarningsAsErrors的渐进策略不要一开始就把所有警告变成错误这会让团队抓狂。渐进路线第 1 步TreatWarningsAsErrors false默认 → 团队看到警告但编译不会失败 第 2 步在 .editorconfig 中将关键规则设为 error → dotnet_diagnostic.CA1001.severity error → dotnet_diagnostic.CA1062.severity error 第 3 步TreatWarningsAsErrors true → 全局启用但此时团队已经适应分阶段筛选!-- Directory.Build.props --PropertyGroupTreatWarningsAsErrorstrue/TreatWarningsAsErrors!-- 排除某些尚在修复中的警告 --WarningsNotAsErrors$(WarningsNotAsErrors);CS0618/WarningsNotAsErrors!-- CS0618 使用过时 API先容忍逐步清理 --/PropertyGroup六、Pre-commit Hook 辅助方案CI/CD 是最后防线Pre-commit Hook 是第一道防线。推荐使用 Husky.NET。安装配置dotnet new tool-manifest dotnet toolinstallHusky dotnet huskyinstalltask-runner.json配置{tasks:[{name:csharpier-format,command:dotnet,args:[csharpier,.],include:[**/*.cs,**/*.xaml]},{name:dotnet-format-fix,command:dotnet,args:[format,style,--severity,info]},{name:stage-formatted-files,command:git,args:[add,.]}]}七、监控与度量在 CI 中统计违规趋势-name:Count warningsid:warningsrun:|WARNING_COUNT$(dotnet build --configuration Release 21 | grep -c warning) echo count$WARNING_COUNT $GITHUB_OUTPUT echo ## Warning Count: $WARNING_COUNT $GITHUB_STEP_SUMMARY-name:Check warning thresholdif:steps.warnings.outputs.count50run:|echo ## ⚠️ Too many warnings! $GITHUB_STEP_SUMMARY exit 1八、完整落地清单阶段要做什么工具/配置本地提交前自动格式化Husky.NET CSharpier dotnet format本地Git Hook 检查Pre-commit hook 阻止包含违规的提交CI格式检查dotnet csharpier --check .CI风格检查dotnet format --verify-no-changesCI质量门禁dotnet build --warnaserrorCIPR 评论GitHub Actions / Azure DevOps 自动评论管理度量趋势统计告警数量设定红线
返回列表