|
7 | 7 | python -m ownlang report file.own # buffer storage report + .ownreport.json |
8 | 8 | python -m ownlang ownir facts.json # check OwnIR facts extracted from C# (P-001) |
9 | 9 | python -m ownlang ownir facts.json --format github|msbuild|human|sarif |
| 10 | + python -m ownlang explain OWN001 [DI002 ...] # explain diagnostic code(s): what/why/fix |
| 11 | + python -m ownlang explain --json findings.json # explain every code in a findings/SARIF file |
| 12 | +
|
| 13 | +`explain` is the diagnostic catalogue side of the CLI (the `ownsharp explain` the |
| 14 | +roslyn-tools-shaped surface advertises): it prints what a code means, why it fires, |
| 15 | +and how to fix it. It lives in the core, next to the catalogue, because there is one |
| 16 | +checker — the C# extractor emits facts, it does not own the diagnostics. |
10 | 17 |
|
11 | 18 | `--format` (ownir only) selects the finding surface: `human` (default CLI line), |
12 | 19 | `github` (CI annotations on the PR diff), `msbuild` (VS Error List), or `sarif` |
|
23 | 30 |
|
24 | 31 | from __future__ import annotations |
25 | 32 |
|
| 33 | +import re |
26 | 34 | import sys |
27 | 35 | from typing import TYPE_CHECKING |
28 | 36 |
|
@@ -192,6 +200,82 @@ def _read(path: str) -> str: |
192 | 200 | return f.read() |
193 | 201 |
|
194 | 202 |
|
| 203 | +# A diagnostic code is OWN/WPF/DI followed by three digits. Used to validate an |
| 204 | +# `explain` argument and to harvest codes out of a findings/SARIF JSON file. |
| 205 | +_CODE_RE = re.compile(r"^(OWN|WPF|DI)\d{3}$") |
| 206 | + |
| 207 | + |
| 208 | +def _explain_one(code: str) -> str: |
| 209 | + """The explanation block for one code: its title and the long-form what/why/fix |
| 210 | + (falling back to just the title when no long-form exists), or an 'unknown code' |
| 211 | + line. Pure text so it is trivially testable.""" |
| 212 | + from .diagnostics import EXPLANATIONS, TITLES |
| 213 | + code = code.upper() |
| 214 | + title = TITLES.get(code) |
| 215 | + body = EXPLANATIONS.get(code) |
| 216 | + if title is None and body is None: |
| 217 | + return f"{code}: unknown diagnostic code" |
| 218 | + out = f"{code}: {title}" if title else code |
| 219 | + if body: |
| 220 | + out += "\n\n" + body |
| 221 | + return out |
| 222 | + |
| 223 | + |
| 224 | +def _codes_from_json(obj: object) -> list[str]: |
| 225 | + """Every distinct diagnostic code reachable in a decoded JSON value, in first-seen |
| 226 | + order. Harvests the values of any `code`/`ruleId` key (so it reads a findings array, |
| 227 | + a single finding, or a SARIF log's results) that look like a diagnostic code.""" |
| 228 | + seen: dict[str, None] = {} |
| 229 | + |
| 230 | + def walk(node: object) -> None: |
| 231 | + if isinstance(node, dict): |
| 232 | + for key, val in node.items(): |
| 233 | + if key in {"code", "ruleId"} and isinstance(val, str) and _CODE_RE.match(val): |
| 234 | + seen.setdefault(val, None) |
| 235 | + else: |
| 236 | + walk(val) |
| 237 | + elif isinstance(node, list): |
| 238 | + for item in node: |
| 239 | + walk(item) |
| 240 | + |
| 241 | + walk(obj) |
| 242 | + return list(seen) |
| 243 | + |
| 244 | + |
| 245 | +def cmd_explain(codes: list[str], json_path: str | None) -> int: |
| 246 | + """Explain diagnostic code(s): print what each means, why it fires, and how to fix |
| 247 | + it. Codes come from the command line (`explain OWN001 DI002`) and/or are harvested |
| 248 | + from a findings/SARIF JSON (`--json findings.json`), so you can explain exactly the |
| 249 | + codes a run produced. Exit 2 on a usage error (no codes) or an unreadable JSON.""" |
| 250 | + import json |
| 251 | + all_codes = list(codes) |
| 252 | + if json_path is not None: |
| 253 | + try: |
| 254 | + with open(json_path, encoding="utf-8") as f: |
| 255 | + data = json.load(f) |
| 256 | + except (OSError, json.JSONDecodeError) as e: |
| 257 | + print(f"explain: cannot read {json_path}: {e}", file=sys.stderr) |
| 258 | + return 2 |
| 259 | + found = _codes_from_json(data) |
| 260 | + if not found: |
| 261 | + print(f"explain: no diagnostic codes found in {json_path}", file=sys.stderr) |
| 262 | + return 2 |
| 263 | + # de-dupe against any codes already given on the command line, preserving order |
| 264 | + for c in found: |
| 265 | + if c not in all_codes: |
| 266 | + all_codes.append(c) |
| 267 | + if not all_codes: |
| 268 | + print("explain: give a code (e.g. OWN001) or --json <findings.json>", file=sys.stderr) |
| 269 | + return 2 |
| 270 | + from .diagnostics import EXPLANATIONS, TITLES |
| 271 | + print("\n\n".join(_explain_one(c) for c in all_codes)) |
| 272 | + # If every requested code is unknown, that is almost certainly a typo — fail (2) |
| 273 | + # rather than silently succeed. A mix of known + unknown still exits 0. |
| 274 | + if all(c.upper() not in TITLES and c.upper() not in EXPLANATIONS for c in all_codes): |
| 275 | + return 2 |
| 276 | + return 0 |
| 277 | + |
| 278 | + |
195 | 279 | def cmd_ownir(path: str, fmt: str = "human", severity: str = "error", |
196 | 280 | verbosity: str = "normal") -> int: |
197 | 281 | """Check OwnIR facts (extracted from real C# by the Roslyn frontend) through |
@@ -261,10 +345,31 @@ def cmd_ownir(path: str, fmt: str = "human", severity: str = "error", |
261 | 345 |
|
262 | 346 |
|
263 | 347 | def main(argv: list[str]) -> int: |
264 | | - if not argv or argv[0] not in {"check", "emit", "cfg", "report", "ownir"}: |
| 348 | + if not argv or argv[0] not in {"check", "emit", "cfg", "report", "ownir", "explain"}: |
265 | 349 | print(__doc__) |
266 | 350 | return 2 |
267 | 351 | cmd = argv[0] |
| 352 | + # `explain` has its own shape — zero-or-more code positionals plus an optional |
| 353 | + # `--json <file>` — so it is handled before the single-positional path below. |
| 354 | + if cmd == "explain": |
| 355 | + codes: list[str] = [] |
| 356 | + json_path: str | None = None |
| 357 | + rest = argv[1:] |
| 358 | + i = 0 |
| 359 | + while i < len(rest): |
| 360 | + a = rest[i] |
| 361 | + if a == "--json": |
| 362 | + if i + 1 >= len(rest): |
| 363 | + print("--json requires a value", file=sys.stderr) |
| 364 | + return 2 |
| 365 | + json_path, i = rest[i + 1], i + 2 |
| 366 | + continue |
| 367 | + if a.startswith("--json="): |
| 368 | + json_path, i = a.split("=", 1)[1], i + 1 |
| 369 | + continue |
| 370 | + codes.append(a) |
| 371 | + i += 1 |
| 372 | + return cmd_explain(codes, json_path) |
268 | 373 | # Pull the optional value-flags (`--format`/`--severity`/`--verbosity`, ownir |
269 | 374 | # only) out of the arguments in either `--flag V` or `--flag=V` form; everything |
270 | 375 | # else is positional. Keeps the other commands' single positional-path contract. |
|
0 commit comments