check-code.py
379 lines
| 13.0 KiB
| text/x-python
|
PythonLexer
/ contrib / check-code.py
Matt Mackall
|
r10281 | #!/usr/bin/env python | ||
# | ||||
# check-code - a style and portability checker for Mercurial | ||||
# | ||||
Matt Mackall
|
r10290 | # Copyright 2010 Matt Mackall <mpm@selenic.com> | ||
Matt Mackall
|
r10281 | # | ||
# This software may be used and distributed according to the terms of the | ||||
# GNU General Public License version 2 or any later version. | ||||
Alecs King
|
r11816 | import re, glob, os, sys | ||
Thomas Arendsen Hein
|
r13074 | import keyword | ||
Matt Mackall
|
r10895 | import optparse | ||
Matt Mackall
|
r10281 | |||
def repquote(m): | ||||
Benoit Boissinot
|
r10722 | t = re.sub(r"\w", "x", m.group('text')) | ||
Matt Mackall
|
r10451 | t = re.sub(r"[^\sx]", "o", t) | ||
Benoit Boissinot
|
r10722 | return m.group('quote') + t + m.group('quote') | ||
Matt Mackall
|
r10281 | |||
Benoit Boissinot
|
r10727 | def reppython(m): | ||
comment = m.group('comment') | ||||
if comment: | ||||
return "#" * len(comment) | ||||
return repquote(m) | ||||
Matt Mackall
|
r10281 | |||
def repcomment(m): | ||||
return m.group(1) + "#" * len(m.group(2)) | ||||
def repccomment(m): | ||||
t = re.sub(r"((?<=\n) )|\S", "x", m.group(2)) | ||||
return m.group(1) + t + "*/" | ||||
def repcallspaces(m): | ||||
t = re.sub(r"\n\s+", "\n", m.group(2)) | ||||
return m.group(1) + t | ||||
def repinclude(m): | ||||
return m.group(1) + "<foo>" | ||||
def rephere(m): | ||||
t = re.sub(r"\S", "x", m.group(2)) | ||||
return m.group(1) + t | ||||
testpats = [ | ||||
Idan Kamara
|
r14009 | [ | ||
Martin Geisler
|
r10374 | (r'(pushd|popd)', "don't use 'pushd' or 'popd', use 'cd'"), | ||
(r'\W\$?\(\([^\)]*\)\)', "don't use (()) or $(()), use 'expr'"), | ||||
Matt Mackall
|
r10281 | (r'^function', "don't use 'function', use old style"), | ||
Martin Geisler
|
r10374 | (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"), | ||
Mads Kiilerich
|
r10373 | (r'echo.*\\n', "don't use 'echo \\n', use printf"), | ||
Martin Geisler
|
r11884 | (r'echo -n', "don't use 'echo -n', use printf"), | ||
Martin Geisler
|
r10374 | (r'^diff.*-\w*N', "don't use 'diff -N'"), | ||
Matt Mackall
|
r10281 | (r'(^| )wc[^|]*$', "filter wc output"), | ||
Martin Geisler
|
r10374 | (r'head -c', "don't use 'head -c', use 'dd'"), | ||
(r'ls.*-\w*R', "don't use 'ls -R', use 'find'"), | ||||
(r'printf.*\\\d\d\d', "don't use 'printf \NNN', use Python"), | ||||
(r'printf.*\\x', "don't use printf \\x, use Python"), | ||||
Matt Mackall
|
r10281 | (r'\$\(.*\)', "don't use $(expr), use `expr`"), | ||
(r'rm -rf \*', "don't use naked rm -rf, target a directory"), | ||||
(r'(^|\|\s*)grep (-\w\s+)*[^|]*[(|]\w', | ||||
"use egrep for extended grep syntax"), | ||||
(r'/bin/', "don't use explicit paths for tools"), | ||||
(r'\$PWD', "don't use $PWD, use `pwd`"), | ||||
(r'[^\n]\Z', "no trailing newline"), | ||||
Mads Kiilerich
|
r10658 | (r'export.*=', "don't export and assign at once"), | ||
Mads Kiilerich
|
r10802 | ('^([^"\']|("[^"]*")|(\'[^\']*\'))*\\^', "^ must be quoted"), | ||
Yuya Nishihara
|
r11210 | (r'^source\b', "don't use 'source', use '.'"), | ||
Dan Villiom Podlaski Christiansen
|
r12367 | (r'touch -d', "don't use 'touch -d', use 'touch -t' instead"), | ||
Martin Geisler
|
r13301 | (r'ls\s+[^|-]+\s+-', "options to 'ls' must come before filenames"), | ||
Martin Geisler
|
r13524 | (r'[^>]>\s*\$HGRCPATH', "don't overwrite $HGRCPATH, append to it"), | ||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
[] | ||||
Matt Mackall
|
r10281 | ] | ||
testfilters = [ | ||||
(r"( *)(#([^\n]*\S)?)", repcomment), | ||||
(r"<<(\S+)((.|\n)*?\n\1)", rephere), | ||||
] | ||||
Matt Mackall
|
r12364 | uprefix = r"^ \$ " | ||
Adrian Buehlmann
|
r12743 | uprefixc = r"^ > " | ||
Matt Mackall
|
r12364 | utestpats = [ | ||
Idan Kamara
|
r14009 | [ | ||
Matt Mackall
|
r12785 | (r'^(\S| $ ).*(\S\s+|^\s+)\n', "trailing whitespace on non-output"), | ||
Matt Mackall
|
r12366 | (uprefix + r'.*\|\s*sed', "use regex test output patterns instead of sed"), | ||
Matt Mackall
|
r12364 | (uprefix + r'(true|exit 0)', "explicit zero exit unnecessary"), | ||
(uprefix + r'.*\$\?', "explicit exit code checks unnecessary"), | ||||
(uprefix + r'.*\|\| echo.*(fail|error)', | ||||
"explicit exit code checks unnecessary"), | ||||
(uprefix + r'set -e', "don't use set -e"), | ||||
Adrian Buehlmann
|
r12743 | (uprefixc + r'( *)\t', "don't use tabs to indent"), | ||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
[] | ||||
Matt Mackall
|
r12364 | ] | ||
Mads Kiilerich
|
r14203 | for i in [0, 1]: | ||
for p, m in testpats[i]: | ||||
if p.startswith('^'): | ||||
p = uprefix + p[1:] | ||||
else: | ||||
p = uprefix + p | ||||
utestpats[i].append((p, m)) | ||||
Matt Mackall
|
r12364 | |||
utestfilters = [ | ||||
(r"( *)(#([^\n]*\S)?)", repcomment), | ||||
] | ||||
Matt Mackall
|
r10281 | pypats = [ | ||
Idan Kamara
|
r14009 | [ | ||
Renato Cunha
|
r11568 | (r'^\s*def\s*\w+\s*\(.*,\s*\(', | ||
"tuple parameter unpacking not available in Python 3+"), | ||||
(r'lambda\s*\(.*,.*\)', | ||||
"tuple parameter unpacking not available in Python 3+"), | ||||
Renato Cunha
|
r11764 | (r'(?<!def)\s+(cmp)\(', "cmp is not available in Python 3+"), | ||
Renato Cunha
|
r11569 | (r'\breduce\s*\(.*', "reduce is not available in Python 3+"), | ||
Martin Geisler
|
r11602 | (r'\.has_key\b', "dict.has_key is not available in Python 3+"), | ||
Matt Mackall
|
r10281 | (r'^\s*\t', "don't use tabs"), | ||
Matt Mackall
|
r10412 | (r'\S;\s*\n', "semicolon"), | ||
Matt Mackall
|
r10281 | (r'\w,\w', "missing whitespace after ,"), | ||
(r'\w[+/*\-<>]\w', "missing whitespace in expression"), | ||||
(r'^\s+\w+=\w+[^,)]$', "missing whitespace in assignment"), | ||||
(r'.{85}', "line too long"), | ||||
(r'[^\n]\Z', "no trailing newline"), | ||||
Martin Geisler
|
r12770 | (r'(\S\s+|^\s+)\n', "trailing whitespace"), | ||
Matt Mackall
|
r10281 | # (r'^\s+[^_ ][^_. ]+_[^_]+\s*=', "don't use underbars in identifiers"), | ||
# (r'\w*[a-z][A-Z]\w*\s*=', "don't use camelcase in identifiers"), | ||||
Matt Mackall
|
r10286 | (r'^\s*(if|while|def|class|except|try)\s[^[]*:\s*[^\]#\s]+', | ||
"linebreak after :"), | ||||
Matt Mackall
|
r10281 | (r'class\s[^(]:', "old-style class, use class foo(object)"), | ||
Thomas Arendsen Hein
|
r13076 | (r'\b(%s)\(' % '|'.join(keyword.kwlist), | ||
"Python keyword is not a function"), | ||||
Matt Mackall
|
r10412 | (r',]', "unneeded trailing ',' in list"), | ||
Matt Mackall
|
r10281 | # (r'class\s[A-Z][^\(]*\((?!Exception)', | ||
# "don't capitalize non-exception classes"), | ||||
# (r'in range\(', "use xrange"), | ||||
# (r'^\s*print\s+', "avoid using print in core and extensions"), | ||||
(r'[\x80-\xff]', "non-ASCII character literal"), | ||||
(r'("\')\.format\(', "str.format() not available in Python 2.4"), | ||||
(r'^\s*with\s+', "with not available in Python 2.4"), | ||||
Matt Mackall
|
r14267 | (r'\.isdisjoint\(', "set.isdisjoint not available in Python 2.4"), | ||
Matt Mackall
|
r13160 | (r'^\s*except.* as .*:', "except as not available in Python 2.4"), | ||
Matt Mackall
|
r13161 | (r'^\s*os\.path\.relpath', "relpath not available in Python 2.4"), | ||
Martin Geisler
|
r11345 | (r'(?<!def)\s+(any|all|format)\(', | ||
"any/all/format not available in Python 2.4"), | ||||
Martin Geisler
|
r11522 | (r'(?<!def)\s+(callable)\(', | ||
"callable not available in Python 3, use hasattr(f, '__call__')"), | ||||
Matt Mackall
|
r10281 | (r'if\s.*\selse', "if ... else form not available in Python 2.4"), | ||
Thomas Arendsen Hein
|
r13074 | (r'^\s*(%s)\s\s' % '|'.join(keyword.kwlist), | ||
"gratuitous whitespace after Python keyword"), | ||||
Matt Mackall
|
r10281 | (r'([\(\[]\s\S)|(\S\s[\)\]])', "gratuitous whitespace in () or []"), | ||
# (r'\s\s=', "gratuitous whitespace before ="), | ||||
Martin Geisler
|
r11345 | (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\S', | ||
"missing whitespace around operator"), | ||||
(r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\s', | ||||
"missing whitespace around operator"), | ||||
(r'\s(\+=|-=|!=|<>|<=|>=|<<=|>>=)\S', | ||||
"missing whitespace around operator"), | ||||
Sune Foldager
|
r14303 | (r'[^+=*/!<>&| -](\s=|=\s)[^= ]', | ||
Martin Geisler
|
r11345 | "wrong whitespace around ="), | ||
Matt Mackall
|
r10451 | (r'raise Exception', "don't raise generic exceptions"), | ||
Idan Kamara
|
r14009 | (r' is\s+(not\s+)?["\'0-9-]', "object comparison with literal"), | ||
(r' [=!]=\s+(True|False|None)', | ||||
"comparison with singleton, use 'is' or 'is not' instead"), | ||||
Martin Geisler
|
r14494 | (r'^\s*(while|if) [01]:', | ||
"use True/False for constant Boolean expression"), | ||||
Dan Villiom Podlaski Christiansen
|
r14169 | (r'opener\([^)]*\).read\(', | ||
"use opener.read() instead"), | ||||
(r'opener\([^)]*\).write\(', | ||||
"use opener.write() instead"), | ||||
(r'[\s\(](open|file)\([^)]*\)\.read\(', | ||||
"use util.readfile() instead"), | ||||
(r'[\s\(](open|file)\([^)]*\)\.write\(', | ||||
"use util.readfile() instead"), | ||||
(r'^[\s\(]*(open(er)?|file)\([^)]*\)', | ||||
"always assign an opened file to a variable, and close it afterwards"), | ||||
(r'[\s\(](open|file)\([^)]*\)\.', | ||||
"always assign an opened file to a variable, and close it afterwards"), | ||||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
[ | ||||
(r'.{81}', "warning: line over 80 characters"), | ||||
Idan Kamara
|
r14005 | (r'^\s*except:$', "warning: naked except clause"), | ||
Martin Geisler
|
r11599 | (r'ui\.(status|progress|write|note|warn)\([\'\"]x', | ||
Matt Mackall
|
r10895 | "warning: unwrapped ui message"), | ||
Idan Kamara
|
r14009 | ] | ||
Matt Mackall
|
r10281 | ] | ||
pyfilters = [ | ||||
Benoit Boissinot
|
r10727 | (r"""(?msx)(?P<comment>\#.*?$)| | ||
((?P<quote>('''|\"\"\"|(?<!')'(?!')|(?<!")"(?!"))) | ||||
(?P<text>(([^\\]|\\.)*?)) | ||||
(?P=quote))""", reppython), | ||||
Matt Mackall
|
r10281 | ] | ||
cpats = [ | ||||
Idan Kamara
|
r14009 | [ | ||
Matt Mackall
|
r10281 | (r'//', "don't use //-style comments"), | ||
(r'^ ', "don't use spaces to indent"), | ||||
(r'\S\t', "don't use tabs except for indent"), | ||||
(r'(\S\s+|^\s+)\n', "trailing whitespace"), | ||||
(r'.{85}', "line too long"), | ||||
(r'(while|if|do|for)\(', "use space after while/if/do/for"), | ||||
(r'return\(', "return is not a function"), | ||||
(r' ;', "no space before ;"), | ||||
(r'\w+\* \w+', "use int *foo, not int* foo"), | ||||
(r'\([^\)]+\) \w+', "use (int)foo, not (int) foo"), | ||||
(r'\S+ (\+\+|--)', "use foo++, not foo ++"), | ||||
(r'\w,\w', "missing whitespace after ,"), | ||||
Matt Mackall
|
r13736 | (r'^[^#]\w[+/*]\w', "missing whitespace in expression"), | ||
Matt Mackall
|
r10281 | (r'^#\s+\w', "use #foo, not # foo"), | ||
(r'[^\n]\Z', "no trailing newline"), | ||||
Dan Villiom Podlaski Christiansen
|
r13748 | (r'^\s*#import\b', "use only #include in standard C code"), | ||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
[] | ||||
Matt Mackall
|
r10281 | ] | ||
cfilters = [ | ||||
(r'(/\*)(((\*(?!/))|[^*])*)\*/', repccomment), | ||||
Benoit Boissinot
|
r10722 | (r'''(?P<quote>(?<!")")(?P<text>([^"]|\\")+)"(?!")''', repquote), | ||
Matt Mackall
|
r10281 | (r'''(#\s*include\s+<)([^>]+)>''', repinclude), | ||
(r'(\()([^)]+\))', repcallspaces), | ||||
] | ||||
timeless
|
r14137 | inutilpats = [ | ||
[ | ||||
(r'\bui\.', "don't use ui in util"), | ||||
], | ||||
# warnings | ||||
[] | ||||
] | ||||
inrevlogpats = [ | ||||
[ | ||||
(r'\brepo\.', "don't use repo in revlog"), | ||||
], | ||||
# warnings | ||||
[] | ||||
] | ||||
Matt Mackall
|
r10281 | checks = [ | ||
('python', r'.*\.(py|cgi)$', pyfilters, pypats), | ||||
('test script', r'(.*/)?test-[^.~]*$', testfilters, testpats), | ||||
('c', r'.*\.c$', cfilters, cpats), | ||||
Matt Mackall
|
r12364 | ('unified test', r'.*\.t$', utestfilters, utestpats), | ||
timeless
|
r14137 | ('layering violation repo in revlog', r'mercurial/revlog\.py', pyfilters, | ||
inrevlogpats), | ||||
('layering violation ui in util', r'mercurial/util\.py', pyfilters, | ||||
inutilpats), | ||||
Matt Mackall
|
r10281 | ] | ||
Pierre-Yves David
|
r10719 | class norepeatlogger(object): | ||
def __init__(self): | ||||
self._lastseen = None | ||||
Matt Mackall
|
r11604 | def log(self, fname, lineno, line, msg, blame): | ||
Pierre-Yves David
|
r10719 | """print error related a to given line of a given file. | ||
The faulty line will also be printed but only once in the case | ||||
of multiple errors. | ||||
Matt Mackall
|
r10281 | |||
Pierre-Yves David
|
r10719 | :fname: filename | ||
:lineno: line number | ||||
:line: actual content of the line | ||||
:msg: error message | ||||
""" | ||||
msgid = fname, lineno, line | ||||
if msgid != self._lastseen: | ||||
Matt Mackall
|
r11604 | if blame: | ||
print "%s:%d (%s):" % (fname, lineno, blame) | ||||
else: | ||||
print "%s:%d:" % (fname, lineno) | ||||
Pierre-Yves David
|
r10719 | print " > %s" % line | ||
self._lastseen = msgid | ||||
print " " + msg | ||||
_defaultlogger = norepeatlogger() | ||||
Matt Mackall
|
r11604 | def getblame(f): | ||
lines = [] | ||||
for l in os.popen('hg annotate -un %s' % f): | ||||
start, line = l.split(':', 1) | ||||
user, rev = start.split() | ||||
lines.append((line[1:-1], user, rev)) | ||||
return lines | ||||
def checkfile(f, logfunc=_defaultlogger.log, maxerr=None, warnings=False, | ||||
timeless
|
r14135 | blame=False, debug=False): | ||
Pierre-Yves David
|
r10719 | """checks style and portability of a given file | ||
:f: filepath | ||||
:logfunc: function used to report error | ||||
logfunc(filename, linenumber, linecontent, errormessage) | ||||
:maxerr: number of error to display before arborting. | ||||
Set to None (default) to report all errors | ||||
Pierre-Yves David
|
r10720 | |||
return True if no error is found, False otherwise. | ||||
Pierre-Yves David
|
r10719 | """ | ||
Matt Mackall
|
r11604 | blamecache = None | ||
Pierre-Yves David
|
r10720 | result = True | ||
Matt Mackall
|
r10281 | for name, match, filters, pats in checks: | ||
timeless
|
r14135 | if debug: | ||
print name, f | ||||
Matt Mackall
|
r10281 | fc = 0 | ||
if not re.match(match, f): | ||||
timeless
|
r14135 | if debug: | ||
print "Skipping %s for %s it doesn't match %s" % ( | ||||
name, match, f) | ||||
Matt Mackall
|
r10281 | continue | ||
Dan Villiom Podlaski Christiansen
|
r13400 | fp = open(f) | ||
pre = post = fp.read() | ||||
fp.close() | ||||
Matt Mackall
|
r10287 | if "no-" + "check-code" in pre: | ||
timeless
|
r14135 | if debug: | ||
print "Skipping %s for %s it has no- and check-code" % ( | ||||
name, f) | ||||
Matt Mackall
|
r10287 | break | ||
Matt Mackall
|
r10281 | for p, r in filters: | ||
post = re.sub(p, r, post) | ||||
Idan Kamara
|
r14009 | if warnings: | ||
pats = pats[0] + pats[1] | ||||
else: | ||||
pats = pats[0] | ||||
Matt Mackall
|
r10281 | # print post # uncomment to show filtered version | ||
z = enumerate(zip(pre.splitlines(), post.splitlines(True))) | ||||
timeless
|
r14135 | if debug: | ||
print "Checking %s for %s" % (name, f) | ||||
Matt Mackall
|
r10281 | for n, l in z: | ||
Matt Mackall
|
r10287 | if "check-code" + "-ignore" in l[0]: | ||
timeless
|
r14135 | if debug: | ||
print "Skipping %s for %s:%s (check-code -ignore)" % ( | ||||
name, f, n) | ||||
Matt Mackall
|
r10287 | continue | ||
Matt Mackall
|
r10281 | for p, msg in pats: | ||
if re.search(p, l[1]): | ||||
Matt Mackall
|
r11604 | bd = "" | ||
if blame: | ||||
bd = 'working directory' | ||||
if not blamecache: | ||||
blamecache = getblame(f) | ||||
if n < len(blamecache): | ||||
bl, bu, br = blamecache[n] | ||||
if bl == l[0]: | ||||
bd = '%s@%s' % (bu, br) | ||||
logfunc(f, n + 1, l[0], msg, bd) | ||||
Matt Mackall
|
r10281 | fc += 1 | ||
Pierre-Yves David
|
r10720 | result = False | ||
Pierre-Yves David
|
r10718 | if maxerr is not None and fc >= maxerr: | ||
Matt Mackall
|
r10281 | print " (too many errors, giving up)" | ||
break | ||||
Pierre-Yves David
|
r10720 | return result | ||
Pierre-Yves David
|
r10717 | |||
Pierre-Yves David
|
r10716 | if __name__ == "__main__": | ||
Matt Mackall
|
r10895 | parser = optparse.OptionParser("%prog [options] [files]") | ||
parser.add_option("-w", "--warnings", action="store_true", | ||||
help="include warning-level checks") | ||||
parser.add_option("-p", "--per-file", type="int", | ||||
help="max warnings per file") | ||||
Matt Mackall
|
r11604 | parser.add_option("-b", "--blame", action="store_true", | ||
help="use annotate to generate blame info") | ||||
timeless
|
r14135 | parser.add_option("", "--debug", action="store_true", | ||
help="show debug information") | ||||
Matt Mackall
|
r10895 | |||
timeless
|
r14135 | parser.set_defaults(per_file=15, warnings=False, blame=False, debug=False) | ||
Matt Mackall
|
r10895 | (options, args) = parser.parse_args() | ||
if len(args) == 0: | ||||
Pierre-Yves David
|
r10716 | check = glob.glob("*") | ||
else: | ||||
Matt Mackall
|
r10895 | check = args | ||
Matt Mackall
|
r10281 | |||
Pierre-Yves David
|
r10716 | for f in check: | ||
Alecs King
|
r11816 | ret = 0 | ||
if not checkfile(f, maxerr=options.per_file, warnings=options.warnings, | ||||
timeless
|
r14135 | blame=options.blame, debug=options.debug): | ||
Alecs King
|
r11816 | ret = 1 | ||
sys.exit(ret) | ||||