Debian Codegraph @

test/sanity/code-smell/black.py

raw
1 """Sanity test which executes black."""
2
3 from __future__ import annotations
4
5 import itertools
6 import os
7 import re
8 import subprocess
9 import sys
10
11
12 def main() -> None:
13 """Main program entry point."""
14 paths = sys.argv[1:] or sys.stdin.read().splitlines()
15
16 separator_idx = paths.index('--')
17 controller_paths = paths[:separator_idx]
18 target_paths = paths[separator_idx + 1 :]
19
20 controller_python_versions = os.environ['ANSIBLE_TEST_CONTROLLER_PYTHON_VERSIONS'].split(',')
21 remote_only_python_versions = os.environ['ANSIBLE_TEST_REMOTE_ONLY_PYTHON_VERSIONS'].split(',')
22 fix_mode = bool(int(os.environ['ANSIBLE_TEST_FIX_MODE']))
23
24 # Report only the oldest controller Python version, which is the oldest version that may be used to run this test.
25 # Reporting newer Python versions to black can result in failures when running on older versions.
26 controller_python_versions = controller_python_versions[:1]
27
28 target_python_versions = remote_only_python_versions + controller_python_versions
29
30 black(controller_paths, controller_python_versions, fix_mode)
31 black(target_paths, target_python_versions, fix_mode)
32
33
34 def black(paths: list[str], python_versions: list[str], fix_mode: bool) -> None:
35 """Run black on the specified paths."""
36 if not paths:
37 return
38
39 version_options = [('-t', f'py{version.replace(".", "")}') for version in python_versions]
40
41 options = {
42 '-m': 'black',
43 '--line-length': '160',
44 '--config': '/dev/null',
45 }
46
47 flags = [
48 '--skip-string-normalization',
49 ]
50
51 if not fix_mode:
52 flags.append('--check')
53
54 cmd = [sys.executable]
55 cmd += itertools.chain.from_iterable(options.items())
56 cmd += itertools.chain.from_iterable(version_options)
57 cmd += flags
58 cmd.extend(paths)
59
60 try:
61 completed_process = subprocess.run(cmd, capture_output=True, check=True, text=True)
62 stdout, stderr = completed_process.stdout, completed_process.stderr
63
64 if stdout:
65 raise Exception(f'{stdout=} {stderr=}')
66 except subprocess.CalledProcessError as ex:
67 if ex.returncode != 1 or ex.stdout or not ex.stderr:
68 raise Exception(f'{ex.returncode=} {ex.stdout=} {ex.stderr=}') from None
69
70 stderr = ex.stderr
71
72 stderr = re.sub('(Oh no|All done).*$', '', stderr, flags=re.DOTALL).strip()
73 lines = stderr.splitlines()
74
75 check_prefix = 'would reformat '
76 fix_prefix = 'reformatted '
77
78 prefix = fix_prefix if fix_mode else check_prefix
79
80 for line in lines:
81 if not line.startswith(prefix):
82 raise Exception(f'{line=}')
83
84 if fix_mode:
85 continue
86
87 line = line.removeprefix(prefix)
88
89 print(f'{line}: Reformatting required. Run `ansible-test sanity --test black --fix` to update this file.')
90
91
92 if __name__ == '__main__':
93 main()