Model the safety net that makes lost commits recoverable.
What to build
A program that simulates commits, amends and resets while recording a reflog, and recovers commits from it.
Requirements
- Commands:
commit MESSAGE…(new id c1, c2, … with HEAD as parent; reflogcommit: MESSAGE),amend MESSAGE…(new id with HEAD's parent; reflogcommit (amend): MESSAGE),reset TARGETwhere TARGET is an id orHEAD@{N}(reflogreset: moving to TARGET),log(ID MESSAGEfrom HEAD through parents), andreflog(ID HEAD@{N}: ACTION, newest first). - The repository starts with no commits; there is no
logorresetbefore the first commit.
Input
Line 1: m. Then m commands.
Output
The lines printed by log and reflog.
Constraints
m ≤ 200.
Example
Input:
6
commit First
commit Second
commit Third
reset c1
log
reflog
Output:
c1 First
c1 HEAD@{0}: reset: moving to c1
c3 HEAD@{1}: commit: Third
c2 HEAD@{2}: commit: Second
c1 HEAD@{3}: commit: First
Why it works
Resets and amends only move HEAD; the old commits stay in the database, and the reflog remembers every place HEAD has been, so any of them can be reached again.
Examples
6 commit First commit Second commit Third reset c1 log reflog
c1 First
c1 HEAD@{0}: reset: moving to c1
c3 HEAD@{1}: commit: Third
c2 HEAD@{2}: commit: Second
c1 HEAD@{3}: commit: First
5
commit First
commit Second
reset c1
reset HEAD@{1}
log
c2 Second c1 First
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the commits (id → parent and message), the current HEAD and a list of reflog entries; every command that moves HEAD adds an entry at the front.
Hint 2
`HEAD@{N}` is the reflog entry N positions back, where 0 is the newest.
Solution
Show one correct solution (try it yourself first)
commits, head, reflog = {}, None, []
for _ in range(int(input())):
command, _, rest = input().partition(" ")
if command in ("commit", "amend"):
oid = f"c{len(commits) + 1}"
parent = head if command == "commit" else commits[head][0]
commits[oid] = (parent, rest)
head = oid
reflog.insert(0, (oid, ("commit: " if command == "commit" else "commit (amend): ") + rest))
elif command == "reset":
target = reflog[int(rest[6:-1])][0] if rest.startswith("HEAD@{") else rest
head = target
reflog.insert(0, (head, f"reset: moving to {rest}"))
elif command == "log":
oid = head
while oid:
print(oid, commits[oid][1])
oid = commits[oid][0]
else:
for n, (oid, action) in enumerate(reflog):
print(f"{oid} HEAD@{{{n}}}: {action}")
Lesson: Undoing changes: restore, reset, revert and the reflog →