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