我们目前正在使用一个git钩子(见下图)在允许用户提交之前在源代码上运行一个样式。这有一个警告,用户必须提交,格式化他们的代码,然后再次提交,这有点麻烦。理想情况下,我们希望钩子格式化代码,然后将格式化的代码包含在原始提交中。我已经尝试重新添加更改的文件,但它导致引用错误(显然)。我还尝试在pre-commit钩子中获取历史记录,并尝试退出钩子并重新运行git commit命令,但没有成功。
# Run astyle on changed .cs files, ignoring $ignored
res=$(exec git diff --cached --name-only | \
grep -Ev $ignored | \
xargs astyle --options=conf/astylerc | \
tail -n 1)
num_formatted=$(echo $res | cut -b 1) # We are only interested in the number preceeding 'formatted'.
[[ $num_formatted -ne 0 ]] && echo "WARNING: Code has been automatically formatted. Please re-add and re-commit" && exit 1 || echo "No code to format! Continuing commit"
有人有什么想法吗?
3条答案
按热度按时间6vl6ewon1#
编辑后this答案。
您可以格式化文件并将其添加回钩子中。问题是您可能对暂存文件进行了未暂存的修改。要以一种干净的方式做到这一点,您可以从索引中获取文件作为tmp,格式化tmp并使用格式化的tmp替换索引中的条目。这里有一个解决问题的方法:
xdnvmnnf2#
在你的pre-commit钩子中,你需要添加你的文件,所以如果你的钩子是这样的:
然后你需要修改它来添加:
要获取所有修改过的文件列表,可以使用git-ls-files:
git ls-files -m
但是,如果您可以从代码中获取修改了哪些文件的列表,或者只是再次添加所有文件,则会更好。
git diff-tree -r --name-only --no-commit-id <tree-ish>
应该可以为您获取所有文件的列表。基本上,在修改后再次添加文件是可行的,因为提交直到你的pre-commit钩子运行后才发生,所以在那个时候工作树中暂存的任何东西都被提交了。
mqkwyuun3#
您可以使用here描述的技术仅存储未暂存的更改。然后只对暂存的更改运行格式化程序并弹出存储。下面的
pre-commit
钩子使用clang-format-diff