mintchip 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mintchip/ingest.py ADDED
@@ -0,0 +1,725 @@
1
+ """Zero-dependency SWE tool ingestors for ``mintchip from <format> [FILE|-]``.
2
+
3
+ Converts standard developer tool outputs directly into ``mintchip`` chips or shared-scale
4
+ tables using only the Python standard library:
5
+
6
+ - ``git-diff``: ``git diff --numstat`` -> ``share`` chip of changed lines by top-level area
7
+ - ``hyperfine``: ``hyperfine --export-json`` -> ``table`` with ``num`` mean + ``dist``
8
+ - ``pytest-bench``: ``pytest-benchmark`` JSON -> ``table`` with ``num`` + ``ci`` or ``bar``
9
+ - ``go-bench``: ``go test -bench`` text -> ``table``
10
+ - ``cargo-bench``: ``cargo bench`` text -> ``table``
11
+ - ``junit``: JUnit XML -> ``strip`` chip (1 suite) or ``table`` with ``strip`` + ``bar``
12
+ - ``auto``: auto-detect any of the above from input content
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import difflib
19
+ import json
20
+ import math
21
+ import re
22
+ import xml.etree.ElementTree as ET
23
+ from collections import defaultdict
24
+ from collections.abc import Sequence
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ import mintchip as mc
29
+
30
+ from .spec import Chip, ChipError
31
+
32
+ __all__ = [
33
+ "INGEST_FORMATS",
34
+ "BenchEntry",
35
+ "add_from_parser",
36
+ "cmd_from",
37
+ "detect_format",
38
+ "ingest",
39
+ "parse_cargo_bench",
40
+ "parse_git_diff",
41
+ "parse_go_bench",
42
+ "parse_hyperfine",
43
+ "parse_junit",
44
+ "parse_pytest_bench",
45
+ ]
46
+
47
+ INGEST_FORMATS: tuple[str, ...] = (
48
+ "auto",
49
+ "git-diff",
50
+ "hyperfine",
51
+ "pytest-bench",
52
+ "go-bench",
53
+ "cargo-bench",
54
+ "junit",
55
+ )
56
+
57
+ OUTPUT_FORMATS: tuple[str, ...] = ("text", "ansi", "md", "html", "json")
58
+
59
+ _TIME_TO_SEC: dict[str, float] = {
60
+ "ns": 1e-9,
61
+ "us": 1e-6,
62
+ "µs": 1e-6,
63
+ "μs": 1e-6,
64
+ "ms": 1e-3,
65
+ "s": 1.0,
66
+ }
67
+
68
+ _GIT_NUMSTAT_RE = re.compile(r"^(\d+|-)\t(\d+|-)\t(.+)$")
69
+ _GO_BENCH_RE = re.compile(
70
+ r"^(Benchmark\S+)\s+(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(ns|us|µs|μs|ms|s)/op"
71
+ r"(?:\s+([0-9]+(?:\.[0-9]+)?)\s+B/op)?"
72
+ r"(?:\s+(\d+)\s+allocs/op)?"
73
+ )
74
+ _CARGO_BENCH_RE = re.compile(
75
+ r"^test\s+(\S+)\s+\.\.\.\s+bench:\s+([0-9,]+(?:\.[0-9]+)?)\s+"
76
+ r"(ns|us|µs|μs|ms|s)/iter\s+\(\+/-\s+([0-9,]+(?:\.[0-9]+)?)\)"
77
+ )
78
+ _RENAME_BRACE_RE = re.compile(r"\{[^{}]*?\s*=>\s*([^{}]*?)\}")
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class BenchEntry:
83
+ """Normalized benchmark observation shared between ``ingest`` and ``diff``."""
84
+
85
+ name: str
86
+ value: float
87
+ unit: str | None = None
88
+ samples: tuple[float, ...] = ()
89
+ stddev: float | None = None
90
+ n: int | None = None
91
+ ci: tuple[float, float] | None = None
92
+ higher_is_better: bool = False
93
+ extra: tuple[tuple[str, float], ...] = ()
94
+
95
+
96
+ def pick_time_unit(seconds: Sequence[float]) -> tuple[float, str]:
97
+ """Choose a clean display multiplier and unit string for a list of durations in seconds."""
98
+ vals = [abs(v) for v in seconds if v is not None and math.isfinite(v)]
99
+ peak = max(vals, default=0.0)
100
+ if peak == 0.0:
101
+ return 1.0, "s"
102
+ if peak < 1e-6:
103
+ return 1e9, "ns"
104
+ if peak < 1e-3:
105
+ return 1e6, "us"
106
+ if peak < 1.0:
107
+ return 1e3, "ms"
108
+ return 1.0, "s"
109
+
110
+
111
+ def _normalize_git_path(raw: str) -> str:
112
+ path = raw.strip()
113
+ if "=>" in path:
114
+ if "{" in path and "}" in path:
115
+ path = _RENAME_BRACE_RE.sub(r"\1", path)
116
+ else:
117
+ path = path.split("=>")[-1].strip()
118
+ path = path.strip('"').strip("/")
119
+ return re.sub(r"/+", "/", path)
120
+
121
+
122
+ def _top_area(path: str) -> str:
123
+ norm = _normalize_git_path(path)
124
+ if "/" not in norm:
125
+ return "root"
126
+ return norm.split("/", 1)[0] or "root"
127
+
128
+
129
+ # --- parsers returning normalized data -------------------------------------------------------
130
+ def parse_git_diff(text: str) -> dict[str, int]:
131
+ """Parse ``git diff --numstat`` output into ``{top_level_area: changed_lines}``."""
132
+ totals: dict[str, int] = defaultdict(int)
133
+ matched = 0
134
+ for line in text.splitlines():
135
+ m = _GIT_NUMSTAT_RE.match(line.strip("\r\n"))
136
+ if not m:
137
+ continue
138
+ matched += 1
139
+ added_s, deleted_s, path = m.groups()
140
+ if added_s == "-" or deleted_s == "-":
141
+ continue
142
+ changed = int(added_s) + int(deleted_s)
143
+ if changed > 0:
144
+ totals[_top_area(path)] += changed
145
+ if matched == 0:
146
+ raise ChipError(
147
+ "mintchip from git-diff: no git diff --numstat lines found.",
148
+ fix_hint="Pipe output from: git diff --numstat | mintchip from git-diff",
149
+ )
150
+ if not totals:
151
+ raise ChipError(
152
+ "mintchip from git-diff: all matched files had 0 changed text lines.",
153
+ fix_hint="Run git diff --numstat against a commit with text changes.",
154
+ )
155
+ return dict(totals)
156
+
157
+
158
+ def parse_hyperfine(text: str) -> list[BenchEntry]:
159
+ """Parse ``hyperfine --export-json`` into normalized :class:`BenchEntry` records (seconds)."""
160
+ try:
161
+ data = json.loads(text)
162
+ except json.JSONDecodeError as e:
163
+ raise ChipError(
164
+ f"mintchip from hyperfine: invalid JSON (line {e.lineno}: {e.msg}).",
165
+ fix_hint="Pass a file created with: hyperfine --export-json bench.json ...",
166
+ ) from None
167
+ results = data.get("results") if isinstance(data, dict) else None
168
+ if not isinstance(results, list) or not results:
169
+ raise ChipError(
170
+ "mintchip from hyperfine: expected a JSON object with a non-empty 'results' list.",
171
+ fix_hint="Pass output from: hyperfine --export-json bench.json ...",
172
+ )
173
+ entries: list[BenchEntry] = []
174
+ for i, item in enumerate(results):
175
+ if not isinstance(item, dict) or "mean" not in item:
176
+ raise ChipError(
177
+ f"mintchip from hyperfine: results[{i}] is missing 'mean'.",
178
+ fix_hint="Export directly with hyperfine --export-json.",
179
+ )
180
+ name = str(item.get("command") or f"cmd-{i + 1}")
181
+ mean = float(item["mean"])
182
+ raw_times = item.get("times")
183
+ samples = (
184
+ tuple(float(t) for t in raw_times if t is not None)
185
+ if isinstance(raw_times, list)
186
+ else ()
187
+ )
188
+ stddev = float(item["stddev"]) if item.get("stddev") is not None else None
189
+ n = len(samples) if samples else None
190
+ entries.append(
191
+ BenchEntry(
192
+ name=name,
193
+ value=mean,
194
+ unit="s",
195
+ samples=samples,
196
+ stddev=stddev,
197
+ n=n,
198
+ higher_is_better=False,
199
+ )
200
+ )
201
+ return entries
202
+
203
+
204
+ def parse_pytest_bench(text: str) -> list[BenchEntry]:
205
+ """Parse ``pytest-benchmark`` JSON into normalized :class:`BenchEntry` records (seconds)."""
206
+ try:
207
+ data = json.loads(text)
208
+ except json.JSONDecodeError as e:
209
+ raise ChipError(
210
+ f"mintchip from pytest-bench: invalid JSON (line {e.lineno}: {e.msg}).",
211
+ fix_hint="Pass a file created with: pytest --benchmark-json=bench.json",
212
+ ) from None
213
+ benches = data.get("benchmarks") if isinstance(data, dict) else None
214
+ if not isinstance(benches, list) or not benches:
215
+ raise ChipError(
216
+ "mintchip from pytest-bench: expected a JSON object with a non-empty 'benchmarks' list.",
217
+ fix_hint="Pass output from: pytest --benchmark-json=bench.json",
218
+ )
219
+ entries: list[BenchEntry] = []
220
+ for i, item in enumerate(benches):
221
+ if not isinstance(item, dict) or not isinstance(item.get("stats"), dict):
222
+ raise ChipError(
223
+ f"mintchip from pytest-bench: benchmarks[{i}] is missing 'stats'.",
224
+ fix_hint="Export directly with pytest --benchmark-json=bench.json.",
225
+ )
226
+ stats = item["stats"]
227
+ if "mean" not in stats:
228
+ raise ChipError(
229
+ f"mintchip from pytest-bench: benchmarks[{i}].stats is missing 'mean'.",
230
+ fix_hint="Export directly with pytest --benchmark-json=bench.json.",
231
+ )
232
+ name = str(item.get("name") or item.get("fullname") or f"bench-{i + 1}")
233
+ mean = float(stats["mean"])
234
+ stddev = float(stats["stddev"]) if stats.get("stddev") is not None else None
235
+ rounds = int(stats["rounds"]) if stats.get("rounds") is not None else None
236
+ raw_data = stats.get("data")
237
+ samples = (
238
+ tuple(float(v) for v in raw_data if v is not None)
239
+ if isinstance(raw_data, list)
240
+ else ()
241
+ )
242
+ ci_bounds: tuple[float, float] | None = None
243
+ if stddev is not None and stddev > 0:
244
+ se = stddev / math.sqrt(rounds) if rounds and rounds > 1 else stddev
245
+ half = 1.96 * se
246
+ ci_bounds = (max(0.0, mean - half), mean + half)
247
+ elif stats.get("q1") is not None and stats.get("q3") is not None:
248
+ lo, hi = float(stats["q1"]), float(stats["q3"])
249
+ if lo <= mean <= hi:
250
+ ci_bounds = (lo, hi)
251
+ entries.append(
252
+ BenchEntry(
253
+ name=name,
254
+ value=mean,
255
+ unit="s",
256
+ samples=samples,
257
+ stddev=stddev,
258
+ n=rounds or (len(samples) if samples else None),
259
+ ci=ci_bounds,
260
+ higher_is_better=False,
261
+ )
262
+ )
263
+ return entries
264
+
265
+
266
+ def parse_go_bench(text: str) -> list[BenchEntry]:
267
+ """Parse ``go test -bench`` text output into normalized :class:`BenchEntry` records (seconds)."""
268
+ grouped_times: dict[str, list[float]] = defaultdict(list)
269
+ grouped_bytes: dict[str, list[float]] = defaultdict(list)
270
+ grouped_allocs: dict[str, list[float]] = defaultdict(list)
271
+ order: list[str] = []
272
+
273
+ for line in text.splitlines():
274
+ m = _GO_BENCH_RE.match(line.strip())
275
+ if not m:
276
+ continue
277
+ raw_name, _iters, val_s, unit_s, bytes_s, allocs_s = m.groups()
278
+ name = re.sub(r"-\d+$", "", raw_name)
279
+ if name not in grouped_times:
280
+ order.append(name)
281
+ sec = float(val_s) * _TIME_TO_SEC[unit_s]
282
+ grouped_times[name].append(sec)
283
+ if bytes_s is not None:
284
+ grouped_bytes[name].append(float(bytes_s))
285
+ if allocs_s is not None:
286
+ grouped_allocs[name].append(float(allocs_s))
287
+
288
+ if not order:
289
+ raise ChipError(
290
+ "mintchip from go-bench: no 'go test -bench' lines found.",
291
+ fix_hint="Pipe output from: go test -bench=. -benchmem | mintchip from go-bench",
292
+ )
293
+
294
+ entries: list[BenchEntry] = []
295
+ for name in order:
296
+ ts = grouped_times[name]
297
+ mean = sum(ts) / len(ts)
298
+ stddev: float | None = None
299
+ if len(ts) >= 2:
300
+ var = sum((x - mean) ** 2 for x in ts) / (len(ts) - 1)
301
+ stddev = math.sqrt(var)
302
+ extras: list[tuple[str, float]] = []
303
+ if name in grouped_bytes:
304
+ bs = grouped_bytes[name]
305
+ extras.append(("bytes", sum(bs) / len(bs)))
306
+ if name in grouped_allocs:
307
+ al = grouped_allocs[name]
308
+ extras.append(("allocs", sum(al) / len(al)))
309
+ entries.append(
310
+ BenchEntry(
311
+ name=name,
312
+ value=mean,
313
+ unit="s",
314
+ samples=tuple(ts) if len(ts) >= 2 else (),
315
+ stddev=stddev,
316
+ n=len(ts),
317
+ higher_is_better=False,
318
+ extra=tuple(extras),
319
+ )
320
+ )
321
+ return entries
322
+
323
+
324
+ def parse_cargo_bench(text: str) -> list[BenchEntry]:
325
+ """Parse ``cargo bench`` output into normalized :class:`BenchEntry` records (seconds)."""
326
+ entries: list[BenchEntry] = []
327
+ for line in text.splitlines():
328
+ m = _CARGO_BENCH_RE.match(line.strip())
329
+ if not m:
330
+ continue
331
+ name, val_s, unit_s, dev_s = m.groups()
332
+ mult = _TIME_TO_SEC[unit_s]
333
+ val = float(val_s.replace(",", "")) * mult
334
+ dev = float(dev_s.replace(",", "")) * mult
335
+ ci_bounds = (max(0.0, val - dev), val + dev) if dev > 0 else None
336
+ entries.append(
337
+ BenchEntry(
338
+ name=name,
339
+ value=val,
340
+ unit="s",
341
+ stddev=dev / 1.96 if dev > 0 else 0.0,
342
+ ci=ci_bounds,
343
+ higher_is_better=False,
344
+ )
345
+ )
346
+ if not entries:
347
+ raise ChipError(
348
+ "mintchip from cargo-bench: no 'cargo bench' lines found.",
349
+ fix_hint="Pipe output from: cargo bench | mintchip from cargo-bench",
350
+ )
351
+ return entries
352
+
353
+
354
+ @dataclass(frozen=True)
355
+ class JUnitSuite:
356
+ name: str
357
+ states: tuple[str, ...]
358
+ case_names: tuple[str, ...]
359
+
360
+
361
+ def parse_junit(text: str) -> list[JUnitSuite]:
362
+ """Parse JUnit XML into per-suite pass/fail/skip state sequences."""
363
+ try:
364
+ root = ET.fromstring(text.strip())
365
+ except ET.ParseError as e:
366
+ raise ChipError(
367
+ f"mintchip from junit: invalid XML ({e}).",
368
+ fix_hint="Pass a JUnit XML report (e.g. pytest --junitxml=report.xml).",
369
+ ) from None
370
+
371
+ tag = root.tag.split("}")[-1]
372
+ if tag == "testsuite":
373
+ suite_elems = [root]
374
+ elif tag == "testsuites":
375
+ suite_elems = [el for el in root if el.tag.split("}")[-1] == "testsuite"]
376
+ else:
377
+ raise ChipError(
378
+ f"mintchip from junit: unexpected root element <{tag}>.",
379
+ fix_hint="Expected <testsuite> or <testsuites> JUnit XML.",
380
+ )
381
+
382
+ suites: list[JUnitSuite] = []
383
+ for idx, suite in enumerate(suite_elems):
384
+ sname = suite.attrib.get("name") or f"suite-{idx + 1}"
385
+ cases = [el for el in suite.iter() if el.tag.split("}")[-1] == "testcase"]
386
+ states: list[str] = []
387
+ cnames: list[str] = []
388
+ if cases:
389
+ for ci, tc in enumerate(cases):
390
+ cname = tc.attrib.get("name") or f"case-{ci + 1}"
391
+ child_tags = {c.tag.split("}")[-1] for c in tc}
392
+ if "failure" in child_tags or "error" in child_tags:
393
+ st = "fail"
394
+ elif "skipped" in child_tags:
395
+ st = "skip"
396
+ else:
397
+ st = "pass"
398
+ states.append(st)
399
+ cnames.append(cname)
400
+ else:
401
+ total = int(suite.attrib.get("tests", "0") or 0)
402
+ failed = int(suite.attrib.get("failures", "0") or 0) + int(
403
+ suite.attrib.get("errors", "0") or 0
404
+ )
405
+ skipped = int(suite.attrib.get("skipped", "0") or 0)
406
+ passed = max(0, total - failed - skipped)
407
+ states = ["pass"] * passed + ["fail"] * failed + ["skip"] * skipped
408
+ cnames = [f"test-{i + 1}" for i in range(len(states))]
409
+ if states:
410
+ suites.append(JUnitSuite(name=sname, states=tuple(states), case_names=tuple(cnames)))
411
+
412
+ if not suites:
413
+ raise ChipError(
414
+ "mintchip from junit: no test cases found in JUnit XML.",
415
+ fix_hint="Ensure the JUnit XML contains at least one <testsuite> with <testcase> entries.",
416
+ )
417
+ return suites
418
+
419
+
420
+ # --- format detection ------------------------------------------------------------------------
421
+ def detect_format(text: str) -> str:
422
+ """Auto-detect the input tool format from its content."""
423
+ stripped = text.lstrip()
424
+ if not stripped:
425
+ raise ChipError(
426
+ "mintchip from auto: input is empty.",
427
+ fix_hint="Pipe tool output to stdin or pass a non-empty file path.",
428
+ )
429
+ if stripped.startswith("<") and ("<testsuite" in stripped or "<testcase" in stripped):
430
+ return "junit"
431
+ if stripped.startswith("{"):
432
+ try:
433
+ obj = json.loads(stripped)
434
+ except json.JSONDecodeError:
435
+ obj = None
436
+ if isinstance(obj, dict):
437
+ if isinstance(obj.get("results"), list) and obj["results"]:
438
+ first = obj["results"][0]
439
+ if isinstance(first, dict) and "mean" in first and "command" in first:
440
+ return "hyperfine"
441
+ if isinstance(obj.get("benchmarks"), list) and obj["benchmarks"]:
442
+ first = obj["benchmarks"][0]
443
+ if isinstance(first, dict) and isinstance(first.get("stats"), dict):
444
+ return "pytest-bench"
445
+ lines = text.splitlines()
446
+ if any(_CARGO_BENCH_RE.match(ln.strip()) for ln in lines):
447
+ return "cargo-bench"
448
+ if any(_GO_BENCH_RE.match(ln.strip()) for ln in lines):
449
+ return "go-bench"
450
+ if any(_GIT_NUMSTAT_RE.match(ln.strip("\r\n")) for ln in lines):
451
+ return "git-diff"
452
+ raise ChipError(
453
+ "mintchip from auto: could not detect input format.",
454
+ fix_hint=(
455
+ "Specify the format explicitly: "
456
+ + ", ".join(f for f in INGEST_FORMATS if f != "auto")
457
+ + "."
458
+ ),
459
+ )
460
+
461
+
462
+ # --- builders turning parsed outputs into Chip / Table ---------------------------------------
463
+ def _build_hyperfine(entries: Sequence[BenchEntry], title: str | None) -> mc.Table:
464
+ all_secs = [e.value for e in entries] + [s for e in entries for s in e.samples]
465
+ mult, unit = pick_time_unit(all_secs)
466
+ has_dist = any(len(e.samples) >= 2 for e in entries)
467
+ has_ci = not has_dist and any(e.stddev and e.stddev > 0 for e in entries)
468
+
469
+ rows: list[dict[str, Any]] = []
470
+ for e in entries:
471
+ row: dict[str, Any] = {
472
+ "command": e.name,
473
+ "mean": e.value * mult,
474
+ }
475
+ if has_dist:
476
+ row["times"] = [s * mult for s in e.samples] if len(e.samples) >= 2 else None
477
+ elif has_ci:
478
+ half = 1.96 * (e.stddev or 0.0) * mult
479
+ v = e.value * mult
480
+ row["ci"] = [v, max(0.0, v - half), v + half]
481
+ rows.append(row)
482
+
483
+ columns: dict[str, Any] = {
484
+ "command": {"chip": "text", "header": "Command"},
485
+ "mean": {"chip": "num", "header": "Mean", "unit": unit},
486
+ }
487
+ if has_dist:
488
+ columns["times"] = {"chip": "dist", "header": "Distribution", "unit": unit}
489
+ elif has_ci:
490
+ columns["ci"] = {
491
+ "chip": "ci",
492
+ "header": "95% CI",
493
+ "unit": unit,
494
+ "level": 0.95,
495
+ "reference": None,
496
+ }
497
+ return mc.table(rows, columns, title=title)
498
+
499
+
500
+ def _build_pytest_bench(entries: Sequence[BenchEntry], title: str | None) -> mc.Table:
501
+ all_secs = [e.value for e in entries] + [
502
+ b for e in entries if e.ci is not None for b in e.ci
503
+ ]
504
+ mult, unit = pick_time_unit(all_secs)
505
+ has_ci = any(e.ci is not None for e in entries)
506
+ max_val = max((e.value * mult for e in entries), default=1.0) or 1.0
507
+
508
+ rows: list[dict[str, Any]] = []
509
+ for e in entries:
510
+ v = e.value * mult
511
+ row: dict[str, Any] = {"benchmark": e.name, "mean": v}
512
+ if has_ci:
513
+ if e.ci is not None:
514
+ row["spread"] = [v, e.ci[0] * mult, e.ci[1] * mult]
515
+ else:
516
+ row["spread"] = [v, v, v]
517
+ else:
518
+ row["rel"] = {"value": v, "total": max_val}
519
+ rows.append(row)
520
+
521
+ columns: dict[str, Any] = {
522
+ "benchmark": {"chip": "text", "header": "Benchmark"},
523
+ "mean": {"chip": "num", "header": "Mean", "unit": unit},
524
+ }
525
+ if has_ci:
526
+ columns["spread"] = {
527
+ "chip": "ci",
528
+ "header": "95% CI",
529
+ "unit": unit,
530
+ "level": 0.95,
531
+ "reference": None,
532
+ }
533
+ else:
534
+ columns["rel"] = {"chip": "bar", "header": "Relative", "unit": unit}
535
+ return mc.table(rows, columns, title=title)
536
+
537
+
538
+ def _build_go_bench(entries: Sequence[BenchEntry], title: str | None) -> mc.Table:
539
+ all_secs = [e.value for e in entries] + [s for e in entries for s in e.samples]
540
+ mult, unit = pick_time_unit(all_secs)
541
+ has_dist = any(len(e.samples) >= 2 for e in entries)
542
+ max_val = max((e.value * mult for e in entries), default=1.0) or 1.0
543
+ extra_keys = {k for e in entries for k, _ in e.extra}
544
+
545
+ rows: list[dict[str, Any]] = []
546
+ for e in entries:
547
+ v = e.value * mult
548
+ ex = dict(e.extra)
549
+ row: dict[str, Any] = {"benchmark": e.name}
550
+ if has_dist:
551
+ row["mean"] = v
552
+ row["dist"] = [s * mult for s in e.samples] if len(e.samples) >= 2 else None
553
+ else:
554
+ row["time"] = {"value": v, "total": max_val}
555
+ if "bytes" in extra_keys:
556
+ row["bytes"] = ex.get("bytes")
557
+ if "allocs" in extra_keys:
558
+ row["allocs"] = ex.get("allocs")
559
+ rows.append(row)
560
+
561
+ columns: dict[str, Any] = {"benchmark": {"chip": "text", "header": "Benchmark"}}
562
+ if has_dist:
563
+ columns["mean"] = {"chip": "num", "header": "Mean", "unit": unit}
564
+ columns["dist"] = {"chip": "dist", "header": "Distribution", "unit": unit}
565
+ else:
566
+ columns["time"] = {"chip": "bar", "header": "Time/op", "unit": unit}
567
+ if "bytes" in extra_keys:
568
+ columns["bytes"] = {"chip": "num", "header": "B/op", "unit": "B"}
569
+ if "allocs" in extra_keys:
570
+ columns["allocs"] = {"chip": "num", "header": "Allocs"}
571
+ return mc.table(rows, columns, title=title)
572
+
573
+
574
+ def _build_cargo_bench(entries: Sequence[BenchEntry], title: str | None) -> mc.Table:
575
+ all_secs = [e.value for e in entries] + [
576
+ b for e in entries if e.ci is not None for b in e.ci
577
+ ]
578
+ mult, unit = pick_time_unit(all_secs)
579
+ has_jitter = any(e.ci is not None for e in entries)
580
+ max_val = max((e.value * mult for e in entries), default=1.0) or 1.0
581
+
582
+ rows: list[dict[str, Any]] = []
583
+ for e in entries:
584
+ v = e.value * mult
585
+ row: dict[str, Any] = {
586
+ "benchmark": e.name,
587
+ "time": {"value": v, "total": max_val},
588
+ }
589
+ if has_jitter:
590
+ row["jitter"] = ((e.ci[1] - e.ci[0]) / 2.0 * mult) if e.ci is not None else 0.0
591
+ rows.append(row)
592
+
593
+ columns: dict[str, Any] = {
594
+ "benchmark": {"chip": "text", "header": "Benchmark"},
595
+ "time": {"chip": "bar", "header": "Time/iter", "unit": unit},
596
+ }
597
+ if has_jitter:
598
+ columns["jitter"] = {"chip": "num", "header": "+/-", "unit": unit}
599
+ return mc.table(rows, columns, title=title)
600
+
601
+
602
+ def _build_junit(suites: Sequence[JUnitSuite], title: str | None) -> Chip | mc.Table:
603
+ if len(suites) == 1:
604
+ s = suites[0]
605
+ return mc.strip(list(s.states), names=list(s.case_names), label=title or s.name)
606
+ rows: list[dict[str, Any]] = []
607
+ for s in suites:
608
+ passed = s.states.count("pass")
609
+ total = len(s.states)
610
+ rows.append(
611
+ {
612
+ "suite": s.name,
613
+ "results": {"values": list(s.states), "names": list(s.case_names)},
614
+ "pass_rate": {"value": passed, "total": total},
615
+ }
616
+ )
617
+ columns = {
618
+ "suite": {"chip": "text", "header": "Suite"},
619
+ "results": {"chip": "strip", "header": "Results"},
620
+ "pass_rate": {"chip": "bar", "header": "Passed"},
621
+ }
622
+ return mc.table(rows, columns, title=title)
623
+
624
+
625
+ def ingest(text: str, *, fmt: str = "auto", title: str | None = None) -> Chip | mc.Table:
626
+ """Parse tool output in ``fmt`` (or ``auto``) and return a :class:`Chip` or :class:`Table`."""
627
+ chosen = fmt.strip().lower()
628
+ if chosen not in INGEST_FORMATS:
629
+ close = difflib.get_close_matches(chosen, INGEST_FORMATS, n=1, cutoff=0.5)
630
+ hint = f"Did you mean {close[0]!r}? " if close else ""
631
+ raise ChipError(
632
+ f"mintchip from: unknown format {fmt!r}.",
633
+ fix_hint=f"{hint}Formats: {', '.join(INGEST_FORMATS)}.",
634
+ )
635
+ if chosen == "auto":
636
+ chosen = detect_format(text)
637
+
638
+ if chosen == "git-diff":
639
+ parts = parse_git_diff(text)
640
+ return mc.share(parts, label=title or "Changed lines", unit="lines")
641
+ if chosen == "hyperfine":
642
+ return _build_hyperfine(parse_hyperfine(text), title=title)
643
+ if chosen == "pytest-bench":
644
+ return _build_pytest_bench(parse_pytest_bench(text), title=title)
645
+ if chosen == "go-bench":
646
+ return _build_go_bench(parse_go_bench(text), title=title)
647
+ if chosen == "cargo-bench":
648
+ return _build_cargo_bench(parse_cargo_bench(text), title=title)
649
+ if chosen == "junit":
650
+ return _build_junit(parse_junit(text), title=title)
651
+ raise AssertionError(f"unhandled format {chosen!r}")
652
+
653
+
654
+ def render_result(obj: Chip | mc.Table, *, format: str = "text", ascii: bool = False) -> str:
655
+ """Render either a :class:`Chip` or :class:`Table` in ``format``."""
656
+ from .cli import _bad_format, chip_output
657
+
658
+ if format not in OUTPUT_FORMATS:
659
+ raise _bad_format(format, OUTPUT_FORMATS)
660
+ if isinstance(obj, Chip):
661
+ return chip_output(obj, format=format, ascii=ascii)
662
+ if format == "json":
663
+ return json.dumps(obj.to_dict(), indent=2, ensure_ascii=ascii)
664
+ if format == "md":
665
+ return obj.markdown()
666
+ if format == "html":
667
+ return obj.html()
668
+ return obj.text(ascii=ascii, color=format == "ansi")
669
+
670
+
671
+ def add_from_parser(sub: Any, formatter_class: Any) -> argparse.ArgumentParser:
672
+ """Register the ``mintchip from`` subcommand."""
673
+ p = sub.add_parser(
674
+ "from",
675
+ help="Ingest SWE tool output (git-diff, hyperfine, pytest/go/cargo bench, junit).",
676
+ description=(
677
+ "Convert standard developer tool output directly into a chip or shared-scale table\n"
678
+ "with zero external dependencies. Pass 'auto' to auto-detect the tool format.\n"
679
+ "Formats: auto, git-diff, hyperfine, pytest-bench, go-bench, cargo-bench, junit."
680
+ ),
681
+ epilog=(
682
+ "examples:\n"
683
+ " $ git diff --numstat | mintchip from git-diff\n"
684
+ " $ mintchip from hyperfine bench.json --format md\n"
685
+ " $ mintchip from auto report.xml"
686
+ ),
687
+ formatter_class=formatter_class,
688
+ )
689
+ p.add_argument(
690
+ "source_format",
691
+ metavar="FORMAT",
692
+ help="Input tool format: auto, git-diff, hyperfine, pytest-bench, go-bench, cargo-bench, junit.",
693
+ )
694
+ p.add_argument(
695
+ "file",
696
+ nargs="?",
697
+ default="-",
698
+ metavar="FILE",
699
+ help="Input file path; - (default) reads stdin.",
700
+ )
701
+ p.add_argument(
702
+ "--format",
703
+ choices=OUTPUT_FORMATS,
704
+ default="text",
705
+ help="Output format: text (default), ansi, md, html or json.",
706
+ )
707
+ p.add_argument("--ascii", action="store_true", help="Pure ASCII output.")
708
+ p.add_argument("--strict", action="store_true", help="Exit 1 on any warning.")
709
+ p.add_argument("--title", help="Optional label (for chips) or title (for tables).")
710
+ p.set_defaults(func=cmd_from, _parser=p)
711
+ return p
712
+
713
+
714
+ def cmd_from(args: argparse.Namespace) -> int:
715
+ """Execute ``mintchip from``."""
716
+ from .cli import _error, _out, _read, _warn
717
+
718
+ try:
719
+ raw = _read(args.file)
720
+ obj = ingest(raw, fmt=args.source_format, title=args.title)
721
+ out = render_result(obj, format=args.format, ascii=args.ascii)
722
+ except ChipError as e:
723
+ return _error(e, "mintchip from auto bench.json")
724
+ _out(out)
725
+ return _warn(obj.warnings, args.strict)