Debian Codegraph @

test/lib/ansible_test/_internal/commands/sanity/pep8.py

raw
1 """Sanity test for PEP 8 style guidelines using pycodestyle."""
2
3 from __future__ import annotations
4
5 import os
6 import typing as t
7
8 from . import (
9 SanitySingleVersion,
10 SanityMessage,
11 SanityFailure,
12 SanitySuccess,
13 SanityTargets,
14 SANITY_ROOT,
15 )
16
17 from ...test import (
18 TestResult,
19 )
20
21 from ...target import (
22 TestTarget,
23 )
24
25 from ...util import (
26 SubprocessError,
27 read_lines_without_comments,
28 parse_to_list_of_dict,
29 is_subdir,
30 common_environment,
31 )
32
33 from ...util_common import (
34 run_command,
35 )
36
37 from ...config import (
38 SanityConfig,
39 )
40
41 from ...host_configs import (
42 PythonConfig,
43 )
44
45
46 class Pep8Test(SanitySingleVersion):
47 """Sanity test for PEP 8 style guidelines using pycodestyle."""
48
49 @property
50 def error_code(self) -> t.Optional[str]:
51 """Error code for ansible-test matching the format used by the underlying test program, or None if the program does not use error codes."""
52 return 'A100'
53
54 def filter_targets(self, targets: list[TestTarget]) -> list[TestTarget]:
55 """Return the given list of test targets, filtered to include only those relevant for the test."""
56 return [target for target in targets if os.path.splitext(target.path)[1] == '.py' or is_subdir(target.path, 'bin')]
57
58 def test(self, args: SanityConfig, targets: SanityTargets, python: PythonConfig) -> TestResult:
59 current_ignore_file = os.path.join(SANITY_ROOT, 'pep8', 'current-ignore.txt')
60 current_ignore = sorted(read_lines_without_comments(current_ignore_file, remove_blank_lines=True))
61
62 settings = self.load_processor(args)
63
64 paths = [target.path for target in targets.include]
65
66 cmd = [
67 python.path,
68 '-m', 'pycodestyle',
69 '--max-line-length', '160',
70 '--config', '/dev/null',
71 '--ignore', ','.join(sorted(current_ignore)),
72 ] + paths # fmt: skip
73
74 env = common_environment()
75 env.update(PYTHONWARNINGS='ignore') # work around os.path.commonprefix deprecation warning triggered by pycodestyle
76
77 if paths:
78 try:
79 stdout, stderr = run_command(args, cmd, capture=True, env=env)
80 status = 0
81 except SubprocessError as ex:
82 stdout = ex.stdout
83 stderr = ex.stderr
84 status = ex.status
85
86 if stderr:
87 raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
88 else:
89 stdout = None
90
91 if args.explain:
92 return SanitySuccess(self.name)
93
94 if stdout:
95 pattern = '^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<code>[WE][0-9]{3}) (?P<message>.*)$'
96
97 results = parse_to_list_of_dict(pattern, stdout)
98 else:
99 results = []
100
101 messages = [SanityMessage(
102 message=r['message'],
103 path=r['path'],
104 line=int(r['line']),
105 column=int(r['column']),
106 level='warning' if r['code'].startswith('W') else 'error',
107 code=r['code'],
108 ) for r in results]
109
110 errors = settings.process_errors(messages, paths)
111
112 if errors:
113 return SanityFailure(self.name, messages=errors)
114
115 return SanitySuccess(self.name)