Get the SHA-1 of HEAD by reading git files directly, without a subprocess. Returns None if the revision cannot be determined this way (e.g. unusual git state), in which case the caller should fall back to git_revision().
(dir: str)
| 29 | |
| 30 | |
| 31 | def git_revision_no_subprocess(dir: str) -> bytes | None: |
| 32 | """Get the SHA-1 of HEAD by reading git files directly, without a subprocess. |
| 33 | |
| 34 | Returns None if the revision cannot be determined this way (e.g. unusual |
| 35 | git state), in which case the caller should fall back to git_revision(). |
| 36 | """ |
| 37 | try: |
| 38 | head_path = os.path.join(dir, ".git", "HEAD") |
| 39 | with open(head_path, "rb") as f: |
| 40 | head = f.read().strip() |
| 41 | if head.startswith(b"ref: "): |
| 42 | ref = head[5:] # e.g. b"refs/heads/main" |
| 43 | ref_path = os.path.join(dir, ".git", os.fsdecode(ref)) |
| 44 | if os.path.exists(ref_path): |
| 45 | with open(ref_path, "rb") as f: |
| 46 | return f.read().strip() |
| 47 | # The ref may be in packed-refs instead of a loose file. |
| 48 | packed_refs_path = os.path.join(dir, ".git", "packed-refs") |
| 49 | if os.path.exists(packed_refs_path): |
| 50 | with open(packed_refs_path, "rb") as f: |
| 51 | for line in f: |
| 52 | if line.startswith(b"#"): |
| 53 | continue |
| 54 | parts = line.strip().split() |
| 55 | if len(parts) >= 2 and parts[1] == ref: |
| 56 | return parts[0] |
| 57 | return None |
| 58 | # Detached HEAD: content is the SHA itself. |
| 59 | if len(head) == 40 and all(chr(c) in "0123456789abcdef" for c in head): |
| 60 | return head |
| 61 | return None |
| 62 | except OSError: |
| 63 | return None |
| 64 | |
| 65 | |
| 66 | def is_dirty(dir: str) -> bool: |
nothing calls this directly
no test coverage detected
searching dependent graphs…