Mercurial > hgbook
comparison en/examples/ch09/check_whitespace.py.lst @ 821:88828b784971
Add more complex example hook
| author | Bryan O'Sullivan <bos@serpentine.com> |
|---|---|
| date | Tue, 28 Apr 2009 23:10:43 -0700 |
| parents | en/examples/data/check_whitespace.py@e3894bb9d1f5 |
| children |
comparison
equal
deleted
inserted
replaced
| 820:3edacbff2b43 | 821:88828b784971 |
|---|---|
| 1 #!/usr/bin/env python | |
| 2 # | |
| 3 # save as .hg/check_whitespace.py and make executable | |
| 4 | |
| 5 import re | |
| 6 | |
| 7 def trailing_whitespace(difflines): | |
| 8 # | |
| 9 linenum, header = 0, False | |
| 10 | |
| 11 for line in difflines: | |
| 12 if header: | |
| 13 # remember the name of the file that this diff affects | |
| 14 m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line) | |
| 15 if m and m.group(1) != '/dev/null': | |
| 16 filename = m.group(1).split('/', 1)[-1] | |
| 17 if line.startswith('+++ '): | |
| 18 header = False | |
| 19 continue | |
| 20 if line.startswith('diff '): | |
| 21 header = True | |
| 22 continue | |
| 23 # hunk header - save the line number | |
| 24 m = re.match(r'@@ -\d+,\d+ \+(\d+),', line) | |
| 25 if m: | |
| 26 linenum = int(m.group(1)) | |
| 27 continue | |
| 28 # hunk body - check for an added line with trailing whitespace | |
| 29 m = re.match(r'\+.*\s$', line) | |
| 30 if m: | |
| 31 yield filename, linenum | |
| 32 if line and line[0] in ' +': | |
| 33 linenum += 1 | |
| 34 | |
| 35 if __name__ == '__main__': | |
| 36 import os, sys | |
| 37 | |
| 38 added = 0 | |
| 39 for filename, linenum in trailing_whitespace(os.popen('hg export tip')): | |
| 40 print >> sys.stderr, ('%s, line %d: trailing whitespace added' % | |
| 41 (filename, linenum)) | |
| 42 added += 1 | |
| 43 if added: | |
| 44 # save the commit message so we don't need to retype it | |
| 45 os.system('hg tip --template "{desc}" > .hg/commit.save') | |
| 46 print >> sys.stderr, 'commit message saved to .hg/commit.save' | |
| 47 sys.exit(1) |
