Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 17.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Merging two changesets: a merge changeset whose tree is the three-way
5//! merge of both trees against their merge base.
6//!
7//! The merge runs landing's rebase: the files that changed from the merge base
8//! to `theirs` are applied to `ours` path by path, so every rule and every
9//! kind of conflict is the one [`land`](crate::land) uses. Paths that only
10//! `ours` changed keep their value without being looked at.
11
12use braid_format::{ChangesetParts, Kind, ObjectId, Objects, Signature};
13
14use crate::access::{EMPTY_TREE, empty_tree_node, read_changeset};
15use crate::ancestry::merge_bases;
16use crate::apply::write_nodes;
17use crate::commit::store_assembled;
18use crate::diff::diff;
19use crate::error::{Error, store_error};
20use crate::land::{Conflict, Rebase};
21
22/// What merging one changeset into another gives.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum MergeOutcome {
25 /// `theirs` is `ours` or one of its ancestors: there is nothing to
26 /// merge. Nothing was stored.
27 UpToDate,
28 /// `ours` is an ancestor of `theirs`, which has everything already: move
29 /// to it, without a merge changeset. Nothing was stored.
30 FastForward(ObjectId),
31 /// The merge changeset, stored.
32 Merged {
33 /// The new changeset, whose parents are `[ours, theirs]`.
34 changeset: ObjectId,
35 /// The paths both sides changed, merged line by line or by kind.
36 merged_paths: Vec<Vec<u8>>,
37 },
38 /// The sides conflict. Nothing was stored.
39 Conflicts(Vec<Conflict>),
40}
41
42/// Merges the changeset `theirs` into the changeset `ours`.
43///
44/// When one contains the other, the outcome says so and nothing is stored.
45/// Otherwise the merge starts from their best common ancestor (see
46/// [`merge_bases`](crate::merge_bases)). The merge changeset has the parents
47/// `[ours, theirs]`; as root, the three-way merge of the three trees; the
48/// change list against `ours`; `committer` as author and committer;
49/// `message`; and `extras` as its extra fields, such as [`AGENT`](crate::AGENT)
50/// naming who merged. It is made even when `ours` already has
51/// every change of `theirs`, with an empty change list, so that its history
52/// records the merge. Blobs, directories and the changeset are stored only
53/// when the outcome is [`Merged`](MergeOutcome::Merged).
54///
55/// The conflicts are the ones [`land`](crate::land) reports for the same
56/// trees, with `ours` as the head and `theirs` as the change. Changesets
57/// without a common ancestor are not merged
58/// ([`Error::UnrelatedHistories`]), and neither are changesets with several
59/// best common ancestors whose trees differ ([`Error::SeveralMergeBases`]),
60/// since the result would depend on which one the merge started from.
61///
62/// The cost follows the changes from the merge base to `theirs`, plus the
63/// walks of history that find the merge base.
64pub fn merge<O: Objects>(
65 objects: &O,
66 ours: ObjectId,
67 theirs: ObjectId,
68 committer: Signature,
69 message: Vec<u8>,
70 extras: Vec<(Vec<u8>, Vec<u8>)>,
71) -> Result<MergeOutcome, Error> {
72 let bases = merge_bases(objects, ours, theirs)?;
73 let base_root = match bases.as_slice() {
74 [] => return Err(Error::UnrelatedHistories { ours, theirs }),
75 [base] if *base == theirs => return Ok(MergeOutcome::UpToDate),
76 [base] if *base == ours => return Ok(MergeOutcome::FastForward(theirs)),
77 [base] => read_changeset(objects, *base)?.root,
78 several => shared_root(objects, ours, theirs, several)?,
79 };
80 let ours_root = read_changeset(objects, ours)?.root;
81 let theirs_root = read_changeset(objects, theirs)?.root;
82
83 // Their side as a change built on the base, rebased onto ours.
84 let changes = diff(objects, base_root, theirs_root)?;
85 let mut rebase = Rebase::new(objects, base_root, ours_root, theirs_root);
86 for change in &changes {
87 rebase.path(change)?;
88 }
89 let applied = rebase.structure()?;
90 if !rebase.conflicts.is_empty() {
91 return Ok(MergeOutcome::Conflicts(rebase.into_conflicts()));
92 }
93
94 for (_, bytes, ours) in &rebase.blobs {
95 objects
96 .put_similar(Kind::Blob, bytes, ours)
97 .map_err(store_error)?;
98 }
99 write_nodes(objects, &applied.nodes)?;
100 if applied.root == EMPTY_TREE {
101 objects
102 .put(Kind::Tree, &empty_tree_node())
103 .map_err(store_error)?;
104 }
105 let assembled = ChangesetParts {
106 parents: vec![ours, theirs],
107 root: applied.root,
108 changes: rebase.resolved,
109 author: committer.clone(),
110 committer,
111 message,
112 extras,
113 git_origin: None,
114 }
115 .assemble()
116 .map_err(Error::Assemble)?;
117 store_assembled(objects, &assembled)?;
118 Ok(MergeOutcome::Merged {
119 changeset: assembled.id,
120 merged_paths: rebase.merged,
121 })
122}
123
124/// The root tree of several merge bases, when they all have the same one:
125/// then the merge does not depend on which of them it starts from.
126fn shared_root<O: Objects>(
127 objects: &O,
128 ours: ObjectId,
129 theirs: ObjectId,
130 bases: &[ObjectId],
131) -> Result<ObjectId, Error> {
132 let mut roots = Vec::with_capacity(bases.len());
133 for base in bases {
134 roots.push(read_changeset(objects, *base)?.root);
135 }
136 match roots.split_first() {
137 Some((first, rest)) if rest.iter().all(|root| root == first) => Ok(*first),
138 _ => Err(Error::SeveralMergeBases {
139 ours,
140 theirs,
141 bases: bases.to_vec(),
142 }),
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149 use crate::access::read_changes;
150 use crate::commit::{admit, commit};
151 use crate::land::{AGENT, ConflictKind, LandOutcome, land};
152 use crate::testing::{Repo, delete, signature, text_map};
153 use braid_format::{Change, Changes};
154
155 /// A base with `files`, and two changesets on it: ours applies `ours`
156 /// and theirs applies `theirs`.
157 struct Fork {
158 repo: Repo,
159 ours: ObjectId,
160 theirs: ObjectId,
161 }
162
163 fn fork(
164 files: &[(&str, &str)],
165 ours: impl FnOnce(&Repo) -> Vec<Change>,
166 theirs: impl FnOnce(&Repo) -> Vec<Change>,
167 ) -> Fork {
168 let repo = Repo::new();
169 let start: Vec<Change> = files.iter().map(|(p, c)| repo.set(p, c)).collect();
170 let base = repo.commit(&[], start);
171 let ours = repo.commit(&[base], ours(&repo));
172 let theirs = commit(
173 &repo.objects,
174 vec![base],
175 theirs(&repo),
176 signature("other"),
177 signature("other"),
178 b"theirs\n".to_vec(),
179 Vec::new(),
180 )
181 .unwrap();
182 Fork { repo, ours, theirs }
183 }
184
185 fn merge_it(fork: &Fork) -> MergeOutcome {
186 merge(
187 &fork.repo.objects,
188 fork.ours,
189 fork.theirs,
190 signature("merger"),
191 b"Merge\n".to_vec(),
192 vec![(AGENT.to_vec(), b"merger".to_vec())],
193 )
194 .unwrap()
195 }
196
197 /// Merges a fork that must merge cleanly, and checks the result: it is
198 /// admissible, and its change list is the diff from ours.
199 fn merged(fork: &Fork) -> (ObjectId, Vec<Vec<u8>>) {
200 let outcome = merge_it(fork);
201 let MergeOutcome::Merged {
202 changeset,
203 merged_paths,
204 } = outcome
205 else {
206 panic!("expected a merge, got {outcome:?}");
207 };
208 let objects = &fork.repo.objects;
209 admit(objects, changeset, |id| {
210 [fork.ours, fork.theirs].contains(id)
211 })
212 .unwrap();
213 let new = read_changeset(objects, changeset).unwrap();
214 assert_eq!(new.parents, [fork.ours, fork.theirs]);
215 let list = read_changes(objects, changeset, &new).unwrap().into_owned();
216 assert_eq!(
217 list,
218 diff(objects, fork.repo.root(fork.ours), new.root).unwrap()
219 );
220 (changeset, merged_paths)
221 }
222
223 #[test]
224 fn one_side_containing_the_other() {
225 let repo = Repo::new();
226 let base = repo.commit(&[], vec![repo.set("a", "1")]);
227 let next = repo.commit(&[base], vec![repo.set("a", "2")]);
228 let later = repo.commit(&[next], vec![repo.set("b", "1")]);
229 let objects = &repo.objects;
230 let stored = objects.len();
231 let run = |ours, theirs| {
232 merge(
233 objects,
234 ours,
235 theirs,
236 signature("m"),
237 Vec::new(),
238 Vec::new(),
239 )
240 .unwrap()
241 };
242 assert_eq!(run(base, later), MergeOutcome::FastForward(later));
243 assert_eq!(run(later, base), MergeOutcome::UpToDate);
244 assert_eq!(run(later, next), MergeOutcome::UpToDate);
245 assert_eq!(run(later, later), MergeOutcome::UpToDate);
246 assert_eq!(objects.len(), stored, "nothing is stored");
247 }
248
249 #[test]
250 fn disjoint_changes_merge() {
251 let f = fork(
252 &[("a", "1"), ("d/b", "2"), ("gone", "x"), ("old/x", "1")],
253 |r| vec![r.set("a", "ours"), r.set("d/new", "o"), delete("gone")],
254 |r| vec![r.set("d/b", "theirs"), r.set("e/f", "t"), delete("old/x")],
255 );
256 let (id, merged_paths) = merged(&f);
257 assert!(merged_paths.is_empty());
258 assert_eq!(
259 f.repo.files(f.repo.root(id)),
260 text_map(&[
261 ("a", "ours"),
262 ("d/b", "theirs"),
263 ("d/new", "o"),
264 ("e/f", "t")
265 ])
266 );
267 let new = read_changeset(&f.repo.objects, id).unwrap();
268 assert_eq!(new.author, signature("merger"));
269 assert_eq!(new.committer, signature("merger"));
270 assert_eq!(new.message, b"Merge\n");
271 assert_eq!(new.extras, [(AGENT.to_vec(), b"merger".to_vec())]);
272 assert_eq!(new.git_origin, None);
273
274 // Merging the other way gives the same tree.
275 let back = merge(
276 &f.repo.objects,
277 f.theirs,
278 f.ours,
279 signature("merger"),
280 Vec::new(),
281 Vec::new(),
282 )
283 .unwrap();
284 let MergeOutcome::Merged { changeset, .. } = back else {
285 panic!("expected a merge, got {back:?}");
286 };
287 assert_eq!(f.repo.root(changeset), new.root);
288 }
289
290 #[test]
291 fn one_file_changed_on_both_sides_merges_line_by_line() {
292 let f = fork(
293 &[("f", "1\n2\n3\n4\n5\n")],
294 |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
295 |r| vec![r.exec("f", "1\n2\n3\n4\nFIVE\n")],
296 );
297 let (id, merged_paths) = merged(&f);
298 assert_eq!(merged_paths, [b"f".to_vec()]);
299 assert_eq!(
300 f.repo.files(f.repo.root(id)),
301 text_map(&[("f", "exec:ONE\n2\n3\n4\nFIVE\n")])
302 );
303 }
304
305 #[test]
306 fn a_merge_that_changes_no_file_is_still_made() {
307 let f = fork(
308 &[("a", "1")],
309 |r| vec![r.set("a", "2"), r.set("b", "1")],
310 |r| vec![r.set("a", "2")],
311 );
312 let (id, _) = merged(&f);
313 let new = read_changeset(&f.repo.objects, id).unwrap();
314 assert_eq!(new.root, f.repo.root(f.ours));
315 assert_eq!(new.changes, Changes::Inline(Vec::new()));
316 }
317
318 #[test]
319 fn deleting_everything() {
320 let f = fork(
321 &[("a", "1"), ("b", "1")],
322 |_| vec![delete("a")],
323 |_| vec![delete("b")],
324 );
325 let (id, _) = merged(&f);
326 assert_eq!(f.repo.root(id), EMPTY_TREE);
327 assert!(f.repo.objects.contains(&EMPTY_TREE).unwrap());
328 }
329
330 #[test]
331 fn conflicts_are_the_ones_landing_finds() {
332 let cases: Vec<Fork> = vec![
333 fork(
334 &[("f", "1\n2\n3\n")],
335 |r| vec![r.set("f", "1\nours\n3\n")],
336 |r| vec![r.set("f", "1\ntheirs\n3\n")],
337 ),
338 fork(
339 &[("f", "1"), ("g", "1")],
340 |r| vec![r.set("f", "2"), delete("g")],
341 |r| vec![delete("f"), r.set("g", "2")],
342 ),
343 fork(
344 &[("a", "1")],
345 |r| vec![r.set("x/y", "o")],
346 |r| vec![r.set("x", "t")],
347 ),
348 fork(
349 &[("d/a", "1"), ("k", "1")],
350 |_| vec![delete("d/a")],
351 |r| vec![r.set("d/b", "2")],
352 ),
353 fork(
354 &[("x", "1")],
355 |r| vec![r.set("README", "o")],
356 |r| vec![r.set("readme", "t")],
357 ),
358 fork(
359 &[("f", "1")],
360 |r| vec![r.symlink("f", "target")],
361 |r| vec![r.exec("f", "1")],
362 ),
363 ];
364 let mut kinds = Vec::new();
365 for f in &cases {
366 let stored = f.repo.objects.len();
367 let MergeOutcome::Conflicts(found) = merge_it(f) else {
368 panic!("expected conflicts");
369 };
370 assert_eq!(f.repo.objects.len(), stored, "nothing is stored");
371 let landed = land(&f.repo.objects, Some(f.ours), f.theirs, signature("x")).unwrap();
372 assert_eq!(landed, LandOutcome::Conflicts(found.clone()));
373 kinds.extend(found.iter().map(|c| c.kind.code()));
374 }
375 assert_eq!(
376 kinds,
377 [
378 "CONTENT",
379 "MODIFY_DELETE",
380 "MODIFY_DELETE",
381 "DF",
382 "DIR_REMOVED",
383 "CASE",
384 "MODE"
385 ]
386 );
387 let MergeOutcome::Conflicts(found) = merge_it(&cases[3]) else {
388 panic!("expected conflicts");
389 };
390 assert_eq!(
391 found[0].kind,
392 ConflictKind::DirectoryRemoved {
393 directory: b"d".to_vec()
394 }
395 );
396 }
397
398 #[test]
399 fn merging_again_after_a_merge() {
400 // The history `git sync` makes: ours and theirs diverge, are merged,
401 // and both sides go on.
402 let f = fork(
403 &[("a", "1"), ("b", "1")],
404 |r| vec![r.set("a", "ours")],
405 |r| vec![r.set("b", "theirs")],
406 );
407 let (first, _) = merged(&f);
408 let repo = &f.repo;
409 let run = |ours, theirs| {
410 merge(
411 &repo.objects,
412 ours,
413 theirs,
414 signature("m"),
415 Vec::new(),
416 Vec::new(),
417 )
418 };
419 assert_eq!(run(first, f.theirs).unwrap(), MergeOutcome::UpToDate);
420 assert_eq!(
421 run(f.theirs, first).unwrap(),
422 MergeOutcome::FastForward(first)
423 );
424
425 let ours = repo.commit(&[first], vec![repo.set("c", "ours")]);
426 let theirs = repo.commit(&[f.theirs], vec![repo.set("b", "again")]);
427 let MergeOutcome::Merged { changeset, .. } = run(ours, theirs).unwrap() else {
428 panic!("expected a merge");
429 };
430 assert_eq!(
431 repo.files(repo.root(changeset)),
432 text_map(&[("a", "ours"), ("b", "again"), ("c", "ours")])
433 );
434 }
435
436 #[test]
437 fn unrelated_histories_are_not_merged() {
438 let repo = Repo::new();
439 let one = repo.commit(&[], vec![repo.set("a", "1")]);
440 let two = repo.commit(&[], vec![repo.set("b", "1")]);
441 let result = merge(
442 &repo.objects,
443 one,
444 two,
445 signature("m"),
446 Vec::new(),
447 Vec::new(),
448 );
449 assert!(
450 matches!(result, Err(Error::UnrelatedHistories { ours, theirs }) if ours == one && theirs == two),
451 "{result:?}"
452 );
453 }
454
455 /// A changeset on `parents` with `changes`, told apart by `message`.
456 fn node(repo: &Repo, parents: &[ObjectId], changes: Vec<Change>, message: &str) -> ObjectId {
457 commit(
458 &repo.objects,
459 parents.to_vec(),
460 changes,
461 signature("author"),
462 signature("author"),
463 message.as_bytes().to_vec(),
464 Vec::new(),
465 )
466 .unwrap()
467 }
468
469 #[test]
470 fn criss_cross_histories() {
471 // Two sides merge each other: `x` and `y` are both best common
472 // ancestors of what comes after.
473 let repo = Repo::new();
474 let root = node(&repo, &[], vec![repo.set("r", "1")], "root");
475 let x = node(&repo, &[root], vec![repo.set("a", "x")], "x");
476 let y = node(&repo, &[root], vec![repo.set("b", "y")], "y");
477 let m1 = node(&repo, &[x, y], vec![repo.set("b", "y")], "m1");
478 let m2 = node(&repo, &[y, x], vec![repo.set("a", "x")], "m2");
479 let ours = node(&repo, &[m1], vec![repo.set("c", "1")], "ours");
480 let theirs = node(&repo, &[m2], vec![repo.set("d", "1")], "theirs");
481 let result = merge(
482 &repo.objects,
483 ours,
484 theirs,
485 signature("m"),
486 Vec::new(),
487 Vec::new(),
488 );
489 assert!(
490 matches!(&result, Err(Error::SeveralMergeBases { bases, .. }) if bases.len() == 2),
491 "{result:?}"
492 );
493
494 // When the best common ancestors have the same tree, the merge does
495 // not depend on which one it starts from.
496 let x = node(&repo, &[root], vec![repo.set("a", "1")], "x again");
497 let y = node(&repo, &[root], vec![repo.set("a", "1")], "y again");
498 let m1 = node(&repo, &[x, y], Vec::new(), "m1 again");
499 let m2 = node(&repo, &[y, x], Vec::new(), "m2 again");
500 let ours = node(&repo, &[m1], vec![repo.set("c", "1")], "ours again");
501 let theirs = node(&repo, &[m2], vec![repo.set("d", "1")], "theirs again");
502 let MergeOutcome::Merged { changeset, .. } = merge(
503 &repo.objects,
504 ours,
505 theirs,
506 signature("m"),
507 Vec::new(),
508 Vec::new(),
509 )
510 .unwrap() else {
511 panic!("expected a merge");
512 };
513 assert_eq!(
514 repo.files(repo.root(changeset)),
515 text_map(&[("a", "1"), ("c", "1"), ("d", "1"), ("r", "1")])
516 );
517 }
518}