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