git.py 980 B

12345678910111213141516171819202122232425262728293031323334
  1. """Git utilities."""
  2. # Used also from setup.py, so don't pull in anything additional here (like mypy or typing):
  3. from __future__ import annotations
  4. import os
  5. import subprocess
  6. def is_git_repo(dir: str) -> bool:
  7. """Is the given directory version-controlled with git?"""
  8. return os.path.exists(os.path.join(dir, ".git"))
  9. def have_git() -> bool:
  10. """Can we run the git executable?"""
  11. try:
  12. subprocess.check_output(["git", "--help"])
  13. return True
  14. except subprocess.CalledProcessError:
  15. return False
  16. except OSError:
  17. return False
  18. def git_revision(dir: str) -> bytes:
  19. """Get the SHA-1 of the HEAD of a git repository."""
  20. return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=dir).strip()
  21. def is_dirty(dir: str) -> bool:
  22. """Check whether a git repository has uncommitted changes."""
  23. output = subprocess.check_output(["git", "status", "-uno", "--porcelain"], cwd=dir)
  24. return output.strip() != b""