mirror of
https://github.com/astral-sh/ruff
synced 2026-01-20 21:10:48 -05:00
# This commit was generated by running the following Python code:
# (followed by `sed -Ei 's/(mod registry;)/\1mod codes;/' crates/ruff/src/lib.rs`
# and `cargo fmt`).
import json
import re
import subprocess
def parse_registry():
file = open('crates/ruff/src/registry.rs')
rules = []
while next(file) != 'ruff_macros::register_rules!(\n':
continue
while (line := next(file)) != ');\n':
line = line.strip().rstrip(',')
if line.startswith('//') or line.startswith('#['):
rules.append(line)
continue
code, path = line.split(' => ')
name = path.rsplit('::')[-1]
rules.append((code, name))
while (line := next(file)) != 'pub enum Linter {\n':
continue
prefixes = []
prefix2linter = []
while (line := next(file).strip()) != '}':
if line.startswith('//'):
continue
if line.startswith('#[prefix = '):
prefixes.append(line.split()[-1].strip('"]'))
else:
for prefix in prefixes:
prefix2linter.append((prefix, line.rstrip(',')))
prefixes.clear()
prefix2linter.sort(key = lambda t: len(t[0]), reverse=True)
return rules, prefix2linter
rules, prefix2linter = parse_registry()
def parse_code(code):
prefix = re.match('[A-Z]+', code).group()
if prefix in ('E', 'W'):
return 'Pycodestyle', code
for prefix, linter in prefix2linter:
if code.startswith(prefix):
return linter, code[len(prefix) :]
assert False
text = '''
use crate::registry::{Linter, Rule};
pub fn code_to_rule(linter: Linter, code: &str) -> Option<Rule> {
#[allow(clippy::enum_glob_use)]
use Linter::*;
Some(match (linter, code) {
'''
for entry in rules:
if isinstance(entry, str):
if entry.startswith('//'):
text += '\n' + entry
else:
text += entry
else:
namespace, code = parse_code(entry[0])
text += f'({namespace}, "{code}") => Rule::{entry[1]},'
text += '\n'
text += '''
_ => return None,
})
}
'''
with open('crates/ruff/src/codes.rs', 'w') as f:
f.write(text)