我们所有的Puppet配置都有这个回购。我写了以下内容来验证任何已更改的.pp文件,如果验证失败,则退出提交。预先提交脚本在git commit
触发时正常运行,但git commit -a
似乎完全跳过了钩子。我们只使用git commit -a
,所以这种行为有点破坏性。
我做错了吗?或者,我该怎么做才能在预提交脚本中复制git commit -a的行为?
#!/bin/bash
# check puppet files for errors before pushing to repo
for name in `git diff --name-only`; do
if [[ $name == *.pp ]]; then
path="$(pwd)/$name"
puppet parser validate "$path"
r=$?
if [ $r -ne 0 ]; then exit 1; fi
fi
done
答案 0 :(得分:2)
即使指定了-a选项,预提交挂钩也会在每次提交时运行。通过创建此脚本来确认:
#!/bin/bash
echo "Running"
将脚本放入.git/hooks/pre-commit
,编辑和暂存文件,然后:
$ git commit -am "Commit"
Running
[master f042adf] Commit
1 file changed, 1 insertion(+), 1 deletion(-)
默认情况下, git diff
会针对未暂存的更改进行区分。例如,编辑README.md然后:
$ git diff --name-only
README.md
$ git add -A
$ git diff --name-only
$
一旦更改完成,它们就不再出现在git diff
。
git commit
上的-a选项在执行预提交挂钩之前对更改进行分阶段。例如,如果我们将预提交挂钩更改为:
#!/bin/bash
echo "Running"
git diff --name-only
再次修改README.md
,然后:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: README.md
no changes added to commit (use "git add" and/or "git commit -a")
$ .git/hooks/pre-commit
Running
README.md
$ git commit -m "Commit"
Running
README.md
On branch master
Changes not staged for commit:
modified: README.md
no changes added to commit
更改显示在diff输出中,但未提交。但是:
$ git commit -am "Commit"
Running
[master a357465] Commit
1 file changed, 1 insertion(+), 1 deletion(-)
这一次,使用-a选项,更改没有显示在diff输出中(因为它们在舞台上)但是它们已被提交。
所以将--cached
选项添加到git diff
命令:
#!/bin/bash
echo "Running"
git diff --name-only --cached
然后,在对README.md
进行另一次更改后:
$ git commit -am "Commit"
Running
README.md
[master eaab554] Commit
1 file changed, 1 insertion(+), 1 deletion(-)
答案是--cached
上的git diff
选项。