Skip to main content
 首页 » 编程设计

python之Git 预提交 Hook 在 Windows 上不起作用

2024年10月24日14zhengyun_ustc

我有一个 git pre-commit 钩子(Hook),但是在提交到本地 repo 之后,脚本没有被调用。这是它的样子,它是在 python 中,钩子(Hook)文件的名称称为 pre-commit 没有任何扩展名:

#!C:/Users/al/AppData/Local/Programs/Python/Python35-32 python 
 
import sys, os 
 
sys.exit(1) 

请您参考如下方法:

您的预提交 Hook 可能会遇到以下一个或多个问题:

shebang 行是否正确?

shebang 行应该是用于运行脚本的可执行文件的完整路径。参见 this找出何时使用(或未使用)shebang 行。在预提交 Hook 的情况下,shebang 行将仅在脚本上设置可执行位时使用。

处理 shebang 行中的空格

如果解释器的完整路径中有空格,要么像这样引用整个路径:

#!"C:/Users/al/AppData/Local/Programs/Python/Python35-32 python" 

或者,像这样转义路径中的空格:

#! C:/Users/al/AppData/Local/Programs/Python/Python35-32\ python 

在 Windows 上通过 msysgit 使用 python 脚本

据报道,msysgit 在解释 shebang 行时存在问题。以下是解决方法。将 python precommit-hook(例如 precommit.py)重命名为其他名称,并使用以下内容作为 precommit-hook:

#!/bin/sh 
python .git/hooks/pre-commit.py $*  

预提交钩子(Hook)脚本是否可执行?

(这并不严格适用于当前问题,因为OP是在windows上,但为了完整起见,我将在此处保留以下内容)

pre-commit 钩子(Hook)如果没有设置为可执行则不会执行。我在本地对此进行了测试,以下输出证明:

$ cd ~/test-git  
$ cat .git/hooks/pre-commit 
#!/usr/local/bin/python 
import sys, os 
print "yo! this is the pre-commit hook" 
sys.exit(1) 
 
$ chmod -x .git/hooks/pre-commit 
$ git commit -am "Test" 
[master (root-commit) 0b1edce] Test 
 1 file changed, 0 insertions(+), 0 deletions(-) 
 create mode 100644 a 
 
$ chmod +x .git/hooks/pre-commit 
$ git commit -am "Test" 
yo! this is the pre-commit hook 

此外,来自 https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

To enable a hook script, put a file in the hooks subdirectory of your .git directory that is named appropriately (without any extension) and is executable.