Undo an old commit by applying its changes in reverse.
What to build
A program that reverts a commit on top of the current snapshot, at the level of whole files.
Requirements
- For every path that differs between the commit's parent P and the commit C: if the current snapshot H has C's version (missing counts as a version), set it to P's version (removing the file if P did not have it); otherwise it is a conflict.
- If there are conflicts, print
error: could not revert: conflict in PATHfor each, sorted, and nothing else. Otherwise print the new snapshot aspath contentlines sorted by path, or(empty).
Input
Three blocks for P, C and H: a line with k, then k lines path content.
Output
The new snapshot, or the conflict lines.
Constraints
At most 200 paths.
Example
Input:
1
a.txt v1
1
a.txt v2
2
a.txt v2
b.txt v1
Output:
a.txt v1
b.txt v1
Why it works
Reverting applies the opposite of each change the commit made, which is only safe where nothing has changed the file since.
Examples
1 a.txt v1 1 a.txt v2 2 a.txt v2 b.txt v1
a.txt v1 b.txt v1
1 a.txt v1 1 a.txt v2 1 a.txt v3
error: could not revert: conflict in a.txt
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The commit's changes are the paths that differ between its parent and itself.
Hint 2
To undo a change to a path, the current version must still equal the commit's version; then it goes back to the parent's version.
Solution
Show one correct solution (try it yourself first)
p = dict(input().split() for _ in range(int(input())))
c = dict(input().split() for _ in range(int(input())))
h = dict(input().split() for _ in range(int(input())))
changed = [path for path in sorted(set(p) | set(c)) if p.get(path) != c.get(path)]
conflicts = [path for path in changed if h.get(path) != c.get(path)]
if conflicts:
for path in conflicts:
print(f"error: could not revert: conflict in {path}")
else:
result = dict(h)
for path in changed:
if path in p:
result[path] = p[path]
else:
result.pop(path, None)
print("\n".join(f"{path} {result[path]}" for path in sorted(result)) if result else "(empty)")
Lesson: Undoing changes: restore, reset, revert and the reflog →