我想创建一个 git 预提交挂钩,以防止未注释的
pytest.set_trace()
或 pdb.set_trace()
和其他 .set_trace()
。这是因为我经常从命令行进行调试,有时忘记了我在代码中留下了调试语句。通过使用预提交钩子,我将来应该能够避免这种情况。
Keul 的博客对此有一个解决方案,但会话必须位于 git 存储库的根目录中才能工作,否则会抱怨。
我基本上希望
not
等价于 grep
#(\s+)?.*\.set_trace\(\)
参见 regexr 测试
谢谢
正确的正则表达式是
^\s?[^#]+\.set_trace\(\)
说明:
^
开始于\s?
匹配一个空格或多个或没有空格[^#]+
匹配除 #
\.set_trace\(\)
匹配任何以 .set_trace()
结尾的函数
pdb
或 pytest
set_trace
来更明确,但可能还有其他包也有 set_trace
Python 代码示例
import pdb
if __name__ == "__main__":
pdb.set_trace()
pytest.set_trace()
# pdb.set_trace()
# pytest.set_trace()
#pytest.set_trace()
# pdb.set_trace()
# somethingelse.set_trace()
ripgrep
进行验证
$ rg '^\s?[^#]+\.set_trace\(\)'
main.py
4: pdb.set_trace()
5: pytest.set_trace()
git-secrets
,它会在预提交挂钩上触发,这将阻止我们提交这一行
$ git secrets --add '^\s?[^#]+\.set_trace\(\)'
$ git add main.py
$ git commit -m 'test'
main.py:4: pdb.set_trace()
main.py:5: pytest.set_trace()
到目前为止,还有一个预提交配置来检查调试器导入(通过这篇博客文章找到它):
.pre-commit-config.yaml
---
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
# Check for debugger imports and py37+ breakpoint() calls
- id: debug-statements