hgbook
diff en/examples/ch09/check_whitespace.py.lst @ 1099:a1b3a1de1038
2.7.2 zh translated
author | Zhaoping Sun <zhaopingsun@gmail.com> |
---|---|
date | Tue Nov 24 22:16:48 2009 -0500 (2009-11-24) |
parents | e3894bb9d1f5 |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/en/examples/ch09/check_whitespace.py.lst Tue Nov 24 22:16:48 2009 -0500 1.3 @@ -0,0 +1,47 @@ 1.4 +#!/usr/bin/env python 1.5 +# 1.6 +# save as .hg/check_whitespace.py and make executable 1.7 + 1.8 +import re 1.9 + 1.10 +def trailing_whitespace(difflines): 1.11 + # 1.12 + linenum, header = 0, False 1.13 + 1.14 + for line in difflines: 1.15 + if header: 1.16 + # remember the name of the file that this diff affects 1.17 + m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line) 1.18 + if m and m.group(1) != '/dev/null': 1.19 + filename = m.group(1).split('/', 1)[-1] 1.20 + if line.startswith('+++ '): 1.21 + header = False 1.22 + continue 1.23 + if line.startswith('diff '): 1.24 + header = True 1.25 + continue 1.26 + # hunk header - save the line number 1.27 + m = re.match(r'@@ -\d+,\d+ \+(\d+),', line) 1.28 + if m: 1.29 + linenum = int(m.group(1)) 1.30 + continue 1.31 + # hunk body - check for an added line with trailing whitespace 1.32 + m = re.match(r'\+.*\s$', line) 1.33 + if m: 1.34 + yield filename, linenum 1.35 + if line and line[0] in ' +': 1.36 + linenum += 1 1.37 + 1.38 +if __name__ == '__main__': 1.39 + import os, sys 1.40 + 1.41 + added = 0 1.42 + for filename, linenum in trailing_whitespace(os.popen('hg export tip')): 1.43 + print >> sys.stderr, ('%s, line %d: trailing whitespace added' % 1.44 + (filename, linenum)) 1.45 + added += 1 1.46 + if added: 1.47 + # save the commit message so we don't need to retype it 1.48 + os.system('hg tip --template "{desc}" > .hg/commit.save') 1.49 + print >> sys.stderr, 'commit message saved to .hg/commit.save' 1.50 + sys.exit(1)