使用预提交挂钩防止 pdb 或 pytest set_trace 被提交

Prevent pdb or pytest set_trace from being committed using a pre commit hook

我想创建一个 git 预提交挂钩,以防止未注释的 pytest.set_trace()pdb.set_trace() 和其他 .set_trace()。这是因为我经常从命令行进行调试,有时会忘记我在代码中留下了调试语句。通过使用预提交挂钩,我应该能够在将来避免这种情况。

Keul's Blog 对此有一个解决方案,但会话必须位于 git 存储库的根目录中才能工作,否则它会抱怨。

我基本上希望 not 等效于此在 grep

中工作
#(\s+)?.*\.set_trace\(\)

查看regexr测试

谢谢

正确的正则表达式是^\s?[^#]+\.set_trace\(\)

解释:

  1. ^ 开头为
  2. \s? 匹配 space 或更多或不匹配 space
  3. [^#]+ 匹配除 #
  4. 之外的任何字符
  5. \.set_trace\(\) 匹配任何以 .set_trace() 结尾的函数
    • 我们可以通过仅包含 pdbpytest 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()