git pre-commit hook可以同时格式化和重新添加文件 [英] git pre-commit hook to format and re-add files at the same time

查看:467
本文介绍了git pre-commit hook可以同时格式化和重新添加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在允许用户提交之前,我们正在使用git钩子(下面)在我们的源代码上运行astyle。这有一个警告,即用户必须提交,格式化他们的代码,然后再次提交,这有点麻烦。理想情况下,我们希望hook来格式化代码,然后在原始提交中包含格式化的代码。我尝试重新添加更改的文件,但它会导致ref错误(显然)。我也尝试在预提交钩子中获取历史记录,并试图退出钩子并重新运行git commit命令,但没有运气。

 #在已更改的.cs文件上运行astyle,忽略$忽略
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)#我们只对'formatted'前面的数字感兴趣。
[[$ num_formatted -ne 0]]&&回声警告:代码已被自动格式化,请重新添加并重新提交&&退出1 || echo没有代码格式化!持续提交

有没有人有任何想法?

解决方案

在你的预提交钩子中,你需要添加你的文件,所以如果你的钩子是这样的:

 #!/ bin / bash 
echo 1>文件
出口0

然后您需要修改它以添加:

 #!/ bin / bash 
echo 1> file
git add file
exit 0

获取所有修改的列表你可以使用git-ls-files:

b
$ b

然而,如果您只需从您的代码中获取哪些文件被修改或仅添加所有文件的列表就会更好。 git diff-tree -r --name-only --no-commit-id< tree-ish> 应该可以让你得到所有文件的列表。 / p>

基本上,在修改后再次添加文件是因为在您的预提交钩子运行之前不会发生提交,所以在那个时候在工作树中执行的任何操作都是承诺。

We're currently using a git hook (below) to run astyle on our source code before allowing the user to commit. This has the caveat that the user must commit, have their code formatted, then commit again which is a bit of a nuisance. Ideally we'd want the hook to format the code and then include that formatted code in the original commit instead. I've tried re-adding the changed files but it causes ref errors (obviously). I've also tried getting the history in the pre-commit hook and trying to exit the hook and re-run the git commit command with no luck.

# 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"

Does anyone have any ideas?

解决方案

In your pre-commit hook, you need to add your files, so if your hook is something like:

#!/bin/bash
echo 1 > file
exit 0

then you would need to modify it to have the add:

#!/bin/bash
echo 1 > file
git add file
exit 0

To get a list of all modified files, you could use git-ls-files:

git ls-files -m

However, it would be better if you could just get a list from your code of which files are modified or just add all files again. git diff-tree -r --name-only --no-commit-id <tree-ish> should work for you to get a list of all files.

Basically, adding the files again after modifying works because the commit does not occur until after your pre-commit hook runs, so whatever is staged in the working tree at that point is committed.

这篇关于git pre-commit hook可以同时格式化和重新添加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆