status_bar_git.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """Current git branch for the CLI status bar.
  2. Reads ``.git/HEAD`` directly (no subprocess) so status-bar repaints stay cheap, with a
  3. short per-directory TTL cache. Worktrees and submodules (``.git`` as a ``gitdir:``
  4. pointer file) resolve to their private git dir, whose HEAD is per-worktree.
  5. """
  6. from __future__ import annotations
  7. import os
  8. import time
  9. from pathlib import Path
  10. from typing import Optional
  11. _TTL_SECONDS = 5.0
  12. _cache: dict = {}
  13. def _resolve_git_dir(start: Path) -> Optional[Path]:
  14. """Nearest enclosing git dir for ``start``, following worktree pointer files."""
  15. for parent in (start, *start.parents):
  16. dotgit = parent / ".git"
  17. if dotgit.is_dir():
  18. return dotgit
  19. if dotgit.is_file():
  20. try:
  21. line = dotgit.read_text(encoding="utf-8-sig", errors="replace").strip()
  22. except OSError:
  23. return None
  24. if line.startswith("gitdir:"):
  25. target = (parent / line.split(":", 1)[1].strip()).resolve()
  26. return target if target.is_dir() else None
  27. return None
  28. return None
  29. def current_git_branch(cwd: Optional[str] = None) -> str:
  30. """Branch name for ``cwd`` (defaults to the process cwd); ``""`` outside a repo.
  31. A detached HEAD renders as the abbreviated commit (``a1b2c3d…``). Results are
  32. cached ~5s per directory so per-repaint calls never re-walk the tree.
  33. """
  34. try:
  35. base = Path(cwd or os.getcwd()).resolve()
  36. except OSError:
  37. return ""
  38. key = str(base)
  39. now = time.monotonic()
  40. hit = _cache.get(key)
  41. if hit and now - hit[0] < _TTL_SECONDS:
  42. return hit[1]
  43. label = ""
  44. git_dir = _resolve_git_dir(base)
  45. if git_dir is not None:
  46. try:
  47. head = (git_dir / "HEAD").read_text(encoding="utf-8-sig", errors="replace").strip()
  48. except OSError:
  49. head = ""
  50. if head.startswith("ref:"):
  51. ref = head.split(":", 1)[1].strip()
  52. label = ref[len("refs/heads/"):] if ref.startswith("refs/heads/") else ref.rsplit("/", 1)[-1]
  53. elif head:
  54. label = f"{head[:8]}…"
  55. _cache[key] = (now, label)
  56. return label