Git: Compute git status --short

Work out exactly what git status --short prints.

What to build

A program that computes the short status lines from HEAD, the index and the working tree.

Requirements

  • For every path in HEAD or the index: X is A if it is in the index but not HEAD, D if in HEAD but not the index, M if both and different, else a space; Y is D if it is in the index but not the working tree, M if both and different, else a space. Print XY path unless both are spaces.
  • Then print ?? path for every path in the working tree that is not in the index. Both groups are sorted by path. If nothing is printed, print nothing to commit, working tree clean.

Input

Three blocks, for HEAD, the index and the working tree: a line with k, then k lines path content.

Output

The status lines.

Constraints

At most 200 paths; no spaces in paths or contents.

Example

Input:

1
app.py v1
1
app.py v1
2
app.py v2
notes.txt n1

Output:

 M app.py
?? notes.txt

Why it works

The index sits between HEAD and the working tree, so each file has two independent comparisons: what is staged, and what is not staged yet.

Examples

Example 1 · Input
1
app.py v1
1
app.py v1
2
app.py v2
notes.txt n1
Expected output
 M app.py
?? notes.txt
Example 2 · Input
1
app.py v1
2
app.py v2
notes.txt n1
2
app.py v3
notes.txt n1
Expected output
MM app.py
A  notes.txt

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

Hints

Hint 1

First letter: compare the index with HEAD (A, D, M or space). Second letter: compare the working tree with the index (D, M or space).

Hint 2

A path in the working tree but not in the index is untracked (`??`); list untracked paths after the others.

Solution

Show one correct solution (try it yourself first)
head = dict(input().split() for _ in range(int(input())))
index = dict(input().split() for _ in range(int(input())))
work = dict(input().split() for _ in range(int(input())))
lines = []
for path in sorted(set(head) | set(index)):
    if path not in head:
        x = "A"
    elif path not in index:
        x = "D"
    else:
        x = "M" if head[path] != index[path] else " "
    if path not in index:
        y = " "
    elif path not in work:
        y = "D"
    else:
        y = "M" if work[path] != index[path] else " "
    if x + y != "  ":
        lines.append(f"{x}{y} {path}")
lines += [f"?? {path}" for path in sorted(work) if path not in index]
print("\n".join(lines) if lines else "nothing to commit, working tree clean")

Lesson: Staging and committing →