]> git.lizzy.rs Git - rust.git/blob - util/update_lints.py
Include error message in tests
[rust.git] / util / update_lints.py
1 #!/usr/bin/env python
2 # Generate a Markdown table of all lints, and put it in README.md.
3 # With -n option, only print the new table to stdout.
4 # With -c option, print a warning and set exit status to 1 if a file would be changed.
5
6 import os
7 import re
8 import sys
9
10 declare_lint_re = re.compile(r'''
11     declare_lint! \s* [{(] \s*
12     pub \s+ (?P<name>[A-Z_]+) \s*,\s*
13     (?P<level>Forbid|Deny|Warn|Allow) \s*,\s*
14     " (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
15 ''', re.X | re.S)
16
17 nl_escape_re = re.compile(r'\\\n\s*')
18
19 wiki_link = 'https://github.com/Manishearth/rust-clippy/wiki'
20
21 def collect(lints, fn):
22     """Collect all lints from a file.
23
24     Adds entries to the lints list as `(module, name, level, desc)`.
25     """
26     with open(fn) as fp:
27         code = fp.read()
28     for match in declare_lint_re.finditer(code):
29         # remove \-newline escapes from description string
30         desc = nl_escape_re.sub('', match.group('desc'))
31         lints.append((os.path.splitext(os.path.basename(fn))[0],
32                       match.group('name').lower(),
33                       match.group('level').lower(),
34                       desc.replace('\\"', '"')))
35
36
37 def gen_table(lints, link=None):
38     """Write lint table in Markdown format."""
39     if link:
40         lints = [(p, '[%s](%s#%s)' % (l, link, l), lvl, d)
41                  for (p, l, lvl, d) in lints]
42     # first and third column widths
43     w_name = max(len(l[1]) for l in lints)
44     w_desc = max(len(l[3]) for l in lints)
45     # header and underline
46     yield '%-*s | default | meaning\n' % (w_name, 'name')
47     yield '%s-|-%s-|-%s\n' % ('-' * w_name, '-' * 7, '-' * w_desc)
48     # one table row per lint
49     for (_, name, default, meaning) in sorted(lints, key=lambda l: l[1]):
50         yield '%-*s | %-7s | %s\n' % (w_name, name, default, meaning)
51
52
53 def gen_group(lints, levels=None):
54     """Write lint group (list of all lints in the form module::NAME)."""
55     if levels:
56         lints = [tup for tup in lints if tup[2] in levels]
57     for (module, name, _, _) in sorted(lints):
58         yield '        %s::%s,\n' % (module, name.upper())
59
60
61 def replace_region(fn, region_start, region_end, callback,
62                    replace_start=True, write_back=True):
63     """Replace a region in a file delimited by two lines matching regexes.
64
65     A callback is called to write the new region.  If `replace_start` is true,
66     the start delimiter line is replaced as well.  The end delimiter line is
67     never replaced.
68     """
69     # read current content
70     with open(fn) as fp:
71         lines = list(fp)
72
73     # replace old region with new region
74     new_lines = []
75     in_old_region = False
76     for line in lines:
77         if in_old_region:
78             if re.search(region_end, line):
79                 in_old_region = False
80                 new_lines.extend(callback())
81                 new_lines.append(line)
82         elif re.search(region_start, line):
83             if not replace_start:
84                 new_lines.append(line)
85             # old region starts here
86             in_old_region = True
87         else:
88             new_lines.append(line)
89
90     # write back to file
91     if write_back:
92         with open(fn, 'w') as fp:
93             fp.writelines(new_lines)
94
95     # if something changed, return true
96     return lines != new_lines
97
98
99 def main(print_only=False, check=False):
100     lints = []
101
102     # check directory
103     if not os.path.isfile('src/lib.rs'):
104         print('Error: call this script from clippy checkout directory!')
105         return
106
107     # collect all lints from source files
108     for root, dirs, files in os.walk('src'):
109         for fn in files:
110             if fn.endswith('.rs'):
111                 collect(lints, os.path.join(root, fn))
112
113     if print_only:
114         sys.stdout.writelines(gen_table(lints))
115         return
116
117     # replace table in README.md
118     changed = replace_region(
119         'README.md', r'^name +\|', '^$',
120         lambda: gen_table(lints, link=wiki_link),
121         write_back=not check)
122
123     changed |= replace_region(
124         'README.md',
125         r'^There are \d+ lints included in this crate:', "",
126         lambda: ['There are %d lints included in this crate:\n' % len(lints)],
127         write_back=not check)
128
129     # same for "clippy" lint collection
130     changed |= replace_region(
131         'src/lib.rs', r'reg.register_lint_group\("clippy"', r'\]\);',
132         lambda: gen_group(lints, levels=('warn', 'deny')),
133         replace_start=False, write_back=not check)
134
135     # same for "clippy_pedantic" lint collection
136     changed |= replace_region(
137         'src/lib.rs', r'reg.register_lint_group\("clippy_pedantic"', r'\]\);',
138         lambda: gen_group(lints, levels=('allow',)),
139         replace_start=False, write_back=not check)
140
141     if check and changed:
142         print('Please run util/update_lints.py to regenerate lints lists.')
143         return 1
144
145
146 if __name__ == '__main__':
147     sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))