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

Question:

I’d like to create a git pre commit hook that prevents an uncommented pytest.set_trace() or a pdb.set_trace() and other .set_trace(). This is because I debug from the command line often and sometimes forget that I left the debug statement in the code. By using a pre commit hook, I should be able to avoid this in the future.

Keul’s Blog has a solution for this but the session has to be in the root directory of the git repo for it to work or it will complain.

I basically want the not equivalent of this to work in grep

#(s+)?.*.set_trace()

See the regexr test

Thanks

Asked By: SomeGuyOnAComputer

||

Answers:

The correct regular expression is ^s?[^#]+.set_trace()

Explanation:

  1. ^ starts with
  2. s? matches a space or more or no space
  3. [^#]+ matches any characters excluding #
  4. .set_trace() matches any function ending with .set_trace()
    • we can be more explicit by only including pdb or pytest set_traces but there may be other packages that also have a set_trace

Sample python code

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()

Verify using ripgrep

$ rg '^s?[^#]+.set_trace()'
main.py
4:      pdb.set_trace()
5:      pytest.set_trace()

Now we can use git-secrets which gets triggered on a pre-commit hook and this will prevent us from committing this line

$ 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()
Answered By: SomeGuyOnAComputer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.