blob: 0d08e7289c87516fcec01ebafdc9d7ef3922a65e [file] [log] [blame]
Georg Brandl9f7a3392009-01-03 20:30:15 +00001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# Check for stylistic and formal issues in .rst and .py
5# files included in the documentation.
6#
7# 01/2009, Georg Brandl
8
9from __future__ import with_statement
10
11import os
12import re
13import sys
14import getopt
15import subprocess
16from os.path import join, splitext, abspath, exists
17from collections import defaultdict
18
19directives = [
20 # standard docutils ones
21 'admonition', 'attention', 'caution', 'class', 'compound', 'container',
22 'contents', 'csv-table', 'danger', 'date', 'default-role', 'epigraph',
23 'error', 'figure', 'footer', 'header', 'highlights', 'hint', 'image',
24 'important', 'include', 'line-block', 'list-table', 'meta', 'note',
25 'parsed-literal', 'pull-quote', 'raw', 'replace',
26 'restructuredtext-test-directive', 'role', 'rubric', 'sectnum', 'sidebar',
27 'table', 'target-notes', 'tip', 'title', 'topic', 'unicode', 'warning',
28 # Sphinx custom ones
29 'acks', 'attribute', 'autoattribute', 'autoclass', 'autodata',
30 'autoexception', 'autofunction', 'automethod', 'automodule', 'centered',
31 'cfunction', 'class', 'classmethod', 'cmacro', 'cmdoption', 'cmember',
32 'code-block', 'confval', 'cssclass', 'ctype', 'currentmodule', 'cvar',
33 'data', 'deprecated', 'describe', 'directive', 'doctest', 'envvar', 'event',
34 'exception', 'function', 'glossary', 'highlight', 'highlightlang', 'index',
35 'literalinclude', 'method', 'module', 'moduleauthor', 'productionlist',
36 'program', 'role', 'sectionauthor', 'seealso', 'sourcecode', 'staticmethod',
37 'tabularcolumns', 'testcode', 'testoutput', 'testsetup', 'toctree', 'todo',
38 'todolist', 'versionadded', 'versionchanged'
39]
40
41all_directives = '(' + '|'.join(directives) + ')'
42seems_directive_re = re.compile(r'\.\. %s([^a-z:]|:(?!:))' % all_directives)
43
44leaked_markup_re = re.compile(r'[a-z]::[^=]|:[a-z]+:|`|\.\.\s*\w+:')
45
46
47checkers = {}
48
49checker_props = {'severity': 1, 'falsepositives': False}
50
51def checker(*suffixes, **kwds):
52 """Decorator to register a function as a checker."""
53 def deco(func):
54 for suffix in suffixes:
55 checkers.setdefault(suffix, []).append(func)
56 for prop in checker_props:
57 setattr(func, prop, kwds.get(prop, checker_props[prop]))
58 return func
59 return deco
60
61
62@checker('.py', severity=4)
63def check_syntax(fn, lines):
64 """Check Python examples for valid syntax."""
65 try:
66 code = ''.join(lines)
67 if '\r' in code:
68 yield 0, '\\r in code file'
69 code = code.replace('\r', '')
70 compile(code, fn, 'exec')
71 except SyntaxError, err:
72 yield err.lineno, 'not compilable: %s' % err
73
74
75@checker('.rst', severity=2)
76def check_suspicious_constructs(fn, lines):
77 """Check for suspicious reST constructs."""
78 for lno, line in enumerate(lines):
79 if seems_directive_re.match(line):
80 yield lno+1, 'comment seems to be intended as a directive'
81
82
83@checker('.py', '.rst')
84def check_whitespace(fn, lines):
85 """Check for whitespace and line length issues."""
86 lasti = 0
87 for lno, line in enumerate(lines):
88 if '\r' in line:
89 yield lno+1, '\\r in line'
90 if '\t' in line:
91 yield lno+1, 'OMG TABS!!!1'
92 if line[:-1].rstrip(' \t') != line[:-1]:
93 yield lno+1, 'trailing whitespace'
94 if len(line) > 86:
95 # don't complain about tables, links and function signatures
96 if line.lstrip()[0] not in '+|' and \
97 'http://' not in line and \
98 not line.lstrip().startswith(('.. function',
99 '.. method',
100 '.. cfunction')):
101 yield lno+1, "line too long"
102
103
104@checker('.html', severity=2, falsepositives=True)
105def check_leaked_markup(fn, lines):
106 """Check HTML files for leaked reST markup; this only works if
107 the HTML files have been built.
108 """
109 for lno, line in enumerate(lines):
110 if leaked_markup_re.search(line):
111 yield lno+1, 'possibly leaked markup: %r' % line
112
113
114def main(argv):
115 usage = '''\
116Usage: %s [-v] [-f] [-s sev] [-i path]* [path]
117
118Options: -v verbose (print all checked file names)
119 -f enable checkers that yield many false positives
120 -s sev only show problems with severity >= sev
121 -i path ignore subdir or file path
122''' % argv[0]
123 try:
124 gopts, args = getopt.getopt(argv[1:], 'vfs:i:')
125 except getopt.GetoptError:
126 print usage
127 return 2
128
129 verbose = False
130 severity = 1
131 ignore = []
132 falsepos = False
133 for opt, val in gopts:
134 if opt == '-v':
135 verbose = True
136 elif opt == '-f':
137 falsepos = True
138 elif opt == '-s':
139 severity = int(val)
140 elif opt == '-i':
141 ignore.append(abspath(val))
142
143 if len(args) == 0:
144 path = '.'
145 elif len(args) == 1:
146 path = args[0]
147 else:
148 print usage
149 return 2
150
151 if not exists(path):
152 print 'Error: path %s does not exist' % path
153 return 2
154
155 count = defaultdict(int)
156 out = sys.stdout
157
158 for root, dirs, files in os.walk(path):
159 # ignore subdirs controlled by svn
160 if '.svn' in dirs:
161 dirs.remove('.svn')
162
163 # ignore subdirs in ignore list
164 if abspath(root) in ignore:
165 del dirs[:]
166 continue
167
168 for fn in files:
169 fn = join(root, fn)
170 if fn[:2] == './':
171 fn = fn[2:]
172
173 # ignore files in ignore list
174 if abspath(fn) in ignore:
175 continue
176
177 ext = splitext(fn)[1]
178 checkerlist = checkers.get(ext, None)
179 if not checkerlist:
180 continue
181
182 if verbose:
183 print 'Checking %s...' % fn
184
185 try:
186 with open(fn, 'r') as f:
187 lines = list(f)
188 except (IOError, OSError), err:
189 print '%s: cannot open: %s' % (fn, err)
190 count[4] += 1
191 continue
192
193 for checker in checkerlist:
194 if checker.falsepositives and not falsepos:
195 continue
196 csev = checker.severity
197 if csev >= severity:
198 for lno, msg in checker(fn, lines):
199 print >>out, '[%d] %s:%d: %s' % (csev, fn, lno, msg)
200 count[csev] += 1
201 if verbose:
202 print
203 if not count:
204 if severity > 1:
205 print 'No problems with severity >= %d found.' % severity
206 else:
207 print 'No problems found.'
208 else:
209 for severity in sorted(count):
210 number = count[severity]
211 print '%d problem%s with severity %d found.' % \
212 (number, number > 1 and 's' or '', severity)
213 return int(bool(count))
214
215
216if __name__ == '__main__':
217 sys.exit(main(sys.argv))