假设你有一个预提交钩子,它执行以下操作:
#!/bin/bash
echo "--- Dataset Pre-Commit Hook ---"
DATASET_REPO_PATH="$(pwd)"
python3 -m my_script_that_generates_or_modifies_a_file
git -C $DATASET_REPO_PATH add file
echo "--- Done ---"
exit
只有在已经有要提交的内容时,它才会起作用。这些内容不一定是同一个文件。如果没有要提交的内容,git add git add file命令会起作用,但不会被提交。
以下是一个有效的示例:
1. 你修改了一个文件,并将其添加(例如,gitignore文件)。
$> git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
运行提交。首先,将运行
pre-commit
钩子并创建
file
。然后进行提交。
[master (root-commit) 2ba2f7c] First commit
3 files changed, 34 insertions(+)
create mode 100644 .gitignore
create mode 100644 file
你可以看到消息说
file
已经提交。而
git status
现在输出:
On branch master
nothing to commit, working tree clean
不起作用的示例
- 你没有任何要添加的内容。当然你可以运行
git add
,但它不会有任何作用。运行git status
会得到以下结果:
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
运行提交。钩子将创建
文件
。但提交消息说他什么都没做。
--- Dataset Pre-Commit Hook ---
--- Done ---
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
验证状态
git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: file
你可以看到文件确实被修改了,并且被添加了,但是还没有提交。你需要再次运行
git commit
来使其生效。
我尝试将其作为
post-commit
钩子添加,但是没有成功。如果有人知道如何解决这个问题,我很愿意知道。
exec
(参见man sh
)。在exec
之后,任何 shell 命令都无法被执行,因为exec
覆盖了当前进程,即用于解释命令的 shell。 - Martin Jambon