Debian Codegraph @

test/sanity/code-smell/boilerplate.py

raw
1 from __future__ import annotations
2
3 import ast
4 import sys
5
6
7 def main():
8 for path in sys.argv[1:] or sys.stdin.read().splitlines():
9 with open(path, 'rb') as path_fd:
10 lines = path_fd.read().splitlines()
11
12 missing = True
13 if not lines:
14 # Files are allowed to be empty of everything including boilerplate
15 missing = False
16
17 invalid_future = []
18
19 for text in lines:
20 if text in (
21 b'from __future__ import annotations',
22 b'from __future__ import annotations as _annotations',
23 b'from __future__ import annotations # pragma: nocover',
24 ):
25 missing = False
26 break
27
28 if text.strip().startswith(b'from __future__ ') or text.strip().startswith(b'__metaclass__ '):
29 invalid_future.append(text.decode())
30
31 if missing:
32 with open(path) as file:
33 contents = file.read()
34
35 # noinspection PyBroadException
36 try:
37 node = ast.parse(contents)
38
39 # files consisting of only assignments have no need for future import boilerplate
40 # the most likely case is that of a documentation only python file
41 if all(isinstance(statement, ast.Assign) for statement in node.body):
42 missing = False
43 except Exception: # pylint: disable=broad-except
44 pass # the compile sanity test will report this error
45
46 if missing:
47 print('%s: missing: from __future__ import annotations' % path)
48
49 for text in invalid_future:
50 print('%s: invalid: %s' % (path, text))
51
52
53 if __name__ == '__main__':
54 main()