1 # Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 # file at the top-level directory of this distribution and at
3 # http://rust-lang.org/COPYRIGHT.
5 # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 # option. This file may not be copied, modified, or distributed
9 # except according to those terms.
12 htmldocck.py is a custom checker script for Rustdoc HTML outputs.
16 The principle is simple: This script receives a path to generated HTML
17 documentation and a "template" script, which has a series of check
18 commands like `@has` or `@matches`. Each command can be used to check if
19 some pattern is present or not present in the particular file or in
20 the particular node of HTML tree. In many cases, the template script
21 happens to be a source code given to rustdoc.
23 While it indeed is possible to test in smaller portions, it has been
24 hard to construct tests in this fashion and major rendering errors were
25 discovered much later. This script is designed for making the black-box
26 and regression testing of Rustdoc easy. This does not preclude the needs
27 for unit testing, but can be used to complement related tests by quickly
28 showing the expected renderings.
30 In order to avoid one-off dependencies for this task, this script uses
31 a reasonably working HTML parser and the existing XPath implementation
32 from Python 2's standard library. Hopefully we won't render
37 Commands start with an `@` followed by a command name (letters and
38 hyphens), and zero or more arguments separated by one or more whitespace
39 and optionally delimited with single or double quotes. The `@` mark
40 cannot be preceded by a non-whitespace character. Other lines (including
41 every text up to the first `@`) are ignored, but it is recommended to
42 avoid the use of `@` in the template file.
44 There are a number of supported commands:
46 * `@has PATH` checks for the existence of given file.
48 `PATH` is relative to the output directory. It can be given as `-`
49 which repeats the most recently used `PATH`.
51 * `@has PATH PATTERN` and `@matches PATH PATTERN` checks for
52 the occurrence of given `PATTERN` in the given file. Only one
53 occurrence of given pattern is enough.
55 For `@has`, `PATTERN` is a whitespace-normalized (every consecutive
56 whitespace being replaced by one single space character) string.
57 The entire file is also whitespace-normalized including newlines.
59 For `@matches`, `PATTERN` is a Python-supported regular expression.
60 The file remains intact but the regexp is matched with no `MULTILINE`
61 and `IGNORECASE` option. You can still use a prefix `(?m)` or `(?i)`
62 to override them, and `\A` and `\Z` for definitely matching
63 the beginning and end of the file.
65 (The same distinction goes to other variants of these commands.)
67 * `@has PATH XPATH PATTERN` and `@matches PATH XPATH PATTERN` checks for
68 the presence of given `XPATH` in the given HTML file, and also
69 the occurrence of given `PATTERN` in the matching node or attribute.
70 Only one occurrence of given pattern in the match is enough.
72 `PATH` should be a valid and well-formed HTML file. It does *not*
73 accept arbitrary HTML5; it should have matching open and close tags
74 and correct entity references at least.
76 `XPATH` is an XPath expression to match. This is fairly limited:
77 `tag`, `*`, `.`, `//`, `..`, `[@attr]`, `[@attr='value']`, `[tag]`,
78 `[POS]` (element located in given `POS`), `[last()-POS]`, `text()`
79 and `@attr` (both as the last segment) are supported. Some examples:
81 - `//pre` or `.//pre` matches any element with a name `pre`.
82 - `//a[@href]` matches any element with an `href` attribute.
83 - `//*[@class="impl"]//code` matches any element with a name `code`,
84 which is an ancestor of some element which `class` attr is `impl`.
85 - `//h1[@class="fqn"]/span[1]/a[last()]/@class` matches a value of
86 `class` attribute in the last `a` element (can be followed by more
87 elements that are not `a`) inside the first `span` in the `h1` with
88 a class of `fqn`. Note that there cannot be no additional elements
89 between them due to the use of `/` instead of `//`.
91 Do not try to use non-absolute paths, it won't work due to the flawed
92 ElementTree implementation. The script rejects them.
94 For the text matches (i.e. paths not ending with `@attr`), any
95 subelements are flattened into one string; this is handy for ignoring
96 highlights for example. If you want to simply check the presence of
97 given node or attribute, use an empty string (`""`) as a `PATTERN`.
99 All conditions can be negated with `!`. `@!has foo/type.NoSuch.html`
100 checks if the given file does not exist, for example.
108 from collections import namedtuple
109 from HTMLParser import HTMLParser
110 from xml.etree import cElementTree as ET
112 # ⇤/⇥ are not in HTML 4 but are in HTML 5
113 from htmlentitydefs import entitydefs
114 entitydefs['larrb'] = u'\u21e4'
115 entitydefs['rarrb'] = u'\u21e5'
117 # "void elements" (no closing tag) from the HTML Standard section 12.1.2
118 VOID_ELEMENTS = set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
119 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'])
121 # simplified HTML parser.
122 # this is possible because we are dealing with very regular HTML from rustdoc;
123 # we only have to deal with i) void elements and ii) empty attributes.
124 class CustomHTMLParser(HTMLParser):
125 def __init__(self, target=None):
126 HTMLParser.__init__(self)
127 self.__builder = target or ET.TreeBuilder()
128 def handle_starttag(self, tag, attrs):
129 attrs = dict((k, v or '') for k, v in attrs)
130 self.__builder.start(tag, attrs)
131 if tag in VOID_ELEMENTS: self.__builder.end(tag)
132 def handle_endtag(self, tag):
133 self.__builder.end(tag)
134 def handle_startendtag(self, tag, attrs):
135 attrs = dict((k, v or '') for k, v in attrs)
136 self.__builder.start(tag, attrs)
137 self.__builder.end(tag)
138 def handle_data(self, data):
139 self.__builder.data(data)
140 def handle_entityref(self, name):
141 self.__builder.data(entitydefs[name])
142 def handle_charref(self, name):
143 code = int(name[1:], 16) if name.startswith(('x', 'X')) else int(name, 10)
144 self.__builder.data(unichr(code).encode('utf-8'))
146 HTMLParser.close(self)
147 return self.__builder.close()
149 Command = namedtuple('Command', 'negated cmd args lineno')
151 # returns a generator out of the file object, which
152 # - removes `\\` then `\n` then a shared prefix with the previous line then optional whitespace;
153 # - keeps a line number (starting from 0) of the first line being concatenated.
154 def concat_multi_lines(f):
155 lastline = None # set to the last line when the last line has a backslash
158 for lineno, line in enumerate(f):
159 line = line.rstrip('\r\n')
161 # strip the common prefix from the current line if needed
162 if lastline is not None:
164 for i in xrange(min(len(line), len(lastline))):
165 if line[i] != lastline[i]: break
167 line = line[maxprefix:].lstrip()
169 firstlineno = firstlineno or lineno
170 if line.endswith('\\'):
172 catenated += line[:-1]
174 yield firstlineno, catenated + line
179 if lastline is not None:
180 raise RuntimeError('Trailing backslash in the end of file')
182 LINE_PATTERN = re.compile(r'''
183 (?<=(?<!\S)@)(?P<negated>!?)
184 (?P<cmd>[A-Za-z]+(?:-[A-Za-z]+)*)
187 def get_commands(template):
188 with open(template, 'rUb') as f:
189 for lineno, line in concat_multi_lines(f):
190 m = LINE_PATTERN.search(line)
193 negated = (m.group('negated') == '!')
195 args = m.group('args')
196 if args and not args[:1].isspace():
197 raise RuntimeError('Invalid template syntax at line {}'.format(lineno+1))
198 args = shlex.split(args)
199 yield Command(negated=negated, cmd=cmd, args=args, lineno=lineno+1)
201 def _flatten(node, acc):
202 if node.text: acc.append(node.text)
205 if e.tail: acc.append(e.tail)
212 def normalize_xpath(path):
213 if path.startswith('//'):
214 return '.' + path # avoid warnings
215 elif path.startswith('.//'):
218 raise RuntimeError('Non-absolute XPath is not supported due to \
219 the implementation issue.')
221 class CachedFiles(object):
222 def __init__(self, root):
226 self.last_path = None
228 def resolve_path(self, path):
230 path = os.path.normpath(path)
231 self.last_path = path
233 elif self.last_path is None:
234 raise RuntimeError('Tried to use the previous path in the first command')
236 return self.last_path
238 def get_file(self, path):
239 path = self.resolve_path(path)
241 return self.files[path]
244 with open(os.path.join(self.root, path)) as f:
246 except Exception as e:
247 raise RuntimeError('Cannot open file {!r}: {}'.format(path, e))
249 self.files[path] = data
252 def get_tree(self, path):
253 path = self.resolve_path(path)
255 return self.trees[path]
258 f = open(os.path.join(self.root, path))
259 except Exception as e:
260 raise RuntimeError('Cannot open file {!r}: {}'.format(path, e))
263 tree = ET.parse(f, CustomHTMLParser())
264 except Exception as e:
265 raise RuntimeError('Cannot parse an HTML file {!r}: {}'.format(path, e))
267 self.trees[path] = tree
268 return self.trees[path]
270 def check_string(data, pat, regexp):
272 return True # special case a presence testing
274 return re.search(pat, data) is not None
276 data = ' '.join(data.split())
277 pat = ' '.join(pat.split())
280 def check_tree_attr(tree, path, attr, pat, regexp):
281 path = normalize_xpath(path)
283 for e in tree.findall(path):
285 value = e.attrib[attr]
289 ret = check_string(value, pat, regexp)
293 def check_tree_text(tree, path, pat, regexp):
294 path = normalize_xpath(path)
296 for e in tree.findall(path):
302 ret = check_string(value, pat, regexp)
306 def check(target, commands):
307 cache = CachedFiles(target)
309 if c.cmd == 'has' or c.cmd == 'matches': # string test
310 regexp = (c.cmd == 'matches')
311 if len(c.args) == 1 and not regexp: # @has <path> = file existence
313 cache.get_file(c.args[0])
317 elif len(c.args) == 2: # @has/matches <path> <pat> = string test
318 ret = check_string(cache.get_file(c.args[0]), c.args[1], regexp)
319 elif len(c.args) == 3: # @has/matches <path> <pat> <match> = XML tree test
320 tree = cache.get_tree(c.args[0])
321 pat, sep, attr = c.args[1].partition('/@')
323 ret = check_tree_attr(cache.get_tree(c.args[0]), pat, attr, c.args[2], regexp)
324 else: # normalized text
326 if pat.endswith('/text()'): pat = pat[:-7]
327 ret = check_tree_text(cache.get_tree(c.args[0]), pat, c.args[2], regexp)
329 raise RuntimeError('Invalid number of @{} arguments \
330 at line {}'.format(c.cmd, c.lineno))
332 elif c.cmd == 'valid-html':
333 raise RuntimeError('Unimplemented @valid-html at line {}'.format(c.lineno))
335 elif c.cmd == 'valid-links':
336 raise RuntimeError('Unimplemented @valid-links at line {}'.format(c.lineno))
339 raise RuntimeError('Unrecognized @{} at line {}'.format(c.cmd, c.lineno))
342 raise RuntimeError('@{}{} check failed at line {}'.format('!' if c.negated else '',
345 if __name__ == '__main__':
346 if len(sys.argv) < 3:
347 print >>sys.stderr, 'Usage: {} <doc dir> <template>'.format(sys.argv[0])
350 check(sys.argv[1], get_commands(sys.argv[2]))