Elffuss BraidHub

utopia-ia/elffuss-braid public

bceec3f3d91e · 52.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Landing a change on a branch: fast-forward when the change was built on
5//! the head, otherwise rebase it onto the head path by path.
6//!
7//! The rebase looks at files, as the change list does. For each path the
8//! change touches, it compares the file in the change's base (B), on the head
9//! (H, "ours") and in the change (C, "theirs"); a directory counts as no
10//! file. If H left the file as it was in B, C's value is taken; if H already
11//! has C's value, there is nothing to do; otherwise both changed it, and only
12//! two regular files can still be merged, line by line.
13//!
14//! Braid is stricter than git about the structure around those files. These
15//! are conflicts too:
16//!
17//! - a file against a directory: C sets a file where H has a directory, or
18//! sets something below a path that H made a file;
19//! - a directory that existed in B, removed by one side while the other added
20//! a file under it;
21//! - a name that C adds next to a name that H added, when the two differ only
22//! in letter case or Unicode normalisation.
23//!
24//! The directory rule applies in both directions, so two changes that touch
25//! unrelated paths land the same whichever goes first.
26
27use std::collections::{BTreeSet, HashMap, HashSet};
28use std::rc::Rc;
29
30use braid_format::{
31 Change, ChangeOp, ChangesetParts, Entry, EntryKind, Kind, ObjectId, Objects, Signature,
32};
33use unicode_normalization::UnicodeNormalization;
34
35use crate::access::{Found, Trees, read_blob, read_changes, read_changeset};
36use crate::ancestry::all_ancestors;
37use crate::apply::{Applied, apply_sorted, write_nodes};
38use crate::commit::store_assembled;
39use crate::diff::diff_trees;
40use crate::error::{ApplyProblem, Error, store_error};
41use crate::merge::{ConflictHunk, MergeResult, merge3};
42use crate::path::{check_depth, join};
43
44/// The extra field a rebased changeset carries: the id, in hex, of the
45/// changeset it was rebased from.
46pub const REBASED_FROM: &[u8] = b"rebased-from";
47
48/// The extra field naming the agent that made a changeset: its label, as
49/// the command line's `--agent` gives it. A rebased changeset keeps the
50/// original's, as it keeps every extra field but [`REBASED_FROM`], so the
51/// field names the agent that made the change, wherever it landed.
52pub const AGENT: &[u8] = b"agent";
53
54/// What landing a change does to the branch.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub enum LandOutcome {
57 /// The change was built on the head: the branch moves to the change
58 /// itself.
59 FastForward(ObjectId),
60 /// The change was rebased onto the head as a new, stored changeset; the
61 /// branch moves to it.
62 Rebased {
63 /// The new changeset.
64 changeset: ObjectId,
65 /// The paths both sides changed, merged line by line or by kind.
66 merged_paths: Vec<Vec<u8>>,
67 },
68 /// The head already has everything the change does: the change itself,
69 /// or a changeset rebased from it, is on the head's first-parent chain,
70 /// or, rebased, it would change no file and every parent it has besides
71 /// its base is already an ancestor of the head. Nothing was stored.
72 AlreadyApplied,
73 /// The change conflicts with the head. Nothing was stored, and the branch
74 /// does not move.
75 Conflicts(Vec<Conflict>),
76}
77
78/// One conflict found while rebasing a change onto the head.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct Conflict {
81 /// Where the conflict is.
82 pub path: Vec<u8>,
83 /// What kind of conflict it is.
84 pub kind: ConflictKind,
85 /// The entry at `path` in the base of the change.
86 pub base: Option<EntryKind>,
87 /// The entry at `path` on the head of the branch.
88 pub ours: Option<EntryKind>,
89 /// The entry at `path` in the change being landed.
90 pub theirs: Option<EntryKind>,
91}
92
93/// The kinds of conflict.
94#[derive(Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub enum ConflictKind {
97 /// Both sides changed the content, and the changes overlap. A conflict
98 /// on binary files, symlink targets or gitlinks has no hunks.
99 Content {
100 /// The conflicting regions of a text file.
101 hunks: Vec<ConflictHunk>,
102 },
103 /// One side deleted the file, the other changed it.
104 ModifyDelete,
105 /// The sides disagree on what the path is: a regular file, an executable,
106 /// a symlink or a gitlink, and the base does not settle it.
107 Mode,
108 /// A file on one side, a directory on the other.
109 DirectoryFile,
110 /// A directory that existed in the base was removed on one side, and the
111 /// other side added the file at `path` under it.
112 DirectoryRemoved {
113 /// The removed directory.
114 directory: Vec<u8>,
115 },
116 /// The change adds a name that differs only in letter case or Unicode
117 /// normalisation from a name the head added at `existing`.
118 Case {
119 /// The path of the name already on the head.
120 existing: Vec<u8>,
121 },
122}
123
124impl ConflictKind {
125 /// A short, stable name for the kind, for reports and JSON:
126 /// `CONTENT`, `MODIFY_DELETE`, `MODE`, `DF`, `DIR_REMOVED` or `CASE`.
127 pub fn code(&self) -> &'static str {
128 match self {
129 ConflictKind::Content { .. } => "CONTENT",
130 ConflictKind::ModifyDelete => "MODIFY_DELETE",
131 ConflictKind::Mode => "MODE",
132 ConflictKind::DirectoryFile => "DF",
133 ConflictKind::DirectoryRemoved { .. } => "DIR_REMOVED",
134 ConflictKind::Case { .. } => "CASE",
135 }
136 }
137
138 fn rank(&self) -> u8 {
139 match self {
140 ConflictKind::Content { .. } => 0,
141 ConflictKind::ModifyDelete => 1,
142 ConflictKind::Mode => 2,
143 ConflictKind::DirectoryFile => 3,
144 ConflictKind::DirectoryRemoved { .. } => 4,
145 ConflictKind::Case { .. } => 5,
146 }
147 }
148}
149
150/// Lands `change` on a branch whose head is `head` (`None` for a branch
151/// without changesets).
152///
153/// The first parent of `change` is its base. The base must be on the head's
154/// first-parent chain, or else the branch is empty and the change has no
155/// parents; otherwise this fails with [`Error::BaseNotOnBranch`].
156///
157/// If `change` is already on the head's first-parent chain, or a changeset
158/// rebased from it (one whose [`REBASED_FROM`] names it) is on the chain
159/// above its base, it has landed before, and the outcome is
160/// [`AlreadyApplied`](LandOutcome::AlreadyApplied): a request sent again
161/// after a lost answer never lands twice.
162/// If its base is the head, the branch fast-forwards to `change`, whatever it
163/// contains. Otherwise the change is rebased onto the head: the new changeset
164/// has the parents `[head] + change.parents[1..]`, the merged tree, the change
165/// list against the head, the author, message and extra fields of `change`
166/// (with [`REBASED_FROM`] naming it), and `committer`. When the merged tree is
167/// the head's own, the outcome is `AlreadyApplied` only if every parent of
168/// `change` after the first is already an ancestor of the head; otherwise the
169/// new changeset is made anyway, with an empty change list, so that a merge
170/// keeps its ancestry. Blobs, directories and the changeset are stored only
171/// when the outcome is [`Rebased`](LandOutcome::Rebased).
172///
173/// This decides and writes objects, but does not move the branch: the caller
174/// runs it inside its serialized section for the branch and publishes the
175/// outcome. The cost follows the size of the change, except for two walks of
176/// history: the one that checks the base, which follows its distance from the
177/// head, and, for a merge that changes no file, the one that looks for its
178/// other parents among the head's ancestors.
179pub fn land<O: Objects>(
180 objects: &O,
181 head: Option<ObjectId>,
182 change: ObjectId,
183 committer: Signature,
184) -> Result<LandOutcome, Error> {
185 let theirs = read_changeset(objects, change)?;
186 let (head_id, base_id) = match (head, theirs.parents.first().copied()) {
187 (Some(head), _) if head == change => return Ok(LandOutcome::AlreadyApplied),
188 (None, None) => return Ok(LandOutcome::FastForward(change)),
189 (Some(head), Some(base)) if head == base => return Ok(LandOutcome::FastForward(change)),
190 (Some(head), Some(base)) => match locate(objects, head, base, change)? {
191 OnChain::Base => (head, base),
192 // Landed already, by a fast-forward or a rebase: nothing to do
193 // again.
194 OnChain::Change => return Ok(LandOutcome::AlreadyApplied),
195 OnChain::Neither => {
196 return Err(Error::BaseNotOnBranch {
197 base: Some(base),
198 head: Some(head),
199 });
200 }
201 },
202 (head, base) => return Err(Error::BaseNotOnBranch { base, head }),
203 };
204 let ours = read_changeset(objects, head_id)?;
205 let base = read_changeset(objects, base_id)?;
206
207 let changes = read_changes(objects, change, &theirs)?;
208 // Every walk below follows these paths: refuse deep ones first.
209 for item in changes.iter() {
210 check_depth(&item.path)?;
211 }
212 let mut rebase = Rebase::new(objects, base.root, ours.root, theirs.root);
213 for item in changes.iter() {
214 rebase.path(item)?;
215 }
216 let applied = rebase.structure()?;
217 if !rebase.conflicts.is_empty() {
218 return Ok(LandOutcome::Conflicts(rebase.into_conflicts()));
219 }
220 if applied.root == ours.root && all_ancestors(objects, &theirs.parents[1..], head_id)? {
221 return Ok(LandOutcome::AlreadyApplied);
222 }
223
224 for (_, bytes, ours) in &rebase.blobs {
225 objects
226 .put_similar(Kind::Blob, bytes, ours)
227 .map_err(store_error)?;
228 }
229 write_nodes(objects, &applied.nodes)?;
230 let mut extras: Vec<(Vec<u8>, Vec<u8>)> = theirs
231 .extras
232 .into_iter()
233 .filter(|(key, _)| key.as_slice() != REBASED_FROM)
234 .collect();
235 extras.push((REBASED_FROM.to_vec(), change.to_hex().into_bytes()));
236 let parents = std::iter::once(head_id)
237 .chain(theirs.parents.iter().skip(1).copied())
238 .collect();
239 let assembled = ChangesetParts {
240 parents,
241 root: applied.root,
242 changes: rebase.resolved,
243 author: theirs.author,
244 committer,
245 message: theirs.message,
246 extras,
247 git_origin: None,
248 }
249 .assemble()
250 .map_err(Error::Assemble)?;
251 store_assembled(objects, &assembled)?;
252 Ok(LandOutcome::Rebased {
253 changeset: assembled.id,
254 merged_paths: rebase.merged,
255 })
256}
257
258/// What the walk down the head's first-parent chain meets first.
259enum OnChain {
260 /// The change's base.
261 Base,
262 /// The change itself, or a changeset rebased from it; either is above
263 /// its base.
264 Change,
265 /// Neither, down to the first changeset.
266 Neither,
267}
268
269/// Walks the first parents of `head` until it meets `base`, `change`, or a
270/// changeset rebased from `change`. The cost follows the distance from the
271/// head to the base.
272fn locate<O: Objects>(
273 objects: &O,
274 head: ObjectId,
275 base: ObjectId,
276 change: ObjectId,
277) -> Result<OnChain, Error> {
278 let origin = change.to_hex().into_bytes();
279 let mut current = head;
280 loop {
281 if current == change {
282 return Ok(OnChain::Change);
283 }
284 if current == base {
285 return Ok(OnChain::Base);
286 }
287 let changeset = read_changeset(objects, current)?;
288 if changeset
289 .extras
290 .iter()
291 .any(|(key, value)| key.as_slice() == REBASED_FROM && *value == origin)
292 {
293 return Ok(OnChain::Change);
294 }
295 match changeset.parents.first() {
296 Some(parent) => current = *parent,
297 None => return Ok(OnChain::Neither),
298 }
299 }
300}
301
302/// A regular file: its blob, size and executable bit.
303#[derive(Clone, Copy)]
304struct Regular {
305 blob: ObjectId,
306 size: u64,
307 executable: bool,
308}
309
310impl Regular {
311 fn of(kind: &EntryKind) -> Option<Self> {
312 match kind {
313 EntryKind::File { blob, size } => Some(Regular {
314 blob: *blob,
315 size: *size,
316 executable: false,
317 }),
318 EntryKind::Executable { blob, size } => Some(Regular {
319 blob: *blob,
320 size: *size,
321 executable: true,
322 }),
323 _ => None,
324 }
325 }
326}
327
328/// The file part of an entry: `None` for a directory.
329fn file(entry: Option<&EntryKind>) -> Option<EntryKind> {
330 entry
331 .filter(|kind| !matches!(kind, EntryKind::Tree { .. }))
332 .cloned()
333}
334
335/// A name as file systems that ignore case and normalisation compare it:
336/// Unicode NFC, lowercased. A name that is not UTF-8 is lowercased as ASCII.
337fn fold(name: &[u8]) -> Vec<u8> {
338 match core::str::from_utf8(name) {
339 Ok(text) => text
340 .nfc()
341 .flat_map(char::to_lowercase)
342 .nfc()
343 .collect::<String>()
344 .into_bytes(),
345 Err(_) => name.to_ascii_lowercase(),
346 }
347}
348
349/// The names of one directory, by folded name.
350type FoldedNames = HashMap<Vec<u8>, Vec<Vec<u8>>>;
351
352/// The state of one rebase. [`merge`](crate::merge) runs one too.
353pub(crate) struct Rebase<'o, O> {
354 trees: Trees<'o, O>,
355 /// Root trees of the base, the head and the change.
356 base: ObjectId,
357 ours: ObjectId,
358 theirs: ObjectId,
359 /// The change list against the head, in path order.
360 pub(crate) resolved: Vec<Change>,
361 /// Paths merged from both sides.
362 pub(crate) merged: Vec<Vec<u8>>,
363 /// Merged contents to store: their id, their bytes, and the head's blob
364 /// at the same path, which they are probably close to.
365 pub(crate) blobs: Vec<(ObjectId, Vec<u8>, ObjectId)>,
366 /// Paths the change adds that had no file in the base or on the head.
367 added: Vec<Vec<u8>>,
368 /// Paths the change deletes.
369 deleted: Vec<Vec<u8>>,
370 pub(crate) conflicts: Vec<Conflict>,
371 /// For each directory of the head, its names by folded name.
372 folded: HashMap<ObjectId, Rc<FoldedNames>>,
373 /// Names the change adds that were checked for collisions already.
374 case_checked: HashSet<Vec<u8>>,
375}
376
377impl<'o, O: Objects> Rebase<'o, O> {
378 pub(crate) fn new(objects: &'o O, base: ObjectId, ours: ObjectId, theirs: ObjectId) -> Self {
379 Rebase {
380 trees: Trees::new(objects),
381 base,
382 ours,
383 theirs,
384 resolved: Vec::new(),
385 merged: Vec::new(),
386 blobs: Vec::new(),
387 added: Vec::new(),
388 deleted: Vec::new(),
389 conflicts: Vec::new(),
390 folded: HashMap::new(),
391 case_checked: HashSet::new(),
392 }
393 }
394
395 /// Records a conflict at `path`, with what each side has there.
396 fn conflict(&mut self, path: &[u8], kind: ConflictKind) -> Result<(), Error> {
397 let base = self.trees.find(self.base, path)?.into_entry();
398 let ours = self.trees.find(self.ours, path)?.into_entry();
399 let theirs = self.trees.find(self.theirs, path)?.into_entry();
400 self.conflicts.push(Conflict {
401 path: path.to_vec(),
402 kind,
403 base,
404 ours,
405 theirs,
406 });
407 Ok(())
408 }
409
410 /// Resolves one path of the change list.
411 pub(crate) fn path(&mut self, change: &Change) -> Result<(), Error> {
412 let path = change.path.as_slice();
413 if matches!(change.op, ChangeOp::Delete) {
414 self.deleted.push(path.to_vec());
415 }
416 let in_base = self.trees.find(self.base, path)?;
417 let in_ours = self.trees.find(self.ours, path)?;
418 let base_file = file(in_base.entry());
419 let ours_file = file(in_ours.entry());
420 let theirs_file = change.op.to_entry();
421
422 if theirs_file == ours_file {
423 // The head already has the change's value.
424 return Ok(());
425 }
426 if base_file == ours_file {
427 // The head left this file alone: take the change's value.
428 if base_file.is_none() {
429 self.added.push(path.to_vec());
430 }
431 self.resolved.push(change.clone());
432 return Ok(());
433 }
434 // Both sides changed this file, differently.
435 match (ours_file, theirs_file) {
436 (Some(ours), Some(theirs)) => self.merge(path, base_file, ours, theirs),
437 (None, Some(_)) => match in_ours {
438 // The head replaced the file with a directory.
439 Found::Entry(EntryKind::Tree { .. }) => {
440 self.conflict(path, ConflictKind::DirectoryFile)
441 }
442 // The head made a directory above it a file.
443 Found::Blocked(at) => self.conflict(&path[..at], ConflictKind::DirectoryFile),
444 _ => self.conflict(path, ConflictKind::ModifyDelete),
445 },
446 (Some(_), None) | (None, None) => self.conflict(path, ConflictKind::ModifyDelete),
447 }
448 }
449
450 /// Both sides changed the file at `path` to different entries.
451 fn merge(
452 &mut self,
453 path: &[u8],
454 base: Option<EntryKind>,
455 ours: EntryKind,
456 theirs: EntryKind,
457 ) -> Result<(), Error> {
458 let (Some(o), Some(t)) = (Regular::of(&ours), Regular::of(&theirs)) else {
459 // Symlinks and gitlinks have no lines to merge.
460 let kind = if ours.code() == theirs.code() {
461 ConflictKind::Content { hunks: Vec::new() }
462 } else {
463 ConflictKind::Mode
464 };
465 return self.conflict(path, kind);
466 };
467 let b = base.as_ref().and_then(Regular::of);
468
469 // The executable bit merges on its own: a side that kept the base's
470 // bit yields to the other.
471 let executable = match b {
472 _ if o.executable == t.executable => Some(o.executable),
473 Some(b) if b.executable == o.executable => Some(t.executable),
474 Some(b) if b.executable == t.executable => Some(o.executable),
475 _ => None,
476 };
477
478 let mut content = None;
479 let mut hunks = None;
480 if o.blob == t.blob {
481 content = Some((o.blob, o.size, None));
482 } else {
483 let objects = self.trees.objects();
484 let base_bytes = match b {
485 Some(b) => read_blob(objects, b.blob)?,
486 // Added on both sides, or a regular file on both sides only now.
487 None => Vec::new(),
488 };
489 let ours_bytes = read_blob(objects, o.blob)?;
490 let theirs_bytes = read_blob(objects, t.blob)?;
491 match merge3(&base_bytes, &ours_bytes, &theirs_bytes) {
492 MergeResult::Clean(bytes) => {
493 let blob = ObjectId::hash(Kind::Blob, &bytes);
494 content = Some((blob, bytes.len() as u64, Some(bytes)));
495 }
496 MergeResult::Conflict { hunks: found } => hunks = Some(found),
497 }
498 }
499
500 if executable.is_none() {
501 self.conflict(path, ConflictKind::Mode)?;
502 }
503 if let Some(hunks) = hunks {
504 self.conflict(path, ConflictKind::Content { hunks })?;
505 }
506 let (Some(executable), Some((blob, size, bytes))) = (executable, content) else {
507 return Ok(());
508 };
509 let op = if executable {
510 ChangeOp::Executable { blob, size }
511 } else {
512 ChangeOp::File { blob, size }
513 };
514 if op.to_entry().as_ref() == Some(&ours) {
515 // The merge gives what the head has.
516 return Ok(());
517 }
518 if let Some(bytes) = bytes {
519 self.blobs.push((blob, bytes, o.blob));
520 }
521 self.resolved.push(Change {
522 path: path.to_vec(),
523 op,
524 });
525 self.merged.push(path.to_vec());
526 Ok(())
527 }
528
529 /// Checks the structure around the resolved changes, applies them to the
530 /// head without storing anything, and turns structural problems into
531 /// conflicts.
532 pub(crate) fn structure(&mut self) -> Result<Applied, Error> {
533 self.removed_under_added()?;
534 self.added_under_removed()?;
535 let sets: Vec<Vec<u8>> = self
536 .resolved
537 .iter()
538 .filter(|change| !matches!(change.op, ChangeOp::Delete))
539 .map(|change| change.path.clone())
540 .collect();
541 for path in sets {
542 self.check_case(&path)?;
543 }
544
545 let resolved = std::mem::take(&mut self.resolved);
546 let sorted: Vec<&Change> = resolved.iter().collect();
547 let mut problems = Vec::new();
548 let applied = apply_sorted(&mut self.trees, self.ours, &sorted, &mut problems)?;
549 self.resolved = resolved;
550 for problem in problems {
551 match problem.problem {
552 ApplyProblem::NotADirectory | ApplyProblem::DirectoryNotEmpty => {
553 self.conflict(&problem.path, ConflictKind::DirectoryFile)?;
554 }
555 // The resolved list only deletes files the head has and only
556 // sets what the head does not have, so nothing else can fail
557 // unless the change itself is not canonical.
558 _ => return Err(problem.into_error()),
559 }
560 }
561 Ok(applied)
562 }
563
564 /// The change adds a file under a directory that existed in the base and
565 /// that the head removed.
566 fn removed_under_added(&mut self) -> Result<(), Error> {
567 for path in std::mem::take(&mut self.added) {
568 let deepest = self.trees.deepest_directory(self.base, &path)?;
569 if deepest == 0 {
570 continue;
571 }
572 let directory = &path[..deepest];
573 if self.trees.find(self.ours, directory)? == Found::Absent {
574 self.conflict(
575 &path,
576 ConflictKind::DirectoryRemoved {
577 directory: directory.to_vec(),
578 },
579 )?;
580 }
581 }
582 Ok(())
583 }
584
585 /// The change removes a directory that existed in the base, and the head
586 /// added files under it.
587 fn added_under_removed(&mut self) -> Result<(), Error> {
588 let mut removed = BTreeSet::new();
589 for path in std::mem::take(&mut self.deleted) {
590 if let Some(len) = self.trees.first_missing_directory(self.theirs, &path)? {
591 removed.insert(path[..len].to_vec());
592 }
593 }
594 for directory in removed {
595 let before = self.trees.find(self.base, &directory)?;
596 let after = self.trees.find(self.ours, &directory)?;
597 let (
598 Found::Entry(EntryKind::Tree { tree: before }),
599 Found::Entry(EntryKind::Tree { tree: after }),
600 ) = (before, after)
601 else {
602 continue;
603 };
604 for item in diff_trees(&mut self.trees, &directory, Some(before), Some(after))? {
605 if item.old.is_none() && item.new.is_some() {
606 self.conflict(
607 &item.path,
608 ConflictKind::DirectoryRemoved {
609 directory: directory.clone(),
610 },
611 )?;
612 }
613 }
614 }
615 Ok(())
616 }
617
618 /// The change sets `path`. Find the first name on it that the head does
619 /// not have; if the head added a name there that folds to the same name,
620 /// the two would collide on a file system that ignores case or
621 /// normalisation.
622 fn check_case(&mut self, path: &[u8]) -> Result<(), Error> {
623 let mut dir = self.ours;
624 let mut start = 0;
625 loop {
626 let slash = path[start..].iter().position(|byte| *byte == b'/');
627 let end = slash.map_or(path.len(), |slash| start + slash);
628 let name = &path[start..end];
629 match (self.trees.entry(dir, name)?, slash) {
630 (Some(EntryKind::Tree { tree }), Some(_)) => {
631 dir = tree;
632 start = end + 1;
633 }
634 // The head has this name already.
635 (Some(_), _) => return Ok(()),
636 (None, _) => {
637 if !self.case_checked.insert(path[..end].to_vec()) {
638 // Another path of the change goes through this name.
639 return Ok(());
640 }
641 let parent = &path[..start.saturating_sub(1)];
642 // A new name is compared with every name of the
643 // directory: only now is it read whole.
644 let entries = self.trees.read(dir)?;
645 let index = self.folded_names(dir, &entries);
646 let others = index.get(&fold(name)).cloned().unwrap_or_default();
647 for other in others {
648 // Only a name the head brought counts: one already in
649 // the base, or one the change has too, makes the
650 // collision the change's own.
651 let existing = join(parent, &other);
652 let in_base = self.trees.find(self.base, &existing)?;
653 let in_change = self.trees.find(self.theirs, &existing)?;
654 if in_base.entry().is_none() && in_change.entry().is_none() {
655 self.conflict(&path[..end], ConflictKind::Case { existing })?;
656 }
657 }
658 return Ok(());
659 }
660 }
661 }
662 }
663
664 /// The names of a directory of the head, by folded name.
665 fn folded_names(&mut self, dir: ObjectId, entries: &[Entry]) -> Rc<FoldedNames> {
666 Rc::clone(self.folded.entry(dir).or_insert_with(|| {
667 let mut index = FoldedNames::new();
668 for entry in entries {
669 index
670 .entry(fold(&entry.name))
671 .or_default()
672 .push(entry.name.clone());
673 }
674 Rc::new(index)
675 }))
676 }
677
678 /// The conflicts, sorted by path and kind, without repeats.
679 pub(crate) fn into_conflicts(self) -> Vec<Conflict> {
680 let mut conflicts = self.conflicts;
681 conflicts.sort_by(|a, b| {
682 a.path
683 .cmp(&b.path)
684 .then_with(|| a.kind.rank().cmp(&b.kind.rank()))
685 });
686 conflicts.dedup_by(|a, b| a.path == b.path && a.kind == b.kind);
687 conflicts
688 }
689}
690
691#[cfg(test)]
692mod tests {
693 use super::*;
694 use crate::commit::{admit, store_assembled};
695 use crate::diff::diff;
696 use crate::merge::HunkSide;
697 use crate::path::MAX_PATH_DEPTH;
698 use crate::testing::{Hinted, Repo, deep_path, delete, gitlink, signature, text_map};
699 use braid_format::Changes;
700
701 struct Setup {
702 repo: Repo,
703 base: ObjectId,
704 head: ObjectId,
705 change: ObjectId,
706 }
707
708 /// A base with `files`, a head that applies `ours` to it, and a change
709 /// that applies `theirs` to it.
710 fn setup(
711 files: &[(&str, &str)],
712 ours: impl FnOnce(&Repo) -> Vec<Change>,
713 theirs: impl FnOnce(&Repo) -> Vec<Change>,
714 ) -> Setup {
715 let repo = Repo::new();
716 let start: Vec<Change> = files.iter().map(|(p, c)| repo.set(p, c)).collect();
717 let base = repo.commit(&[], start);
718 let head = repo.commit(&[base], ours(&repo));
719 let change = repo.commit(&[base], theirs(&repo));
720 Setup {
721 repo,
722 base,
723 head,
724 change,
725 }
726 }
727
728 fn land_it(setup: &Setup) -> LandOutcome {
729 land(
730 &setup.repo.objects,
731 Some(setup.head),
732 setup.change,
733 signature("lander"),
734 )
735 .unwrap()
736 }
737
738 fn rebased(setup: &Setup) -> (ObjectId, Vec<Vec<u8>>) {
739 match land_it(setup) {
740 LandOutcome::Rebased {
741 changeset,
742 merged_paths,
743 } => {
744 // Whatever lands is admissible, and its list is the diff.
745 let objects = &setup.repo.objects;
746 admit(objects, changeset, |id| *id == setup.head).unwrap();
747 let new = read_changeset(objects, changeset).unwrap();
748 let list = read_changes(objects, changeset, &new).unwrap().into_owned();
749 let head_root = setup.repo.root(setup.head);
750 assert_eq!(list, diff(objects, head_root, new.root).unwrap());
751 (changeset, merged_paths)
752 }
753 other => panic!("expected a rebase, got {other:?}"),
754 }
755 }
756
757 fn conflicts(setup: &Setup) -> Vec<(String, &'static str)> {
758 match land_it(setup) {
759 LandOutcome::Conflicts(conflicts) => conflicts
760 .iter()
761 .map(|c| (String::from_utf8(c.path.clone()).unwrap(), c.kind.code()))
762 .collect(),
763 other => panic!("expected conflicts, got {other:?}"),
764 }
765 }
766
767 fn pairs(expected: &[(&str, &'static str)]) -> Vec<(String, &'static str)> {
768 expected
769 .iter()
770 .map(|(path, code)| (path.to_string(), *code))
771 .collect()
772 }
773
774 #[test]
775 fn fast_forward_when_the_base_is_the_head() {
776 let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new());
777 let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]);
778 assert_eq!(
779 land(&s.repo.objects, Some(s.head), on_head, signature("x")).unwrap(),
780 LandOutcome::FastForward(on_head)
781 );
782 // Even a change that changes nothing.
783 assert_eq!(
784 land(&s.repo.objects, Some(s.base), s.change, signature("x")).unwrap(),
785 LandOutcome::FastForward(s.change)
786 );
787 // The first changeset of an empty branch.
788 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
789 assert_eq!(
790 land(&s.repo.objects, None, root, signature("x")).unwrap(),
791 LandOutcome::FastForward(root)
792 );
793 }
794
795 #[test]
796 fn landing_again_is_already_applied() {
797 let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new());
798 let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]);
799 let objects = &s.repo.objects;
800 // The change is the head.
801 assert_eq!(
802 land(objects, Some(on_head), on_head, signature("x")).unwrap(),
803 LandOutcome::AlreadyApplied
804 );
805 // The change is further down the first-parent chain.
806 let later = s.repo.commit(&[on_head], vec![s.repo.set("b", "4")]);
807 assert_eq!(
808 land(objects, Some(later), on_head, signature("x")).unwrap(),
809 LandOutcome::AlreadyApplied
810 );
811 // A first changeset that is the head.
812 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
813 assert_eq!(
814 land(objects, Some(root), root, signature("x")).unwrap(),
815 LandOutcome::AlreadyApplied
816 );
817 }
818
819 #[test]
820 fn landing_again_after_a_rebase_is_already_applied() {
821 let s = setup(
822 &[("a", "1"), ("b", "1")],
823 |r| vec![r.set("a", "2")],
824 |r| vec![r.set("b", "2")],
825 );
826 let (rebased, _) = rebased(&s);
827 let objects = &s.repo.objects;
828 assert_eq!(
829 land(objects, Some(rebased), s.change, signature("x")).unwrap(),
830 LandOutcome::AlreadyApplied
831 );
832 // Neither a later edit of the same file nor putting it back makes
833 // the change land a second time.
834 for content in ["3", "1"] {
835 let later = s.repo.commit(&[rebased], vec![s.repo.set("b", content)]);
836 assert_eq!(
837 land(objects, Some(later), s.change, signature("x")).unwrap(),
838 LandOutcome::AlreadyApplied
839 );
840 }
841 }
842
843 #[test]
844 fn merges_that_change_no_file_keep_their_ancestry() {
845 let repo = Repo::new();
846 let base = repo.commit(&[], vec![repo.set("a", "1")]);
847 let head = repo.commit(&[base], vec![repo.set("h", "1")]);
848 let side = repo.commit(&[base], vec![repo.set("s", "1")]);
849 // Merges `side` but keeps none of its files: no change against `base`.
850 let merge = commit_with_extras(&repo, vec![base, side], Vec::new(), Vec::new());
851 let objects = &repo.objects;
852
853 let outcome = land(objects, Some(head), merge, signature("x")).unwrap();
854 let LandOutcome::Rebased {
855 changeset,
856 merged_paths,
857 } = outcome
858 else {
859 panic!("expected a rebase, got {outcome:?}");
860 };
861 assert!(merged_paths.is_empty());
862 let new = read_changeset(objects, changeset).unwrap();
863 assert_eq!(new.parents, [head, side]);
864 assert_eq!(new.root, repo.root(head));
865 assert_eq!(new.changes, Changes::Inline(Vec::new()));
866 admit(objects, changeset, |id| [head, side].contains(id)).unwrap();
867
868 // Landed again on the new head, the merge has nothing left to add.
869 assert_eq!(
870 land(objects, Some(changeset), merge, signature("x")).unwrap(),
871 LandOutcome::AlreadyApplied
872 );
873 // Nor has another merge of the same side, once `side` is in history.
874 let again = commit_with_extras(
875 &repo,
876 vec![base, side],
877 Vec::new(),
878 vec![(b"note".to_vec(), b"again".to_vec())],
879 );
880 assert_eq!(
881 land(objects, Some(changeset), again, signature("x")).unwrap(),
882 LandOutcome::AlreadyApplied
883 );
884 // A merge built on the head fast-forwards, changes or not.
885 let on_head = commit_with_extras(&repo, vec![head, side], Vec::new(), Vec::new());
886 assert_eq!(
887 land(objects, Some(head), on_head, signature("x")).unwrap(),
888 LandOutcome::FastForward(on_head)
889 );
890 }
891
892 #[test]
893 fn landing_respects_the_depth_limit() {
894 let deepest = deep_path(MAX_PATH_DEPTH);
895 let s = setup(
896 &[("a", "1")],
897 |r| vec![r.set("a", "2")],
898 |r| vec![r.set(&deepest, "c")],
899 );
900 let (id, _) = rebased(&s);
901 assert_eq!(
902 s.repo.files(s.repo.root(id)),
903 text_map(&[("a", "2"), (&deepest, "c")])
904 );
905
906 // A change one name deeper, made by hand since `commit` refuses it.
907 let forged = ChangesetParts {
908 parents: vec![s.base],
909 root: s.repo.root(s.base),
910 changes: vec![s.repo.set(&deep_path(MAX_PATH_DEPTH + 1), "c")],
911 author: signature("a"),
912 committer: signature("a"),
913 message: Vec::new(),
914 extras: Vec::new(),
915 git_origin: None,
916 }
917 .assemble()
918 .unwrap();
919 store_assembled(&s.repo.objects, &forged).unwrap();
920 let result = land(&s.repo.objects, Some(s.head), forged.id, signature("x"));
921 assert!(matches!(result, Err(Error::TooDeep { .. })), "{result:?}");
922 }
923
924 #[test]
925 fn base_must_be_on_the_branch() {
926 let s = setup(
927 &[("a", "1")],
928 |r| vec![r.set("a", "2")],
929 |r| vec![r.set("b", "1")],
930 );
931 let objects = &s.repo.objects;
932 // A change built on a changeset that is not on the branch.
933 let on_side = s.repo.commit(&[s.change], vec![s.repo.set("c", "1")]);
934 assert!(matches!(
935 land(objects, Some(s.head), on_side, signature("x")),
936 Err(Error::BaseNotOnBranch { .. })
937 ));
938 // A change with parents on an empty branch, and a root change on a
939 // branch with a head.
940 assert!(matches!(
941 land(objects, None, s.change, signature("x")),
942 Err(Error::BaseNotOnBranch { head: None, .. })
943 ));
944 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
945 assert!(matches!(
946 land(objects, Some(s.head), root, signature("x")),
947 Err(Error::BaseNotOnBranch { base: None, .. })
948 ));
949 // A base further down the first-parent chain is fine.
950 let later = s.repo.commit(&[s.head], vec![s.repo.set("d", "1")]);
951 assert!(matches!(
952 land(objects, Some(later), s.change, signature("x")).unwrap(),
953 LandOutcome::Rebased { .. }
954 ));
955 }
956
957 #[test]
958 fn disjoint_changes_rebase_cleanly() {
959 let s = setup(
960 &[("a", "1"), ("d/b", "2")],
961 |r| vec![r.set("a", "head"), r.set("d/new", "h")],
962 |r| vec![r.set("d/b", "change"), r.set("e/f", "c")],
963 );
964 let (id, merged) = rebased(&s);
965 assert!(merged.is_empty());
966 assert_eq!(
967 s.repo.files(s.repo.root(id)),
968 text_map(&[
969 ("a", "head"),
970 ("d/b", "change"),
971 ("d/new", "h"),
972 ("e/f", "c")
973 ])
974 );
975 let new = read_changeset(&s.repo.objects, id).unwrap();
976 let original = read_changeset(&s.repo.objects, s.change).unwrap();
977 assert_eq!(new.parents, [s.head]);
978 assert_eq!(new.author, original.author);
979 assert_eq!(new.message, original.message);
980 assert_eq!(new.committer, signature("lander"));
981 assert_eq!(
982 new.extras,
983 [(REBASED_FROM.to_vec(), s.change.to_hex().into_bytes())]
984 );
985 assert_eq!(new.git_origin, None);
986 }
987
988 #[test]
989 fn rebasing_keeps_extra_parents_and_replaces_rebased_from() {
990 let repo = Repo::new();
991 let base = repo.commit(&[], vec![repo.set("a", "1")]);
992 let head = repo.commit(&[base], vec![repo.set("h", "1")]);
993 let other = repo.commit(&[base], vec![repo.set("o", "1")]);
994 let merge = commit_with_extras(
995 &repo,
996 vec![base, other],
997 vec![repo.set("m", "1")],
998 vec![
999 (b"keep".to_vec(), b"me".to_vec()),
1000 (REBASED_FROM.to_vec(), b"old".to_vec()),
1001 ],
1002 );
1003 let outcome = land(&repo.objects, Some(head), merge, signature("x")).unwrap();
1004 let LandOutcome::Rebased { changeset, .. } = outcome else {
1005 panic!("expected a rebase, got {outcome:?}");
1006 };
1007 let new = read_changeset(&repo.objects, changeset).unwrap();
1008 assert_eq!(new.parents, [head, other]);
1009 assert_eq!(
1010 new.extras,
1011 [
1012 (b"keep".to_vec(), b"me".to_vec()),
1013 (REBASED_FROM.to_vec(), merge.to_hex().into_bytes()),
1014 ]
1015 );
1016 }
1017
1018 fn commit_with_extras(
1019 repo: &Repo,
1020 parents: Vec<ObjectId>,
1021 changes: Vec<Change>,
1022 extras: Vec<(Vec<u8>, Vec<u8>)>,
1023 ) -> ObjectId {
1024 crate::commit::commit(
1025 &repo.objects,
1026 parents,
1027 changes,
1028 signature("author"),
1029 signature("author"),
1030 b"merge\n".to_vec(),
1031 extras,
1032 )
1033 .unwrap()
1034 }
1035
1036 #[test]
1037 fn a_merged_file_names_the_heads_version() {
1038 let objects = Hinted::default();
1039 let file = |path: &str, text: &str| Change {
1040 path: path.as_bytes().to_vec(),
1041 op: ChangeOp::File {
1042 blob: objects.put(Kind::Blob, text.as_bytes()).unwrap(),
1043 size: text.len() as u64,
1044 },
1045 };
1046 let commit = |parents: Vec<ObjectId>, changes| {
1047 crate::commit::commit(
1048 &objects,
1049 parents,
1050 changes,
1051 signature("author"),
1052 signature("author"),
1053 b"change\n".to_vec(),
1054 Vec::new(),
1055 )
1056 .unwrap()
1057 };
1058 let base = commit(Vec::new(), vec![file("f", "1\n2\n3\n4\n5\n")]);
1059 let head = commit(vec![base], vec![file("f", "ONE\n2\n3\n4\n5\n")]);
1060 let change = commit(vec![base], vec![file("f", "1\n2\n3\n4\nFIVE\n")]);
1061 objects.hints.take();
1062 let outcome = land(&objects, Some(head), change, signature("x")).unwrap();
1063 assert!(
1064 matches!(outcome, LandOutcome::Rebased { .. }),
1065 "{outcome:?}"
1066 );
1067 let merged = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\nFIVE\n");
1068 let heads = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\n5\n");
1069 let hints = objects.hints.take();
1070 assert!(hints.contains(&(merged, heads)), "{hints:?}");
1071 }
1072
1073 #[test]
1074 fn both_sides_editing_a_file_merge_line_by_line() {
1075 let s = setup(
1076 &[("f", "1\n2\n3\n4\n5\n")],
1077 |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
1078 |r| vec![r.set("f", "1\n2\n3\n4\nFIVE\n")],
1079 );
1080 let (id, merged) = rebased(&s);
1081 assert_eq!(merged, [b"f".to_vec()]);
1082 assert_eq!(
1083 s.repo.files(s.repo.root(id)),
1084 text_map(&[("f", "ONE\n2\n3\n4\nFIVE\n")])
1085 );
1086 }
1087
1088 #[test]
1089 fn executable_bit_and_content_merge_separately() {
1090 let s = setup(
1091 &[("run", "1\n2\n3\n")],
1092 |r| vec![r.exec("run", "1\n2\n3\n")],
1093 |r| vec![r.set("run", "1\n2\nthree\n")],
1094 );
1095 let (id, merged) = rebased(&s);
1096 assert_eq!(merged, [b"run".to_vec()]);
1097 assert_eq!(
1098 s.repo.files(s.repo.root(id)),
1099 text_map(&[("run", "exec:1\n2\nthree\n")])
1100 );
1101 }
1102
1103 #[test]
1104 fn already_applied() {
1105 let s = setup(
1106 &[("a", "1"), ("b", "2")],
1107 |r| vec![r.set("a", "new"), delete("b"), r.set("c", "3")],
1108 |r| vec![r.set("a", "new"), delete("b")],
1109 );
1110 assert_eq!(land_it(&s), LandOutcome::AlreadyApplied);
1111 // A merge that gives what the head has is nothing to do either.
1112 let s = setup(
1113 &[("f", "1\n2\n3\n4\n5\n")],
1114 |r| vec![r.set("f", "ONE\n2\n3\n4\nFIVE\n")],
1115 |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
1116 );
1117 assert_eq!(land_it(&s), LandOutcome::AlreadyApplied);
1118 }
1119
1120 #[test]
1121 fn content_conflict() {
1122 let s = setup(
1123 &[("f", "1\n2\n3\n")],
1124 |r| vec![r.set("f", "1\nours\n3\n")],
1125 |r| vec![r.set("f", "1\ntheirs\n3\n")],
1126 );
1127 let LandOutcome::Conflicts(found) = land_it(&s) else {
1128 panic!("expected conflicts");
1129 };
1130 assert_eq!(found.len(), 1);
1131 let conflict = &found[0];
1132 assert_eq!(conflict.path, b"f");
1133 assert_eq!(conflict.base, Some(s.repo.file_kind("1\n2\n3\n")));
1134 assert_eq!(conflict.ours, Some(s.repo.file_kind("1\nours\n3\n")));
1135 assert_eq!(conflict.theirs, Some(s.repo.file_kind("1\ntheirs\n3\n")));
1136 let ConflictKind::Content { hunks } = &conflict.kind else {
1137 panic!("expected a content conflict");
1138 };
1139 let side = |lines, text: &str| HunkSide {
1140 lines,
1141 text: text.as_bytes().to_vec(),
1142 };
1143 assert_eq!(
1144 hunks,
1145 &[ConflictHunk {
1146 base: side(1..2, "2\n"),
1147 ours: side(1..2, "ours\n"),
1148 theirs: side(1..2, "theirs\n"),
1149 }]
1150 );
1151
1152 // Both sides add the same path with different content.
1153 let s = setup(
1154 &[],
1155 |r| vec![r.set("n", "a\n")],
1156 |r| vec![r.set("n", "b\n")],
1157 );
1158 assert_eq!(conflicts(&s), pairs(&[("n", "CONTENT")]));
1159 // Two symlink targets, and two gitlink commits.
1160 let s = setup(
1161 &[("x", "1")],
1162 |r| vec![r.symlink("l", "one"), gitlink("g", 1)],
1163 |r| vec![r.symlink("l", "two"), gitlink("g", 2)],
1164 );
1165 assert_eq!(conflicts(&s), pairs(&[("g", "CONTENT"), ("l", "CONTENT")]));
1166 // Binary content.
1167 let s = setup(
1168 &[("bin", "\0base")],
1169 |r| vec![r.set("bin", "\0ours")],
1170 |r| vec![r.set("bin", "\0theirs")],
1171 );
1172 let LandOutcome::Conflicts(found) = land_it(&s) else {
1173 panic!("expected conflicts");
1174 };
1175 assert_eq!(found[0].kind, ConflictKind::Content { hunks: Vec::new() });
1176 }
1177
1178 #[test]
1179 fn modify_delete_conflict() {
1180 let s = setup(
1181 &[("f", "1"), ("g", "1")],
1182 |r| vec![r.set("f", "2"), delete("g")],
1183 |r| vec![delete("f"), r.set("g", "2")],
1184 );
1185 assert_eq!(
1186 conflicts(&s),
1187 pairs(&[("f", "MODIFY_DELETE"), ("g", "MODIFY_DELETE")])
1188 );
1189 }
1190
1191 #[test]
1192 fn mode_conflict() {
1193 // Both changed the kind, differently.
1194 let s = setup(
1195 &[("f", "1")],
1196 |r| vec![r.symlink("f", "target")],
1197 |r| vec![r.exec("f", "1")],
1198 );
1199 assert_eq!(conflicts(&s), pairs(&[("f", "MODE")]));
1200 // Added on both sides, executable on one only: the base cannot settle
1201 // the bit.
1202 let s = setup(
1203 &[],
1204 |r| vec![r.exec("n", "same")],
1205 |r| vec![r.set("n", "same")],
1206 );
1207 assert_eq!(conflicts(&s), pairs(&[("n", "MODE")]));
1208 }
1209
1210 #[test]
1211 fn directory_file_conflicts() {
1212 // The change sets a file where the head now has a directory.
1213 let s = setup(
1214 &[("a", "1")],
1215 |r| vec![r.set("x/y", "h")],
1216 |r| vec![r.set("x", "c")],
1217 );
1218 assert_eq!(conflicts(&s), pairs(&[("x", "DF")]));
1219 // The change sets something below a path the head made a file.
1220 let s = setup(
1221 &[("d/a", "1")],
1222 |r| vec![delete("d/a"), r.set("d", "file")],
1223 |r| vec![r.set("d/b", "c")],
1224 );
1225 assert_eq!(conflicts(&s), pairs(&[("d", "DF")]));
1226 // The change edits a file below a path the head made a file.
1227 let s = setup(
1228 &[("d/a", "1")],
1229 |r| vec![delete("d/a"), r.set("d", "file")],
1230 |r| vec![r.set("d/a", "2")],
1231 );
1232 assert_eq!(conflicts(&s), pairs(&[("d", "DF")]));
1233 // The change edits a file the head replaced with a directory.
1234 let s = setup(
1235 &[("f", "1")],
1236 |r| vec![delete("f"), r.set("f/inner", "h")],
1237 |r| vec![r.set("f", "2")],
1238 );
1239 assert_eq!(conflicts(&s), pairs(&[("f", "DF")]));
1240 // The change replaces a directory with a file, and the head added a
1241 // file to that directory.
1242 let s = setup(
1243 &[("p/x", "1")],
1244 |r| vec![r.set("p/new", "h")],
1245 |r| vec![delete("p/x"), r.set("p", "file")],
1246 );
1247 assert_eq!(conflicts(&s), pairs(&[("p", "DF")]));
1248 }
1249
1250 #[test]
1251 fn replacing_a_directory_the_head_also_emptied() {
1252 // The head deleted one file of `p`; the change deleted both and put a
1253 // file in its place. Nothing is left in the directory: no conflict.
1254 let s = setup(
1255 &[("p/x", "1"), ("p/y", "2")],
1256 |_| vec![delete("p/y")],
1257 |r| vec![delete("p/x"), delete("p/y"), r.set("p", "file")],
1258 );
1259 let (id, _) = rebased(&s);
1260 assert_eq!(s.repo.files(s.repo.root(id)), text_map(&[("p", "file")]));
1261 // The head replaced a file with a directory, and the change deleted
1262 // the file: both removed it, the directory stays.
1263 let s = setup(
1264 &[("f", "1"), ("g", "1")],
1265 |r| vec![delete("f"), r.set("f/inner", "h")],
1266 |r| vec![delete("f"), r.set("g", "2")],
1267 );
1268 let (id, _) = rebased(&s);
1269 assert_eq!(
1270 s.repo.files(s.repo.root(id)),
1271 text_map(&[("f/inner", "h"), ("g", "2")])
1272 );
1273 }
1274
1275 #[test]
1276 fn directory_removed_conflicts() {
1277 // The head removed `d`; the change adds a file in it.
1278 let s = setup(
1279 &[("d/a", "1"), ("k", "1")],
1280 |_| vec![delete("d/a")],
1281 |r| vec![r.set("d/b", "2")],
1282 );
1283 let LandOutcome::Conflicts(found) = land_it(&s) else {
1284 panic!("expected conflicts");
1285 };
1286 assert_eq!(found.len(), 1);
1287 assert_eq!(found[0].path, b"d/b");
1288 assert_eq!(
1289 found[0].kind,
1290 ConflictKind::DirectoryRemoved {
1291 directory: b"d".to_vec()
1292 }
1293 );
1294 // Also when the new file is deeper, in a directory the change creates.
1295 let s = setup(
1296 &[("d/e/a", "1"), ("k", "1")],
1297 |_| vec![delete("d/e/a")],
1298 |r| vec![r.set("d/e/new/f", "2")],
1299 );
1300 assert_eq!(conflicts(&s), pairs(&[("d/e/new/f", "DIR_REMOVED")]));
1301 // The other way: the change removed `d`, the head added a file in it.
1302 let s = setup(
1303 &[("d/a", "1"), ("k", "1")],
1304 |r| vec![r.set("d/b", "2")],
1305 |_| vec![delete("d/a")],
1306 );
1307 let LandOutcome::Conflicts(found) = land_it(&s) else {
1308 panic!("expected conflicts");
1309 };
1310 assert_eq!(found[0].path, b"d/b");
1311 assert_eq!(found[0].ours, Some(s.repo.file_kind("2")));
1312 assert_eq!(found[0].theirs, None);
1313 // A directory that keeps other files is not removed.
1314 let s = setup(
1315 &[("d/a", "1"), ("d/z", "1")],
1316 |_| vec![delete("d/a")],
1317 |r| vec![r.set("d/b", "2")],
1318 );
1319 let (id, _) = rebased(&s);
1320 assert_eq!(
1321 s.repo.files(s.repo.root(id)),
1322 text_map(&[("d/b", "2"), ("d/z", "1")])
1323 );
1324 }
1325
1326 #[test]
1327 fn case_conflicts() {
1328 let s = setup(
1329 &[("x", "1")],
1330 |r| vec![r.set("README", "h")],
1331 |r| vec![r.set("readme", "c")],
1332 );
1333 let LandOutcome::Conflicts(found) = land_it(&s) else {
1334 panic!("expected conflicts");
1335 };
1336 assert_eq!(found.len(), 1);
1337 assert_eq!(found[0].path, b"readme");
1338 assert_eq!(
1339 found[0].kind,
1340 ConflictKind::Case {
1341 existing: b"README".to_vec()
1342 }
1343 );
1344 // Unicode normalisation: precomposed and decomposed forms.
1345 let s = setup(
1346 &[("x", "1")],
1347 |r| vec![r.set("docs/caf\u{e9}.md", "h")],
1348 |r| vec![r.set("docs/cafe\u{301}.md", "c")],
1349 );
1350 assert_eq!(conflicts(&s), pairs(&[("docs/cafe\u{301}.md", "CASE")]));
1351 // A directory name that collides, reported once.
1352 let s = setup(
1353 &[("x", "1")],
1354 |r| vec![r.set("Docs/a", "h")],
1355 |r| vec![r.set("docs/b", "c"), r.set("docs/c", "c")],
1356 );
1357 assert_eq!(conflicts(&s), pairs(&[("docs", "CASE")]));
1358 // A collision with a name that was already in the base is the
1359 // change's own business.
1360 let s = setup(
1361 &[("README", "1")],
1362 |r| vec![r.set("x", "h")],
1363 |r| vec![r.set("readme", "c")],
1364 );
1365 rebased(&s);
1366 // Renaming by case alone is fine too.
1367 let s = setup(
1368 &[("README", "1")],
1369 |r| vec![r.set("x", "h")],
1370 |r| vec![delete("README"), r.set("Readme", "1")],
1371 );
1372 rebased(&s);
1373 // Two names on the head fold to the name the change adds: each
1374 // collision is reported once, however many files go through it.
1375 let s = setup(
1376 &[("x", "1")],
1377 |r| vec![r.set("Docs/a", "h"), r.set("DOCS/b", "h")],
1378 |r| vec![r.set("docs/c", "c"), r.set("docs/d", "c")],
1379 );
1380 let LandOutcome::Conflicts(found) = land_it(&s) else {
1381 panic!("expected conflicts");
1382 };
1383 let existing: Vec<&ConflictKind> = found.iter().map(|c| &c.kind).collect();
1384 assert_eq!(
1385 existing,
1386 [
1387 &ConflictKind::Case {
1388 existing: b"DOCS".to_vec()
1389 },
1390 &ConflictKind::Case {
1391 existing: b"Docs".to_vec()
1392 },
1393 ]
1394 );
1395 // Both sides create the directory `cafe\u{301}`, and the change also
1396 // adds `caf\u{e9}` next to it. That collision is the change's own,
1397 // whichever side lands first.
1398 let dir = |r: &Repo| vec![r.set("cafe\u{301}/z", "h")];
1399 let own = |r: &Repo| vec![r.set("cafe\u{301}/b", "c"), r.set("caf\u{e9}", "c")];
1400 rebased(&setup(&[("x", "1")], dir, own));
1401 rebased(&setup(&[("x", "1")], own, dir));
1402 }
1403
1404 #[test]
1405 fn several_conflicts_are_all_reported_in_order() {
1406 let s = setup(
1407 &[("a", "1\n"), ("b", "1"), ("c", "1")],
1408 |r| vec![r.set("a", "ours\n"), delete("b"), r.set("Z", "h")],
1409 |r| {
1410 vec![
1411 r.set("a", "theirs\n"),
1412 r.set("b", "2"),
1413 r.set("z", "c"),
1414 r.set("c", "2"),
1415 ]
1416 },
1417 );
1418 let stored = s.repo.objects.len();
1419 assert_eq!(
1420 conflicts(&s),
1421 pairs(&[("a", "CONTENT"), ("b", "MODIFY_DELETE"), ("z", "CASE")])
1422 );
1423 // A landing with conflicts stores nothing.
1424 assert_eq!(s.repo.objects.len(), stored);
1425 }
1426}