plugins_provenance.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. """Plugin provenance: the 2x2 reconciliation of install metadata.
  2. Row-presence says "hermes installed this" (the .install-metadata.json
  3. sidecar); ``.git``-presence cross-checks it. The reconciliation IS the
  4. disambiguation — ``source`` alone does not distinguish a git install
  5. from a manual copy (settled 2026-09-03, plugin-auto-update plan):
  6. row+git = git install — updatable via the recorded source
  7. neither = manual drop — not auto-updatable, listed as such
  8. git only = self-cloned — adoptable; origin URL carried ready
  9. row only = provenance drift — flagged with a reinstall remedy
  10. Pure functions over (plugins_dir, sidecar rows) — no globals, no
  11. network, fully testable. The sidecar remains the single authority for
  12. what *hermes* installed; this module only reads it.
  13. """
  14. from __future__ import annotations
  15. import json
  16. import subprocess
  17. from dataclasses import dataclass
  18. from enum import Enum
  19. from pathlib import Path
  20. from typing import Optional
  21. class ProvenanceClass(Enum):
  22. GIT = "git"
  23. MANUAL = "manual"
  24. SELF_CLONED = "self-cloned"
  25. DRIFT = "drift"
  26. @dataclass
  27. class Provenance:
  28. name: str
  29. klass: ProvenanceClass
  30. path: Path
  31. row: Optional[dict] = None # the sidecar row, when present
  32. origin_url: Optional[str] = None # self-cloned: the .git remote
  33. saved_update_url: Optional[str] = None # the row's saved feed tag
  34. def read_sidecar_rows(plugins_dir: Path) -> dict:
  35. """The install-metadata rows for this plugins dir; {} when absent
  36. or unreadable (manual-only installs never wrote one)."""
  37. sidecar = plugins_dir / ".install-metadata.json"
  38. if not sidecar.is_file():
  39. return {}
  40. try:
  41. data = json.loads(sidecar.read_text(encoding="utf-8-sig"))
  42. except (OSError, ValueError): # ValueError: bad JSON and bytes that are not UTF-8
  43. return {}
  44. return data if isinstance(data, dict) else {}
  45. def _git_origin_url(plugin_dir: Path) -> Optional[str]:
  46. """origin's URL from the installed .git — remote get-url on a real
  47. repo, config-file parse as the fallback (works for partial/copy
  48. installs where git refuses)."""
  49. # fast path: real git repo. Same resolver as install/update: PATH may be minimal
  50. # (gateway service, Windows without Git on PATH); no git → straight to the config parse.
  51. from hermes_cli.plugins_cmd import _resolve_git_executable
  52. git = _resolve_git_executable()
  53. if git is not None:
  54. try:
  55. proc = subprocess.run(
  56. [git, "-C", str(plugin_dir), "remote", "get-url", "origin"],
  57. capture_output=True,
  58. text=True, encoding="utf-8", errors="replace",
  59. timeout=10,
  60. check=False,
  61. )
  62. if proc.returncode == 0:
  63. url = (proc.stdout or "").strip()
  64. if url:
  65. return url
  66. except (OSError, subprocess.TimeoutExpired):
  67. pass
  68. # fallback: parse .git/config directly (a .git dir with a config
  69. # file is all the adopt path needs)
  70. config = plugin_dir / ".git" / "config"
  71. if not config.is_file():
  72. return None
  73. try:
  74. text = config.read_text(encoding="utf-8-sig")
  75. except OSError:
  76. return None
  77. in_origin = False
  78. for line in text.splitlines():
  79. stripped = line.strip()
  80. if stripped == '[remote "origin"]':
  81. in_origin = True
  82. continue
  83. if stripped.startswith("["):
  84. in_origin = False
  85. continue
  86. if in_origin and stripped.startswith("url"):
  87. _, _, value = stripped.partition("=")
  88. url = value.strip()
  89. return url or None
  90. return None
  91. def plugins_provenance(plugins_dir: Path) -> list[Provenance]:
  92. """Classify every plugin dir under plugins_dir per the 2x2."""
  93. rows = read_sidecar_rows(plugins_dir)
  94. out: list[Provenance] = []
  95. if not plugins_dir.is_dir():
  96. return out
  97. try:
  98. entries = sorted(plugins_dir.iterdir(), key=lambda p: p.name)
  99. except OSError:
  100. return out
  101. for plugin_dir in entries:
  102. if not plugin_dir.is_dir() or plugin_dir.name.startswith("."):
  103. continue
  104. has_git = (plugin_dir / ".git").exists()
  105. row = rows.get(plugin_dir.name)
  106. row = row if isinstance(row, dict) else None
  107. if row and has_git:
  108. klass = ProvenanceClass.GIT
  109. elif row and not has_git:
  110. klass = ProvenanceClass.DRIFT
  111. elif has_git and not row:
  112. klass = ProvenanceClass.SELF_CLONED
  113. else:
  114. klass = ProvenanceClass.MANUAL
  115. out.append(
  116. Provenance(
  117. name=plugin_dir.name,
  118. klass=klass,
  119. path=plugin_dir,
  120. row=row,
  121. origin_url=_git_origin_url(plugin_dir) if klass is ProvenanceClass.SELF_CLONED else None,
  122. saved_update_url=(row or {}).get("update_url") or None,
  123. )
  124. )
  125. return out