Debian Codegraph @

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

raw
1 """Sanity test using shellcheck."""
2
3 from __future__ import annotations
4
5 import os
6 import typing as t
7
8 from xml.etree.ElementTree import (
9 fromstring,
10 Element,
11 )
12
13 from . import (
14 SanityVersionNeutral,
15 SanityMessage,
16 SanityFailure,
17 SanitySuccess,
18 SanitySkipped,
19 SanityTargets,
20 SANITY_ROOT,
21 )
22
23 from ...test import (
24 TestResult,
25 )
26
27 from ...target import (
28 TestTarget,
29 )
30
31 from ...util import (
32 SubprocessError,
33 read_lines_without_comments,
34 find_executable,
35 )
36
37 from ...util_common import (
38 run_command,
39 )
40
41 from ...config import (
42 SanityConfig,
43 )
44
45
46 class ShellcheckTest(SanityVersionNeutral):
47 """Sanity test using shellcheck."""
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 'AT1000'
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] == '.sh']
57
58 def test(self, args: SanityConfig, targets: SanityTargets) -> TestResult:
59 exclude_file = os.path.join(SANITY_ROOT, 'shellcheck', 'exclude.txt')
60 exclude = set(read_lines_without_comments(exclude_file, remove_blank_lines=True, optional=True))
61
62 settings = self.load_processor(args)
63
64 paths = [target.path for target in targets.include]
65
66 if not find_executable('shellcheck', required='warning'):
67 return SanitySkipped(self.name)
68
69 cmd = [
70 'shellcheck',
71 '-e', ','.join(sorted(exclude)),
72 '--format', 'checkstyle',
73 ] + paths # fmt: skip
74
75 try:
76 stdout, stderr = run_command(args, cmd, capture=True)
77 status = 0
78 except SubprocessError as ex:
79 stdout = ex.stdout
80 stderr = ex.stderr
81 status = ex.status
82
83 if stderr or status > 1:
84 raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
85
86 if args.explain:
87 return SanitySuccess(self.name)
88
89 # json output is missing file paths in older versions of shellcheck, so we'll use xml instead
90 root: Element = fromstring(stdout)
91
92 results = []
93
94 for item in root:
95 for entry in item:
96 results.append(SanityMessage(
97 message=entry.attrib['message'],
98 path=item.attrib['name'],
99 line=int(entry.attrib['line']),
100 column=int(entry.attrib['column']),
101 level=entry.attrib['severity'],
102 code=entry.attrib['source'].replace('ShellCheck.', ''),
103 ))
104
105 results = settings.process_errors(results, paths)
106
107 if results:
108 return SanityFailure(self.name, messages=results)
109
110 return SanitySuccess(self.name)