Git: Recover commits with the reflog

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; reflog commit: MESSAGE), amend MESSAGE… (new id with HEAD's parent; reflog commit (amend): MESSAGE), reset TARGET where TARGET is an id or HEAD@{N} (reflog reset: moving to TARGET), log (ID MESSAGE from HEAD through parents), and reflog (ID HEAD@{N}: ACTION, newest first).
  • The repository starts with no commits; there is no log or reset before 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

Example 1 · Input
6
commit First
commit Second
commit Third
reset c1
log
reflog
Expected 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
Example 2 · Input
5
commit First
commit Second
reset c1
reset HEAD@{1}
log
Expected output
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 →