Git钩子脚本对于在提交代码审查之前识别简单问题很有用。我们在每次提交时都运行钩子,以自动指出代码中的问题,例如缺少分号,尾随空白和调试语句。通过在代码审阅之前指出这些问题,代码审阅者可以专注于更改的体系结构,而不会浪费琐碎的样式问题。
我们建立了预提交来解决钩子问题。它是用于预提交挂钩的多语言包管理器。您可以指定所需的挂钩列表,并且在每次提交之前,预提交可以管理用任何语言编写的任何挂钩的安装和执行。 pre-commit是专门为不需要root访问而设计的。如果您的开发人员之一未安装节点,但修改了JavaScript文件,则预提交会自动处理下载和构建节点,以在没有root的情况下运行eslint。
在此介绍的pre-commit只是git hook的一部分, git hook分客户端和服务端的,pre-commit属于客户端的。
下面我将以我在linux 下安装pre-commit 检查python代码为例子讲解 。
官网:https://pre-commit.com/
安装
pip3 install pre-commit
查看版本
pre-commit --version
帮助
pre-commit run --help
配置好后,最好做个全文的检查,修复问题。
pre-commit run --all-files
$ cat .git/hooks/pre-commit
#!/usr/bin/env python.exe # File generated by pre-commit: https://pre-commit.com # ID: 138fd403232d2ddd5efb44317e38bf03 import os import sys # we try our best, but the shebang of this script is difficult to determine: # - macos doesn't ship with python3 # - windows executables are almost always `python.exe` # therefore we continue to support python2 for this small script if sys.version_info < (3, 3): from distutils.spawn import find_executable as which else: from shutil import which # work around https://github.com/Homebrew/homebrew-core/issues/30445 os.environ.pop('__PYVENV_LAUNCHER__', None) # start templated INSTALL_PYTHON = 'c:\users\wuh17\appdata\local\programs\python\python37-32\python.exe' ARGS = ['hook-impl', '--config=.pre-commit-config.yaml', '--hook-type=pre-commit'] # end templated ARGS.extend(('--hook-dir', os.path.realpath(os.path.dirname(__file__)))) ARGS.append('--') ARGS.extend(sys.argv[1:]) DNE = '`pre-commit` not found. Did you forget to activate your virtualenv?' if os.access(INSTALL_PYTHON, os.X_OK): CMD = [INSTALL_PYTHON, '-mpre_commit'] elif which('pre-commit'): CMD = ['pre-commit'] else: raise SystemExit(DNE) CMD.extend(ARGS) if sys.platform == 'win32': # https://bugs.python.org/issue19124 import subprocess if sys.version_info < (3, 7): # https://bugs.python.org/issue25942 raise SystemExit(subprocess.Popen(CMD).wait()) else: raise SystemExit(subprocess.call(CMD)) else: os.execvp(CMD[0], CMD)
$ ls .git/hooks/
applypatch-msg.sample post-update.sample pre-commit.sample pre-push.sample update.sample commit-msg.sample pre-applypatch.sample pre-merge-commit.sample pre-rebase.sample fsmonitor-watchman.sample pre-commit prepare-commit-msg.sample pre-receive.sample