plugins_cmd_update_all.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """``hermes plugins update`` with no name: update every installed plugin that has an update.
  2. The list comes from the read-only ``check-updates`` probe (:func:`hermes_cli.plugins_updates.run_checks`);
  3. each plugin is then updated through the single-plugin
  4. path (:func:`~hermes_cli.plugins_cmd_update.update_one`), so catalog consent, the security scan and
  5. capability re-consent still apply per plugin.
  6. Sibling of :mod:`hermes_cli.plugins_cmd` (the facade is imported late, never at module level).
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import sys
  11. from dataclasses import dataclass, field
  12. from typing import Any
  13. # Only these classes have an update path `hermes plugins update <name>` can drive: a catalog install
  14. # re-pins to the reviewed sha, a tracked git install pulls. A pip row is a PyPI distribution that
  15. # Hermes never upgrades (#132494), so offering it would promise an update nothing applies.
  16. _UPDATE_KIND = {"catalog": "catalog re-pin", "git": "git pull"}
  17. logger = logging.getLogger(__name__)
  18. def _pc():
  19. from hermes_cli import plugins_cmd
  20. return plugins_cmd
  21. @dataclass
  22. class UpdatePlan:
  23. """What ``update`` with no name would do: *movable* rows it updates, *skipped* ``(row, reason)``
  24. pairs it cannot move, *current* the count already up to date."""
  25. movable: list[Any] = field(default_factory=list)
  26. skipped: list[tuple[Any, str]] = field(default_factory=list)
  27. current: int = 0
  28. def plan_update_all(results: list[Any], installs: dict | None = None) -> UpdatePlan:
  29. """Split ``run_checks`` rows into the plugins ``update`` can move and the ones it cannot (with why).
  30. *installs* (the install records the check ran against) lets a catalog install held with ``--ref``
  31. be skipped: only naming it (``hermes plugins update <name>``) moves it."""
  32. from hermes_cli.plugins_auto_update import HELD_WITH_REF, held_with_ref
  33. from hermes_cli.plugins_updates import held_for_newer_hermes
  34. plan = UpdatePlan()
  35. installs = installs or {}
  36. for row in results:
  37. if row.needs_fixing:
  38. plan.skipped.append((row, f"needs fixing: {row.needs_fixing}"))
  39. elif row.update_available is True and (held := held_for_newer_hermes(row)):
  40. plan.skipped.append((row, f"update available after updating Hermes ({held})"))
  41. elif row.update_available is True and held_with_ref(installs.get(row.name)):
  42. plan.skipped.append((row, HELD_WITH_REF.format(name=row.name)))
  43. elif row.update_available is True and row.klass in _UPDATE_KIND:
  44. plan.movable.append(row)
  45. elif row.update_available is True:
  46. plan.skipped.append((row, f"{row.klass} distribution; Hermes does not upgrade it"))
  47. elif row.update_available is None:
  48. plan.skipped.append((row, row.reason or "update status unknown"))
  49. elif row.reason: # up to date by construction but worth naming (pinned)
  50. plan.skipped.append((row, row.reason))
  51. else:
  52. plan.current += 1
  53. return plan
  54. def _short(reason: str) -> str:
  55. first = reason.strip().splitlines()[0] if reason.strip() else ""
  56. return first if len(first) <= 200 else first[:197] + "..."
  57. def _update_one(row, console, *, interactive: bool) -> tuple[str, str]:
  58. """Run the single-plugin update for one plan row; return ``(status, detail)``, status being
  59. updated/current/failed. A refusal is printed like ``update <name>`` prints it, then recorded."""
  60. from rich.markup import escape
  61. from hermes_cli.plugins_cmd_catalog import RepinConsentRequired
  62. from hermes_cli.plugins_cmd_update import update_one
  63. target = _pc()._user_installed_plugin_dir(row.name)
  64. if target is None:
  65. return "failed", "no longer installed"
  66. try:
  67. moved = update_one(row.name, target, console, interactive=interactive)
  68. except RepinConsentRequired as exc:
  69. console.print(f"[yellow]Update of {escape(row.name)} not applied:[/yellow] {escape(str(exc))}")
  70. return "failed", _short(f"not applied: {exc}")
  71. except _pc().PluginOperationError as exc:
  72. console.print(f"[red]Error:[/red] {escape(str(exc))}")
  73. return "failed", _short(str(exc))
  74. except Exception as exc: # per-plugin batch boundary: a feed timeout or crash must not stop the rest
  75. logger.warning("update of plugin %s failed", row.name, exc_info=True)
  76. console.print(f"[red]Error:[/red] {escape(type(exc).__name__)}: {escape(str(exc))}")
  77. return "failed", _short(f"{type(exc).__name__}: {exc}")
  78. if not moved:
  79. return "current", ""
  80. return "updated", f"{(row.current or '')[:8]}..{(row.latest or '')[:8]}"
  81. def _print_plan(console, plan: UpdatePlan) -> None:
  82. from rich.markup import escape
  83. table = _pc()._table([("#", "dim"), ("Plugin", "bold"), ("Current", ""), ("Latest", ""), ("Update", "")],
  84. title="Plugin updates available")
  85. for i, row in enumerate(plan.movable, 1):
  86. table.add_row(str(i), row.name, (row.current or "-")[:12], (row.latest or "-")[:12], _UPDATE_KIND[row.klass])
  87. console.print()
  88. console.print(table)
  89. for row, reason in plan.skipped:
  90. console.print(f" [dim]skipped {escape(row.name)} ({row.klass}): {escape(reason)}[/dim]")
  91. def cmd_update_all(*, yes: bool = False) -> None:
  92. """``hermes plugins update [--yes]``: list the plugins with an update and update them all.
  93. A terminal asks once (``Update all N? [Y/n]``); without one nothing moves unless ``--yes`` is
  94. given. Each plugin then goes through ``update_one``, interactive only when a terminal is present,
  95. so per-plugin consent prompts still appear there and stay closed (fail closed) under ``--yes``
  96. in scripts. One failure does not stop the rest; exit 1 when any update failed.
  97. """
  98. from rich.markup import escape
  99. from hermes_cli.plugins_updates import run_checks
  100. console = _pc()._console()
  101. console.print("[dim]Checking installed plugins for updates...[/dim]")
  102. from hermes_cli.plugins_cadence import snapshot_installs
  103. plugins_dir = _pc()._plugins_dir()
  104. checked = snapshot_installs(plugins_dir)
  105. plan = plan_update_all(run_checks(plugins_dir), checked)
  106. if not plan.movable:
  107. for row, reason in plan.skipped:
  108. console.print(f" [dim]skipped {escape(row.name)} ({row.klass}): {escape(reason)}[/dim]")
  109. console.print("[green]✓[/green] No plugin updates to apply.")
  110. return
  111. _print_plan(console, plan)
  112. count = len(plan.movable)
  113. tty = _pc()._is_tty()
  114. if not yes:
  115. if not tty:
  116. _pc()._fail(console, f"[yellow]Not updating: no terminal to confirm. Re-run with --yes to update "
  117. f"these {count} plugin(s).[/yellow]")
  118. try:
  119. answer = input(f"\nUpdate all {count}? [Y/n]: ").strip().lower()
  120. except (EOFError, KeyboardInterrupt):
  121. answer = "n"
  122. if answer not in ("", "y", "yes"):
  123. console.print("Cancelled. Nothing was updated.")
  124. return
  125. outcomes = []
  126. for row in plan.movable:
  127. console.print(f"\n[bold]── {row.name}[/bold]")
  128. outcomes.append((row.name, *_update_one(row, console, interactive=tty)))
  129. console.print("\n[bold]Summary[/bold]")
  130. marks = {"updated": "[green]✓ updated[/green]", "current": "[dim]= already current[/dim]",
  131. "failed": "[red]✗ failed[/red]"}
  132. for name, status, detail in outcomes:
  133. console.print(f" {marks[status]} {escape(name)}" + (f" [dim]{escape(detail)}[/dim]" if detail else ""),
  134. highlight=False)
  135. if any(status == "failed" for _, status, _ in outcomes):
  136. sys.exit(1)