在Visual Studio 2022中使用Git pre-commit hook

7
我尝试使用VS2022中的dotnet format在预提交挂钩中进行一些代码检查。但问题是,当我使用VS Git GUI提交更改时,预提交挂钩似乎没有被调用,即使在命令行中使用时它是可以工作的。即使命令行正确地取消了提交,GUI错误地创建了一个提交。
我该如何让VS实际使用预提交挂钩呢? 我已经看到它可以正确使用预推挂钩。
预提交:
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

echo >&2 "Running git format"
LC_ALL=C
# Select files to format
FILES=$(git diff --name-only --diff-filter=ACM "*.cs" | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Format all selected files
echo "$FILES" | cat | xargs | sed -e 's/ /,/g' | xargs dotnet-format --files
# Add back the modified files to staging
echo "$FILES" | xargs git add
echo >&2 "Deliberate failure"
exit 1

命令行输出:

C:\Users\<username>\source\repos\WpfApp1>git commit -m "Test"
Running git format
xargs: dotnet-format: No such file or directory
Deliberate failure
2个回答

3
我最近发现(通过我的自己的VS pre-commit问题),Visual Studio实现了它自己内部版本的git(包括grep和sed)。在其中,xargs不被允许。Visual Studio不会告诉你它失败了,而只会提交。尝试从代码中删除任何xargs引用。此外,dotnet-format也是一个自定义安装程序,因此无法通过VS工作。
如果您想要所有已声明的功能,则将VS切换为使用系统安装的git可能会更好: 配置Visual Studio以使用系统安装的Git.exe 要进行故障排除/使您的代码正常工作,我建议测试某些命令是否甚至在Visual Studio中被允许。只需在pre-commit文件的顶部放置类似于以下代码的代码,并尝试从Visual Studio提交:
xargs
echo "This outputs in VS git error window"
exit 1

Visual Studio example output


0

我最近回到这个项目并成功地让它工作起来了。看起来 Visual Studio 的更新意味着现在支持 xargs,我能够使用 dotnet format 代替 dotnet-format


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接