check-code.py
546 lines
| 19.3 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 | ||
Simon Heimberg
|
r19310 | try: | ||
import re2 | ||||
except ImportError: | ||||
re2 = None | ||||
def compilere(pat, multiline=False): | ||||
if multiline: | ||||
pat = '(?m)' + pat | ||||
if re2: | ||||
try: | ||||
return re2.compile(pat) | ||||
except re2.error: | ||||
pass | ||||
return re.compile(pat) | ||||
Matt Mackall
|
r10281 | |||
def repquote(m): | ||||
Simon Heimberg
|
r19999 | fromc = '.:' | ||
tochr = 'pq' | ||||
def encodechr(i): | ||||
if i > 255: | ||||
return 'u' | ||||
c = chr(i) | ||||
if c in ' \n': | ||||
return c | ||||
if c.isalpha(): | ||||
return 'x' | ||||
if c.isdigit(): | ||||
return 'n' | ||||
try: | ||||
return tochr[fromc.find(c)] | ||||
except (ValueError, IndexError): | ||||
return 'o' | ||||
t = m.group('text') | ||||
tt = ''.join(encodechr(i) for i in xrange(256)) | ||||
t = t.translate(tt) | ||||
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: | ||||
Mads Kiilerich
|
r18959 | l = len(comment.rstrip()) | ||
return "#" * l + comment[l:] | ||||
Benoit Boissinot
|
r10727 | 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 | [ | ||
Mads Kiilerich
|
r16495 | (r'pushd|popd', "don't use 'pushd' or 'popd', use 'cd'"), | ||
Matt Mackall
|
r15281 | (r'\W\$?\(\([^\)\n]*\)\)', "don't use (()) or $(()), use 'expr'"), | ||
Martin Geisler
|
r10374 | (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"), | ||
Danek Duvall
|
r19626 | (r'(?<!hg )grep.*-a', "don't use 'grep -a', use in-line python"), | ||
Matt Mackall
|
r16332 | (r'sed.*-i', "don't use 'sed -i', use a temporary file"), | ||
Mads Kiilerich
|
r16965 | (r'\becho\b.*\\n', "don't use 'echo \\n', use printf"), | ||
Martin Geisler
|
r11884 | (r'echo -n', "don't use 'echo -n', use printf"), | ||
Matt Mackall
|
r15372 | (r'(^| )wc[^|]*$\n(?!.*\(re\))', "filter wc output"), | ||
Martin Geisler
|
r10374 | (r'head -c', "don't use 'head -c', use 'dd'"), | ||
Danek Duvall
|
r19628 | (r'tail -n', "don't use the '-n' option to tail, just use '-<num>'"), | ||
Matt Mackall
|
r15389 | (r'sha1sum', "don't use sha1sum, use $TESTDIR/md5sum.py"), | ||
Martin Geisler
|
r10374 | (r'ls.*-\w*R', "don't use 'ls -R', use 'find'"), | ||
Simon Heimberg
|
r19380 | (r'printf.*[^\\]\\([1-9]|0\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"), | ||||
Matt Mackall
|
r15372 | (r'(^|\|\s*)grep (-\w\s+)*[^|]*[(|]\w', | ||
Matt Mackall
|
r10281 | "use egrep for extended grep syntax"), | ||
(r'/bin/', "don't use explicit paths for tools"), | ||||
(r'[^\n]\Z', "no trailing newline"), | ||||
Mads Kiilerich
|
r10658 | (r'export.*=', "don't export and assign at once"), | ||
Matt Mackall
|
r15372 | (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"), | ||
Matt Mackall
|
r15364 | (r'ls +[^|\n-]+ +-', "options to 'ls' must come before filenames"), | ||
Matt Mackall
|
r15281 | (r'[^>\n]>\s*\$HGRCPATH', "don't overwrite $HGRCPATH, append to it"), | ||
Matt Mackall
|
r15372 | (r'^stop\(\)', "don't use 'stop' as a shell function name"), | ||
Mads Kiilerich
|
r15282 | (r'(\[|\btest\b).*-e ', "don't use 'test -e', use 'test -f'"), | ||
Mads Kiilerich
|
r16013 | (r'^alias\b.*=', "don't use alias, use a function"), | ||
Mads Kiilerich
|
r16485 | (r'if\s*!', "don't use '!' to negate exit status"), | ||
Mads Kiilerich
|
r16494 | (r'/dev/u?random', "don't use entropy, use /dev/zero"), | ||
Mads Kiilerich
|
r16496 | (r'do\s*true;\s*done', "don't use true as loop body, use sleep 0"), | ||
Mads Kiilerich
|
r16497 | (r'^( *)\t', "don't use tabs to indent"), | ||
Kevin Bullock
|
r19083 | (r'sed (-e )?\'(\d+|/[^/]*/)i(?!\\\n)', | ||
Kevin Bullock
|
r19080 | "put a backslash-escaped newline after sed 'i' command"), | ||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
Mads Kiilerich
|
r16672 | [ | ||
(r'^function', "don't use 'function', use old style"), | ||||
(r'^diff.*-\w*N', "don't use 'diff -N'"), | ||||
Mads Kiilerich
|
r18508 | (r'\$PWD|\${PWD}', "don't use $PWD, use `pwd`"), | ||
Mads Kiilerich
|
r16672 | (r'^([^"\'\n]|("[^"\n]*")|(\'[^\'\n]*\'))*\^', "^ must be quoted"), | ||
Kevin Bullock
|
r18575 | (r'kill (`|\$\()', "don't use kill, use killdaemons.py") | ||
Mads Kiilerich
|
r16672 | ] | ||
Matt Mackall
|
r10281 | ] | ||
testfilters = [ | ||||
(r"( *)(#([^\n]*\S)?)", repcomment), | ||||
(r"<<(\S+)((.|\n)*?\n\1)", rephere), | ||||
] | ||||
Simon Heimberg
|
r18832 | winglobmsg = "use (glob) to match Windows paths too" | ||
Matt Mackall
|
r15372 | uprefix = r"^ \$ " | ||
Matt Mackall
|
r12364 | utestpats = [ | ||
Idan Kamara
|
r14009 | [ | ||
Mads Kiilerich
|
r17347 | (r'^(\S.*|| [$>] .*)[ \t]\n', "trailing whitespace on non-output"), | ||
Mads Kiilerich
|
r16673 | (uprefix + r'.*\|\s*sed[^|>\n]*\n', | ||
"use regex test output patterns instead of sed"), | ||||
Matt Mackall
|
r12364 | (uprefix + r'(true|exit 0)', "explicit zero exit unnecessary"), | ||
Patrick Mezard
|
r15607 | (uprefix + r'.*(?<!\[)\$\?', "explicit exit code checks unnecessary"), | ||
Matt Mackall
|
r12364 | (uprefix + r'.*\|\| echo.*(fail|error)', | ||
"explicit exit code checks unnecessary"), | ||||
(uprefix + r'set -e', "don't use set -e"), | ||||
Mads Kiilerich
|
r19873 | (uprefix + r'(\s|fi\b|done\b)', "use > for continued lines"), | ||
Simon Heimberg
|
r18832 | (r'^ saved backup bundle to \$TESTTMP.*\.hg$', winglobmsg), | ||
Bryan O'Sullivan
|
r18835 | (r'^ changeset .* references (corrupted|missing) \$TESTTMP/.*[^)]$', | ||
winglobmsg), | ||||
Simon Heimberg
|
r18834 | (r'^ pulling from \$TESTTMP/.*[^)]$', winglobmsg, '\$TESTTMP/unix-repo$'), | ||
Matt Mackall
|
r19123 | (r'^ reverting .*/.*[^)]$', winglobmsg, '\$TESTTMP/unix-repo$'), | ||
(r'^ cloning subrepo \S+/.*[^)]$', winglobmsg, '\$TESTTMP/unix-repo$'), | ||||
(r'^ pushing to \$TESTTMP/.*[^)]$', winglobmsg, '\$TESTTMP/unix-repo$'), | ||||
Matt Mackall
|
r19168 | (r'^ pushing subrepo \S+/\S+ to.*[^)]$', winglobmsg, | ||
'\$TESTTMP/unix-repo$'), | ||||
Brendan Cully
|
r19133 | (r'^ moving \S+/.*[^)]$', winglobmsg), | ||
Matt Mackall
|
r19123 | (r'^ no changes made to subrepo since.*/.*[^)]$', | ||
winglobmsg, '\$TESTTMP/unix-repo$'), | ||||
(r'^ .*: largefile \S+ not available from file:.*/.*[^)]$', | ||||
winglobmsg, '\$TESTTMP/unix-repo$'), | ||||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
Simon Heimberg
|
r18683 | [ | ||
(r'^ [^*?/\n]* \(glob\)$', | ||||
Simon Heimberg
|
r19422 | "glob match with no glob character (?*/)"), | ||
Simon Heimberg
|
r18683 | ] | ||
Matt Mackall
|
r12364 | ] | ||
Mads Kiilerich
|
r14203 | for i in [0, 1]: | ||
for p, m in testpats[i]: | ||||
Matt Mackall
|
r15372 | if p.startswith(r'^'): | ||
Mads Kiilerich
|
r16672 | p = r"^ [$>] (%s)" % p[1:] | ||
Mads Kiilerich
|
r14203 | else: | ||
Mads Kiilerich
|
r16672 | p = r"^ [$>] .*(%s)" % p | ||
Mads Kiilerich
|
r14203 | utestpats[i].append((p, m)) | ||
Matt Mackall
|
r12364 | |||
utestfilters = [ | ||||
Idan Kamara
|
r17711 | (r"<<(\S+)((.|\n)*?\n > \1)", rephere), | ||
Matt Mackall
|
r12364 | (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+"), | ||||
Augie Fackler
|
r19793 | (r'import (.+,[^.]+\.[^.]+|[^.]+\.[^.]+,)', | ||
'2to3 can\'t always rewrite "import qux, foo.bar", ' | ||||
'use "import foo.bar" on its own line instead.'), | ||||
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+"), | ||
Augie Fackler
|
r18183 | (r'\s<>\s', '<> operator is not available in Python 3+, use !='), | ||
Matt Mackall
|
r10281 | (r'^\s*\t', "don't use tabs"), | ||
Matt Mackall
|
r10412 | (r'\S;\s*\n', "semicolon"), | ||
Matt Mackall
|
r16234 | (r'[^_]_\("[^"]+"\s*%', "don't use % inside _()"), | ||
(r"[^_]_\('[^']+'\s*%", "don't use % inside _()"), | ||||
Mads Kiilerich
|
r18054 | (r'(\w|\)),\w', "missing whitespace after ,"), | ||
(r'(\w|\))[+/*\-<>]\w', "missing whitespace in expression"), | ||||
Mads Kiilerich
|
r18055 | (r'^\s+(\w|\.)+=\w[^,()\n]*$', "missing whitespace in assignment"), | ||
Matt Mackall
|
r15372 | (r'(\s+)try:\n((?:\n|\1\s.*\n)+?)\1except.*?:\n' | ||
Mads Kiilerich
|
r17428 | r'((?:\n|\1\s.*\n)+?)\1finally:', 'no try/except/finally in Python 2.4'), | ||
Augie Fackler
|
r19501 | (r'(?<!def)(\s+|^|\()next\(.+\)', | ||
'no next(foo) in Python 2.4 and 2.5, use foo.next() instead'), | ||||
Thomas Arendsen Hein
|
r17620 | (r'(\s+)try:\n((?:\n|\1\s.*\n)*?)\1\s*yield\b.*?' | ||
r'((?:\n|\1\s.*\n)+?)\1finally:', | ||||
'no yield inside try/finally in Python 2.4'), | ||||
Brodie Rao
|
r16702 | (r'.{81}', "line too long"), | ||
Matt Mackall
|
r15372 | (r' x+[xo][\'"]\n\s+[\'"]x', 'string join across lines with no space'), | ||
Matt Mackall
|
r10281 | (r'[^\n]\Z', "no trailing newline"), | ||
Matt Mackall
|
r15281 | (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"), | ||
Brodie Rao
|
r16683 | # (r'^\s+[^_ \n][^_. \n]+_[^_\n]+\s*=', | ||
# "don't use underbars in identifiers"), | ||||
Matt Mackall
|
r15457 | (r'^\s+(self\.)?[A-za-z][a-z0-9]+[A-Z]\w* = ', | ||
"don't use camelcase in identifiers"), | ||||
Matt Mackall
|
r15281 | (r'^\s*(if|while|def|class|except|try)\s[^[\n]*:\s*[^\\n]#\s]+', | ||
Matt Mackall
|
r10286 | "linebreak after :"), | ||
Matt Mackall
|
r15281 | (r'class\s[^( \n]+:', "old-style class, use class foo(object)"), | ||
(r'class\s[^( \n]+\(\):', | ||||
Thomas Arendsen Hein
|
r14763 | "class foo() not available in Python 2.4, 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)\(', | ||
Augie Fackler
|
r14978 | "callable not available in Python 3, use getattr(f, '__call__', None)"), | ||
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
|
r15281 | (r'([\(\[][ \t]\S)|(\S[ \t][\)\]])', "gratuitous whitespace in () or []"), | ||
Matt Mackall
|
r10281 | # (r'\s\s=', "gratuitous whitespace before ="), | ||
Pierre-Yves David
|
r17167 | (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\S', | ||
Martin Geisler
|
r11345 | "missing whitespace around operator"), | ||
Pierre-Yves David
|
r17167 | (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\s', | ||
Martin Geisler
|
r11345 | "missing whitespace around operator"), | ||
Pierre-Yves David
|
r17167 | (r'\s(\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\S', | ||
Martin Geisler
|
r11345 | "missing whitespace around operator"), | ||
Pierre-Yves David
|
r17167 | (r'[^^+=*/!<>&| %-](\s=|=\s)[^= ]', | ||
Martin Geisler
|
r11345 | "wrong whitespace around ="), | ||
Mads Kiilerich
|
r19872 | (r'\([^()]*( =[^=]|[^<>!=]= )', | ||
"no whitespace around = for named parameters"), | ||||
Matt Mackall
|
r10451 | (r'raise Exception', "don't raise generic exceptions"), | ||
Augie Fackler
|
r18180 | (r'raise [^,(]+, (\([^\)]+\)|[^,\(\)]+)$', | ||
"don't use old-style two-argument raise, use Exception(message)"), | ||||
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"), | ||||
Patrick Mezard
|
r16416 | (r'(?:(?<!def)\s+|\()hasattr', | ||
Augie Fackler
|
r14978 | 'hasattr(foo, bar) is broken, use util.safehasattr(foo, bar) instead'), | ||
Dan Villiom Podlaski Christiansen
|
r14169 | (r'opener\([^)]*\).read\(', | ||
"use opener.read() instead"), | ||||
Mads Kiilerich
|
r17428 | (r'BaseException', 'not in Python 2.4, use Exception'), | ||
(r'os\.path\.relpath', 'os.path.relpath is not in Python 2.5'), | ||||
Dan Villiom Podlaski Christiansen
|
r14169 | (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"), | ||||
Matt Mackall
|
r14549 | (r'(?i)descendent', "the proper spelling is descendAnt"), | ||
Matt Mackall
|
r14709 | (r'\.debug\(\_', "don't mark debug messages for translation"), | ||
Martin Geisler
|
r16590 | (r'\.strip\(\)\.split\(\)', "no need to strip before splitting"), | ||
Simon Heimberg
|
r18762 | (r'^\s*except\s*:', "naked except clause", r'#.*re-raises'), | ||
Mads Kiilerich
|
r17299 | (r':\n( )*( ){1,3}[^ ]', "must indent 4 spaces"), | ||
Matt Mackall
|
r17957 | (r'ui\.(status|progress|write|note|warn)\([\'\"]x', | ||
"missing _() in ui message (use () to hide false-positives)"), | ||||
Matt Mackall
|
r19031 | (r'release\(.*wlock, .*lock\)', "wrong lock release order"), | ||
Idan Kamara
|
r14009 | ], | ||
# warnings | ||||
[ | ||||
Simon Heimberg
|
r19999 | (r'(^| )pp +xxxxqq[ \n][^\n]', "add two newlines after '.. note::'"), | ||
Idan Kamara
|
r14009 | ] | ||
Matt Mackall
|
r10281 | ] | ||
pyfilters = [ | ||||
Benoit Boissinot
|
r10727 | (r"""(?msx)(?P<comment>\#.*?$)| | ||
((?P<quote>('''|\"\"\"|(?<!')'(?!')|(?<!")"(?!"))) | ||||
(?P<text>(([^\\]|\\.)*?)) | ||||
(?P=quote))""", reppython), | ||||
Matt Mackall
|
r10281 | ] | ||
Mads Kiilerich
|
r18960 | txtfilters = [] | ||
txtpats = [ | ||||
[ | ||||
('\s$', 'trailing whitespace'), | ||||
], | ||||
[] | ||||
] | ||||
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"), | ||||
Matt Mackall
|
r15281 | (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"), | ||
Brodie Rao
|
r16702 | (r'.{81}', "line too long"), | ||
Matt Mackall
|
r10281 | (r'(while|if|do|for)\(', "use space after while/if/do/for"), | ||
(r'return\(', "return is not a function"), | ||||
(r' ;', "no space before ;"), | ||||
Matt Mackall
|
r19745 | (r'[)][{]', "space between ) and {"), | ||
Matt Mackall
|
r10281 | (r'\w+\* \w+', "use int *foo, not int* foo"), | ||
Matt Mackall
|
r19731 | (r'\W\([^\)]+\) \w+', "use (int)foo, not (int) foo"), | ||
Matt Mackall
|
r16413 | (r'\w+ (\+\+|--)', "use foo++, not foo ++"), | ||
Matt Mackall
|
r10281 | (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), | ||||
Matt Mackall
|
r19732 | ('c', r'.*\.[ch]$', 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), | ||||
Mads Kiilerich
|
r18960 | ('txt', r'.*\.txt$', txtfilters, txtpats), | ||
Matt Mackall
|
r10281 | ] | ||
Simon Heimberg
|
r19307 | def _preparepats(): | ||
for c in checks: | ||||
failandwarn = c[-1] | ||||
for pats in failandwarn: | ||||
for i, pseq in enumerate(pats): | ||||
# fix-up regexes for multi-line searches | ||||
Simon Heimberg
|
r19378 | p = pseq[0] | ||
Simon Heimberg
|
r19307 | # \s doesn't match \n | ||
p = re.sub(r'(?<!\\)\\s', r'[ \\t]', p) | ||||
# [^...] doesn't match newline | ||||
p = re.sub(r'(?<!\\)\[\^', r'[^\\n', p) | ||||
Simon Heimberg
|
r19308 | pats[i] = (re.compile(p, re.MULTILINE),) + pseq[1:] | ||
Simon Heimberg
|
r19309 | filters = c[2] | ||
for i, flt in enumerate(filters): | ||||
filters[i] = re.compile(flt[0]), flt[1] | ||||
Simon Heimberg
|
r19307 | _preparepats() | ||
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, | ||||
Mads Kiilerich
|
r15502 | blame=False, debug=False, lineno=True): | ||
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) | ||||
Mads Kiilerich
|
r17424 | :maxerr: number of error to display before aborting. | ||
Mads Kiilerich
|
r15873 | Set to false (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 | ||
Simon Heimberg
|
r19494 | try: | ||
fp = open(f) | ||||
except IOError, e: | ||||
print "Skipping %s, %s" % (f, str(e).split(':', 1)[0]) | ||||
continue | ||||
Dan Villiom Podlaski Christiansen
|
r13400 | pre = post = fp.read() | ||
fp.close() | ||||
Simon Heimberg
|
r19382 | if "no-" "check-code" in pre: | ||
timeless
|
r14135 | if debug: | ||
Mads Kiilerich
|
r19965 | print "Skipping %s for %s it has no-" "check-code" % ( | ||
timeless
|
r14135 | name, f) | ||
Matt Mackall
|
r10287 | break | ||
Matt Mackall
|
r10281 | for p, r in filters: | ||
post = re.sub(p, r, post) | ||||
Simon Heimberg
|
r19422 | nerrs = len(pats[0]) # nerr elements are errors | ||
Idan Kamara
|
r14009 | if warnings: | ||
pats = pats[0] + pats[1] | ||||
else: | ||||
pats = pats[0] | ||||
Matt Mackall
|
r10281 | # print post # uncomment to show filtered version | ||
Matt Mackall
|
r15281 | |||
timeless
|
r14135 | if debug: | ||
print "Checking %s for %s" % (name, f) | ||||
Matt Mackall
|
r15281 | |||
prelines = None | ||||
errors = [] | ||||
Simon Heimberg
|
r19422 | for i, pat in enumerate(pats): | ||
Brodie Rao
|
r16705 | if len(pat) == 3: | ||
p, msg, ignore = pat | ||||
else: | ||||
p, msg = pat | ||||
ignore = None | ||||
Matt Mackall
|
r15281 | pos = 0 | ||
n = 0 | ||||
Simon Heimberg
|
r19308 | for m in p.finditer(post): | ||
Matt Mackall
|
r15281 | if prelines is None: | ||
prelines = pre.splitlines() | ||||
postlines = post.splitlines(True) | ||||
start = m.start() | ||||
while n < len(postlines): | ||||
step = len(postlines[n]) | ||||
if pos + step > start: | ||||
break | ||||
pos += step | ||||
n += 1 | ||||
l = prelines[n] | ||||
Simon Heimberg
|
r19382 | if "check-code" "-ignore" in l: | ||
Matt Mackall
|
r15281 | if debug: | ||
Simon Heimberg
|
r19382 | print "Skipping %s for %s:%s (check-code" "-ignore)" % ( | ||
Matt Mackall
|
r15281 | name, f, n) | ||
continue | ||||
Brodie Rao
|
r16705 | elif ignore and re.search(ignore, l, re.MULTILINE): | ||
continue | ||||
Matt Mackall
|
r15281 | bd = "" | ||
if blame: | ||||
bd = 'working directory' | ||||
if not blamecache: | ||||
blamecache = getblame(f) | ||||
if n < len(blamecache): | ||||
bl, bu, br = blamecache[n] | ||||
if bl == l: | ||||
bd = '%s@%s' % (bu, br) | ||||
Simon Heimberg
|
r19422 | if i >= nerrs: | ||
msg = "warning: " + msg | ||||
Mads Kiilerich
|
r15502 | errors.append((f, lineno and n + 1, l, msg, bd)) | ||
Matt Mackall
|
r15281 | result = False | ||
errors.sort() | ||||
for e in errors: | ||||
logfunc(*e) | ||||
fc += 1 | ||||
Mads Kiilerich
|
r15873 | if maxerr and fc >= maxerr: | ||
Matt Mackall
|
r10281 | print " (too many errors, giving up)" | ||
break | ||||
Matt Mackall
|
r15281 | |||
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") | ||||
Mads Kiilerich
|
r15502 | parser.add_option("", "--nolineno", action="store_false", | ||
dest='lineno', help="don't show line numbers") | ||||
Matt Mackall
|
r10895 | |||
Mads Kiilerich
|
r15502 | parser.set_defaults(per_file=15, warnings=False, blame=False, debug=False, | ||
lineno=True) | ||||
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 | |||
Mads Kiilerich
|
r15544 | ret = 0 | ||
Pierre-Yves David
|
r10716 | for f in check: | ||
Alecs King
|
r11816 | if not checkfile(f, maxerr=options.per_file, warnings=options.warnings, | ||
Mads Kiilerich
|
r15502 | blame=options.blame, debug=options.debug, | ||
lineno=options.lineno): | ||||
Alecs King
|
r11816 | ret = 1 | ||
sys.exit(ret) | ||||