Debian Codegraph @

test/sanity/code-smell/codespell.py

raw
1 """Check for common misspelled words using codespell."""
2
3 from __future__ import annotations
4
5 import pathlib
6 import re
7 import subprocess
8 import sys
9 import tempfile
10
11 import typing as t
12
13
14 def main() -> None:
15 paths = sys.argv[1:] or sys.stdin.read().splitlines()
16
17 ignore_words_lines = (pathlib.Path(__file__).parent / 'codespell' / 'ignore-words.txt').read_text().splitlines()
18 ignore_words = [re.split(r'\s*#', line, maxsplit=1)[0] for line in ignore_words_lines]
19
20 quiet_level = (
21 32 # don't print configuration file
22 + 16 # don't print the list of fixed files
23 + 4 # omit warnings about automatic fixes that were disabled in the dictionary
24 + 2 # disable warnings about binary files
25 + 1 # disable warnings about wrong encoding
26 )
27
28 paths = [path for path in paths if path != 'test/sanity/ignore.txt']
29
30 with tempfile.NamedTemporaryFile(mode='wt') as ignore_words_temp_file:
31 ignore_words_temp_file.write('\n'.join(ignore_words))
32 ignore_words_temp_file.flush()
33
34 cmd = [
35 sys.executable,
36 '-m',
37 'codespell_lib',
38 '--disable-colors',
39 '--builtin',
40 'clear', # minimize false positives
41 '--quiet-level',
42 str(quiet_level),
43 '--ignore-words',
44 ignore_words_temp_file.name,
45 ] + paths
46
47 process = subprocess.run(
48 cmd,
49 stdin=subprocess.DEVNULL,
50 capture_output=True,
51 check=False,
52 text=True,
53 )
54
55 if process.stderr:
56 print(process.stderr.strip(), file=sys.stderr)
57 sys.exit(1)
58
59 if not (stdout := process.stdout.strip()):
60 return
61
62 if process.returncode not in (0, 65):
63 print(f'Unexpected return code: {process.returncode}')
64 sys.exit(1)
65
66 pattern = re.compile(r'^(?P<path>[^:]*):(?P<line>[0-9]+): (?P<left>.*) ==> (?P<right>.*)$')
67 matches = parse_to_list_of_dict(pattern, stdout)
68 results: list[str] = []
69
70 for match in matches:
71 path, line_num_str, left, right = match['path'], match['line'], match['left'], match['right']
72 line_num = int(line_num_str)
73
74 try:
75 line = pathlib.Path(path).read_text().splitlines()[line_num - 1]
76 col_num = line.index(left) + 1
77 except UnicodeDecodeError:
78 col_num = 0
79
80 if len(left) <= 3 and pathlib.Path(path).suffix == '.py':
81 continue # ignore short words in Python files, as they're likely just short variable names
82
83 code = re.sub('[^a-zA-Z]', '_', left)
84
85 results.append(f"{path}:{line_num}:{col_num}: {code}: {left} ==> {right}")
86
87 if results:
88 print('\n'.join(results))
89
90
91 def parse_to_list_of_dict(pattern: re.Pattern, value: str) -> list[dict[str, t.Any]]:
92 matched = []
93 unmatched = []
94
95 for line in value.splitlines():
96 match = re.search(pattern, line)
97
98 if match:
99 matched.append(match.groupdict())
100 else:
101 unmatched.append(line)
102
103 if unmatched:
104 raise Exception(f'Pattern {pattern!r} did not match values:\n' + '\n'.join(unmatched))
105
106 return matched
107
108
109 if __name__ == '__main__':
110 main()