我想做一个预提交钩子(Hook)来检查Python代码是否遵循pep8,所以我像https://www.stavros.io/posts/more-pep8-git-hooks/中那样做了这个
我创建了 .git/hooks/pre-commit
文件。并添加了以下内容:
#!/bin/sh
flake8 .
然后:chmod +x .git/hooks/pre-commit
但是当我输入 git commit
时,它实际上会检查整个分支,如果它在分支中发现任何不遵循 pep8 的内容,它将终止(该存储库有点旧,有些代码做了从一开始就没有遵循 pep8,所以我知道它可以重构,但我不需要 pre-hook
来告诉我关于已经提交的代码)。
如何让它只检查应该提交的当前提交的代码?
最佳答案
How can I make it only check the code for the current commit that is supposed to be committed?
使用git checkout-index
来 checkout 您正在提交的文件
进入临时目录,然后在该临时目录上运行 flake8
目录。
首先,创建一个临时目录:
tmpdir=$(mktemp -d commitXXXXXX)
trap "rm -rf $tmpdir" EXIT
然后 checkout 要提交到该目录的文件:
git checkout-index --prefix=$tmpdir/ -af
获取此提交中修改的文件列表并运行 flake8
他们:
git diff --cached --name-only --diff-filter=ACM | grep '\.py$' |
(cd $tmpdir; xargs --no-run-if-empty flake8)
关于git 预提交钩子(Hook) : trigger only to actual to be commited code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36790935/