This repository was archived by the owner on Jan 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcppcheck_junit.py
More file actions
executable file
·217 lines (171 loc) · 6.22 KB
/
cppcheck_junit.py
File metadata and controls
executable file
·217 lines (171 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python3
"""Converts Cppcheck XML version 2 output to JUnit XML format."""
import argparse
import collections
from dataclasses import dataclass
from datetime import datetime
from socket import gethostname
import sys
from typing import Dict, List
from xml.etree import ElementTree
from exitstatus import ExitStatus
from junitparser import Error, JUnitXml, TestCase, TestSuite
@dataclass
class CppcheckLocation:
"""
file: Error location file.
line: Error location line.
column: Error location column.
info: Error location info.
"""
file: str
line: int
column: int
info: str
@dataclass
class CppcheckError:
"""
file: File error originated on.
locations: Error locations.
message: Error message.
severity: Severity of the error.
error_id: Unique identifier for the error.
verbose: Verbose error message.
"""
file: str
locations: List[CppcheckLocation]
message: str
severity: str
error_id: str
verbose: str
def parse_arguments(args: List[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Converts Cppcheck XML version 2 to JUnit XML format.\n"
"Usage:\n"
"\t$ cppcheck --xml-version=2 --enable=all . 2> cppcheck-result.xml\n"
"\t$ cppcheck_junit cppcheck-result.xml cppcheck-junit.xml\n",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("input_file", type=str, help="Cppcheck XML version 2 stderr file.")
parser.add_argument("output_file", type=str, help="JUnit XML output file.")
parser.add_argument(
"error_exitcode",
type=int,
nargs="?",
default=ExitStatus.success,
help="If errors are found, "
f"integer <n> is returned instead of default {ExitStatus.success}.",
)
return parser.parse_args(args)
def parse_cppcheck(file_name: str) -> Dict[str, List[CppcheckError]]:
"""Parses a Cppcheck XML version 2 file.
Args:
file_name: Cppcheck XML file.
Returns:
Parsed errors grouped by file name.
Raises:
IOError: If file_name does not exist (More specifically, FileNotFoundError on Python 3).
xml.etree.ElementTree.ParseError: If file_name is not a valid XML file.
ValueError: If unsupported Cppcheck XML version.
"""
root: ElementTree.Element = ElementTree.parse(file_name).getroot()
if int(root.get("version", "0")) != 2:
raise ValueError("Parser only supports Cppcheck XML version 2. Use --xml-version=2.")
error_root = root.find("errors")
errors = collections.defaultdict(list)
if error_root is not None:
for error_element in error_root:
file = error_element.get("file0", "")
locations = []
for location in error_element.findall("location"):
if not file:
file = location.get("file", "")
locations.append(
CppcheckLocation(
location.get("file", ""),
int(location.get("line", 0)),
int(location.get("column", 0)),
location.get("info", ""),
)
)
error = CppcheckError(
file=file,
locations=locations,
message=error_element.get("msg", ""),
severity=error_element.get("severity", ""),
error_id=error_element.get("id", ""),
verbose=error_element.get("verbose", ""),
)
errors[error.file].append(error)
return errors
def generate_test_error(error: CppcheckError) -> Error:
"""Converts parsed Cppcheck error into Error.
Args:
error: Cppcheck error
Returns:
Error
"""
jerror = Error(error.message, f"{error.severity}:{error.error_id}")
if len(error.locations) == 0:
jerror.text = error.verbose
elif len(error.locations) == 1 and error.locations[0].info == "":
location = error.locations[0]
jerror.text = f"{location.file}:{location.line}:{location.column}: {error.verbose}"
else:
jerror.text = error.verbose
for location in error.locations:
jerror.text += f"\n{location.file}:{location.line}:{location.column}: {location.info}"
return jerror
def generate_test_case(name: str, class_name: str, errors: List[CppcheckError]) -> TestCase:
"""Converts parsed Cppcheck errors into TestCase.
Args:
name: Name for the test case
class_name: Class for the test case
errors: Parsed cppcheck errors.
Returns:
TestCase
"""
test_case = TestCase(name if name else "Cppcheck", class_name, 1)
jerrors = []
for error in errors:
jerrors.append(generate_test_error(error))
test_case.result = jerrors
return test_case
def generate_test_suite(errors: Dict[str, List[CppcheckError]]) -> TestSuite:
"""Converts parsed Cppcheck errors into TestSuite.
Args:
errors: Parsed cppcheck errors.
Returns:
TestSuite
"""
test_suite = TestSuite("Cppcheck")
test_suite.timestamp = datetime.isoformat(datetime.now())
test_suite.hostname = gethostname()
if len(errors) == 0:
test_suite.add_testcase(generate_test_case("", "Cppcheck success", []))
for name, cerrors in errors.items():
test_suite.add_testcase(generate_test_case(name, "Cppcheck error", cerrors))
return test_suite
def main() -> int: # pragma: no cover
"""Main function.
Returns:
Exit code.
"""
args = parse_arguments(sys.argv[1:])
try:
errors = parse_cppcheck(args.input_file)
except ValueError as e:
print(str(e))
return ExitStatus.failure
except IOError as e:
print(str(e))
return ExitStatus.failure
except ElementTree.ParseError as e:
print(f"{args.input_file} is a malformed XML file. Did you use --xml-version=2?\n{e}")
return ExitStatus.failure
tree = JUnitXml("Cppcheck")
tree.add_testsuite(generate_test_suite(errors))
tree.write(args.output_file)
return int(args.error_exitcode) if len(errors) > 0 else ExitStatus.success
if __name__ == "__main__": # pragma: no cover
sys.exit(main())