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