Diff Two Directory Trees Into the Fewest Edits
An agent changed a checkout, and you want the smallest set of edits that turns the old tree into the new one, with moves recognised as moves. Each tree is {path: content}. Implement tree_diff(before, after) and apply_ops(before, ops).
tree_diff returns a list of ops, each a dict:
{"op": "rename", "from": p, "to": q}:pis gone andqis new with byte-identical content.{"op": "modify", "path": p, "content": c}:pis in both, with different contentcinafter.{"op": "add", "path": p, "content": c}:pis only inafter.{"op": "delete", "path": p}:pis only inbefore.
- Order. Renames first, then modifies, then adds, then deletes. Within a group, sort by path, and renames by
from. - Pairing. A vanished path becomes a rename when a new path has identical content. When several new paths share that content, pair with the one whose path is closest (
difflib.SequenceMatcherratio on the two paths), and on a tie the smaller new path. Each new path pairs once. - Unchanged paths produce no op.
- Content wins over name. A path that moved and whose content also changed is a delete and an add, never a rename, because the content is not identical.
apply_ops(before, ops) applies the ops in order and returns the new tree. apply_ops(before, tree_diff(before, after)) must equal after.
The catch. Pair renames before you call anything a plain add or delete, or a moved file shows up as both.