Git钩子能否自动添加文件到提交? [英] Can a Git hook automatically add files to the commit?
问题描述
我想使用Git中的提交前或提交后钩子将自动生成的文件添加到同一提交中,具体取决于该提交中修改的文件。我会如何去做这件事?
我试过这个作为预先提交的钩子,但没有运气:
#!/ bin / sh
files =`git diff --cached --name-status`
re =<重要文件>
if [[$ files =〜$ re]]
然后
echo创建文件
exec bundle exec create_my_files
exec git add my_files
exec git commit --amend -C HEAD
fi
成功将它们添加到存储库中,但不会将它们添加到提交中。我也试过在post-commit钩子中使用最后两个exec行以及pre-commit检查,但都不行。
解决方案由于git add在预先提交时并不适合我,所以我遵循mark的关于使用.commit文件的想法,并将该流程拆分为提交前和提交后。以下是一些应该很容易理解的代码:
在预先提交中:
< blockquote>
- 触摸文件.commit或其他内容。 (请务必将其添加到.gitignore中)
#!/ bin / sh
echo
touch .commit
exit
<如果.commit存在,你知道一个提交已经发生,但是一个
post-commit:
提交尚未运行。所以,你可以在这里做你的代码生成。
此外,测试.commit,如果存在:
- 添加文件
- commit --amend -C HEAD --no-verify(避免循环)
- 删除.commit文件
blockquote>
#!/ bin / sh
echo
if [-a .commit]
then
rm .commit
git add yourfile
git commit --amend -C HEAD --no-verify
fi
exit
希望这可以让那些没有bash知识的人更容易遵循mark的想法。
I'd like to add an automatically generated file to the same commit using a pre- or post-commit hook in Git, dependent on the files that were modified in that commit. How would I go about this?
I've tried this as a pre-commit hook, but no luck:
#!/bin/sh files=`git diff --cached --name-status` re="<files of importance>" if [[ $files =~ $re ]] then echo "Creating files" exec bundle exec create_my_files exec git add my_files exec git commit --amend -C HEAD fi
This successfully adds them to the repository, but does not add them to the commit. I've also tried using the last two exec lines in a post-commit hook along with the pre-commit inspection, but no good either.
解决方案Since git add was also not working for me in a pre commit, I followed mark's idea of using a .commit file and splitting the process into pre- and post-commit.
Here is some code that should be easy to understand
In the pre-commit:
- Touch a file .commit or something. (be sure to add this to .gitignore)
#!/bin/sh echo touch .commit exit
In the post-commit:
if .commit exists you know a commit has just taken place but a post-commit hasn't run yet. So, you can do your code generation here. Additionally, test for .commit and if it exists:
- add the files
- commit --amend -C HEAD --no-verify (avoid looping)
- delete .commit file
#!/bin/sh echo if [ -a .commit ] then rm .commit git add yourfile git commit --amend -C HEAD --no-verify fi exit
Hope this makes it easier for people with few bash knowledge to follow mark's idea.
这篇关于Git钩子能否自动添加文件到提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!