record_cmd.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. """Windows-friendly command recorder. Writes <name>.log and <name>.meta."""
  3. from __future__ import annotations
  4. import hashlib
  5. import os
  6. import subprocess
  7. import sys
  8. import time
  9. from datetime import datetime, timezone
  10. from pathlib import Path
  11. def _utc() -> str:
  12. return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
  13. def main() -> int:
  14. if len(sys.argv) < 3:
  15. raise SystemExit("usage: record_cmd.py NAME command...")
  16. name = sys.argv[1]
  17. cmd = sys.argv[2:]
  18. run = Path(os.environ["HTH_RUN_DIR"])
  19. run.mkdir(parents=True, exist_ok=True)
  20. start = _utc()
  21. t0 = time.time()
  22. log = run / f"{name}.log"
  23. meta = run / f"{name}.meta"
  24. proc = subprocess.run(cmd, cwd=os.environ.get("HTH_REC_CWD") or os.getcwd(), capture_output=True)
  25. out = (proc.stdout or b"") + (proc.stderr or b"")
  26. log.write_bytes(out)
  27. end = _utc()
  28. status = "PASS" if proc.returncode == 0 else ("NOT RUN" if proc.returncode == 2 else "FAIL")
  29. meta.write_text(
  30. "\n".join(
  31. [
  32. f"run_id={os.environ.get('HTH_RUN_ID', run.name)}",
  33. f"commit={os.environ.get('HTH_GIT_COMMIT', '')}",
  34. f"tree={os.environ.get('HTH_GIT_TREE', '')}",
  35. f"dirty={os.environ.get('HTH_GIT_DIRTY', 'dirty')}",
  36. f"cwd={os.getcwd()}",
  37. f"start_utc={start}",
  38. f"end_utc={end}",
  39. f"duration_s={int(time.time() - t0)}",
  40. f"exit={proc.returncode}",
  41. f"status={status}",
  42. f"log_sha256={hashlib.sha256(out).hexdigest()}",
  43. f"command={' '.join(cmd)}",
  44. "",
  45. ]
  46. ),
  47. encoding="utf-8",
  48. )
  49. print(f"{name} status={status} exit={proc.returncode}")
  50. return proc.returncode
  51. if __name__ == "__main__":
  52. raise SystemExit(main())