belaran@966: #!/usr/bin/env python belaran@966: # belaran@966: # save as .hg/check_whitespace.py and make executable belaran@966: belaran@966: import re belaran@966: belaran@966: def trailing_whitespace(difflines): belaran@966: # belaran@966: linenum, header = 0, False belaran@966: belaran@966: for line in difflines: belaran@966: if header: belaran@966: # remember the name of the file that this diff affects belaran@966: m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line) belaran@966: if m and m.group(1) != '/dev/null': belaran@966: filename = m.group(1).split('/', 1)[-1] belaran@966: if line.startswith('+++ '): belaran@966: header = False belaran@966: continue belaran@966: if line.startswith('diff '): belaran@966: header = True belaran@966: continue belaran@966: # hunk header - save the line number belaran@966: m = re.match(r'@@ -\d+,\d+ \+(\d+),', line) belaran@966: if m: belaran@966: linenum = int(m.group(1)) belaran@966: continue belaran@966: # hunk body - check for an added line with trailing whitespace belaran@966: m = re.match(r'\+.*\s$', line) belaran@966: if m: belaran@966: yield filename, linenum belaran@966: if line and line[0] in ' +': belaran@966: linenum += 1 belaran@966: belaran@966: if __name__ == '__main__': belaran@966: import os, sys belaran@966: belaran@966: added = 0 belaran@966: for filename, linenum in trailing_whitespace(os.popen('hg export tip')): belaran@966: print >> sys.stderr, ('%s, line %d: trailing whitespace added' % belaran@966: (filename, linenum)) belaran@966: added += 1 belaran@966: if added: belaran@966: # save the commit message so we don't need to retype it belaran@966: os.system('hg tip --template "{desc}" > .hg/commit.save') belaran@966: print >> sys.stderr, 'commit message saved to .hg/commit.save' belaran@966: sys.exit(1)