Mercurial codesmell extension
I know it’s bad behavior, but I’m simply too lazy
to do a hg diff before commit, so quite often I committed debugging statements like
import pdb; pdb.set_trace() or print foo, left in some module by accident.
Thankfully I’m using Mercurial for most projects now, so it was easy (and fun) to hack up a little extension to “fix” this.
The extension is called hgcodesmell and can be found, as always, on BitBucket. It currently asks you for confirmation when it recognizes any of these smelly changes:
- Debugging helpers left in Python code:
printstatementspdb.set_trace()1/0
- vim
:qand similar ex commands leaking into the source - Windows newlines (on non-Windows platforms)
The patterns to recognize are in a simple dictionary mapping from file name glob patterns to a list of (regex, reason) pairs that are checked against all added lines in files that match the respective pattern:
# smelly patterns are tuples (regex, reason) print_stmt = (re.compile(r'^\+\s*print\b'), 'print statement') zero_div = (re.compile(r'^\+\s*1/0'), 'zero division error') set_trace = (re.compile(r'\bpdb\.set_trace\(\)'), 'set_trace') vim_cmd = (re.compile(r':(w|wq|q|x)$', re.M), 'vim exit command') # the master dict maps glob patterns to a list of smelly patterns SMELLY_STUFF = { '*.py': [print_stmt, zero_div, set_trace], '*': [vim_cmd], }
It has since saved me quite a few hg rollbacks or worse, commits to fix such stuff,
and I think you might find it useful too – get it
from here, and please send me any new
patterns that are useful for others too!
Nice idea!
— Nick on Friday, January 8, 2010 17:12 #
Nice extension. It would be nice if it can also catch committing *.pyc files (or any other unneeded files) .. because, in the past, I have sometimes mistakenly committed them.
— srid on Friday, January 8, 2010 18:13 #
@srid: how would you determine “unneeded” files? Files that would be ignored by .hgignore, or by a list of patterns?
— Georg on Friday, January 8, 2010 18:44 #
We had a similar system at Resolver Systems - but using a PyLint checker. It wouldn’t let you commit anything with “TODO” in it… :-)
— Michael Foord on Friday, January 8, 2010 18:55 #
Reading this kills me. You ALWAYS check your diff. Find a gui commit tool if you don’t like typing it. Those show you diffs as part of your commit process.
— Darrin Thompson on Saturday, January 9, 2010 4:00 #
@Georg: even though you may have listed “.pyc” in your .hgignore, doing “hg add path/to/directory” will add the .pyc files under that directory. (I believe it was svn or hg that did this to me once - not sure which one it was)
— srid on Saturday, January 9, 2010 4:07 #
Hello
Nice extension. I’m lazy too, so I use a script as HGEDITOR which opens a file for the commit message alongside with the diff.
srid, if it was Mercurial, it looks like a bug to me.
Regards
— Merwok on Sunday, January 31, 2010 18:31 #