Myers diff
Demo of the p/moul/x/daily/myersdiff library: the shortest edit script between two documents, the algorithm behind git diff.
It walks a grid whose diagonals are matching lines, taking the furthest-reaching path at each round, and stops the first time a path reaches the far corner. That round number is the number of edits, and it is minimal because no shorter path was available at any earlier round.
The scenarios
| scenario | edits | minimal | what it shows |
|---|---|---|---|
| patch | 5 | yes | A small patch in a large file |
| insert | 3 | yes | Appending to an empty document |
| move | 2 | yes | A moved line is a delete and an insert |
| starved | 10 | no | A budget too small for the answer |
Context width
Append a number to widen or narrow the unchanged lines printed around each change: patch/0 shows the changes alone, patch/6 shows the whole file as one hunk. Anything out of range is clamped to 0..6.
API
Lines(a, b string) Scriptis the whole surface for text.Script.Apply(a []string) ([]string, bool)replays the script and says whether it describes that document.Hunks(s Script, context int) []Hunkgroups the script the way a review tool prints it.Unified(a, b string, context int) stringis the two above, as text.