]> git.lizzy.rs Git - rust.git/blob - util/update_lints.py
Merge pull request #2007 from rust-lang-nursery/wiki
[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.VERBOSE | re.DOTALL)
17
18 declare_deprecated_lint_re = re.compile(r'''
19     declare_deprecated_lint! \s* [{(] \s*
20     pub \s+ (?P<name>[A-Z_][A-Z_0-9]*) \s*,\s*
21     " (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
22 ''', re.VERBOSE | re.DOTALL)
23
24 declare_restriction_lint_re = re.compile(r'''
25     declare_restriction_lint! \s* [{(] \s*
26     pub \s+ (?P<name>[A-Z_][A-Z_0-9]*) \s*,\s*
27     " (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
28 ''', re.VERBOSE | re.DOTALL)
29
30 nl_escape_re = re.compile(r'\\\n\s*')
31
32 docs_link = 'https://rust-lang-nursery.github.io/rust-clippy/master/index.html'
33
34
35 def collect(lints, deprecated_lints, restriction_lints, fn):
36     """Collect all lints from a file.
37
38     Adds entries to the lints list as `(module, name, level, desc)`.
39     """
40     with open(fn) as fp:
41         code = fp.read()
42     for match in declare_lint_re.finditer(code):
43         # remove \-newline escapes from description string
44         desc = nl_escape_re.sub('', match.group('desc'))
45         lints.append((os.path.splitext(os.path.basename(fn))[0],
46                       match.group('name').lower(),
47                       match.group('level').lower(),
48                       desc.replace('\\"', '"')))
49
50     for match in declare_deprecated_lint_re.finditer(code):
51         # remove \-newline escapes from description string
52         desc = nl_escape_re.sub('', match.group('desc'))
53         deprecated_lints.append((os.path.splitext(os.path.basename(fn))[0],
54                                 match.group('name').lower(),
55                                 desc.replace('\\"', '"')))
56
57     for match in declare_restriction_lint_re.finditer(code):
58         # remove \-newline escapes from description string
59         desc = nl_escape_re.sub('', match.group('desc'))
60         restriction_lints.append((os.path.splitext(os.path.basename(fn))[0],
61                                   match.group('name').lower(),
62                                   "allow",
63                                   desc.replace('\\"', '"')))
64
65
66 def gen_group(lints, levels=None):
67     """Write lint group (list of all lints in the form module::NAME)."""
68     if levels:
69         lints = [tup for tup in lints if tup[2] in levels]
70     for (module, name, _, _) in sorted(lints):
71         yield '        %s::%s,\n' % (module, name.upper())
72
73
74 def gen_mods(lints):
75     """Declare modules"""
76
77     for module in sorted(set(lint[0] for lint in lints)):
78         yield 'pub mod %s;\n' % module
79
80
81 def gen_deprecated(lints):
82     """Declare deprecated lints"""
83
84     for lint in lints:
85         yield '    store.register_removed(\n'
86         yield '        "%s",\n' % lint[1]
87         yield '        "%s",\n' % lint[2]
88         yield '    );\n'
89
90
91 def replace_region(fn, region_start, region_end, callback,
92                    replace_start=True, write_back=True):
93     """Replace a region in a file delimited by two lines matching regexes.
94
95     A callback is called to write the new region.  If `replace_start` is true,
96     the start delimiter line is replaced as well.  The end delimiter line is
97     never replaced.
98     """
99     # read current content
100     with open(fn) as fp:
101         lines = list(fp)
102
103     # replace old region with new region
104     new_lines = []
105     in_old_region = False
106     for line in lines:
107         if in_old_region:
108             if re.search(region_end, line):
109                 in_old_region = False
110                 new_lines.extend(callback())
111                 new_lines.append(line)
112         elif re.search(region_start, line):
113             if not replace_start:
114                 new_lines.append(line)
115             # old region starts here
116             in_old_region = True
117         else:
118             new_lines.append(line)
119
120     # write back to file
121     if write_back:
122         with open(fn, 'w') as fp:
123             fp.writelines(new_lines)
124
125     # if something changed, return true
126     return lines != new_lines
127
128
129 def main(print_only=False, check=False):
130     lints = []
131     deprecated_lints = []
132     restriction_lints = []
133
134     # check directory
135     if not os.path.isfile('clippy_lints/src/lib.rs'):
136         print('Error: call this script from clippy checkout directory!')
137         return
138
139     # collect all lints from source files
140     for fn in os.listdir('clippy_lints/src'):
141         if fn.endswith('.rs'):
142             collect(lints, deprecated_lints, restriction_lints,
143                     os.path.join('clippy_lints', 'src', fn))
144
145     # determine version
146     with open('Cargo.toml') as fp:
147         for line in fp:
148             if line.startswith('version ='):
149                 clippy_version = line.split()[2].strip('"')
150                 break
151         else:
152             print('Error: version not found in Cargo.toml!')
153             return
154
155     if print_only:
156         sys.stdout.writelines(gen_table(lints + restriction_lints))
157         return
158
159     # update the lint counter in README.md
160     changed = replace_region(
161         'README.md',
162         r'^\[There are \d+ lints included in this crate\]\(https://rust-lang-nursery.github.io/rust-clippy/master/index.html\)$', "",
163         lambda: ['[There are %d lints included in this crate](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)\n' %
164                  (len(lints) + len(restriction_lints))],
165         write_back=not check)
166
167     # update the links in the CHANGELOG
168     changed |= replace_region(
169         'CHANGELOG.md',
170         "<!-- begin autogenerated links to wiki -->",
171         "<!-- end autogenerated links to wiki -->",
172         lambda: ["[`{0}`]: {1}#{0}\n".format(l[1], docs_link) for l in
173                  sorted(lints + restriction_lints + deprecated_lints,
174                         key=lambda l: l[1])],
175         replace_start=False, write_back=not check)
176
177     # update version of clippy_lints in Cargo.toml
178     changed |= replace_region(
179         'Cargo.toml', r'# begin automatic update', '# end automatic update',
180         lambda: ['clippy_lints = { version = "%s", path = "clippy_lints" }\n' %
181                  clippy_version],
182         replace_start=False, write_back=not check)
183
184     # update version of clippy_lints in Cargo.toml
185     changed |= replace_region(
186         'clippy_lints/Cargo.toml', r'# begin automatic update', '# end automatic update',
187         lambda: ['version = "%s"\n' % clippy_version],
188         replace_start=False, write_back=not check)
189
190     # update the `pub mod` list
191     changed |= replace_region(
192         'clippy_lints/src/lib.rs', r'begin lints modules', r'end lints modules',
193         lambda: gen_mods(lints + restriction_lints),
194         replace_start=False, write_back=not check)
195
196     # same for "clippy" lint collection
197     changed |= replace_region(
198         'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy"', r'\]\);',
199         lambda: gen_group(lints, levels=('warn', 'deny')),
200         replace_start=False, write_back=not check)
201
202     # same for "deprecated" lint collection
203     changed |= replace_region(
204         'clippy_lints/src/lib.rs', r'let mut store', r'end deprecated lints',
205         lambda: gen_deprecated(deprecated_lints),
206         replace_start=False,
207         write_back=not check)
208
209     # same for "clippy_pedantic" lint collection
210     changed |= replace_region(
211         'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy_pedantic"', r'\]\);',
212         lambda: gen_group(lints, levels=('allow',)),
213         replace_start=False, write_back=not check)
214
215     # same for "clippy_restrictions" lint collection
216     changed |= replace_region(
217         'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy_restrictions"',
218         r'\]\);', lambda: gen_group(restriction_lints),
219         replace_start=False, write_back=not check)
220
221     if check and changed:
222         print('Please run util/update_lints.py to regenerate lints lists.')
223         return 1
224
225
226 if __name__ == '__main__':
227     sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))