source_stamp.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Atomically publish identity for a mutable source checkout."""
  2. from __future__ import annotations
  3. from contextlib import suppress
  4. from datetime import datetime, timezone, UTC
  5. import json
  6. import os
  7. from pathlib import Path
  8. import tempfile
  9. from hermes_cli.version_info import _git_version_info, _reset_version_info_cache
  10. def write_source_stamp(root: Path, *, adopted: bool = False) -> dict | None:
  11. """Replace ``install-stamp.json`` with identity read from ``root`` itself.
  12. *adopted* marks a boot-time adoption (``adoptedAt``): identity only, nothing
  13. built, so it must never read as a completed install/update of this commit.
  14. A root git cannot identify -- the ZIP update fallback runs precisely because
  15. git is unusable -- publishes no identity: the old stamp is removed rather
  16. than left naming the commit that was just replaced. Returns None then.
  17. """
  18. root = Path(root).resolve()
  19. info = _git_version_info(root, include_untracked=True)
  20. if info.commit is None:
  21. with suppress(FileNotFoundError):
  22. (root / "install-stamp.json").unlink()
  23. _reset_version_info_cache()
  24. return None
  25. stamp = {
  26. "schemaVersion": 2,
  27. "commit": info.commit,
  28. "commitDate": info.commit_date,
  29. "branch": info.branch,
  30. "builtAt": datetime.now(UTC).isoformat(),
  31. "dirty": info.dirty,
  32. "source": "git",
  33. "distribution": None,
  34. "updateMechanism": "self",
  35. "baseVersion": info.base_version,
  36. "displayVersion": info.derived_version,
  37. "distance": info.distance,
  38. "payload": "bootstrap",
  39. "tag": None,
  40. }
  41. if adopted:
  42. stamp["adoptedAt"] = stamp["builtAt"]
  43. stamp_path = root / "install-stamp.json"
  44. fd, tmp_name = tempfile.mkstemp(dir=root, prefix=".install-stamp.", suffix=".tmp")
  45. try:
  46. with os.fdopen(fd, "w", encoding="utf-8") as handle:
  47. handle.write(json.dumps(stamp, indent=2) + "\n")
  48. handle.flush()
  49. os.fsync(handle.fileno())
  50. os.replace(tmp_name, stamp_path)
  51. with suppress(OSError):
  52. directory_fd = os.open(root, os.O_RDONLY)
  53. try:
  54. os.fsync(directory_fd)
  55. finally:
  56. os.close(directory_fd)
  57. finally:
  58. with suppress(OSError):
  59. os.unlink(tmp_name)
  60. _reset_version_info_cache()
  61. # Every path that publishes a new checkout identity (completion handoff, the PM
  62. # updater's finish, boot-time adoption) moves the installers' receipt with it.
  63. refresh_bootstrap_receipt(root, stamp)
  64. return stamp
  65. BOOTSTRAP_RECEIPT = ".hermes-bootstrap-complete"
  66. def refresh_bootstrap_receipt(root: Path, stamp: dict) -> None:
  67. """Move the installers' bootstrap receipt to the commit ``stamp`` just published.
  68. install.sh / install.ps1 write the receipt once, at the commit they installed;
  69. an update that moves the checkout has to move it too, or it keeps naming the
  70. replaced release. Only an existing receipt is refreshed: its presence is what
  71. marks a script install, so a manual clone never grows one.
  72. """
  73. receipt_path = Path(root) / BOOTSTRAP_RECEIPT
  74. try:
  75. # install.ps1 writes it with Windows PowerShell's UTF-8 BOM.
  76. previous = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
  77. except FileNotFoundError:
  78. return
  79. except (OSError, ValueError):
  80. previous = {}
  81. if not isinstance(previous, dict):
  82. previous = {}
  83. receipt = {
  84. **previous,
  85. "schemaVersion": 1,
  86. "pinnedCommit": stamp["commit"],
  87. # A detached checkout keeps the branch it was installed from.
  88. "pinnedBranch": stamp["branch"] or previous.get("pinnedBranch"),
  89. "completedAt": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
  90. }
  91. fd, tmp_name = tempfile.mkstemp(dir=root, prefix=".hermes-bootstrap-complete.", suffix=".tmp")
  92. try:
  93. with os.fdopen(fd, "w", encoding="utf-8") as handle:
  94. handle.write(json.dumps(receipt, indent=2) + "\n")
  95. os.replace(tmp_name, receipt_path)
  96. finally:
  97. with suppress(OSError):
  98. os.unlink(tmp_name)