Algorithmcore
diff3 algorithm
Also called diff3 merge.
Merge by diffing the ancestor with each version, splitting the files into stable and unstable chunks, and taking the side that changed in each chunk.
- Time
- O(n^2) worst
- Space
- O(n^2) extra
- Where
- n = the total number of lines of the three files
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
diff3 is the standard method for a three-way merge of text files. It compares the common ancestor with each of the two versions and , using a line diff such as Myers' algorithm, and gets two matchings of equal lines. A line of that is matched in both versions is stable. One pass over the three files cuts them into stable chunks, where all three agree, and unstable chunks between them. In each unstable chunk the merge takes the side that changed, or the common change if both changed it in the same way, and it marks a conflict where the two sides changed it in different ways. It is the method of the GNU diff3 program, and version control systems such as CVS and Subversion use it to merge files. Khanna, Kunal and Pierce wrote it as a precise algorithm in 2007 and showed that it has fewer of the expected properties than its users believe.
In plain words
Two people edit copies of the same file. To merge their work, compare the original with each copy, line by line.
Some lines are still in both copies, in their places. They are anchors. Between two anchors there is a gap, and in each gap you look at three small pieces: the original, the first copy and the second copy.
If the piece of one copy is the same as the original, only the other person changed this part, so you take their version. If both copies have the same new text, you take it. If all three pieces are different, both people changed the same part in different ways. That is a conflict, and the merge writes both versions, with the original, between marker lines, so that a person can choose.
The problem
The input is a base and two versions and , each a sequence of lines, and two matchings: pairs lines of with equal lines of , and pairs lines of with equal lines of , each strictly increasing in both files. Usually each matching is a longest common subsequence, from a shortest edit script. For a line of that has a partner in both, let and be its partners; the triple is then a stable point. The output is the merged file, with the stable lines, the changes of each side, and a marked region for each conflict.
The algorithm
The indices , and are the first lines of the three files that no chunk has taken yet.
DIFF3(A, O, B, M_A, M_B)- 1
l_O ← 0; l_A ← 0; l_B ← 0; P ← an empty list of chunks - 2
loop: i ← 1; while (l_O + i - 1, l_A + i - 1, l_B + i - 1) is a stable point do i ← i + 1 - 3
if i = 1 then x ← the least line x ≥ l_O of O with partners in both; if there is none, leave the loop - 4
append the unstable chunk (A[l_A .. a(x) - 1], O[l_O .. x - 1], B[l_B .. b(x) - 1]) to P; (l_O, l_A, l_B) ← (x, a(x), b(x)) - 5
else append the stable chunk of the next i - 1 lines of each file to P; add i - 1 to l_O, l_A and l_B - 6
if some lines are left, append the rest of the three files to P as an unstable chunk - 7
for each chunk (A_i, O_i, B_i) of P: if it is stable, or O_i = B_i, or A_i = B_i, output A_i; else if O_i = A_i, output B_i; else output a conflict region - 8
return the output and the number of conflicts
Lines L1 to L6 are Figure 2 of Khanna, Kunal and Pierce, with indices from 0. Line L7 is the merge rule. Khanna, Kunal and Pierce name the classes of an unstable chunk: changed in A if , changed in B if , falsely conflicting if , and truly conflicting if the three pieces are all different. A conflict region is written in the diff3 style of Git:
<<<<<<< A
the lines of A_i
||||||| O
the lines of O_i
=======
the lines of B_i
>>>>>>> B
The implementation takes both matchings from the shared helper, a longest common subsequence by dynamic programming, or from the caller. It also returns the three new versions , and of the paper, in which a chunk that changed on one side is copied to all three.
Example
This is Figure 1 of Khanna, Kunal and Pierce. Let , and . GNU diff3 matches the lines 1, 2, 3, 6 of with , and the lines 1, 2, 4, 5, 6 of with . The stable points are the lines 1, 2 and 6 of .
| chunk | class | merge | |||
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | stable | 1 |
| 2 | 4, 5 | changed in A | 4, 5 | ||
| 3 | 2 | 2 | 2 | stable | 2 |
| 4 | 3 | 3, 4, 5 | 4, 5, 3 | truly conflicting | conflict region |
| 5 | 6 | 6 | 6 | stable | 6 |
So the merge is 1, 4, 5, 2, then a conflict that shows , and , then 6. In the form of the paper the output is , and .
The matching of with is not unique: 1, 4, 5, 6 is also a longest common subsequence, and the helper of this page picks it. Then the stable points are 1, 4, 5 and 6, and the merge has two conflicts, and . The same three files give a different merge with a different diff.
Correctness
The proof file shows that lines L1 to L6 return a diff3 parse, the definition of Khanna, Kunal and Pierce: the chunks cut the three files into consecutive pieces, every stable point lies in a stable chunk at the same place in its three pieces, and each stable chunk is as large as possible. The key fact is an invariant: every stable point that is not yet in a stable chunk lies after , and in the three files, because the matchings increase. Line L3 takes the least such point, so no stable point falls inside an unstable chunk. Each round takes at least one line, so the loop ends. The proof then shows that the merge rule does what it should when only one side changed the file: if , the merge is , and if , the merge is , both without a conflict.
Proof: The chunk pass gives a diff3 parse, and the merge keeps the change of a side that alone changed the filefull
We use the pseudocode of the page, with indices from 0. The inputs are the base , the versions and , and two matchings: , a set of pairs with , and , a set of pairs with , each strictly increasing in both coordinates. Since is increasing, a line of has at most one partner in , and in the same way at most one partner in . A triple is for a line of that is matched in both. A stable chunk with starts and length is one where is a triple for each .
Khanna, Kunal and Pierce call a list of chunks a diff3 parse if the chunks cut , and into consecutive pieces, (I) every triple lies in some stable chunk, at the same offset in its three pieces, and (II) each stable chunk is as large as possible.
Lemma 1 (invariant). At line L2, the chunks emitted so far cut , and into consecutive pieces, and every triple has one of two forms: and the triple lies in an emitted stable chunk, or , and .
Proof. At line L1 nothing is emitted and , so every triple has the second form. Assume the invariant at line L2.
A stable chunk. Lines L2 and L5 find the largest such that is a triple for each , and emit these lines as a stable chunk. A triple with is the one of the line , because each line has at most one partner on each side, so it lies in this chunk. A triple with comes after the triple of in both increasing matchings, so and . The new values of , , are these sums, so the invariant holds.
An unstable chunk. If , line L3 takes the least line of that is matched in both. Its triple has the second form, so and , and line L4 emits the pieces , and , which follow the earlier pieces. No triple has its first index in , by the choice of , and the triples at and after keep the second form for the new values , , . So the invariant holds.
Lemma 2 (progress). Each round of the loop emits a nonempty chunk and increases . So the loop ends.
Proof. A stable chunk has lines in each piece. For an unstable chunk, all three pieces are empty only if , and , but then is a triple, and line L2 would have found . The sum is at most .
Theorem 1 (a diff3 parse). The chunks returned by the parse form a diff3 parse of , and with respect to and .
Proof. The loop stops at line L3 when no line is matched in both. Line L6 then emits the rest of the three files as one chunk if it is not empty, so by Lemma 1 the chunks cut the three files into consecutive pieces. When the loop stops, no triple has the second form of Lemma 1, so every triple lies in a stable chunk, at the same offset in its three pieces: this is (I).
For (II), take a stable chunk with starts and length . It cannot grow at the end: line L2 stopped because is not a triple, so a chunk that follows starts with an unstable chunk or nothing. It cannot grow at the start either. If it is the first chunk, then . Otherwise the chunk before it is unstable, because a stable chunk is never followed by another one, and it was made at line L4 with the least line that is matched in both. If were a triple, then by the choice of , so . An unstable chunk ends at a triple, so the next round emits a stable chunk; so the chunk before this unstable chunk is stable, and the triple of is its last one, . Then and , and the unstable chunk would be empty, against Lemma 2.
Classes. Each unstable chunk gets one class from its three pieces : changed in if , changed in if , falsely conflicting if , and truly conflicting if all three differ. The code adds one more class, unchanged, for . This class is empty when and are maximum: the pairs of that start in end in , because the chunk borders are triples, so the part of in the chunk is a maximum matching of and , and so it is the identity. The same holds for , so the first line of the chunk would start a triple at the start of the three pieces, and the chunk would be stable.
Theorem 2 (the merge rule). The merge takes the stable chunks, for a chunk that is changed in , falsely conflicting or unchanged, and for a chunk that is changed in ; it marks the truly conflicting chunks. As a result:
- If and is a maximum matching, the merge is , with no conflict, for any .
- If and is a maximum matching, the merge is , with no conflict, for any .
- If and , the merge is , with no conflict.
Proof. The first sentence is lines L7 and L8. For part 1, a maximum matching of with itself has increasing pairs, so it is the identity. Then at each round: a stable chunk adds the same length to both, and an unstable chunk sets . So in every chunk, and each chunk is stable, unchanged or changed in . In each case the merge takes a piece equal to , and by Theorem 1 the pieces , in order, make . Part 2 is the same with the two sides swapped. For part 3, gives for each , so at each round and in every chunk. Each chunk is then stable, unchanged or falsely conflicting, and the merge takes .
Output triples. The function for the outputs of the paper writes for a chunk that is changed in , for a chunk that is changed in , and for the other chunks, which is the definition of the output of a chunk.
Cost. By Lemma 2 there are at most rounds. Line L2 tests triples and the round moves by . Line L3 scans the lines to and the round moves to , so each line of is scanned at most twice over all rounds. With hash sets for the matchings, each test takes expected time, and the copies of the pieces take in total. So the chunk pass is expected linear. The two matchings of the shared helper cost .
Complexity
Let be the total number of lines of the three files, and count in the word-RAM with lines compared in , for example by a hash of each line.
- The chunk pass. Each line of is tested at most twice in lines L2 and L3, and each line of each file is copied once, so lines L1 to L8 take expected time with hash sets for the matchings.
- The matchings. Two line diffs dominate. With the dynamic program of the helper they cost time and space. With Myers' algorithm they cost time, where is the size of the larger edit script, and space in the linear space version.
Properties
- One side unchanged. If , the merge is , and if , it is , for any maximum matchings. If and both use the same matching, the merge is .
- Depends on the matchings. Two longest matchings can give different chunks and different conflicts, as in the example.
- Not idempotent. Figure 4 of Khanna, Kunal and Pierce: for , and , where each pair has one maximum matching, a run gives , and , and a second run on these changes them again, to , and .
- Not local. Figure 3: let , let add at the start and replace the last by . The two edits are far apart for large , yet with a maximum matching that shifts by one period the last chunk is a conflict, for every .
- Safe inputs. Theorem 4.1.1: cut into a start, a middle and an end. If at most one side changes the start, at most one side changes the end, no side changes the middle, and the middle has a line that occurs exactly once in each of the three files, the merge is unique and has no conflict. A unique line such as a function header often plays this role in source code.
- Not stable. Khanna, Kunal and Pierce also show that similar inputs can give very different outputs, even without conflicts.
Variants and improvements
- Conflict styles. The RCS merge style, the default of Git, shows only and . The diff3 style adds after a
|||||||marker. The zdiff3 style of Git also moves the equal lines at the start and end of a conflict out of the region. - The diff used. The matchings can come from any line diff, such as patience diff or histogram diff, which match unique or rare lines first and so often give anchors that people expect.
- Structure. Semistructured merge parses the files into declarations and runs a diff3 merge only inside method bodies, and tree merges use a tree diff such as Chawathe's change detection.
- Operations instead of states. Editors for live collaboration merge each edit as it happens, with operational transformation or a CRDT, and never show a conflict.
When to use it
Use diff3 to merge two versions of a text file that have a known common ancestor, as version control systems do. It is simple, fast and easy to explain, and its conflict regions are what most programmers know. When the files have structure that a line merge does not respect, such as declarations whose order does not matter, use a structured or semistructured merge. For edits that arrive one at a time from many users, use operational transformation.
Pitfalls
- Adjacent edits conflict. If changes one line and changes the next line, no stable point lies between them, and the chunk is a conflict: , and give one conflict. With one stable line between the edits there is no conflict.
- False conflicts are taken without a note. If both sides made the same change, the merge takes it once. This is right in most cases, but if both sides added the same line for different reasons, one copy is lost.
- The matchings are part of the input. A different diff, or another version of the same diff, can give different conflicts. Tests must fix the matchings or the diff.
- A clean merge is not a correct program. diff3 sees lines, not meaning. Two changes without a conflict can still break the program together, for example when one side renames a function and the other side adds a call to its old name.
- Marker lines in the data. A file that already has lines such as
=======makes the conflict regions hard to read and to parse again.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diff3/. The authors are listed in prov/8YT0S8.jsonl.
"""The diff3 merge, after the algorithm of Khanna, Kunal and Pierce (FSTTCS 2007, Figure 2).
The inputs are the base o and the two versions a and b. The matchings ma (pairs
(i, j) with o[i] == a[j]) and mb (pairs (i, j) with o[i] == b[j]) are increasing
lists; by default each one is a longest matching from the shared helper. The
parse cuts the three files into stable chunks, where all three agree line by
line, and unstable chunks between them. Indices are 0-based; the paper counts
from 1.
"""
from collections.abc import Hashable, Sequence
from typing import NamedTuple
from txdiff import is_matching, lcs_matching
STABLE = "stable"
CHANGED_A = "changed in A"
CHANGED_B = "changed in B"
FALSE_CONFLICT = "falsely conflicting"
CONFLICT = "truly conflicting"
UNCHANGED = "unchanged" # an unstable chunk with three equal pieces; only matchings that are not maximum give it
class Chunk(NamedTuple):
kind: str
a: list
o: list
b: list
def _classify(a: list, o: list, b: list) -> str:
if a == o == b:
return UNCHANGED
if o == b and o != a:
return CHANGED_A
if o == a and o != b:
return CHANGED_B
if a == b and a != o:
return FALSE_CONFLICT
return CONFLICT
def diff3_parse(a: Sequence[Hashable], o: Sequence[Hashable], b: Sequence[Hashable],
ma: Sequence[tuple[int, int]] | None = None,
mb: Sequence[tuple[int, int]] | None = None) -> list[Chunk]:
"""Return the chunks of the diff3 parse of (a, o, b) for the matchings ma and mb."""
ma = list(ma) if ma is not None else lcs_matching(o, a)
mb = list(mb) if mb is not None else lcs_matching(o, b)
if not is_matching(o, a, ma) or not is_matching(o, b, mb):
raise ValueError("ma and mb must be increasing matchings of equal lines")
in_a, in_b = set(ma), set(mb)
a_of = dict(ma) # line of o -> its partner in a
b_of = dict(mb)
chunks: list[Chunk] = []
def emit(kind: str | None, la: int, ha: int, lo: int, ho: int, lb: int, hb: int) -> None:
pa, po, pb = list(a[la:ha]), list(o[lo:ho]), list(b[lb:hb])
chunks.append(Chunk(kind or _classify(pa, po, pb), pa, po, pb))
lo = la = lb = 0 # @line L1
while True:
i = 1 # @line L2
while (lo + i - 1, la + i - 1) in in_a and (lo + i - 1, lb + i - 1) in in_b:
i += 1
if i == 1: # @line L3
o_next = next((x for x in range(lo, len(o)) if x in a_of and x in b_of), None)
if o_next is None:
break
ja, jb = a_of[o_next], b_of[o_next]
emit(None, la, ja, lo, o_next, lb, jb) # @line L4
lo, la, lb = o_next, ja, jb
else:
emit(STABLE, la, la + i - 1, lo, lo + i - 1, lb, lb + i - 1) # @line L5
lo, la, lb = lo + i - 1, la + i - 1, lb + i - 1
if lo < len(o) or la < len(a) or lb < len(b): # @line L6
emit(None, la, len(a), lo, len(o), lb, len(b))
return chunks
def diff3_output(chunks: Sequence[Chunk]) -> tuple[list, list, list]:
"""Return the three new versions (A', O', B') of the paper: a chunk changed on one side is taken on all three."""
out_a: list = []
out_o: list = []
out_b: list = []
for c in chunks:
if c.kind == CHANGED_A:
parts = (c.a, c.a, c.a)
elif c.kind == CHANGED_B:
parts = (c.b, c.b, c.b)
else:
parts = (c.a, c.o, c.b)
out_a += parts[0]
out_o += parts[1]
out_b += parts[2]
return out_a, out_o, out_b
def diff3_merge(a: Sequence[Hashable], o: Sequence[Hashable], b: Sequence[Hashable],
ma: Sequence[tuple[int, int]] | None = None, mb: Sequence[tuple[int, int]] | None = None,
names: tuple[str, str, str] = ("A", "O", "B")) -> tuple[list, int]:
"""Return the merged lines, with a marked region for each true conflict, and the number of conflicts."""
merged: list = []
conflicts = 0
for c in diff3_parse(a, o, b, ma, mb): # @line L7
if c.kind in (STABLE, UNCHANGED, CHANGED_A, FALSE_CONFLICT):
merged += c.a
elif c.kind == CHANGED_B:
merged += c.b
else:
conflicts += 1
merged += [f"<<<<<<< {names[0]}", *c.a, f"||||||| {names[1]}", *c.o, "=======", *c.b,
f">>>>>>> {names[2]}"]
return merged, conflicts # @line L8
txdiff.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Common parts of the diff and merge pages: lines, edit scripts, the LCS matcher and a unified diff printer.
An edit script turns a sequence a into a sequence b. It is a list of Op values in
order. Each Op has a kind, an index i into a, an index j into b, and the item:
- Op(KEEP, i, j, a[i]): a[i] is kept, and it is b[j];
- Op(DELETE, i, j, a[i]): a[i] is deleted; j is the number of items of b made so far;
- Op(INSERT, i, j, b[j]): b[j] is inserted; i is the number of items of a used so far.
A matching is a list of pairs (i, j), increasing in both coordinates, of items
that the script keeps. The named algorithms of the pages are not in this file.
"""
from collections.abc import Callable, Sequence
from typing import Any, NamedTuple
KEEP = "="
DELETE = "-"
INSERT = "+"
class Op(NamedTuple):
kind: str
i: int
j: int
item: Any
def split_lines(text: str) -> list[str]:
"""Split text at each "\\n" into lines without the line feed; a final line feed adds no empty line."""
if text == "":
return []
lines = text.split("\n")
if lines[-1] == "":
lines.pop()
return lines
def is_matching(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]],
eq: Callable[[Any, Any], bool] | None = None) -> bool:
"""Return True if pairs is strictly increasing in both coordinates and each pair is equal by eq."""
eq = eq if eq is not None else (lambda x, y: x == y)
pi, pj = -1, -1
for i, j in pairs:
if not (pi < i < len(a) and pj < j < len(b)) or not eq(a[i], b[j]):
return False
pi, pj = i, j
return True
def lcs_matching(a: Sequence[Any], b: Sequence[Any],
eq: Callable[[Any, Any], bool] | None = None) -> list[tuple[int, int]]:
"""Return a longest matching of a and b by the O(n m) dynamic program.
eq(x, y) decides whether x and y may be matched; the default is ==. Ties go to
the earliest pair, so the result is fixed for given inputs.
"""
eq = eq if eq is not None else (lambda x, y: x == y)
n, m = len(a), len(b)
# length[i][j] is the length of a longest matching of a[i:] and b[j:].
length = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
row, below = length[i], length[i + 1]
ai = a[i]
for j in range(m - 1, -1, -1):
if eq(ai, b[j]):
row[j] = below[j + 1] + 1
else:
row[j] = below[j] if below[j] >= row[j + 1] else row[j + 1]
pairs: list[tuple[int, int]] = []
i = j = 0
while i < n and j < m:
if eq(a[i], b[j]):
pairs.append((i, j))
i += 1
j += 1
elif length[i + 1][j] >= length[i][j + 1]:
i += 1
else:
j += 1
return pairs
def matching_to_script(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]]) -> list[Op]:
"""Return the edit script that keeps the pairs; in each gap the deletes come before the inserts."""
script: list[Op] = []
i = j = 0
for pi, pj in list(pairs) + [(len(a), len(b))]:
if pi < i or pj < j:
raise ValueError("the pairs are not increasing")
while i < pi:
script.append(Op(DELETE, i, j, a[i]))
i += 1
while j < pj:
script.append(Op(INSERT, i, j, b[j]))
j += 1
if pi < len(a) and pj < len(b):
script.append(Op(KEEP, i, j, a[i]))
i += 1
j += 1
return script
def script_matching(script: Sequence[Op]) -> list[tuple[int, int]]:
"""Return the pairs (i, j) that the script keeps."""
return [(op.i, op.j) for op in script if op.kind == KEEP]
def apply_script(a: Sequence[Any], script: Sequence[Op]) -> list[Any]:
"""Apply the script to a and return the new sequence; raise ValueError if the script does not fit a."""
out: list[Any] = []
i = 0
for op in script:
if op.kind == INSERT:
if op.i != i or op.j != len(out):
raise ValueError(f"bad insert {op}")
out.append(op.item)
elif op.kind in (KEEP, DELETE):
if op.i != i or i >= len(a) or op.item != a[i] or op.j != len(out):
raise ValueError(f"bad {op.kind} {op}")
if op.kind == KEEP:
out.append(a[i])
i += 1
else:
raise ValueError(f"unknown kind {op.kind!r}")
if i != len(a):
raise ValueError("the script does not use all of a")
return out
def is_valid_script(a: Sequence[Any], b: Sequence[Any], script: Sequence[Op]) -> bool:
"""Return True if the script fits a and turns a into b."""
try:
return apply_script(a, script) == list(b)
except ValueError:
return False
def script_cost(script: Sequence[Op]) -> int:
"""Return the number of deletes and inserts of the script."""
return sum(1 for op in script if op.kind != KEEP)
def _opcodes(script: Sequence[Op]) -> list[tuple[str, int, int, int, int]]:
"""Group the script into runs in the format of difflib: equal, delete, insert or replace."""
codes: list[tuple[str, int, int, int, int]] = []
i = j = 0
k = 0
while k < len(script):
i1, j1 = i, j
if script[k].kind == KEEP:
while k < len(script) and script[k].kind == KEEP:
i, j, k = i + 1, j + 1, k + 1
codes.append(("equal", i1, i, j1, j))
else:
while k < len(script) and script[k].kind != KEEP:
if script[k].kind == DELETE:
i += 1
else:
j += 1
k += 1
tag = "replace" if i > i1 and j > j1 else ("delete" if i > i1 else "insert")
codes.append((tag, i1, i, j1, j))
return codes
def _range(start: int, stop: int) -> str:
length = stop - start
first = start + 1
if length == 1:
return f"{first}"
if length == 0:
first -= 1
return f"{first},{length}"
def unified_diff(a: Sequence[str], b: Sequence[str], script: Sequence[Op], context: int = 3,
from_name: str = "a", to_name: str = "b") -> list[str]:
"""Return the lines of a unified diff of the script, without line feeds, in the layout of GNU diff -u.
The hunks are grouped as difflib.unified_diff groups them, so for the same
matching the output is the same. If the script changes nothing, the result is [].
"""
codes = _opcodes(script)
if not codes:
codes = [("equal", 0, 1, 0, 1)]
n = context
if codes[0][0] == "equal":
tag, i1, i2, j1, j2 = codes[0]
codes[0] = (tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2)
if codes[-1][0] == "equal":
tag, i1, i2, j1, j2 = codes[-1]
codes[-1] = (tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))
groups: list[list[tuple[str, int, int, int, int]]] = []
group: list[tuple[str, int, int, int, int]] = []
for tag, i1, i2, j1, j2 in codes:
if tag == "equal" and i2 - i1 > 2 * n:
group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)))
groups.append(group)
group = []
i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
group.append((tag, i1, i2, j1, j2))
if group and not (len(group) == 1 and group[0][0] == "equal"):
groups.append(group)
out: list[str] = []
for group in groups:
if not out:
out += [f"--- {from_name}", f"+++ {to_name}"]
first, last = group[0], group[-1]
out.append(f"@@ -{_range(first[1], last[2])} +{_range(first[3], last[4])} @@")
for tag, i1, i2, j1, j2 in group:
if tag == "equal":
out += [" " + line for line in a[i1:i2]]
continue
if tag in ("replace", "delete"):
out += ["-" + line for line in a[i1:i2]]
if tag in ("replace", "insert"):
out += ["+" + line for line in b[j1:j2]]
return out
test_diff3.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diff3/. The authors are listed in prov/8YT0S8.jsonl.
import random
from diff3 import (CHANGED_A, CHANGED_B, CONFLICT, FALSE_CONFLICT, STABLE, UNCHANGED, diff3_merge, diff3_output,
diff3_parse)
from txdiff import lcs_matching
# Figure 1 of Khanna, Kunal and Pierce, with the matchings of GNU diff3.
A1, O1, B1 = [1, 4, 5, 2, 3, 6], [1, 2, 3, 4, 5, 6], [1, 2, 4, 5, 3, 6]
MA1 = [(0, 0), (1, 3), (2, 4), (5, 5)]
MB1 = [(0, 0), (1, 1), (3, 2), (4, 3), (5, 5)]
def test_figure_1() -> None:
chunks = diff3_parse(A1, O1, B1, MA1, MB1)
assert [(c.kind, c.a, c.o, c.b) for c in chunks] == [
(STABLE, [1], [1], [1]),
(CHANGED_A, [4, 5], [], []),
(STABLE, [2], [2], [2]),
(CONFLICT, [3], [3, 4, 5], [4, 5, 3]),
(STABLE, [6], [6], [6]),
]
assert diff3_output(chunks) == ([1, 4, 5, 2, 3, 6], [1, 4, 5, 2, 3, 4, 5, 6], [1, 4, 5, 2, 4, 5, 3, 6])
merged, conflicts = diff3_merge(A1, O1, B1, MA1, MB1)
assert conflicts == 1
assert merged == [1, 4, 5, 2, "<<<<<<< A", 3, "||||||| O", 3, 4, 5, "=======", 4, 5, 3, ">>>>>>> B", 6]
def test_the_matching_changes_the_result() -> None:
# The helper takes another longest matching of O and A: 1, 4, 5, 6 instead of 1, 2, 3, 6.
ma = lcs_matching(O1, A1)
assert ma == [(0, 0), (3, 1), (4, 2), (5, 5)] and len(ma) == len(MA1)
chunks = diff3_parse(A1, O1, B1, ma, MB1)
assert [c.kind for c in chunks] == [STABLE, CONFLICT, STABLE, CONFLICT, STABLE]
assert chunks[2].o == [4, 5]
assert diff3_merge(A1, O1, B1, ma, MB1)[1] == 2
def test_not_idempotent() -> None:
# Figure 4: each pair of files has one maximum matching, and a second run changes the result.
a, o, b = [1, 2, 4, 6, 8], [1, 2, 3, 4, 5, 5, 5, 6, 7, 8], [1, 4, 5, 5, 5, 6, 2, 3, 4, 8]
first = diff3_output(diff3_parse(a, o, b))
assert first == ([1, 2, 4, 6, 8], [1, 2, 3, 4, 6, 7, 8], [1, 4, 6, 2, 3, 4, 8])
second = diff3_output(diff3_parse(*first))
assert second == ([1, 4, 6, 2, 4, 6, 8], [1, 4, 6, 2, 4, 6, 7, 8], [1, 4, 6, 2, 4, 8])
def test_locality() -> None:
# Figure 3: A edits the start and B edits the end, yet there is a conflict for every n.
for n in (1, 3, 6):
o2 = [1, 2] * n
a, o, b = [1, 2] + o2 + [1, 2], o2 + [1, 2], o2 + [3]
assert lcs_matching(o, a) == [(k, k) for k in range(2 * n + 2)] # the matching of the paper
chunks = diff3_parse(a, o, b)
assert [(c.kind, c.a, c.o, c.b) for c in chunks] == [(STABLE, o2, o2, o2), (CONFLICT, [1, 2, 1, 2], [1, 2], [3])]
# Theorem 4.1.1: a line that occurs once in each file, in the middle part, removes the conflict.
o2 = [1, 2] * n + [9] + [1, 2] * n
a, o, b = [1, 2] + o2 + [1, 2], o2 + [1, 2], o2 + [3]
assert diff3_merge(a, o, b) == ([1, 2] + o2 + [3], 0)
def test_page_examples() -> None:
o = ["a", "b", "c"]
assert diff3_merge(["a", "x", "b", "c"], o, ["a", "b", "c", "y"]) == (["a", "x", "b", "c", "y"], 0)
merged, conflicts = diff3_merge(["a", "p", "c"], o, ["a", "q", "c"])
assert conflicts == 1
assert merged == ["a", "<<<<<<< A", "p", "||||||| O", "b", "=======", "q", ">>>>>>> B", "c"]
# The same change on both sides is a false conflict, and the merge takes it.
chunks = diff3_parse(["a", "z", "c"], o, ["a", "z", "c"])
assert [c.kind for c in chunks] == [STABLE, FALSE_CONFLICT, STABLE]
assert diff3_merge(["a", "z", "c"], o, ["a", "z", "c"]) == (["a", "z", "c"], 0)
# A deletion on one side and no change on the other.
assert diff3_merge(["a", "c"], o, o) == (["a", "c"], 0)
assert [c.kind for c in diff3_parse(o, o, ["a", "c"])] == [STABLE, CHANGED_B, STABLE]
assert diff3_merge([], [], []) == ([], 0)
def test_bad_matching() -> None:
for ma in ([(1, 0)], [(0, 0), (0, 1)], [(3, 3)]):
try:
diff3_parse(["x", "y"], ["x", "y"], ["x", "y"], ma, None)
except ValueError:
continue
raise AssertionError(f"{ma} was accepted")
def _edit(rng: random.Random, s: list[str]) -> list[str]:
t = list(s)
for _ in range(rng.randint(0, 3)):
k = rng.randint(0, len(t))
if t and rng.random() < 0.5:
del t[min(k, len(t) - 1)]
else:
t.insert(k, rng.choice("abcxy"))
return t
def _check_parse(a: list[str], o: list[str], b: list[str], ma: list[tuple[int, int]],
mb: list[tuple[int, int]]) -> None:
chunks = diff3_parse(a, o, b, ma, mb)
assert sum((c.a for c in chunks), []) == a
assert sum((c.o for c in chunks), []) == o
assert sum((c.b for c in chunks), []) == b
triples = set()
pa = po = pb = 0
for k, c in enumerate(chunks):
assert c.a or c.o or c.b
if c.kind == STABLE:
assert c.a == c.o == c.b
triples |= {(po + t, pa + t, pb + t) for t in range(len(c.o))}
# Each stable chunk is as large as possible: the next chunk is not stable.
assert k + 1 == len(chunks) or chunks[k + 1].kind != STABLE
pa, po, pb = pa + len(c.a), po + len(c.o), pb + len(c.b)
a_of, b_of = dict(ma), dict(mb)
both = {(x, a_of[x], b_of[x]) for x in a_of if x in b_of}
assert both <= triples # property (I) of a diff3 parse
def test_random_parses() -> None:
rng = random.Random(8)
for _ in range(400):
o = [rng.choice("abc") for _ in range(rng.randint(0, 7))]
a, b = _edit(rng, o), _edit(rng, o)
ma, mb = lcs_matching(o, a), lcs_matching(o, b)
_check_parse(a, o, b, ma, mb)
assert UNCHANGED not in [c.kind for c in diff3_parse(a, o, b, ma, mb)]
# Any increasing matchings give a parse, also ones that are not maximum.
sub_a = [p for p in ma if rng.random() < 0.6]
sub_b = [p for p in mb if rng.random() < 0.6]
_check_parse(a, o, b, sub_a, sub_b)
for x, y in ((sub_a, sub_b), (ma, mb)):
# One side unchanged: the merge is the other side.
assert diff3_merge(o, o, b, None, y) == (b, 0)
assert diff3_merge(a, o, o, x, None) == (a, 0)
# The same change on both sides with the same matching: the merge is that change.
assert diff3_merge(a, o, a, x, x) == (a, 0)
History
Khanna, Kunal and Pierce write that diff3 was developed by Randy Smith in 1988, as the GNU diff3 program, and that version control systems such as CVS and Subversion made it popular. The default conflict style of Git is the one of the merge program of RCS, and Git's merge-file command is a minimal clone of that program. In 2007 Khanna, Kunal and Pierce gave a formal account of diff3, with its chunk algorithm, the counterexamples to idempotence, stability and locality, and the condition on a unique line under which a merge is safe.
References
- Sanjeev Khanna, Keshav Kunal and Benjamin C. Pierce, A formal investigation of Diff3, FSTTCS 2007, LNCS 4855, 485-496, Section 2, the stable and unstable chunks, their four classes and the output of a chunk; Figure 2, the algorithm of the parse, with Lemma 3.1; Figure 1, the example with the matchings of GNU diff3; Figures 3 and 4 and Theorem 4.1.1 on locality and idempotence; the history in Section 1
- Git, git-merge, how conflicts are presented, the conflict markers of the default style, the diff3 style with the base after the ||||||| marker, and the zdiff3 style
- Git, git-merge-file, the three-way merge of three files, the conflict markers, the labels of the -L option, the number of conflicts as exit value, and the note that it is a minimal clone of RCS merge
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8YT0S8 Edit this page History Report an error Markdown