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

Husky .NET:推送前仅检查暂存文件的代码警告实现需求

预推送阶段针对暂存文件检查代码警告的实现方案

要实现你需求的"仅针对暂存文件检查IDE/CA类警告并阻断不合格推送",可以通过自定义脚本过滤build输出 + 预推送钩子配置来完成,以下是具体实现步骤:

一、编写警告过滤脚本

由于dotnet build本身无法直接仅针对暂存文件输出警告,我们需要先执行完整build,再过滤出属于暂存文件的IDE/CA类警告。根据你的操作系统选择对应的脚本:

PowerShell脚本(适用于Windows)

创建Check-StagedWarnings.ps1文件:

# 获取暂存的C#文件绝对路径列表
$stagedFiles = git diff --name-only --cached | Where-Object { $_ -like "*.cs" } | ForEach-Object { Resolve-Path $_ }

# 执行build命令并捕获所有输出
$buildOutput = dotnet build -warnaserrors 2>&1

# 过滤出属于暂存文件的IDE/CA类警告
$filteredWarnings = $buildOutput | Where-Object {
    $_ -match "^.*\((\d+,\d+)\): warning (IDE|CA)\d+:.*$" -and
    $stagedFiles -contains (Resolve-Path ($_ -split ':')[0])
}

# 存在警告则输出并终止推送
if ($filteredWarnings) {
    Write-Host "暂存文件中存在代码风格/质量警告:"
    $filteredWarnings | ForEach-Object { Write-Host $_ }
    exit 1
}

exit 0

Shell脚本(适用于Linux/macOS)

创建check-staged-warnings.sh文件并添加执行权限(chmod +x check-staged-warnings.sh):

#!/bin/bash

# 获取暂存的C#文件绝对路径列表
staged_files=$(git diff --name-only --cached | grep "\.cs$" | xargs realpath 2>/dev/null)

# 执行build命令并捕获所有输出
build_output=$(dotnet build -warnaserrors 2>&1)

# 过滤出属于暂存文件的IDE/CA类警告
filtered_warnings=$(echo "$build_output" | grep -E "warning (IDE|CA)[0-9]+:" | while read -r line; do
    file_path=$(echo "$line" | cut -d ':' -f 1)
    real_file=$(realpath "$file_path" 2>/dev/null)
    if echo "$staged_files" | grep -q "$real_file"; then
        echo "$line"
    fi
done)

# 存在警告则输出并终止推送
if [ -n "$filtered_warnings" ]; then
    echo "暂存文件中存在代码风格/质量警告:"
    echo "$filtered_warnings"
    exit 1
fi

exit 0

二、更新预推送任务配置

在你已有的任务配置中,添加新的检查任务,确保它和dotnet format同属pre-push-operations组:

{
   "tasks": [
     {
       "name": "dotnet-format-staged-files",
       "group": "pre-push-operations",
       "command": "dotnet",
       "args": ["format", "--include", "${staged}"],
       "include": ["**/*.cs"]
     },
     {
       "name": "check-staged-code-warnings",
       "group": "pre-push-operations",
       "command": "pwsh", // Linux/macOS环境替换为"bash"
       "args": ["./Check-StagedWarnings.ps1"], // Linux/macOS替换为"./check-staged-warnings.sh"
       "include": ["**/*.cs"]
     }
   ]
}

三、核心逻辑说明

  • 脚本通过git diff --cached精准获取即将推送的暂存文件,避免检查无关代码
  • dotnet build -warnaserrors确保所有警告被捕获,再通过正则过滤出IDE(代码风格)和CA(代码质量)类警告
  • 若过滤后存在警告,脚本返回非零错误码,触发预推送钩子自动终止推送操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:15