| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Three-way merges of file contents, line by line. |
| 5 | //! |
| 6 | //! Both sides are compared with the base, using imara-diff's histogram diff. |
| 7 | //! Each change is a hunk: a range of base lines replaced by a range of lines |
| 8 | //! of that side. Hunks of the two sides that overlap or touch form one region: |
| 9 | //! where only one side changed, its lines are taken; where both changed the |
| 10 | //! region to the same lines, those are taken; otherwise the region is a |
| 11 | //! conflict. Changes on adjacent lines therefore conflict, as they do in git. |
| 12 | |
| 13 | use core::ops::Range; |
| 14 | |
| 15 | use imara_diff::sources::byte_lines; |
| 16 | use imara_diff::{Algorithm, Diff, Hunk, IndentHeuristic, IndentLevel, Interner, Token}; |
| 17 | |
| 18 | /// Content with a NUL byte among this many leading bytes is binary, the rule |
| 19 | /// git uses. |
| 20 | pub const BINARY_SNIFF_BYTES: usize = 8000; |
| 21 | |
| 22 | /// Content this long or longer is not merged line by line. |
| 23 | const MAX_TEXT_BYTES: usize = i32::MAX as usize; |
| 24 | |
| 25 | /// Tab width for the indentation heuristic that places ambiguous hunks. |
| 26 | const TAB_WIDTH: u8 = 8; |
| 27 | |
| 28 | /// Whether content is binary: it has a NUL byte among its first |
| 29 | /// [`BINARY_SNIFF_BYTES`] bytes. |
| 30 | pub fn is_binary(content: &[u8]) -> bool { |
| 31 | content[..content.len().min(BINARY_SNIFF_BYTES)].contains(&0) |
| 32 | } |
| 33 | |
| 34 | /// The outcome of a three-way merge. |
| 35 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 36 | pub enum MergeResult { |
| 37 | /// The merged content. |
| 38 | Clean(Vec<u8>), |
| 39 | /// The sides changed the same lines differently. A conflict on binary |
| 40 | /// content has no hunks: it cannot be split into lines. |
| 41 | Conflict { |
| 42 | /// Each conflicting region, in order. |
| 43 | hunks: Vec<ConflictHunk>, |
| 44 | }, |
| 45 | } |
| 46 | |
| 47 | impl MergeResult { |
| 48 | /// Whether the merge succeeded. |
| 49 | pub fn is_clean(&self) -> bool { |
| 50 | matches!(self, MergeResult::Clean(_)) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// One region that the two sides changed differently. |
| 55 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 56 | pub struct ConflictHunk { |
| 57 | /// The region in the base. |
| 58 | pub base: HunkSide, |
| 59 | /// What ours has instead. |
| 60 | pub ours: HunkSide, |
| 61 | /// What theirs has instead. |
| 62 | pub theirs: HunkSide, |
| 63 | } |
| 64 | |
| 65 | /// A run of lines of one input. |
| 66 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 67 | pub struct HunkSide { |
| 68 | /// Line numbers, counted from 0, end excluded. An empty range sits before |
| 69 | /// the line it starts at. |
| 70 | pub lines: Range<usize>, |
| 71 | /// The lines themselves, with their line endings. |
| 72 | pub text: Vec<u8>, |
| 73 | } |
| 74 | |
| 75 | /// Merges `ours` and `theirs`, two versions of `base`. |
| 76 | /// |
| 77 | /// Lines end after each `\n`; a last line without one is a line of its own, |
| 78 | /// so adding or removing a final newline is a change to that line. Changes |
| 79 | /// that overlap, touch (on adjacent lines, or an insertion right next to a |
| 80 | /// change) or insert at the same place conflict, unless both sides made them |
| 81 | /// identically. |
| 82 | /// |
| 83 | /// If one side equals the base, or both sides are equal, the result is the |
| 84 | /// other side, whatever the content. Otherwise binary content (see |
| 85 | /// [`is_binary`]) is a conflict without hunks. |
| 86 | pub fn merge3(base: &[u8], ours: &[u8], theirs: &[u8]) -> MergeResult { |
| 87 | if ours == theirs || theirs == base { |
| 88 | return MergeResult::Clean(ours.to_vec()); |
| 89 | } |
| 90 | if ours == base { |
| 91 | return MergeResult::Clean(theirs.to_vec()); |
| 92 | } |
| 93 | if [base, ours, theirs] |
| 94 | .iter() |
| 95 | .any(|content| content.len() >= MAX_TEXT_BYTES || is_binary(content)) |
| 96 | { |
| 97 | return MergeResult::Conflict { hunks: Vec::new() }; |
| 98 | } |
| 99 | Merge::new(base, ours, theirs).run() |
| 100 | } |
| 101 | |
| 102 | /// The lines of one input and their interned tokens. |
| 103 | struct Text<'a> { |
| 104 | lines: Vec<&'a [u8]>, |
| 105 | tokens: Vec<Token>, |
| 106 | } |
| 107 | |
| 108 | impl<'a> Text<'a> { |
| 109 | fn new(content: &'a [u8], interner: &mut Interner<&'a [u8]>) -> Self { |
| 110 | let lines: Vec<&[u8]> = byte_lines(content).collect(); |
| 111 | let tokens = lines.iter().map(|&line| interner.intern(line)).collect(); |
| 112 | Text { lines, tokens } |
| 113 | } |
| 114 | |
| 115 | fn side(&self, lines: Range<usize>) -> HunkSide { |
| 116 | HunkSide { |
| 117 | text: self.lines[lines.clone()].concat(), |
| 118 | lines, |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | struct Merge<'a> { |
| 124 | base: Text<'a>, |
| 125 | ours: Text<'a>, |
| 126 | theirs: Text<'a>, |
| 127 | interner: Interner<&'a [u8]>, |
| 128 | } |
| 129 | |
| 130 | impl<'a> Merge<'a> { |
| 131 | fn new(base: &'a [u8], ours: &'a [u8], theirs: &'a [u8]) -> Self { |
| 132 | let mut interner = Interner::new(0); |
| 133 | let base = Text::new(base, &mut interner); |
| 134 | let ours = Text::new(ours, &mut interner); |
| 135 | let theirs = Text::new(theirs, &mut interner); |
| 136 | Merge { |
| 137 | base, |
| 138 | ours, |
| 139 | theirs, |
| 140 | interner, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// The hunks that turn the base into `side`. |
| 145 | fn hunks(&self, side: &Text<'_>) -> Vec<Hunk> { |
| 146 | let mut diff = Diff::default(); |
| 147 | diff.compute_with( |
| 148 | Algorithm::Histogram, |
| 149 | &self.base.tokens, |
| 150 | &side.tokens, |
| 151 | self.interner.num_tokens(), |
| 152 | ); |
| 153 | diff.postprocess_with( |
| 154 | &self.base.tokens, |
| 155 | &side.tokens, |
| 156 | IndentHeuristic::new(|token| { |
| 157 | IndentLevel::for_ascii_line(self.interner[token].iter().copied(), TAB_WIDTH) |
| 158 | }), |
| 159 | ); |
| 160 | diff.hunks().collect() |
| 161 | } |
| 162 | |
| 163 | fn run(self) -> MergeResult { |
| 164 | let ours = self.hunks(&self.ours); |
| 165 | let theirs = self.hunks(&self.theirs); |
| 166 | let mut out: Vec<u8> = Vec::new(); |
| 167 | let mut hunks = Vec::new(); |
| 168 | let (mut i, mut j) = (0, 0); |
| 169 | // Base lines before `copied` are in the output already. |
| 170 | let mut copied = 0; |
| 171 | // Line number on each side minus line number in the base, for the |
| 172 | // lines between regions. |
| 173 | let (mut ours_shift, mut theirs_shift) = (0isize, 0isize); |
| 174 | |
| 175 | while i < ours.len() || j < theirs.len() { |
| 176 | // A region starts with the hunk that starts first, and grows while |
| 177 | // a hunk of either side starts inside it or right at its end. |
| 178 | let ours_first = match (ours.get(i), theirs.get(j)) { |
| 179 | (Some(o), Some(t)) => o.before.start <= t.before.start, |
| 180 | (o, _) => o.is_some(), |
| 181 | }; |
| 182 | let first = if ours_first { &ours[i] } else { &theirs[j] }; |
| 183 | let start = first.before.start as usize; |
| 184 | let mut end = first.before.end as usize; |
| 185 | let (i0, j0) = (i, j); |
| 186 | if ours_first { |
| 187 | i += 1; |
| 188 | } else { |
| 189 | j += 1; |
| 190 | } |
| 191 | loop { |
| 192 | if let Some(hunk) = ours.get(i).filter(|h| h.before.start as usize <= end) { |
| 193 | end = end.max(hunk.before.end as usize); |
| 194 | i += 1; |
| 195 | } else if let Some(hunk) = theirs.get(j).filter(|h| h.before.start as usize <= end) |
| 196 | { |
| 197 | end = end.max(hunk.before.end as usize); |
| 198 | j += 1; |
| 199 | } else { |
| 200 | break; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | let ours_growth = growth(&ours[i0..i]); |
| 205 | let theirs_growth = growth(&theirs[j0..j]); |
| 206 | let ours_lines = shift(start, ours_shift)..shift(end, ours_shift + ours_growth); |
| 207 | let theirs_lines = shift(start, theirs_shift)..shift(end, theirs_shift + theirs_growth); |
| 208 | ours_shift += ours_growth; |
| 209 | theirs_shift += theirs_growth; |
| 210 | |
| 211 | push_lines(&mut out, &self.base.lines[copied..start]); |
| 212 | copied = end; |
| 213 | if j == j0 { |
| 214 | push_lines(&mut out, &self.ours.lines[ours_lines]); |
| 215 | } else if i == i0 { |
| 216 | push_lines(&mut out, &self.theirs.lines[theirs_lines]); |
| 217 | } else if self.ours.tokens[ours_lines.clone()] |
| 218 | == self.theirs.tokens[theirs_lines.clone()] |
| 219 | { |
| 220 | // Both sides made the same change. |
| 221 | push_lines(&mut out, &self.ours.lines[ours_lines]); |
| 222 | } else { |
| 223 | hunks.push(ConflictHunk { |
| 224 | base: self.base.side(start..end), |
| 225 | ours: self.ours.side(ours_lines), |
| 226 | theirs: self.theirs.side(theirs_lines), |
| 227 | }); |
| 228 | } |
| 229 | } |
| 230 | push_lines(&mut out, &self.base.lines[copied..]); |
| 231 | |
| 232 | if hunks.is_empty() { |
| 233 | MergeResult::Clean(out) |
| 234 | } else { |
| 235 | MergeResult::Conflict { hunks } |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn push_lines(out: &mut Vec<u8>, lines: &[&[u8]]) { |
| 241 | for line in lines { |
| 242 | out.extend_from_slice(line); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | /// How many lines the hunks add, minus how many they remove. |
| 247 | fn growth(hunks: &[Hunk]) -> isize { |
| 248 | hunks |
| 249 | .iter() |
| 250 | .map(|hunk| hunk.after.len() as isize - hunk.before.len() as isize) |
| 251 | .sum() |
| 252 | } |
| 253 | |
| 254 | fn shift(line: usize, by: isize) -> usize { |
| 255 | line.checked_add_signed(by) |
| 256 | .expect("a hunk never maps a line before the start") |
| 257 | } |
| 258 | |
| 259 | #[cfg(test)] |
| 260 | mod tests { |
| 261 | use super::*; |
| 262 | |
| 263 | fn clean(base: &str, ours: &str, theirs: &str) -> String { |
| 264 | match merge3(base.as_bytes(), ours.as_bytes(), theirs.as_bytes()) { |
| 265 | MergeResult::Clean(bytes) => String::from_utf8(bytes).unwrap(), |
| 266 | conflict => panic!("expected a clean merge, got {conflict:?}"), |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | fn conflict(base: &str, ours: &str, theirs: &str) -> Vec<ConflictHunk> { |
| 271 | match merge3(base.as_bytes(), ours.as_bytes(), theirs.as_bytes()) { |
| 272 | MergeResult::Conflict { hunks } => hunks, |
| 273 | clean => panic!("expected a conflict, got {clean:?}"), |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | fn side(lines: Range<usize>, text: &str) -> HunkSide { |
| 278 | HunkSide { |
| 279 | lines, |
| 280 | text: text.as_bytes().to_vec(), |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn one_side_unchanged() { |
| 286 | assert_eq!(clean("a\nb\n", "a\nb\n", "a\nc\n"), "a\nc\n"); |
| 287 | assert_eq!(clean("a\nb\n", "a\nc\n", "a\nb\n"), "a\nc\n"); |
| 288 | assert_eq!(clean("a\n", "x\n", "x\n"), "x\n"); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn separate_edits_both_apply() { |
| 293 | let base = "1\n2\n3\n4\n5\n6\n7\n"; |
| 294 | let ours = "1\nTWO\n3\n4\n5\n6\n7\n"; |
| 295 | let theirs = "1\n2\n3\n4\n5\nSIX\n7\n"; |
| 296 | assert_eq!(clean(base, ours, theirs), "1\nTWO\n3\n4\n5\nSIX\n7\n"); |
| 297 | assert_eq!(clean(base, theirs, ours), "1\nTWO\n3\n4\n5\nSIX\n7\n"); |
| 298 | // Insertions and deletions far apart. |
| 299 | let ours = "0\n1\n2\n3\n4\n5\n6\n7\n"; |
| 300 | let theirs = "1\n2\n3\n4\n5\n6\n"; |
| 301 | assert_eq!(clean(base, ours, theirs), "0\n1\n2\n3\n4\n5\n6\n"); |
| 302 | // One unchanged line between the edits is enough. |
| 303 | let ours = "1\nTWO\n3\n4\n5\n6\n7\n"; |
| 304 | let theirs = "1\n2\n3\nFOUR\n5\n6\n7\n"; |
| 305 | assert_eq!(clean(base, ours, theirs), "1\nTWO\n3\nFOUR\n5\n6\n7\n"); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn overlapping_edits_conflict() { |
| 310 | let hunks = conflict("1\n2\n3\n", "1\nX\n3\n", "1\nY\n3\n"); |
| 311 | assert_eq!( |
| 312 | hunks, |
| 313 | [ConflictHunk { |
| 314 | base: side(1..2, "2\n"), |
| 315 | ours: side(1..2, "X\n"), |
| 316 | theirs: side(1..2, "Y\n"), |
| 317 | }] |
| 318 | ); |
| 319 | // Partly overlapping ranges make one region. |
| 320 | let hunks = conflict("1\n2\n3\n4\n5\n", "1\nA\nB\n4\n5\n", "1\n2\nC\nD\n5\n"); |
| 321 | assert_eq!(hunks.len(), 1); |
| 322 | assert_eq!(hunks[0].base, side(1..4, "2\n3\n4\n")); |
| 323 | assert_eq!(hunks[0].ours, side(1..4, "A\nB\n4\n")); |
| 324 | assert_eq!(hunks[0].theirs, side(1..4, "2\nC\nD\n")); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn adjacent_edits_conflict() { |
| 329 | let hunks = conflict("1\n2\n3\n4\n", "1\nX\n3\n4\n", "1\n2\nY\n4\n"); |
| 330 | assert_eq!(hunks.len(), 1); |
| 331 | assert_eq!(hunks[0].base, side(1..3, "2\n3\n")); |
| 332 | assert_eq!(hunks[0].ours, side(1..3, "X\n3\n")); |
| 333 | assert_eq!(hunks[0].theirs, side(1..3, "2\nY\n")); |
| 334 | // An insertion right after a changed line touches it. |
| 335 | conflict("1\n2\n3\n", "1\nX\n3\n", "1\n2\nnew\n3\n"); |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn identical_edits_are_clean() { |
| 340 | let base = "1\n2\n3\n4\n5\n"; |
| 341 | let both = "1\nX\n3\n4\nY\n"; |
| 342 | assert_eq!(clean(base, both, both), both); |
| 343 | // The same edit on both sides, plus a separate one on one side. |
| 344 | let ours = "1\nX\n3\n4\nZ\n"; |
| 345 | let theirs = "1\nX\n3\n4\n5\n"; |
| 346 | assert_eq!(clean(base, ours, theirs), ours); |
| 347 | // Both delete the same line. |
| 348 | assert_eq!(clean(base, "1\n3\n4\n5\n", "1\n3\n4\n5\n"), "1\n3\n4\n5\n"); |
| 349 | } |
| 350 | |
| 351 | #[test] |
| 352 | fn insertions_at_the_same_place() { |
| 353 | let hunks = conflict("a\nb\n", "a\nX\nb\n", "a\nY\nb\n"); |
| 354 | assert_eq!( |
| 355 | hunks, |
| 356 | [ConflictHunk { |
| 357 | base: side(1..1, ""), |
| 358 | ours: side(1..2, "X\n"), |
| 359 | theirs: side(1..2, "Y\n"), |
| 360 | }] |
| 361 | ); |
| 362 | // The same insertion is clean, and kept once. |
| 363 | assert_eq!(clean("a\nb\n", "a\nX\nb\n", "a\nX\nb\n"), "a\nX\nb\n"); |
| 364 | // At the very start and the very end. |
| 365 | conflict("a\n", "X\na\n", "Y\na\n"); |
| 366 | conflict("a\n", "a\nX\n", "a\nY\n"); |
| 367 | assert_eq!( |
| 368 | clean("a\nb\nc\n", "X\na\nb\nc\n", "a\nb\nc\nY\n"), |
| 369 | "X\na\nb\nc\nY\n" |
| 370 | ); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn empty_files() { |
| 375 | assert_eq!(clean("", "", "new\n"), "new\n"); |
| 376 | assert_eq!(clean("", "", ""), ""); |
| 377 | assert_eq!(clean("a\n", "", "a\n"), ""); |
| 378 | // Both sides add different content to an empty file. |
| 379 | let hunks = conflict("", "x\n", "y\n"); |
| 380 | assert_eq!(hunks[0].base, side(0..0, "")); |
| 381 | // One side empties the file, the other edits it. |
| 382 | conflict("a\nb\n", "", "a\nc\n"); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn missing_final_newline() { |
| 387 | // Adding a newline at the end changes the last line. |
| 388 | assert_eq!(clean("a\nb", "a\nb\n", "a\nb"), "a\nb\n"); |
| 389 | // An edit at the start and a new last line at the end. |
| 390 | assert_eq!(clean("a\nb\nc", "A\nb\nc", "a\nb\nc\nd"), "A\nb\nc\nd"); |
| 391 | // Both change the unterminated last line. |
| 392 | let hunks = conflict("a\nb", "a\nc", "a\nd"); |
| 393 | assert_eq!(hunks[0].base, side(1..2, "b")); |
| 394 | assert_eq!(hunks[0].ours, side(1..2, "c")); |
| 395 | assert_eq!(hunks[0].theirs, side(1..2, "d")); |
| 396 | // One adds the newline, the other changes the line. |
| 397 | conflict("a\nb", "a\nb\n", "a\nB"); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn binary_content() { |
| 402 | assert!(is_binary(b"a\0b")); |
| 403 | assert!(!is_binary(b"plain text\n")); |
| 404 | let mut late = vec![b'a'; BINARY_SNIFF_BYTES]; |
| 405 | late.push(0); |
| 406 | assert!(!is_binary(&late), "only the first bytes are looked at"); |
| 407 | |
| 408 | let base = b"\0base"; |
| 409 | assert_eq!( |
| 410 | merge3(base, base, b"\0theirs"), |
| 411 | MergeResult::Clean(b"\0theirs".to_vec()) |
| 412 | ); |
| 413 | assert_eq!( |
| 414 | merge3(base, b"\0ours", base), |
| 415 | MergeResult::Clean(b"\0ours".to_vec()) |
| 416 | ); |
| 417 | assert_eq!( |
| 418 | merge3(base, b"\0same", b"\0same"), |
| 419 | MergeResult::Clean(b"\0same".to_vec()) |
| 420 | ); |
| 421 | assert_eq!( |
| 422 | merge3(base, b"\0ours", b"\0theirs"), |
| 423 | MergeResult::Conflict { hunks: Vec::new() } |
| 424 | ); |
| 425 | // Text on two sides is not enough when the base is binary. |
| 426 | assert_eq!( |
| 427 | merge3(b"a\0\n1\n2\n3\n", b"a\0\nX\n2\n3\n", b"a\0\n1\n2\nY\n"), |
| 428 | MergeResult::Conflict { hunks: Vec::new() } |
| 429 | ); |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn several_conflicts_and_clean_parts_between_them() { |
| 434 | let base = "1\n2\n3\n4\n5\n6\n7\n8\n9\n"; |
| 435 | let ours = "1\nA\n3\n4\nX\n6\n7\nC\n9\n"; |
| 436 | let theirs = "1\nB\n3\n4\n5\n6\n7\nD\n9\n"; |
| 437 | let hunks = conflict(base, ours, theirs); |
| 438 | assert_eq!(hunks.len(), 2); |
| 439 | assert_eq!(hunks[0].ours, side(1..2, "A\n")); |
| 440 | assert_eq!(hunks[1].base, side(7..8, "8\n")); |
| 441 | assert_eq!(hunks[1].theirs, side(7..8, "D\n")); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn line_numbers_follow_earlier_growth() { |
| 446 | // Ours grows the file before the conflict; theirs shrinks it. |
| 447 | let base = "1\n2\n3\n4\n5\n6\n"; |
| 448 | let ours = "1\n2\nnew\nnew2\n3\n4\nX\n6\n"; |
| 449 | let theirs = "2\n3\n4\nY\n6\n"; |
| 450 | let hunks = conflict(base, ours, theirs); |
| 451 | assert_eq!( |
| 452 | hunks, |
| 453 | [ConflictHunk { |
| 454 | base: side(4..5, "5\n"), |
| 455 | ours: side(6..7, "X\n"), |
| 456 | theirs: side(3..4, "Y\n"), |
| 457 | }] |
| 458 | ); |
| 459 | // An insertion right after a line the other side deletes touches it. |
| 460 | conflict(base, "1\nnew\n2\n3\n4\n5\n6\n", "2\n3\n4\n5\n6\n"); |
| 461 | } |
| 462 | } |