Debian Codegraph @

scripts/check_repeated_token.py

raw
1 #!/usr/bin/env python
2 """
3 Checker for repeated tokens
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6 Helper script to find suspicious lexers which produce the same token
7 repeatedly, i.e. for example:
8
9 .. code::
10
11 'd' Text
12 'a' Text
13 't' Text
14 'a' Text
15 'b' Text
16 'a' Text
17 's' Text
18 'e' Text
19
20 This script has two test modes: Check for tokens repeating more often than
21 a given threshold, and exclude anything but single-character tokens.
22 Repeated single-character tokens are quite problematic as they result in
23 bloated output and are usually an indication that someone is missing
24 a + or * in the regex.
25
26 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
27 :license: BSD, see LICENSE for details.
28 """
29 import argparse
30 import sys
31
32 from utility import unpack_output_file, process_output_files
33
34
35 def check_file(path, threshold, single_only):
36 current_token = ''
37 current_token_repeat_count = 1
38
39 for value, token, linenumber in unpack_output_file(path):
40 if single_only and len(value) > 1:
41 token = ''
42 current_token_repeat_count = 1
43 continue
44
45 if token != current_token:
46 current_token = token
47 current_token_repeat_count = 1
48 else:
49 current_token_repeat_count += 1
50
51 if current_token_repeat_count > threshold:
52 print(f'{path}:{linenumber}')
53 return False
54
55 return True
56
57
58 def main():
59 parser = argparse.ArgumentParser()
60 parser.add_argument('TEST_ROOT',
61 help='Root directory containing the tests')
62 parser.add_argument('-t', '--threshold', type=int, default=5,
63 help='Warn if a token repeats itself more often then '
64 'this number.')
65 parser.add_argument('-s', '--single', action='store_true', default=False,
66 help='Only look at tokens matching a single character')
67 args = parser.parse_args()
68
69 def check_file_callback(path):
70 return check_file(path, args.threshold, args.single)
71
72 if process_output_files(args.TEST_ROOT, check_file_callback) > 0:
73 return 1
74 return 0
75
76
77 if __name__ == '__main__':
78 sys.exit(main())