hgbook

annotate en/examples/ch09/check_whitespace.py.lst @ 732:1c31e38a9720

Complete revision of Ch.2.
author Giulio@puck
date Sun Jun 28 17:18:56 2009 +0200 (2009-06-28)
parents e3894bb9d1f5
children
rev   line source
bos@694 1 #!/usr/bin/env python
bos@694 2 #
bos@694 3 # save as .hg/check_whitespace.py and make executable
bos@44 4
bos@49 5 import re
bos@44 6
bos@49 7 def trailing_whitespace(difflines):
bos@694 8 #
bos@694 9 linenum, header = 0, False
bos@44 10
bos@49 11 for line in difflines:
bos@49 12 if header:
bos@65 13 # remember the name of the file that this diff affects
bos@65 14 m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line)
bos@65 15 if m and m.group(1) != '/dev/null':
bos@65 16 filename = m.group(1).split('/', 1)[-1]
bos@49 17 if line.startswith('+++ '):
bos@49 18 header = False
bos@49 19 continue
bos@49 20 if line.startswith('diff '):
bos@49 21 header = True
bos@49 22 continue
bos@49 23 # hunk header - save the line number
bos@65 24 m = re.match(r'@@ -\d+,\d+ \+(\d+),', line)
bos@49 25 if m:
bos@49 26 linenum = int(m.group(1))
bos@49 27 continue
bos@49 28 # hunk body - check for an added line with trailing whitespace
bos@49 29 m = re.match(r'\+.*\s$', line)
bos@49 30 if m:
bos@694 31 yield filename, linenum
bos@49 32 if line and line[0] in ' +':
bos@49 33 linenum += 1
bos@44 34
bos@49 35 if __name__ == '__main__':
bos@49 36 import os, sys
bos@49 37
bos@694 38 added = 0
bos@694 39 for filename, linenum in trailing_whitespace(os.popen('hg export tip')):
bos@694 40 print >> sys.stderr, ('%s, line %d: trailing whitespace added' %
bos@694 41 (filename, linenum))
bos@694 42 added += 1
bos@49 43 if added:
bos@49 44 # save the commit message so we don't need to retype it
bos@49 45 os.system('hg tip --template "{desc}" > .hg/commit.save')
bos@49 46 print >> sys.stderr, 'commit message saved to .hg/commit.save'
bos@49 47 sys.exit(1)