Read HEAD the way git status does on its first line.
What to build
A program that reports the current branch and commit from the contents of HEAD and the refs.
Requirements
- HEAD is either
ref: refs/heads/NAMEor a commit id. Refs are given asrefs/heads/NAME IDlines. - Print
on branch NAME at ID,on branch NAME (no commits yet)if the branch has no ref, orHEAD detached at ID(use the first 7 characters of the id in all cases).
Input
Line 1: the contents of HEAD. Line 2: r. Then r ref lines.
Output
One line.
Constraints
r ≤ 100.
Example
Input:
ref: refs/heads/main
2
refs/heads/main 2c623d019401c86e05e6f585ee783b71d4992287
refs/heads/feature 8adc98c37fe8f03bb3f34f15969d7c267a162b98
Output:
on branch main at 2c623d0
Why it works
HEAD is either a pointer to a branch, which is itself a pointer to a commit, or a direct pointer to a commit.
Examples
Example 1 · Input
ref: refs/heads/main 2 refs/heads/main 2c623d019401c86e05e6f585ee783b71d4992287 refs/heads/feature 8adc98c37fe8f03bb3f34f15969d7c267a162b98
Expected output
on branch main at 2c623d0
Example 2 · Input
8adc98c37fe8f03bb3f34f15969d7c267a162b98 1 refs/heads/main 2c623d019401c86e05e6f585ee783b71d4992287
Expected output
HEAD detached at 8adc98c
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
If HEAD's content starts with `ref: `, it names a ref; look that ref up.
Hint 2
A branch ref that does not exist yet means the branch has no commits.
Solution
Show one correct solution (try it yourself first)
head = input().strip()
refs = dict(input().split() for _ in range(int(input())))
if head.startswith("ref: "):
ref = head[5:]
name = ref.removeprefix("refs/heads/")
print(f"on branch {name} at {refs[ref][:7]}" if ref in refs else f"on branch {name} (no commits yet)")
else:
print(f"HEAD detached at {head[:7]}")