Debian Codegraph @

contrib/check-code.py

raw
1 #!/usr/bin/env python3
2 #
3 # check-code - a style and portability checker for Mercurial
4 #
5 # Copyright 2010 Olivia Mackall <[email protected]>
6 #
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
9
10 """style and portability checker for Mercurial
11
12 when a rule triggers wrong, do one of the following (prefer one from top):
13 * do the work-around the rule suggests
14 * doublecheck that it is a false match
15 * improve the rule pattern
16 * add an ignore pattern to the rule (3rd arg) which matches your good line
17 (you can append a short comment and match this, like: #re-raises)
18 * change the pattern to a warning and list the exception in test-check-code-hg
19 * ONLY use no--check-code for skipping entire files from external sources
20 """
21
22 import glob
23 import keyword
24 import optparse
25 import os
26 import re
27 import sys
28
29 if sys.version_info[0] < 3:
30 opentext = open
31 else:
32
33 def opentext(f):
34 return open(f, encoding='latin1')
35
36
37 try:
38 xrange
39 except NameError:
40 xrange = range
41 try:
42 import re2
43 except ImportError:
44 re2 = None
45
46 import testparseutil
47
48
49 def compilere(pat, multiline=False):
50 if multiline:
51 pat = '(?m)' + pat
52 if re2:
53 try:
54 return re2.compile(pat)
55 except re2.error:
56 pass
57 return re.compile(pat)
58
59
60 # check "rules depending on implementation of repquote()" in each
61 # patterns (especially pypats), before changing around repquote()
62 _repquotefixedmap = {
63 ' ': ' ',
64 '\n': '\n',
65 '.': 'p',
66 ':': 'q',
67 '%': '%',
68 '\\': 'b',
69 '*': 'A',
70 '+': 'P',
71 '-': 'M',
72 }
73
74
75 def _repquoteencodechr(i):
76 if i > 255:
77 return 'u'
78 c = chr(i)
79 if c in _repquotefixedmap:
80 return _repquotefixedmap[c]
81 if c.isalpha():
82 return 'x'
83 if c.isdigit():
84 return 'n'
85 return 'o'
86
87
88 _repquotett = ''.join(_repquoteencodechr(i) for i in xrange(256))
89
90
91 def repquote(m):
92 t = m.group('text')
93 t = t.translate(_repquotett)
94 return m.group('quote') + t + m.group('quote')
95
96
97 def reppython(m):
98 comment = m.group('comment')
99 if comment:
100 l = len(comment.rstrip())
101 return "#" * l + comment[l:]
102 return repquote(m)
103
104
105 def repcomment(m):
106 return m.group(1) + "#" * len(m.group(2))
107
108
109 def repccomment(m):
110 t = re.sub(r"((?<=\n) )|\S", "x", m.group(2))
111 return m.group(1) + t + "*/"
112
113
114 def repcallspaces(m):
115 t = re.sub(r"\n\s+", "\n", m.group(2))
116 return m.group(1) + t
117
118
119 def repinclude(m):
120 return m.group(1) + "<foo>"
121
122
123 def rephere(m):
124 t = re.sub(r"\S", "x", m.group(2))
125 return m.group(1) + t
126
127
128 testpats = [
129 [
130 (r'\b(push|pop)d\b', "don't use 'pushd' or 'popd', use 'cd'"),
131 (r'\W\$?\(\([^\)\n]*\)\)', "don't use (()) or $(()), use 'expr'"),
132 (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"),
133 (r'(?<!hg )grep.* -a', "don't use 'grep -a', use in-line python"),
134 (r'sed.*-i', "don't use 'sed -i', use a temporary file"),
135 (r'\becho\b.*\\n', "don't use 'echo \\n', use printf"),
136 (r'echo -n', "don't use 'echo -n', use printf"),
137 (
138 r'(^|\|\s*)\bwc\b[^|]*$\n(?!.*\(re\))',
139 r'use `f --line-count` or filter wc output (use "\s*42 (re)")',
140 ),
141 (r'head -c', "don't use 'head -c', use 'dd'"),
142 (r'tail -n', "don't use the '-n' option to tail, just use '-<num>'"),
143 (r'sha1sum', "don't use sha1sum, use $TESTDIR/md5sum.py"),
144 (r'\bls\b.*-\w*R', "don't use 'ls -R', use 'find'"),
145 (r'printf.*[^\\]\\([1-9]|0\d)', r"don't use 'printf \NNN', use Python"),
146 (r'printf.*[^\\]\\x', "don't use printf \\x, use Python"),
147 (r'rm -rf \*', "don't use naked rm -rf, target a directory"),
148 (
149 r'\[[^\]]+==',
150 '[ foo == bar ] is a bashism, use [ foo = bar ] instead',
151 ),
152 (r'(^|\|\s*)egrep', "use grep -E for extended grep syntax"),
153 (r'(^|\|\s*)fgrep', "use grep -F for fixed string grepping"),
154 (r'(^|\|\s*)e?grep .*\\S', "don't use \\S in regular expression"),
155 (r'(?<!!)/bin/', "don't use explicit paths for tools"),
156 (r'#!.*/bash', "don't use bash in shebang, use sh"),
157 (r'[^\n]\Z', "no trailing newline"),
158 (
159 r'\bexport[ \t]+[_a-zA-Z][_a-zA-Z0-9]*=',
160 "don't export and assign at once",
161 ),
162 (r'^source\b', "don't use 'source', use '.'"),
163 (r'touch -d', "don't use 'touch -d', use 'touch -t' instead"),
164 (r'\bls +[^|\n-]+ +-', "options to 'ls' must come before filenames"),
165 (r'[^>\n]>\s*\$HGRCPATH', "don't overwrite $HGRCPATH, append to it"),
166 (r'^stop\(\)', "don't use 'stop' as a shell function name"),
167 (r'(\[|\btest\b).*-e ', "don't use 'test -e', use 'test -f'"),
168 (r'\[\[\s+[^\]]*\]\]', "don't use '[[ ]]', use '[ ]'"),
169 (r'^alias\b.*=', "don't use alias, use a function"),
170 # Solaris sh can not negate exit status with '!'
171 (
172 r'if\s*!',
173 "don't use '!' to negate exit status (use `||` or if/else)",
174 ),
175 (r'/dev/u?random', "don't use entropy, use /dev/zero"),
176 (r'do\s*true;\s*done', "don't use true as loop body, use sleep 0"),
177 (
178 r'sed (-e )?\'(\d+|/[^/]*/)i(?!\\\n)',
179 "put a backslash-escaped newline after sed 'i' command",
180 ),
181 (r'^diff *-\w*[uU].*$\n(^ \$ |^$)', "prefix diff -u/-U with cmp"),
182 (r'^\s+(if)? diff *-\w*[uU]', "prefix diff -u/-U with cmp"),
183 (r'[\s="`\']python\s(?!bindings)', "don't use 'python', use '$PYTHON'"),
184 (r'seq ', "don't use 'seq', use $TESTDIR/seq.py"),
185 (r'\butil\.Abort\b', "directly use error.Abort"),
186 (r'\|&', "don't use |&, use 2>&1"),
187 (r'\w = +\w', "only one space after = allowed"),
188 (
189 r'\bsed\b.*[^\\]\\n',
190 "don't use 'sed ... \\n', use a \\ and a newline",
191 ),
192 (r'env.*-u', "don't use 'env -u VAR', use 'unset VAR'"),
193 (r'cp.* -r ', "don't use 'cp -r', use 'cp -R'"),
194 (r'grep.* -[ABC]', "don't use grep's context flags"),
195 (
196 r'find.*-printf',
197 "don't use 'find -printf', it doesn't exist on BSD find(1)",
198 ),
199 (r'\$RANDOM ', "don't use bash-only $RANDOM to generate random values"),
200 ],
201 # warnings
202 [
203 (r'^function', "don't use 'function', use old style"),
204 (r'^diff.*-\w*N', "don't use 'diff -N'"),
205 (r'\$PWD|\${PWD}', "don't use $PWD, use `pwd`", "no-pwd-check"),
206 (r'^([^"\'\n]|("[^"\n]*")|(\'[^\'\n]*\'))*\^', "^ must be quoted"),
207 (r'kill (`|\$\()', "don't use kill, use killdaemons.py"),
208 ],
209 ]
210
211 testfilters = [
212 (r"( *)(#([^!][^\n]*\S)?)", repcomment),
213 (r"<<(\S+)((.|\n)*?\n\1)", rephere),
214 ]
215
216 uprefix = r"^ \$ "
217 utestpats = [
218 [
219 (r'^(\S.*|| [$>] \S.*)[ \t]\n', "trailing whitespace on non-output"),
220 (
221 uprefix + r'.*\|\s*sed[^|>\n]*\n',
222 "use regex test output patterns instead of sed",
223 ),
224 (uprefix + r'(true|exit 0)', "explicit zero exit unnecessary"),
225 (
226 uprefix + r'.*\|\| echo.*(fail|error)',
227 "explicit exit code checks unnecessary",
228 ),
229 (uprefix + r'set -e', "don't use set -e"),
230 (uprefix + r'(\s|fi\b|done\b)', "use > for continued lines"),
231 (
232 uprefix + r'.*:\.\S*/',
233 "x:.y in a path does not work on msys, rewrite "
234 "as x://.y, or see `hg log -k msys` for alternatives",
235 r'-\S+:\.|' '# no-msys', # -Rxxx
236 ), # in test-pull.t which is skipped on windows
237 (
238 r'^ [^$>].*27\.0\.0\.1',
239 'use $LOCALIP not an explicit loopback address',
240 ),
241 (
242 r'^ (?![>$] ).*\$LOCALIP.*[^)]$',
243 'mark $LOCALIP output lines with (glob) to help tests in BSD jails',
244 ),
245 (
246 r'^ (cat|find): .*: \$ENOENT\$',
247 'use test -f to test for file existence',
248 ),
249 (
250 r'^ diff -[^ -]*p',
251 "don't use (external) diff with -p for portability",
252 ),
253 (r' readlink ', 'use readlink.py instead of readlink'),
254 (
255 r'^ [-+][-+][-+] .* [-+]0000 \(glob\)',
256 "glob timezone field in diff output for portability",
257 ),
258 (
259 r'^ @@ -[0-9]+ [+][0-9]+,[0-9]+ @@',
260 "use '@@ -N* +N,n @@ (glob)' style chunk header for portability",
261 ),
262 (
263 r'^ @@ -[0-9]+,[0-9]+ [+][0-9]+ @@',
264 "use '@@ -N,n +N* @@ (glob)' style chunk header for portability",
265 ),
266 (
267 r'^ @@ -[0-9]+ [+][0-9]+ @@',
268 "use '@@ -N* +N* @@ (glob)' style chunk header for portability",
269 ),
270 (
271 uprefix + r'hg( +-[^ ]+( +[^ ]+)?)* +extdiff'
272 r'( +(-[^ po-]+|--(?!program|option)[^ ]+|[^-][^ ]*))*$',
273 "use $RUNTESTDIR/pdiff via extdiff (or -o/-p for false-positives)",
274 ),
275 ],
276 # warnings
277 [
278 (
279 r'^ (?!.*\$LOCALIP)[^*?/\n]* \(glob\)$',
280 "glob match with no glob string (?, *, /, and $LOCALIP)",
281 ),
282 ],
283 ]
284
285 # transform plain test rules to unified test's
286 for i in [0, 1]:
287 for tp in testpats[i]:
288 p = tp[0]
289 m = tp[1]
290 if p.startswith('^'):
291 p = "^ [$>] (%s)" % p[1:]
292 else:
293 p = "^ [$>] .*(%s)" % p
294 utestpats[i].append((p, m) + tp[2:])
295
296 # don't transform the following rules:
297 # " > \t" and " \t" should be allowed in unified tests
298 testpats[0].append((r'^( *)\t', "don't use tabs to indent"))
299 utestpats[0].append((r'^( ?)\t', "don't use tabs to indent"))
300
301 utestfilters = [
302 (r"<<(\S+)((.|\n)*?\n > \1)", rephere),
303 (r"( +)(#([^!][^\n]*\S)?)", repcomment),
304 ]
305
306 # common patterns to check *.py
307 commonpypats = [
308 [
309 (r'\\$', 'Use () to wrap long lines in Python, not \\'),
310 (
311 r'^\s*def\s*\w+\s*\(.*,\s*\(',
312 "tuple parameter unpacking not available in Python 3+",
313 ),
314 (
315 r'lambda\s*\(.*,.*\)',
316 "tuple parameter unpacking not available in Python 3+",
317 ),
318 (r'(?<!def)\s+(cmp)\(', "cmp is not available in Python 3+"),
319 (r'(?<!\.)\breduce\s*\(.*', "reduce is not available in Python 3+"),
320 (
321 r'\bdict\(.*=',
322 'dict() is different in Py2 and 3 and is slower than {}',
323 'dict-from-generator',
324 ),
325 (r'\.has_key\b', "dict.has_key is not available in Python 3+"),
326 (r'\s<>\s', '<> operator is not available in Python 3+, use !='),
327 (r'^\s*\t', "don't use tabs"),
328 (r'\S;\s*\n', "semicolon"),
329 (r'[^_]_\([ \t\n]*(?:"[^"]+"[ \t\n+]*)+%', "don't use % inside _()"),
330 (r"[^_]_\([ \t\n]*(?:'[^']+'[ \t\n+]*)+%", "don't use % inside _()"),
331 (r'(\w|\)),\w', "missing whitespace after ,"),
332 (r'(\w|\))[+/*\-<>]\w', "missing whitespace in expression"),
333 (r'\w\s=\s\s+\w', "gratuitous whitespace after ="),
334 (
335 (
336 # a line ending with a colon, potentially with trailing comments
337 r':([ \t]*#[^\n]*)?\n'
338 # one that is not a pass and not only a comment
339 r'(?P<indent>[ \t]+)[^#][^\n]+\n'
340 # more lines at the same indent level
341 r'((?P=indent)[^\n]+\n)*'
342 # a pass at the same indent level, which is bogus
343 r'(?P=indent)pass[ \t\n#]'
344 ),
345 'omit superfluous pass',
346 ),
347 (r'[^\n]\Z', "no trailing newline"),
348 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
349 (
350 r'^\s*(if|while|def|class|except|try)\s[^[\n]*:\s*[^\\n]#\s]+',
351 "linebreak after :",
352 ),
353 (
354 r'\b(%s)\('
355 % '|'.join(k for k in keyword.kwlist if k not in ('print', 'exec')),
356 "Python keyword is not a function",
357 ),
358 # (r'class\s[A-Z][^\(]*\((?!Exception)',
359 # "don't capitalize non-exception classes"),
360 # (r'in range\(', "use xrange"),
361 # (r'^\s*print\s+', "avoid using print in core and extensions"),
362 (r'[\x80-\xff]', "non-ASCII character literal"),
363 (r'("\')\.format\(', "str.format() has no bytes counterpart, use %"),
364 (
365 r'([\(\[][ \t]\S)|(\S[ \t][\)\]])',
366 "gratuitous whitespace in () or []",
367 ),
368 # (r'\s\s=', "gratuitous whitespace before ="),
369 (
370 r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\S',
371 "missing whitespace around operator",
372 ),
373 (
374 r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\s',
375 "missing whitespace around operator",
376 ),
377 (
378 r'\s(\+=|-=|!=|<>|<=|>=|<<=|>>=|%=)\S',
379 "missing whitespace around operator",
380 ),
381 (r'[^^+=*/!<>&| %-:](\s=|=\s)[^= ]', "wrong whitespace around ="),
382 (
383 r'raise [^,(]+, (\([^\)]+\)|[^,\(\)]+)$',
384 "don't use old-style two-argument raise, use Exception(message)",
385 ),
386 (r' is\s+(not\s+)?["\'0-9-]', "object comparison with literal"),
387 (
388 r' [=!]=\s+(True|False|None)',
389 "comparison with singleton, use 'is' or 'is not' instead",
390 ),
391 (
392 r'^\s*(while|if) [01]:',
393 "use True/False for constant Boolean expression",
394 ),
395 (r'^\s*if False(:| +and)', 'Remove code instead of using `if False`'),
396 (r'opener\([^)]*\).read\(', "use opener.read() instead"),
397 (r'opener\([^)]*\).write\(', "use opener.write() instead"),
398 (r'(?i)descend[e]nt', "the proper spelling is descendAnt"),
399 (r'\.debug\(\_', "don't mark debug messages for translation"),
400 (r'\.strip\(\)\.split\(\)', "no need to strip before splitting"),
401 (r'^\s*except\s*:', "naked except clause", r'#.*re-raises'),
402 (
403 r'^\s*except\s([^\(,]+|\([^\)]+\))\s*,',
404 'legacy exception syntax; use "as" instead of ","',
405 ),
406 (r'release\(.*wlock, .*lock\)', "wrong lock release order"),
407 (
408 r'os\.path\.join\(.*, *(""|\'\')\)',
409 "use pathutil.normasprefix(path) instead of os.path.join(path, '')",
410 ),
411 (r'\s0[0-7]+\b', 'legacy octal syntax; use "0o" prefix instead of "0"'),
412 # XXX only catch mutable arguments on the first line of the definition
413 (r'def.*[( ]\w+=\{\}', "don't use mutable default arguments"),
414 (r'\butil\.Abort\b', "directly use error.Abort"),
415 (
416 r'^@(\w*\.)?cachefunc',
417 "module-level @cachefunc is risky, please avoid",
418 ),
419 (
420 r'^(from|import) mercurial\.(cext|pure|cffi)',
421 "use mercurial.policy.importmod instead",
422 ),
423 (r'\.next\(\)', "don't use .next(), use next(...)"),
424 (
425 r'([a-z]*).revision\(\1\.node\(',
426 "don't convert rev to node before passing to revision(nodeorrev)",
427 ),
428 (r'platform\.system\(\)', "don't use platform.system(), use pycompat"),
429 ],
430 # warnings
431 [],
432 ]
433
434 # patterns to check normal *.py files
435 pypats = [
436 [
437 # Ideally, these should be placed in "commonpypats" for
438 # consistency of coding rules in Mercurial source tree.
439 # But on the other hand, these are not so seriously required for
440 # python code fragments embedded in test scripts. Fixing test
441 # scripts for these patterns requires many changes, and has less
442 # profit than effort.
443 (r'raise Exception', "don't raise generic exceptions"),
444 (r'[\s\(](open|file)\([^)]*\)\.read\(', "use util.readfile() instead"),
445 (
446 r'[\s\(](open|file)\([^)]*\)\.write\(',
447 "use util.writefile() instead",
448 ),
449 (
450 r'^[\s\(]*(open(er)?|file)\([^)]*\)(?!\.close\(\))',
451 "always assign an opened file to a variable, and close it afterwards",
452 ),
453 (
454 r'[\s\(](open|file)\([^)]*\)\.(?!close\(\))',
455 "always assign an opened file to a variable, and close it afterwards",
456 ),
457 (r':\n( )*( ){1,3}[^ ]', "must indent 4 spaces"),
458 (r'^import atexit', "don't use atexit, use ui.atexit"),
459 # rules depending on implementation of repquote()
460 (
461 r' x+[xpqo%APM][\'"]\n\s+[\'"]x',
462 'string join across lines with no space',
463 ),
464 (
465 r'''(?x)ui\.(status|progress|write|note|warn)\(
466 [ \t\n#]*
467 (?# any strings/comments might precede a string, which
468 # contains translatable message)
469 b?((['"]|\'\'\'|""")[ \npq%bAPMxno]*(['"]|\'\'\'|""")[ \t\n#]+)*
470 (?# sequence consisting of below might precede translatable message
471 # - formatting string: "% 10s", "%05d", "% -3.2f", "%*s", "%%" ...
472 # - escaped character: "\\", "\n", "\0" ...
473 # - character other than '%', 'b' as '\', and 'x' as alphabet)
474 (['"]|\'\'\'|""")
475 ((%([ n]?[PM]?([np]+|A))?x)|%%|b[bnx]|[ \nnpqAPMo])*x
476 (?# this regexp can't use [^...] style,
477 # because _preparepats forcibly adds "\n" into [^...],
478 # even though this regexp wants match it against "\n")''',
479 "missing _() in ui message (use `noi18n` method to hide false-positives)",
480 ),
481 ]
482 + commonpypats[0],
483 # warnings
484 [
485 # rules depending on implementation of repquote()
486 (r'(^| )pp +xxxxqq[ \n][^\n]', "add two newlines after '.. note::'"),
487 ]
488 + commonpypats[1],
489 ]
490
491 # patterns to check *.py for embedded ones in test script
492 embeddedpypats = [
493 [] + commonpypats[0],
494 # warnings
495 [] + commonpypats[1],
496 ]
497
498 # common filters to convert *.py
499 commonpyfilters = [
500 (
501 r"""(?msx)(?P<comment>\#.*?$)|
502 ((?P<quote>('''|\"\"\"|(?<!')'(?!')|(?<!")"(?!")))
503 (?P<text>(([^\\]|\\.)*?))
504 (?P=quote))""",
505 reppython,
506 ),
507 ]
508
509 # pattern only for mercurial and extensions
510 core_py_pats = [
511 [
512 # Windows tend to get confused about capitalization of the drive letter
513 #
514 # see mercurial.windows.abspath for details
515 (
516 r'os\.path\.abspath',
517 "use util.abspath instead (windows)",
518 r'#.*re-exports',
519 ),
520 ],
521 # warnings
522 [],
523 ]
524
525 # filters to convert normal *.py files
526 pyfilters = [] + commonpyfilters
527
528 # non-filter patterns
529 pynfpats = [
530 [
531 (r'pycompat\.osname\s*[=!]=\s*[\'"]nt[\'"]', "use pycompat.iswindows"),
532 (r'pycompat\.osname\s*[=!]=\s*[\'"]posix[\'"]', "use pycompat.isposix"),
533 (
534 r'pycompat\.sysplatform\s*[!=]=\s*[\'"]darwin[\'"]',
535 "use pycompat.isdarwin",
536 ),
537 ],
538 # warnings
539 [],
540 ]
541
542 # filters to convert *.py for embedded ones in test script
543 embeddedpyfilters = [] + commonpyfilters
544
545 # extension non-filter patterns
546 pyextnfpats = [
547 [(r'^"""\n?[A-Z]', "don't capitalize docstring title")],
548 # warnings
549 [],
550 ]
551
552 txtfilters = []
553
554 txtpats = [
555 [
556 (r'\s$', 'trailing whitespace'),
557 ('.. note::[ \n][^\n]', 'add two newlines after note::'),
558 ],
559 [],
560 ]
561
562 cpats = [
563 [
564 (r'//', "don't use //-style comments"),
565 (r'\S\t', "don't use tabs except for indent"),
566 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
567 (r'(while|if|do|for)\(', "use space after while/if/do/for"),
568 (r'return\(', "return is not a function"),
569 (r' ;', "no space before ;"),
570 (r'[^;] \)', "no space before )"),
571 (r'[)][{]', "space between ) and {"),
572 (r'\w+\* \w+', "use int *foo, not int* foo"),
573 (r'\W\([^\)]+\) \w+', "use (int)foo, not (int) foo"),
574 (r'\w+ (\+\+|--)', "use foo++, not foo ++"),
575 (r'\w,\w', "missing whitespace after ,"),
576 (r'^[^#]\w[+/*]\w', "missing whitespace in expression"),
577 (r'\w\s=\s\s+\w', "gratuitous whitespace after ="),
578 (r'^#\s+\w', "use #foo, not # foo"),
579 (r'[^\n]\Z', "no trailing newline"),
580 (r'^\s*#import\b', "use only #include in standard C code"),
581 (r'strcpy\(', "don't use strcpy, use strlcpy or memcpy"),
582 (r'strcat\(', "don't use strcat"),
583 # rules depending on implementation of repquote()
584 ],
585 # warnings
586 [
587 # rules depending on implementation of repquote()
588 ],
589 ]
590
591 cfilters = [
592 (r'(/\*)(((\*(?!/))|[^*])*)\*/', repccomment),
593 (r'''(?P<quote>(?<!")")(?P<text>([^"]|\\")+)"(?!")''', repquote),
594 (r'''(#\s*include\s+<)([^>]+)>''', repinclude),
595 (r'(\()([^)]+\))', repcallspaces),
596 ]
597
598 inutilpats = [
599 [
600 (r'\bui\.', "don't use ui in util"),
601 ],
602 # warnings
603 [],
604 ]
605
606 inrevlogpats = [
607 [
608 (r'\brepo\.', "don't use repo in revlog"),
609 ],
610 # warnings
611 [],
612 ]
613
614 webtemplatefilters = []
615
616 webtemplatepats = [
617 [],
618 [
619 (
620 r'{desc(\|(?!websub|firstline)[^\|]*)+}',
621 'follow desc keyword with either firstline or websub',
622 ),
623 ],
624 ]
625
626 allfilesfilters = []
627
628 allfilespats = [
629 [
630 (
631 r'(http|https)://[a-zA-Z0-9./]*selenic.com/',
632 'use mercurial-scm.org domain URL',
633 ),
634 (
635 r'mercurial@selenic\.com',
636 'use mercurial-scm.org domain for mercurial ML address',
637 ),
638 (
639 r'mercurial-devel@selenic\.com',
640 'use mercurial-scm.org domain for mercurial-devel ML address',
641 ),
642 ],
643 # warnings
644 [],
645 ]
646
647 py3pats = [
648 [
649 (
650 r'os\.environ',
651 "use encoding.environ instead (py3)",
652 r'#.*re-exports',
653 ),
654 (r'os\.name', "use pycompat.osname instead (py3)"),
655 (r'os\.getcwd', "use encoding.getcwd instead (py3)", r'#.*re-exports'),
656 (r'os\.sep', "use pycompat.ossep instead (py3)"),
657 (r'os\.pathsep', "use pycompat.ospathsep instead (py3)"),
658 (r'os\.altsep', "use pycompat.osaltsep instead (py3)"),
659 (r'sys\.platform', "use pycompat.sysplatform instead (py3)"),
660 (r'getopt\.getopt', "use pycompat.getoptb instead (py3)"),
661 (r'os\.getenv', "use encoding.environ.get instead"),
662 (r'(?<!pycompat\.)xrange', "use pycompat.xrange instead (py3)"),
663 ],
664 # warnings
665 [],
666 ]
667
668 checks = [
669 ('python', r'.*\.(py|cgi)$', r'^#!.*python', pyfilters, pypats),
670 ('python', r'.*\.(py|cgi)$', r'^#!.*python', [], pynfpats),
671 ('python', r'.*hgext.*\.py$', '', [], pyextnfpats),
672 (
673 'python 3',
674 r'.*(hgext|mercurial)/(?!demandimport|policy|pycompat).*\.py',
675 '',
676 pyfilters,
677 py3pats,
678 ),
679 (
680 'core files',
681 r'.*(hgext|mercurial)/(?!demandimport|policy|pycompat).*\.py',
682 '',
683 pyfilters,
684 core_py_pats,
685 ),
686 ('test script', r'(.*/)?test-[^.~]*$', '', testfilters, testpats),
687 ('c', r'.*\.[ch]$', '', cfilters, cpats),
688 ('unified test', r'.*\.t$', '', utestfilters, utestpats),
689 (
690 'layering violation repo in revlog',
691 r'mercurial/revlog\.py',
692 '',
693 pyfilters,
694 inrevlogpats,
695 ),
696 (
697 'layering violation ui in util',
698 r'mercurial/util\.py',
699 '',
700 pyfilters,
701 inutilpats,
702 ),
703 ('txt', r'.*\.txt$', '', txtfilters, txtpats),
704 (
705 'web template',
706 r'mercurial/templates/.*\.tmpl',
707 '',
708 webtemplatefilters,
709 webtemplatepats,
710 ),
711 ('all except for .po', r'.*(?<!\.po)$', '', allfilesfilters, allfilespats),
712 ]
713
714 # (desc,
715 # func to pick up embedded code fragments,
716 # list of patterns to convert target files
717 # list of patterns to detect errors/warnings)
718 embeddedchecks = [
719 (
720 'embedded python',
721 testparseutil.pyembedded,
722 embeddedpyfilters,
723 embeddedpypats,
724 )
725 ]
726
727
728 def _preparepats():
729 def preparefailandwarn(failandwarn):
730 for pats in failandwarn:
731 for i, pseq in enumerate(pats):
732 # fix-up regexes for multi-line searches
733 p = pseq[0]
734 # \s doesn't match \n (done in two steps)
735 # first, we replace \s that appears in a set already
736 p = re.sub(r'\[\\s', r'[ \\t', p)
737 # now we replace other \s instances.
738 p = re.sub(r'(?<!(\\|\[))\\s', r'[ \\t]', p)
739 # [^...] doesn't match newline
740 p = re.sub(r'(?<!\\)\[\^', r'[^\\n', p)
741
742 pats[i] = (re.compile(p, re.MULTILINE),) + pseq[1:]
743
744 def preparefilters(filters):
745 for i, flt in enumerate(filters):
746 filters[i] = re.compile(flt[0]), flt[1]
747
748 for cs in (checks, embeddedchecks):
749 for c in cs:
750 failandwarn = c[-1]
751 preparefailandwarn(failandwarn)
752
753 filters = c[-2]
754 preparefilters(filters)
755
756
757 class norepeatlogger:
758 def __init__(self):
759 self._lastseen = None
760
761 def log(self, fname, lineno, line, msg, blame):
762 """print error related a to given line of a given file.
763
764 The faulty line will also be printed but only once in the case
765 of multiple errors.
766
767 :fname: filename
768 :lineno: line number
769 :line: actual content of the line
770 :msg: error message
771 """
772 msgid = fname, lineno, line
773 if msgid != self._lastseen:
774 if blame:
775 print("%s:%d (%s):" % (fname, lineno, blame))
776 else:
777 print("%s:%d:" % (fname, lineno))
778 print(" > %s" % line)
779 self._lastseen = msgid
780 print(" " + msg)
781
782
783 _defaultlogger = norepeatlogger()
784
785
786 def getblame(f):
787 lines = []
788 for l in os.popen('hg annotate -un %s' % f):
789 start, line = l.split(':', 1)
790 user, rev = start.split()
791 lines.append((line[1:-1], user, rev))
792 return lines
793
794
795 def checkfile(
796 f,
797 logfunc=_defaultlogger.log,
798 maxerr=None,
799 warnings=False,
800 blame=False,
801 debug=False,
802 lineno=True,
803 ):
804 """checks style and portability of a given file
805
806 :f: filepath
807 :logfunc: function used to report error
808 logfunc(filename, linenumber, linecontent, errormessage)
809 :maxerr: number of error to display before aborting.
810 Set to false (default) to report all errors
811
812 return True if no error is found, False otherwise.
813 """
814 result = True
815
816 try:
817 with opentext(f) as fp:
818 try:
819 pre = fp.read()
820 except UnicodeDecodeError as e:
821 print("%s while reading %s" % (e, f))
822 return result
823 except OSError as e:
824 print("Skipping %s, %s" % (f, str(e).split(':', 1)[0]))
825 return result
826
827 # context information shared while single checkfile() invocation
828 context = {'blamecache': None}
829
830 for name, match, magic, filters, pats in checks:
831 if debug:
832 print(name, f)
833 if not (re.match(match, f) or (magic and re.search(magic, pre))):
834 if debug:
835 print(
836 "Skipping %s for %s it doesn't match %s" % (name, match, f)
837 )
838 continue
839 if "no-" "check-code" in pre:
840 # If you're looking at this line, it's because a file has:
841 # no- check- code
842 # but the reason to output skipping is to make life for
843 # tests easier. So, instead of writing it with a normal
844 # spelling, we write it with the expected spelling from
845 # tests/test-check-code.t
846 print("Skipping %s it has no-che?k-code (glob)" % f)
847 return "Skip" # skip checking this file
848
849 fc = _checkfiledata(
850 name,
851 f,
852 pre,
853 filters,
854 pats,
855 context,
856 logfunc,
857 maxerr,
858 warnings,
859 blame,
860 debug,
861 lineno,
862 )
863 if fc:
864 result = False
865
866 if f.endswith('.t') and "no-" "check-code" not in pre:
867 if debug:
868 print("Checking embedded code in %s" % f)
869
870 prelines = pre.splitlines()
871 embeddederros = []
872 for name, embedded, filters, pats in embeddedchecks:
873 # "reset curmax at each repetition" treats maxerr as "max
874 # nubmer of errors in an actual file per entry of
875 # (embedded)checks"
876 curmaxerr = maxerr
877
878 for found in embedded(f, prelines, embeddederros):
879 filename, starts, ends, code = found
880 fc = _checkfiledata(
881 name,
882 f,
883 code,
884 filters,
885 pats,
886 context,
887 logfunc,
888 curmaxerr,
889 warnings,
890 blame,
891 debug,
892 lineno,
893 offset=starts - 1,
894 )
895 if fc:
896 result = False
897 if curmaxerr:
898 if fc >= curmaxerr:
899 break
900 curmaxerr -= fc
901
902 return result
903
904
905 def _checkfiledata(
906 name,
907 f,
908 filedata,
909 filters,
910 pats,
911 context,
912 logfunc,
913 maxerr,
914 warnings,
915 blame,
916 debug,
917 lineno,
918 offset=None,
919 ):
920 """Execute actual error check for file data
921
922 :name: of the checking category
923 :f: filepath
924 :filedata: content of a file
925 :filters: to be applied before checking
926 :pats: to detect errors
927 :context: a dict of information shared while single checkfile() invocation
928 Valid keys: 'blamecache'.
929 :logfunc: function used to report error
930 logfunc(filename, linenumber, linecontent, errormessage)
931 :maxerr: number of error to display before aborting, or False to
932 report all errors
933 :warnings: whether warning level checks should be applied
934 :blame: whether blame information should be displayed at error reporting
935 :debug: whether debug information should be displayed
936 :lineno: whether lineno should be displayed at error reporting
937 :offset: line number offset of 'filedata' in 'f' for checking
938 an embedded code fragment, or None (offset=0 is different
939 from offset=None)
940
941 returns number of detected errors.
942 """
943 blamecache = context['blamecache']
944 if offset is None:
945 lineoffset = 0
946 else:
947 lineoffset = offset
948
949 fc = 0
950 pre = post = filedata
951
952 if True: # TODO: get rid of this redundant 'if' block
953 for p, r in filters:
954 post = re.sub(p, r, post)
955 nerrs = len(pats[0]) # nerr elements are errors
956 if warnings:
957 pats = pats[0] + pats[1]
958 else:
959 pats = pats[0]
960 # print post # uncomment to show filtered version
961
962 if debug:
963 print("Checking %s for %s" % (name, f))
964
965 prelines = None
966 errors = []
967 for i, pat in enumerate(pats):
968 if len(pat) == 3:
969 p, msg, ignore = pat
970 else:
971 p, msg = pat
972 ignore = None
973 if i >= nerrs:
974 msg = "warning: " + msg
975
976 pos = 0
977 n = 0
978 for m in p.finditer(post):
979 if prelines is None:
980 prelines = pre.splitlines()
981 postlines = post.splitlines(True)
982
983 start = m.start()
984 while n < len(postlines):
985 step = len(postlines[n])
986 if pos + step > start:
987 break
988 pos += step
989 n += 1
990 l = prelines[n]
991
992 if ignore and re.search(ignore, l, re.MULTILINE):
993 if debug:
994 print(
995 "Skipping %s for %s:%s (ignore pattern)"
996 % (name, f, (n + lineoffset))
997 )
998 continue
999 bd = ""
1000 if blame:
1001 bd = 'working directory'
1002 if blamecache is None:
1003 blamecache = getblame(f)
1004 context['blamecache'] = blamecache
1005 if (n + lineoffset) < len(blamecache):
1006 bl, bu, br = blamecache[(n + lineoffset)]
1007 if offset is None and bl == l:
1008 bd = '%s@%s' % (bu, br)
1009 elif offset is not None and bl.endswith(l):
1010 # "offset is not None" means "checking
1011 # embedded code fragment". In this case,
1012 # "l" does not have information about the
1013 # beginning of an *original* line in the
1014 # file (e.g. ' > ').
1015 # Therefore, use "str.endswith()", and
1016 # show "maybe" for a little loose
1017 # examination.
1018 bd = '%s@%s, maybe' % (bu, br)
1019
1020 errors.append((f, lineno and (n + lineoffset + 1), l, msg, bd))
1021
1022 errors.sort()
1023 for e in errors:
1024 logfunc(*e)
1025 fc += 1
1026 if maxerr and fc >= maxerr:
1027 print(" (too many errors, giving up)")
1028 break
1029
1030 return fc
1031
1032
1033 def main():
1034 parser = optparse.OptionParser("%prog [options] [files | -]")
1035 parser.add_option(
1036 "-w",
1037 "--warnings",
1038 action="store_true",
1039 help="include warning-level checks",
1040 )
1041 parser.add_option(
1042 "-p", "--per-file", type="int", help="max warnings per file"
1043 )
1044 parser.add_option(
1045 "-b",
1046 "--blame",
1047 action="store_true",
1048 help="use annotate to generate blame info",
1049 )
1050 parser.add_option(
1051 "", "--debug", action="store_true", help="show debug information"
1052 )
1053 parser.add_option(
1054 "",
1055 "--nolineno",
1056 action="store_false",
1057 dest='lineno',
1058 help="don't show line numbers",
1059 )
1060
1061 parser.set_defaults(
1062 per_file=15, warnings=False, blame=False, debug=False, lineno=True
1063 )
1064 (options, args) = parser.parse_args()
1065
1066 if len(args) == 0:
1067 check = glob.glob("*")
1068 elif args == ['-']:
1069 # read file list from stdin
1070 check = sys.stdin.read().splitlines()
1071 else:
1072 check = args
1073
1074 _preparepats()
1075
1076 ret = 0
1077 for f in check:
1078 if not checkfile(
1079 f,
1080 maxerr=options.per_file,
1081 warnings=options.warnings,
1082 blame=options.blame,
1083 debug=options.debug,
1084 lineno=options.lineno,
1085 ):
1086 ret = 1
1087 return ret
1088
1089
1090 if __name__ == "__main__":
1091 sys.exit(main())