Coverage for src/governed_harness/validators/parsers.py: 88%
329 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Deterministic parsers of validator output (``verification.outputParsers``).
3A failing command validator produced a single finding without a location; the reviewer had to
4open the stored output to see which test or which line failed. These parsers read the output
5the tools already print and return one issue per reported problem with path, line and the
6tool's rule id. Supported formats, recognized by content:
8* SARIF 2.1.0 (any tool that emits it), ESLint JSON (``-f json``), Ruff JSON
9 (``--output-format json``) and JUnit XML (printed, or written with ``--junitxml``);
10* text: Ruff (concise and full formats), Mypy, TypeScript ``tsc`` and the pytest failure
11 summary (``FAILED``/``ERROR`` lines, with the line taken from the traceback);
12* since #56, for the tools of the language standards packs: Checkstyle XML (Checkstyle, ktlint,
13 detekt, golangci-lint, SwiftLint, PHPStan and ESLint can all write it), RuboCop JSON
14 (``--format json``) and Cargo JSON messages (``cargo clippy --message-format=json``); the
15 MSBuild diagnostics of ``dotnet build`` only with ``parser: msbuild``.
17Parsing never runs a command and never changes a validator's status; a format it does not
18recognize yields no issue. XML is parsed without DTDs or entity expansion."""
20from __future__ import annotations
22import json
23import re
24import sys
25import xml.etree.ElementTree as ElementTree # nosec B405 - DTDs and entities are refused below
26from dataclasses import dataclass
27from pathlib import Path, PurePosixPath
28from typing import Any, Literal
30Level = Literal["error", "warning", "note"]
32MAX_ISSUES = 200
33"""Issues kept per validator run; the rest are counted, not recorded."""
34_MESSAGE_CHARS = 1000
37@dataclass(frozen=True)
38class ParsedIssue:
39 rule: str
40 message: str
41 level: Level = "error"
42 path: str | None = None
43 line: int | None = None
44 end_line: int | None = None
45 tool: str = ""
48_DRIVE_URI_PATH = re.compile(r"/[A-Za-z]:[/\\]")
49"""What ``file:///C:/x`` leaves after its scheme: a Windows drive path behind a slash."""
52def _relative(path: str | None, workspace: Path) -> str | None:
53 if not path:
54 return None
55 path = path.removeprefix("file://")
56 if sys.platform == "win32" and _DRIVE_URI_PATH.match(path):
57 path = path[1:]
58 candidate = Path(path)
59 # A rooted path such as "/ws/x.py" is absolute on POSIX; on Windows it lacks a drive, so
60 # ``is_absolute`` is false, yet it names a place on the current drive, not one in the workspace.
61 if candidate.is_absolute() or candidate.root:
62 try:
63 return candidate.resolve().relative_to(workspace.resolve()).as_posix()
64 except (ValueError, OSError):
65 return candidate.as_posix()
66 return PurePosixPath(path.replace("\\", "/")).as_posix().removeprefix("./")
69def _line(value: Any) -> int | None:
70 try:
71 number = int(value)
72 except (TypeError, ValueError):
73 return None
74 return number if number >= 1 else None
77def _message(text: Any) -> str:
78 value = " ".join(str(text or "").split())
79 return value[:_MESSAGE_CHARS] or "no message"
82# ----- JSON formats -----------------------------------------------------------------------
83_SARIF_LEVELS: dict[str, Level] = {"error": "error", "warning": "warning", "note": "note"}
86def parse_sarif(data: dict[str, Any], workspace: Path) -> list[ParsedIssue]:
87 issues: list[ParsedIssue] = []
88 for run in data.get("runs") or []:
89 tool = str(((run.get("tool") or {}).get("driver") or {}).get("name") or "sarif")
90 for result in run.get("results") or []:
91 issues.append(_sarif_issue(result, tool, workspace))
92 return issues
95def _sarif_issue(result: dict[str, Any], tool: str, workspace: Path) -> ParsedIssue:
96 location = ((result.get("locations") or [{}])[0] or {}).get("physicalLocation") or {}
97 region = location.get("region") or {}
98 return ParsedIssue(
99 rule=str(result.get("ruleId") or "result"),
100 message=_message((result.get("message") or {}).get("text")),
101 level=_SARIF_LEVELS.get(str(result.get("level") or "warning"), "warning"),
102 path=_relative((location.get("artifactLocation") or {}).get("uri"), workspace),
103 line=_line(region.get("startLine")),
104 end_line=_line(region.get("endLine")),
105 tool=tool,
106 )
109def parse_eslint_json(data: list[dict[str, Any]], workspace: Path) -> list[ParsedIssue]:
110 issues: list[ParsedIssue] = []
111 for item in data:
112 for message in item.get("messages") or []:
113 issues.append(
114 ParsedIssue(
115 rule=str(message.get("ruleId") or "parse-error"),
116 message=_message(message.get("message")),
117 level="error" if message.get("severity") == 2 else "warning",
118 path=_relative(item.get("filePath"), workspace),
119 line=_line(message.get("line")),
120 end_line=_line(message.get("endLine")),
121 tool="eslint",
122 )
123 )
124 return issues
127def parse_ruff_json(data: list[dict[str, Any]], workspace: Path) -> list[ParsedIssue]:
128 return [
129 ParsedIssue(
130 rule=str(item.get("code") or "syntax-error"),
131 message=_message(item.get("message")),
132 path=_relative(item.get("filename"), workspace),
133 line=_line((item.get("location") or {}).get("row")),
134 end_line=_line((item.get("end_location") or {}).get("row")),
135 tool="ruff",
136 )
137 for item in data
138 ]
141def _parse_json(text: str, workspace: Path) -> list[ParsedIssue] | None:
142 stripped = text.strip()
143 if not stripped.startswith(("{", "[")):
144 return None
145 try:
146 data = json.loads(stripped)
147 except ValueError:
148 return None
149 if isinstance(data, dict):
150 return _parse_json_object(data, workspace)
151 if isinstance(data, list): 151 ↛ 153line 151 didn't jump to line 153 because the condition on line 151 was always true
152 return _parse_json_list(data, workspace)
153 return None
156def _parse_json_object(data: dict[str, Any], workspace: Path) -> list[ParsedIssue] | None:
157 """A SARIF 2.x log or a RuboCop report."""
158 if "runs" in data and str(data.get("version", "")).startswith("2."):
159 return parse_sarif(data, workspace)
160 if isinstance(data.get("files"), list) and "summary" in data: 160 ↛ 162line 160 didn't jump to line 162 because the condition on line 160 was always true
161 return parse_rubocop_json(data, workspace)
162 return None
165def _parse_json_list(data: list[Any], workspace: Path) -> list[ParsedIssue] | None:
166 """An ESLint or Ruff report; an empty list is a report without issues."""
167 if not data: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 return []
169 if not all(isinstance(item, dict) for item in data):
170 return None
171 if all("filePath" in item and "messages" in item for item in data):
172 return parse_eslint_json(data, workspace)
173 if all("code" in item and "filename" in item for item in data): 173 ↛ 175line 173 didn't jump to line 175 because the condition on line 173 was always true
174 return parse_ruff_json(data, workspace)
175 return None
178def parse_rubocop_json(data: dict[str, Any], workspace: Path) -> list[ParsedIssue]:
179 return [
180 _rubocop_issue(item, offense, workspace)
181 for item in data.get("files") or []
182 if isinstance(item, dict)
183 for offense in item.get("offenses") or []
184 if isinstance(offense, dict)
185 ]
188def _rubocop_issue(item: dict[str, Any], offense: dict[str, Any], workspace: Path) -> ParsedIssue:
189 severity = str(offense.get("severity") or "warning")
190 location = offense.get("location") or {}
191 return ParsedIssue(
192 rule=str(offense.get("cop_name") or "offense"),
193 message=_message(offense.get("message")),
194 level="error" if severity in {"error", "fatal"} else "warning",
195 path=_relative(item.get("path"), workspace),
196 line=_line(location.get("start_line")),
197 end_line=_line(location.get("last_line")),
198 tool="rubocop",
199 )
202def parse_cargo_messages(text: str, workspace: Path) -> list[ParsedIssue]:
203 """``cargo clippy --message-format=json``: one JSON object per line; the compiler
204 messages carry the lint code, the level and the primary span."""
205 issues: list[ParsedIssue] = []
206 for raw in text.splitlines():
207 message = _cargo_message(raw.strip())
208 if message is not None:
209 issues.append(_cargo_issue(message, workspace))
210 return issues
213def _cargo_message(line: str) -> dict[str, Any] | None:
214 """The compiler message (an error or a warning) of one line of cargo's JSON output."""
215 if not line.startswith("{") or "compiler-message" not in line:
216 return None
217 try:
218 record = json.loads(line)
219 except ValueError:
220 return None
221 message = record.get("message") if isinstance(record, dict) else None
222 if not isinstance(message, dict) or message.get("level") not in {"error", "warning"}: 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 return None
224 return message
227def _cargo_issue(message: dict[str, Any], workspace: Path) -> ParsedIssue:
228 spans = [item for item in message.get("spans") or [] if isinstance(item, dict)]
229 primary = next((item for item in spans if item.get("is_primary")), spans[0] if spans else {})
230 code = message.get("code")
231 return ParsedIssue(
232 rule=str((code if isinstance(code, dict) else {}).get("code") or "compiler"),
233 message=_message(message.get("message")),
234 level="error" if message.get("level") == "error" else "warning",
235 path=_relative(primary.get("file_name"), workspace),
236 line=_line(primary.get("line_start")),
237 end_line=_line(primary.get("line_end")),
238 tool="cargo",
239 )
242_CHECKSTYLE_LEVELS: dict[str, Level] = {"error": "error", "warning": "warning", "info": "note"}
245def parse_checkstyle(text: str, workspace: Path) -> list[ParsedIssue]:
246 """Checkstyle XML: ``<file name=...><error line severity message source/></file>``."""
247 if "<!DOCTYPE" in text or "<!ENTITY" in text:
248 return []
249 start = text.find("<")
250 try:
251 root = ElementTree.fromstring(text[max(start, 0) :].strip()) # nosec B314 - DTDs refused
252 except ElementTree.ParseError:
253 return []
254 issues: list[ParsedIssue] = []
255 for item in root.iter("file"):
256 for error in item.iter("error"):
257 source = error.get("source") or "checkstyle"
258 issues.append(
259 ParsedIssue(
260 rule=source.rsplit(".", 1)[-1].removesuffix("Check") or source,
261 message=_message(error.get("message")),
262 level=_CHECKSTYLE_LEVELS.get(error.get("severity") or "error", "warning"),
263 path=_relative(item.get("name"), workspace),
264 line=_line(error.get("line")),
265 tool="checkstyle",
266 )
267 )
268 return issues
271# ----- JUnit XML --------------------------------------------------------------------------
272def parse_junit(text: str, workspace: Path) -> list[ParsedIssue]:
273 if "<!DOCTYPE" in text or "<!ENTITY" in text:
274 return []
275 try:
276 root = ElementTree.fromstring(text) # nosec B314 - DTDs and entities refused above
277 except ElementTree.ParseError:
278 return []
279 issues: list[ParsedIssue] = []
280 for case in root.iter("testcase"):
281 for kind in ("failure", "error"):
282 node = case.find(kind)
283 if node is None:
284 continue
285 issues.append(_junit_issue(case, kind, node, workspace))
286 return issues
289def _junit_issue(
290 case: ElementTree.Element, kind: str, node: ElementTree.Element, workspace: Path
291) -> ParsedIssue:
292 """The issue of one ``failure`` or ``error`` element of a test case."""
293 name = case.get("name") or "test"
294 classname = case.get("classname") or ""
295 identifier = f"{classname}::{name}" if classname else name
296 text_lines = (node.text or "").strip().splitlines()
297 message = node.get("message") or (text_lines[0] if text_lines else kind)
298 return ParsedIssue(
299 rule="test-failed" if kind == "failure" else "test-error",
300 message=_message(f"{identifier} {kind}: {_message(message)}"),
301 path=_relative(case.get("file"), workspace),
302 line=_line(case.get("line")),
303 tool="junit",
304 )
307# ----- text formats -----------------------------------------------------------------------
308_RUFF_CONCISE = re.compile(
309 r"^(?P<path>[^\s:][^:]*):(?P<line>\d+):(?P<col>\d+): (?P<rule>[A-Z]+\d+) (?:\[\*\] )?(?P<msg>.+)$"
310)
311_RUFF_FULL_HEAD = re.compile(r"^(?P<rule>[A-Z]+\d+) (?:\[\*\] )?(?P<msg>.+)$")
312# The path starts after the blanks, or is the last blank itself when a colon follows them.
313_RUFF_FULL_ARROW = re.compile(
314 r"^\s*-->\s*(?P<path>[^\s:][^:]*|\s(?=:)):(?P<line>\d+):(?P<col>\d+)\s*$"
315)
316_MYPY = re.compile(
317 r"^(?P<path>[^\s:][^:]*\.pyi?):(?P<line>\d+)(?::\d+)?: (?P<level>error|warning|note): "
318 r"(?P<msg>.+?)(?:\s+\[(?P<code>[a-z0-9-]+)\])?$"
319)
320_TSC_PAREN = re.compile(
321 r"^(?P<path>[^\s(][^(]*)\((?P<line>\d+),\d+\): (?P<level>error|warning) (?P<code>TS\d+): (?P<msg>.+)$"
322)
323_TSC_PRETTY = re.compile(
324 r"^(?P<path>[^\s:][^:]*):(?P<line>\d+):\d+ - (?P<level>error|warning) (?P<code>TS\d+): (?P<msg>.+)$"
325)
326_PYTEST_SUMMARY = re.compile(r"^(?P<kind>FAILED|ERROR) (?P<node>\S+)(?: - (?P<msg>.*))?$")
327_PYTEST_SECTION = re.compile(r"^_{3,} (?:ERROR collecting )?(?P<name>.+?) _{3,}$")
328_MSBUILD = re.compile(
329 r"^\s*(?P<path>[^\s(][^(]*)\((?P<line>\d+),\d+(?:,\d+,\d+)?\): (?P<level>error|warning) "
330 r"(?P<code>[A-Z]+\d+): (?P<msg>.+?)(?: \[[^\]]+\])?$"
331)
334def parse_msbuild_text(lines: list[str]) -> list[ParsedIssue]:
335 """``dotnet build`` diagnostics: ``path(line,col): warning CA1062: message [project]``;
336 repeated diagnostics (MSBuild prints them again in the summary) are kept once."""
337 issues: list[ParsedIssue] = []
338 seen: set[tuple[str, int, str]] = set()
339 for line in lines:
340 match = _MSBUILD.match(line)
341 if not match:
342 continue
343 key = (match["path"].strip(), int(match["line"]), match["code"])
344 if key in seen:
345 continue
346 seen.add(key)
347 issues.append(
348 ParsedIssue(
349 rule=match["code"],
350 message=_message(match["msg"]),
351 level="error" if match["level"] == "error" else "warning",
352 path=match["path"].strip(),
353 line=int(match["line"]),
354 tool="msbuild",
355 )
356 )
357 return issues
360def parse_ruff_text(lines: list[str]) -> list[ParsedIssue]:
361 issues: list[ParsedIssue] = []
362 pending: tuple[str, str] | None = None
363 for line in lines:
364 if match := _RUFF_CONCISE.match(line):
365 issues.append(
366 ParsedIssue(
367 rule=match["rule"],
368 message=_message(match["msg"]),
369 path=match["path"],
370 line=int(match["line"]),
371 tool="ruff",
372 )
373 )
374 pending = None
375 elif match := _RUFF_FULL_HEAD.match(line):
376 pending = (match["rule"], match["msg"])
377 elif pending and (match := _RUFF_FULL_ARROW.match(line)):
378 issues.append(
379 ParsedIssue(
380 rule=pending[0],
381 message=_message(pending[1]),
382 path=match["path"],
383 line=int(match["line"]),
384 tool="ruff",
385 )
386 )
387 pending = None
388 return issues
391def parse_mypy_text(lines: list[str]) -> list[ParsedIssue]:
392 issues = []
393 for line in lines:
394 if match := _MYPY.match(line):
395 if match["level"] == "note":
396 continue
397 issues.append(
398 ParsedIssue(
399 rule=match["code"] or "error",
400 message=_message(match["msg"]),
401 level="error" if match["level"] == "error" else "warning",
402 path=match["path"],
403 line=int(match["line"]),
404 tool="mypy",
405 )
406 )
407 return issues
410def parse_tsc_text(lines: list[str]) -> list[ParsedIssue]:
411 issues = []
412 for line in lines:
413 match = _TSC_PAREN.match(line) or _TSC_PRETTY.match(line)
414 if match:
415 issues.append(
416 ParsedIssue(
417 rule=match["code"],
418 message=_message(match["msg"]),
419 level="error" if match["level"] == "error" else "warning",
420 path=match["path"].strip(),
421 line=int(match["line"]),
422 tool="tsc",
423 )
424 )
425 return issues
428def _frame_path(path: str) -> str:
429 """The pattern of a node id's path in a traceback frame: pytest prints node ids with ``/``
430 but, on Windows, the frames with the native ``\\``."""
431 pattern = re.escape(path)
432 if sys.platform == "win32" and "/" in path:
433 native = re.escape(path.replace("/", "\\"))
434 pattern = f"(?:{pattern}|{native})"
435 return pattern
438def parse_pytest_text(lines: list[str]) -> list[ParsedIssue]:
439 sections = _pytest_sections(lines)
440 issues = []
441 for line in lines:
442 match = _PYTEST_SUMMARY.match(line)
443 if not match:
444 continue
445 issue = _pytest_issue(match, sections)
446 if issue is not None: 446 ↛ 441line 446 didn't jump to line 441 because the condition on line 446 was always true
447 issues.append(issue)
448 return issues
451def _pytest_sections(lines: list[str]) -> dict[str, list[str]]:
452 """The lines of each ``___ name ___`` section of a pytest report, by name."""
453 sections: dict[str, list[str]] = {}
454 current: list[str] | None = None
455 for line in lines:
456 if match := _PYTEST_SECTION.match(line):
457 current = sections.setdefault(match["name"], [])
458 elif current is not None:
459 current.append(line)
460 return sections
463def _pytest_issue(match: re.Match[str], sections: dict[str, list[str]]) -> ParsedIssue | None:
464 """The issue of one summary line, at the last frame of its section in the test file;
465 ``None`` for a node outside a ``.py`` file."""
466 node = match["node"]
467 path = node.split("::", 1)[0]
468 if not path.endswith(".py"): 468 ↛ 469line 468 didn't jump to line 469 because the condition on line 468 was never true
469 return None
470 name = node.split("::")[-1] if "::" in node else path
471 section = sections.get(name) or sections.get(node.split("::", 1)[-1].replace("::", ".")) or []
472 frames = [
473 int(found.group(1))
474 for text in section
475 if (found := re.match(rf"^{_frame_path(path)}:(\d+): ", text))
476 ]
477 kind = "test-failed" if match["kind"] == "FAILED" else "test-error"
478 return ParsedIssue(
479 rule=kind,
480 message=_message(f"{node} {match['kind'].lower()}: {match['msg'] or ''}".rstrip(": ")),
481 path=path,
482 line=frames[-1] if frames else None,
483 tool="pytest",
484 )
487def _load_json(text: str) -> Any:
488 stripped = text.strip()
489 if not stripped.startswith(("{", "[")): 489 ↛ 490line 489 didn't jump to line 490 because the condition on line 489 was never true
490 return None
491 try:
492 return json.loads(stripped)
493 except ValueError:
494 return None
497def _parse_only(
498 parser: str, stdout: str, stderr: str, workspace: Path, reports: tuple[str, ...]
499) -> list[ParsedIssue]:
500 """The issues of one named format (``toolchain.validators[].parser``)."""
501 texts = (*reports, stdout)
502 lines = [line.rstrip() for line in (stdout + "\n" + stderr).splitlines()]
503 if parser in {"junit", "checkstyle", "cargo"}: 503 ↛ 504line 503 didn't jump to line 504 because the condition on line 503 was never true
504 return _parse_reports(parser, texts, workspace)
505 text_parsers = {
506 "mypy": parse_mypy_text,
507 "tsc": parse_tsc_text,
508 "pytest": parse_pytest_text,
509 "msbuild": parse_msbuild_text,
510 }
511 if parser in text_parsers:
512 return text_parsers[parser](lines)
513 issues: list[ParsedIssue] = []
514 for text in texts:
515 issues.extend(_parse_json_named(parser, _load_json(text), workspace))
516 if parser == "ruff" and not issues: 516 ↛ 517line 516 didn't jump to line 517 because the condition on line 516 was never true
517 issues.extend(parse_ruff_text(lines))
518 return issues
521def _parse_reports(parser: str, texts: tuple[str, ...], workspace: Path) -> list[ParsedIssue]:
522 """The issues of the ``junit``, ``checkstyle`` or ``cargo`` reports among ``texts``."""
523 issues: list[ParsedIssue] = []
524 for text in texts:
525 if parser == "junit":
526 if "<testsuite" in text:
527 issues.extend(parse_junit(text, workspace))
528 elif parser == "checkstyle":
529 if "<checkstyle" in text:
530 issues.extend(parse_checkstyle(text, workspace))
531 else:
532 issues.extend(parse_cargo_messages(text, workspace))
533 return issues
536def _parse_json_named(parser: str, data: Any, workspace: Path) -> list[ParsedIssue]:
537 """The issues of one JSON document in the named format; none for any other document."""
538 if parser == "sarif" and isinstance(data, dict) and "runs" in data:
539 return parse_sarif(data, workspace)
540 if parser == "rubocop" and isinstance(data, dict): 540 ↛ 541line 540 didn't jump to line 541 because the condition on line 540 was never true
541 return parse_rubocop_json(data, workspace)
542 if parser in {"eslint", "ruff"} and isinstance(data, list): 542 ↛ 549line 542 didn't jump to line 549 because the condition on line 542 was always true
543 rows = [item for item in data if isinstance(item, dict)]
544 return (
545 parse_eslint_json(rows, workspace)
546 if parser == "eslint"
547 else parse_ruff_json(rows, workspace)
548 )
549 return []
552def parse_output(
553 stdout: str,
554 stderr: str,
555 workspace: Path,
556 reports: tuple[str, ...] = (),
557 parser: str = "auto",
558) -> list[ParsedIssue]:
559 """Every issue the output of one validator run reports, in order, at most ``MAX_ISSUES``
560 (callers count the rest). ``parser`` names one format (``sarif``, ``junit``, ``ruff``,
561 ``mypy``, ``eslint``, ``tsc``, ``pytest``, ``checkstyle``, ``rubocop``, ``cargo``); ``auto``
562 recognizes every format by content."""
563 if parser == "none": 563 ↛ 564line 563 didn't jump to line 564 because the condition on line 563 was never true
564 return []
565 if parser != "auto":
566 return _normalized(_parse_only(parser, stdout, stderr, workspace, reports), workspace)
567 issues: list[ParsedIssue] = []
568 for text in (*reports, stdout):
569 parsed = _parse_json(text, workspace)
570 if parsed is not None:
571 issues.extend(parsed)
572 continue
573 if "<testsuite" in text:
574 issues.extend(parse_junit(text, workspace))
575 elif "<checkstyle" in text: 575 ↛ 576line 575 didn't jump to line 576 because the condition on line 575 was never true
576 issues.extend(parse_checkstyle(text, workspace))
577 elif "compiler-message" in text: 577 ↛ 578line 577 didn't jump to line 578 because the condition on line 577 was never true
578 issues.extend(parse_cargo_messages(text, workspace))
579 if not issues:
580 lines = [line.rstrip() for line in (stdout + "\n" + stderr).splitlines()]
581 for text_parser in (parse_ruff_text, parse_mypy_text, parse_tsc_text, parse_pytest_text):
582 issues.extend(text_parser(lines))
583 return _normalized(issues, workspace)
586def _normalized(issues: list[ParsedIssue], workspace: Path) -> list[ParsedIssue]:
587 return [
588 ParsedIssue(
589 rule=item.rule,
590 message=item.message,
591 level=item.level,
592 path=_relative(item.path, workspace),
593 line=item.line,
594 end_line=item.end_line,
595 tool=item.tool,
596 )
597 for item in issues
598 ]
601def report_files(argv: tuple[str, ...], workspace: Path) -> list[Path]:
602 """JUnit or SARIF files a validator command writes (``--junitxml=``, ``--junit-xml``,
603 ``--output-file``/``-o`` with a .sarif/.xml/.json name), resolved inside the workspace."""
604 found: list[Path] = []
605 for index, item in enumerate(argv):
606 value: str | None = None
607 for flag in ("--junitxml=", "--junit-xml=", "--output-file=", "--output="):
608 if item.startswith(flag):
609 value = item[len(flag) :]
610 if item in {"--junitxml", "--junit-xml", "--output-file", "-o"} and index + 1 < len(argv):
611 value = argv[index + 1]
612 if value and value.endswith((".xml", ".sarif", ".json")):
613 path = (workspace / value).resolve()
614 try:
615 path.relative_to(workspace.resolve())
616 except ValueError:
617 continue
618 found.append(path)
619 return found