Git: Apply an interactive rebase to-do list

Carry out the edits of an interactive rebase.

What to build

A program that applies an interactive rebase to-do list and prints the resulting commits.

Requirements

  • Actions: pick ID keeps the commit; reword ID MESSAGE… keeps it with a new message; squash ID adds its message to the previous new commit, joined with +; fixup ID melds it into the previous commit, keeping only that commit's message; drop ID removes it. New commits are numbered n1, n2, … in the final order.
  • Print nK MESSAGE for each resulting commit, oldest first, or nothing to do if none remain.

Input

Line 1: c. Then c lines ID MESSAGE… (the original commits). Then t and t to-do lines.

Output

One line per resulting commit.

Constraints

c, t ≤ 100; the first kept line is never squash or fixup.

Example

Input:

3
f1 Add search box
f2 Fix typo
f3 Search results
3
pick f1
fixup f2
pick f3

Output:

n1 Add search box
n2 Search results

Why it works

Each to-do line either adds a commit, changes the previous one, or removes one, so processing them in order rebuilds the series exactly as described.

Examples

Example 1 · Input
3
f1 Add search box
f2 Fix typo
f3 Search results
3
pick f1
fixup f2
pick f3
Expected output
n1 Add search box
n2 Search results
Example 2 · Input
2
a First
b Second
2
reword a Initial version
squash b
Expected output
n1 Initial version + Second

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Process the to-do lines in order, building a list of new commits; squash and fixup change the last one instead of adding.

Hint 2

reword lines carry the new message after the id: `reword ID NEW MESSAGE`.

Solution

Show one correct solution (try it yourself first)
messages = dict(input().split(maxsplit=1) for _ in range(int(input())))
result = []
for _ in range(int(input())):
    parts = input().split(maxsplit=2)
    action, oid = parts[0], parts[1]
    if action == "pick":
        result.append(messages[oid])
    elif action == "reword":
        result.append(parts[2])
    elif action == "squash":
        result[-1] += " + " + messages[oid]
print("\n".join(f"n{k} {m}" for k, m in enumerate(result, start=1)) if result else "nothing to do")

Lesson: Rebasing →