1 | n/a | """ |
---|
2 | n/a | Try to detect suspicious constructs, resembling markup |
---|
3 | n/a | that has leaked into the final output. |
---|
4 | n/a | |
---|
5 | n/a | Suspicious lines are reported in a comma-separated-file, |
---|
6 | n/a | ``suspicious.csv``, located in the output directory. |
---|
7 | n/a | |
---|
8 | n/a | The file is utf-8 encoded, and each line contains four fields: |
---|
9 | n/a | |
---|
10 | n/a | * document name (normalized) |
---|
11 | n/a | * line number in the source document |
---|
12 | n/a | * problematic text |
---|
13 | n/a | * complete line showing the problematic text in context |
---|
14 | n/a | |
---|
15 | n/a | It is common to find many false positives. To avoid reporting them |
---|
16 | n/a | again and again, they may be added to the ``ignored.csv`` file |
---|
17 | n/a | (located in the configuration directory). The file has the same |
---|
18 | n/a | format as ``suspicious.csv`` with a few differences: |
---|
19 | n/a | |
---|
20 | n/a | - each line defines a rule; if the rule matches, the issue |
---|
21 | n/a | is ignored. |
---|
22 | n/a | - line number may be empty (that is, nothing between the |
---|
23 | n/a | commas: ",,"). In this case, line numbers are ignored (the |
---|
24 | n/a | rule matches anywhere in the file). |
---|
25 | n/a | - the last field does not have to be a complete line; some |
---|
26 | n/a | surrounding text (never more than a line) is enough for |
---|
27 | n/a | context. |
---|
28 | n/a | |
---|
29 | n/a | Rules are processed sequentially. A rule matches when: |
---|
30 | n/a | |
---|
31 | n/a | * document names are the same |
---|
32 | n/a | * problematic texts are the same |
---|
33 | n/a | * line numbers are close to each other (5 lines up or down) |
---|
34 | n/a | * the rule text is completely contained into the source line |
---|
35 | n/a | |
---|
36 | n/a | The simplest way to create the ignored.csv file is by copying |
---|
37 | n/a | undesired entries from suspicious.csv (possibly trimming the last |
---|
38 | n/a | field.) |
---|
39 | n/a | |
---|
40 | n/a | Copyright 2009 Gabriel A. Genellina |
---|
41 | n/a | |
---|
42 | n/a | """ |
---|
43 | n/a | |
---|
44 | n/a | import os |
---|
45 | n/a | import re |
---|
46 | n/a | import csv |
---|
47 | n/a | import sys |
---|
48 | n/a | |
---|
49 | n/a | from docutils import nodes |
---|
50 | n/a | from sphinx.builders import Builder |
---|
51 | n/a | |
---|
52 | n/a | detect_all = re.compile(r''' |
---|
53 | n/a | ::(?=[^=])| # two :: (but NOT ::=) |
---|
54 | n/a | :[a-zA-Z][a-zA-Z0-9]+| # :foo |
---|
55 | n/a | `| # ` (seldom used by itself) |
---|
56 | n/a | (?<!\.)\.\.[ \t]*\w+: # .. foo: (but NOT ... else:) |
---|
57 | n/a | ''', re.UNICODE | re.VERBOSE).finditer |
---|
58 | n/a | |
---|
59 | n/a | py3 = sys.version_info >= (3, 0) |
---|
60 | n/a | |
---|
61 | n/a | |
---|
62 | n/a | class Rule: |
---|
63 | n/a | def __init__(self, docname, lineno, issue, line): |
---|
64 | n/a | """A rule for ignoring issues""" |
---|
65 | n/a | self.docname = docname # document to which this rule applies |
---|
66 | n/a | self.lineno = lineno # line number in the original source; |
---|
67 | n/a | # this rule matches only near that. |
---|
68 | n/a | # None -> don't care |
---|
69 | n/a | self.issue = issue # the markup fragment that triggered this rule |
---|
70 | n/a | self.line = line # text of the container element (single line only) |
---|
71 | n/a | self.used = False |
---|
72 | n/a | |
---|
73 | n/a | def __repr__(self): |
---|
74 | n/a | return '{0.docname},,{0.issue},{0.line}'.format(self) |
---|
75 | n/a | |
---|
76 | n/a | |
---|
77 | n/a | |
---|
78 | n/a | class dialect(csv.excel): |
---|
79 | n/a | """Our dialect: uses only linefeed as newline.""" |
---|
80 | n/a | lineterminator = '\n' |
---|
81 | n/a | |
---|
82 | n/a | |
---|
83 | n/a | class CheckSuspiciousMarkupBuilder(Builder): |
---|
84 | n/a | """ |
---|
85 | n/a | Checks for possibly invalid markup that may leak into the output. |
---|
86 | n/a | """ |
---|
87 | n/a | name = 'suspicious' |
---|
88 | n/a | |
---|
89 | n/a | def init(self): |
---|
90 | n/a | # create output file |
---|
91 | n/a | self.log_file_name = os.path.join(self.outdir, 'suspicious.csv') |
---|
92 | n/a | open(self.log_file_name, 'w').close() |
---|
93 | n/a | # load database of previously ignored issues |
---|
94 | n/a | self.load_rules(os.path.join(os.path.dirname(__file__), '..', |
---|
95 | n/a | 'susp-ignored.csv')) |
---|
96 | n/a | |
---|
97 | n/a | def get_outdated_docs(self): |
---|
98 | n/a | return self.env.found_docs |
---|
99 | n/a | |
---|
100 | n/a | def get_target_uri(self, docname, typ=None): |
---|
101 | n/a | return '' |
---|
102 | n/a | |
---|
103 | n/a | def prepare_writing(self, docnames): |
---|
104 | n/a | pass |
---|
105 | n/a | |
---|
106 | n/a | def write_doc(self, docname, doctree): |
---|
107 | n/a | # set when any issue is encountered in this document |
---|
108 | n/a | self.any_issue = False |
---|
109 | n/a | self.docname = docname |
---|
110 | n/a | visitor = SuspiciousVisitor(doctree, self) |
---|
111 | n/a | doctree.walk(visitor) |
---|
112 | n/a | |
---|
113 | n/a | def finish(self): |
---|
114 | n/a | unused_rules = [rule for rule in self.rules if not rule.used] |
---|
115 | n/a | if unused_rules: |
---|
116 | n/a | self.warn('Found %s/%s unused rules:' % |
---|
117 | n/a | (len(unused_rules), len(self.rules))) |
---|
118 | n/a | for rule in unused_rules: |
---|
119 | n/a | self.info(repr(rule)) |
---|
120 | n/a | return |
---|
121 | n/a | |
---|
122 | n/a | def check_issue(self, line, lineno, issue): |
---|
123 | n/a | if not self.is_ignored(line, lineno, issue): |
---|
124 | n/a | self.report_issue(line, lineno, issue) |
---|
125 | n/a | |
---|
126 | n/a | def is_ignored(self, line, lineno, issue): |
---|
127 | n/a | """Determine whether this issue should be ignored.""" |
---|
128 | n/a | docname = self.docname |
---|
129 | n/a | for rule in self.rules: |
---|
130 | n/a | if rule.docname != docname: continue |
---|
131 | n/a | if rule.issue != issue: continue |
---|
132 | n/a | # Both lines must match *exactly*. This is rather strict, |
---|
133 | n/a | # and probably should be improved. |
---|
134 | n/a | # Doing fuzzy matches with levenshtein distance could work, |
---|
135 | n/a | # but that means bringing other libraries... |
---|
136 | n/a | # Ok, relax that requirement: just check if the rule fragment |
---|
137 | n/a | # is contained in the document line |
---|
138 | n/a | if rule.line not in line: continue |
---|
139 | n/a | # Check both line numbers. If they're "near" |
---|
140 | n/a | # this rule matches. (lineno=None means "don't care") |
---|
141 | n/a | if (rule.lineno is not None) and \ |
---|
142 | n/a | abs(rule.lineno - lineno) > 5: continue |
---|
143 | n/a | # if it came this far, the rule matched |
---|
144 | n/a | rule.used = True |
---|
145 | n/a | return True |
---|
146 | n/a | return False |
---|
147 | n/a | |
---|
148 | n/a | def report_issue(self, text, lineno, issue): |
---|
149 | n/a | if not self.any_issue: self.info() |
---|
150 | n/a | self.any_issue = True |
---|
151 | n/a | self.write_log_entry(lineno, issue, text) |
---|
152 | n/a | if py3: |
---|
153 | n/a | self.warn('[%s:%d] "%s" found in "%-.120s"' % |
---|
154 | n/a | (self.docname, lineno, issue, text)) |
---|
155 | n/a | else: |
---|
156 | n/a | self.warn('[%s:%d] "%s" found in "%-.120s"' % ( |
---|
157 | n/a | self.docname.encode(sys.getdefaultencoding(),'replace'), |
---|
158 | n/a | lineno, |
---|
159 | n/a | issue.encode(sys.getdefaultencoding(),'replace'), |
---|
160 | n/a | text.strip().encode(sys.getdefaultencoding(),'replace'))) |
---|
161 | n/a | self.app.statuscode = 1 |
---|
162 | n/a | |
---|
163 | n/a | def write_log_entry(self, lineno, issue, text): |
---|
164 | n/a | if py3: |
---|
165 | n/a | f = open(self.log_file_name, 'a') |
---|
166 | n/a | writer = csv.writer(f, dialect) |
---|
167 | n/a | writer.writerow([self.docname, lineno, issue, text.strip()]) |
---|
168 | n/a | f.close() |
---|
169 | n/a | else: |
---|
170 | n/a | f = open(self.log_file_name, 'ab') |
---|
171 | n/a | writer = csv.writer(f, dialect) |
---|
172 | n/a | writer.writerow([self.docname.encode('utf-8'), |
---|
173 | n/a | lineno, |
---|
174 | n/a | issue.encode('utf-8'), |
---|
175 | n/a | text.strip().encode('utf-8')]) |
---|
176 | n/a | f.close() |
---|
177 | n/a | |
---|
178 | n/a | def load_rules(self, filename): |
---|
179 | n/a | """Load database of previously ignored issues. |
---|
180 | n/a | |
---|
181 | n/a | A csv file, with exactly the same format as suspicious.csv |
---|
182 | n/a | Fields: document name (normalized), line number, issue, surrounding text |
---|
183 | n/a | """ |
---|
184 | n/a | self.info("loading ignore rules... ", nonl=1) |
---|
185 | n/a | self.rules = rules = [] |
---|
186 | n/a | try: |
---|
187 | n/a | if py3: |
---|
188 | n/a | f = open(filename, 'r') |
---|
189 | n/a | else: |
---|
190 | n/a | f = open(filename, 'rb') |
---|
191 | n/a | except IOError: |
---|
192 | n/a | return |
---|
193 | n/a | for i, row in enumerate(csv.reader(f)): |
---|
194 | n/a | if len(row) != 4: |
---|
195 | n/a | raise ValueError( |
---|
196 | n/a | "wrong format in %s, line %d: %s" % (filename, i+1, row)) |
---|
197 | n/a | docname, lineno, issue, text = row |
---|
198 | n/a | if lineno: |
---|
199 | n/a | lineno = int(lineno) |
---|
200 | n/a | else: |
---|
201 | n/a | lineno = None |
---|
202 | n/a | if not py3: |
---|
203 | n/a | docname = docname.decode('utf-8') |
---|
204 | n/a | issue = issue.decode('utf-8') |
---|
205 | n/a | text = text.decode('utf-8') |
---|
206 | n/a | rule = Rule(docname, lineno, issue, text) |
---|
207 | n/a | rules.append(rule) |
---|
208 | n/a | f.close() |
---|
209 | n/a | self.info('done, %d rules loaded' % len(self.rules)) |
---|
210 | n/a | |
---|
211 | n/a | |
---|
212 | n/a | def get_lineno(node): |
---|
213 | n/a | """Obtain line number information for a node.""" |
---|
214 | n/a | lineno = None |
---|
215 | n/a | while lineno is None and node: |
---|
216 | n/a | node = node.parent |
---|
217 | n/a | lineno = node.line |
---|
218 | n/a | return lineno |
---|
219 | n/a | |
---|
220 | n/a | |
---|
221 | n/a | def extract_line(text, index): |
---|
222 | n/a | """text may be a multiline string; extract |
---|
223 | n/a | only the line containing the given character index. |
---|
224 | n/a | |
---|
225 | n/a | >>> extract_line("abc\ndefgh\ni", 6) |
---|
226 | n/a | >>> 'defgh' |
---|
227 | n/a | >>> for i in (0, 2, 3, 4, 10): |
---|
228 | n/a | ... print extract_line("abc\ndefgh\ni", i) |
---|
229 | n/a | abc |
---|
230 | n/a | abc |
---|
231 | n/a | abc |
---|
232 | n/a | defgh |
---|
233 | n/a | defgh |
---|
234 | n/a | i |
---|
235 | n/a | """ |
---|
236 | n/a | p = text.rfind('\n', 0, index) + 1 |
---|
237 | n/a | q = text.find('\n', index) |
---|
238 | n/a | if q < 0: |
---|
239 | n/a | q = len(text) |
---|
240 | n/a | return text[p:q] |
---|
241 | n/a | |
---|
242 | n/a | |
---|
243 | n/a | class SuspiciousVisitor(nodes.GenericNodeVisitor): |
---|
244 | n/a | |
---|
245 | n/a | lastlineno = 0 |
---|
246 | n/a | |
---|
247 | n/a | def __init__(self, document, builder): |
---|
248 | n/a | nodes.GenericNodeVisitor.__init__(self, document) |
---|
249 | n/a | self.builder = builder |
---|
250 | n/a | |
---|
251 | n/a | def default_visit(self, node): |
---|
252 | n/a | if isinstance(node, (nodes.Text, nodes.image)): # direct text containers |
---|
253 | n/a | text = node.astext() |
---|
254 | n/a | # lineno seems to go backwards sometimes (?) |
---|
255 | n/a | self.lastlineno = lineno = max(get_lineno(node) or 0, self.lastlineno) |
---|
256 | n/a | seen = set() # don't report the same issue more than only once per line |
---|
257 | n/a | for match in detect_all(text): |
---|
258 | n/a | issue = match.group() |
---|
259 | n/a | line = extract_line(text, match.start()) |
---|
260 | n/a | if (issue, line) not in seen: |
---|
261 | n/a | self.builder.check_issue(line, lineno, issue) |
---|
262 | n/a | seen.add((issue, line)) |
---|
263 | n/a | |
---|
264 | n/a | unknown_visit = default_visit |
---|
265 | n/a | |
---|
266 | n/a | def visit_document(self, node): |
---|
267 | n/a | self.lastlineno = 0 |
---|
268 | n/a | |
---|
269 | n/a | def visit_comment(self, node): |
---|
270 | n/a | # ignore comments -- too much false positives. |
---|
271 | n/a | # (although doing this could miss some errors; |
---|
272 | n/a | # there were two sections "commented-out" by mistake |
---|
273 | n/a | # in the Python docs that would not be caught) |
---|
274 | n/a | raise nodes.SkipNode |
---|