doctor_report.py 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """Doctor output primitives shared by every ``hermes_cli.doctor_*`` module."""
  2. from __future__ import annotations
  3. import functools
  4. from contextlib import contextmanager
  5. from dataclasses import dataclass, field
  6. from hermes_cli.colors import Colors, color
  7. def _mark(glyph: str, col: str):
  8. return lambda text, detail="": print(f" {color(glyph, col)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
  9. check_ok, check_warn, check_fail = _mark("✓", Colors.GREEN), _mark("⚠", Colors.YELLOW), _mark("✗", Colors.RED)
  10. def check_info(text: str):
  11. print(f" {color('→', Colors.CYAN)} {text}")
  12. def check_bool(cond, ok, bad, *, fail: bool = False):
  13. """``check_ok(*ok)`` when *cond* else ``check_warn(*bad)`` (``check_fail`` with fail=True); returns bool(cond).
  14. *ok* / *bad* are a text string or a ``(text, detail)`` tuple."""
  15. args = ok if cond else bad
  16. (check_ok if cond else (check_fail if fail else check_warn))(*((args,) if isinstance(args, str) else args))
  17. return bool(cond)
  18. def _section(title: str) -> None:
  19. """Print a doctor section banner: blank line + bold cyan ◆ title."""
  20. print()
  21. print(color(f"◆ {title}", Colors.CYAN, Colors.BOLD))
  22. def _fail_and_issue(text: str, detail: str, fix: str, issues: list[str]) -> None:
  23. """Emit a check_fail and append the corresponding fix instruction."""
  24. check_fail(text, detail)
  25. issues.append(fix)
  26. @contextmanager
  27. def warn_on_error(text: str, detail: str = "({e})", report=check_warn):
  28. """Best-effort block: an exception prints ``report(text.format(e=e), detail.format(e=e))`` (nothing when
  29. *text* is ``""``) instead of propagating. ``{e}`` in either string is the exception."""
  30. try:
  31. yield
  32. except Exception as e:
  33. if text:
  34. report(text.format(e=e), detail.format(e=e))
  35. @dataclass
  36. class Finding:
  37. """What one doctor check contributed: auto-fixable issues, manual-only issues, fixes applied."""
  38. issues: list = field(default_factory=list)
  39. manual_issues: list = field(default_factory=list)
  40. fixed: int = 0
  41. def merge(self, other: Finding) -> None:
  42. self.issues.extend(other.issues)
  43. self.manual_issues.extend(other.manual_issues)
  44. self.fixed += other.fixed
  45. def doctor_check(on_error: str | None = None, detail: str = ""):
  46. """Turn ``fn(should_fix, f: Finding)`` into a ``(should_fix) -> Finding`` doctor check.
  47. *on_error* None: exceptions propagate (as they always did for that check). Otherwise the check is
  48. best-effort via :func:`warn_on_error` (``""`` = silent) and the partial Finding is still returned,
  49. so issues recorded before the crash survive."""
  50. def deco(fn):
  51. @functools.wraps(fn)
  52. def check(should_fix: bool) -> Finding:
  53. f = Finding()
  54. if on_error is None:
  55. fn(should_fix, f)
  56. else:
  57. with warn_on_error(on_error, detail):
  58. fn(should_fix, f)
  59. return f
  60. return check
  61. return deco
  62. def ensure_dir(f: Finding, should_fix: bool, path, exists_msg: str, created_msg: str, missing_msg: str) -> None:
  63. """ok when *path* exists; with --fix create it (counts as fixed); else warn "(will be created on first use)"."""
  64. if path.exists():
  65. check_ok(exists_msg)
  66. elif should_fix:
  67. path.mkdir(parents=True, exist_ok=True)
  68. check_ok(created_msg)
  69. f.fixed += 1
  70. else:
  71. check_warn(missing_msg, "(will be created on first use)")