Coverage for collectra/gui/run_log.py: 100.00%
49 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Append-only plain-text log of the runs started from the GUI Run button."""
3from __future__ import annotations
5import re
6from datetime import datetime
7from pathlib import Path
9from collectra.pipelines.run_plan import RunPlan, RunReport
11LOG_NAME = "run-log.txt"
12NOTE_LIMIT = 200
15def clean_note(note: str) -> str:
16 """Collapse all whitespace to single spaces, trim and cap the length."""
17 return " ".join(note.split())[:NOTE_LIMIT]
20def _append(folder: Path, lines: list[str]) -> None:
21 """Append lines to the log; raises OSError if it cannot be written."""
22 with open(folder / LOG_NAME, "a", encoding="utf-8") as handle:
23 handle.write("\n".join(lines) + "\n")
26def begin_entry(
27 folder: Path,
28 *,
29 pipeline: str,
30 version: str | None,
31 note: str,
32 plan: RunPlan,
33 now: datetime | None = None,
34) -> None:
35 """Append the "started" block of a run: when, what, and the plan."""
36 now = now or datetime.now()
37 title = f"{pipeline} {version}" if version else pipeline
38 lines = ["", f"{now:%Y-%m-%d %H:%M:%S} started {title}"]
39 note = clean_note(note)
40 if note:
41 lines.append(f" note: {note}")
42 for warning in plan.warnings:
43 lines.append(f" warning: {warning}")
44 for task in plan.tasks:
45 lines.append(f" {task.name} planned to {task.action}: {task.reason}")
46 _append(folder, lines)
49def _outcome_line(name: str, status: str, detail: str) -> str:
50 """The one-line description of what happened to a task."""
51 detail = " ".join(detail.split())
52 if status == "re-ran":
53 kept = "produced nothing, kept existing output"
54 text = f"re-ran, {kept if kept in detail else 'replaced existing output'}"
55 match = re.search(r"upstream (\S+) ran", detail)
56 if match:
57 text += f" (upstream {match.group(1)} ran)"
58 elif status == "skipped":
59 text = "skipped (kept existing output)"
60 elif status in ("failed", "cancelled"):
61 text = f"{status}: {detail}" if detail else status
62 else:
63 text = status
64 return f" {name} {text}"
67def summarize(report: RunReport) -> str:
68 """How many tasks ran, were skipped, failed and were cancelled."""
69 statuses = [outcome.status for outcome in report.outcomes]
70 ran = statuses.count("ran") + statuses.count("re-ran")
71 summary = (
72 f"{ran} ran, {statuses.count('skipped')} skipped,"
73 f" {statuses.count('failed')} failed"
74 )
75 if statuses.count("cancelled"):
76 summary += f", {statuses.count('cancelled')} cancelled"
77 return summary
80def finish_entry(folder: Path, report: RunReport, seconds: float) -> None:
81 """Append one line per task outcome and a summary line."""
82 lines = [_outcome_line(o.name, o.status, o.detail) for o in report.outcomes]
83 lines.append(f" result {summarize(report)}, {seconds:.1f} s")
84 _append(folder, lines)