Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 52.0 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, lookup, 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 let entries = self.trees.read(dir)?;
630 match (lookup(&entries, name), slash) {
631 (Some(EntryKind::Tree { tree }), Some(_)) => {
632 dir = *tree;
633 start = end + 1;
634 }
635 // The head has this name already.
636 (Some(_), _) => return Ok(()),
637 (None, _) => {
638 if !self.case_checked.insert(path[..end].to_vec()) {
639 // Another path of the change goes through this name.
640 return Ok(());
641 }
642 let parent = &path[..start.saturating_sub(1)];
643 let index = self.folded_names(dir, &entries);
644 let others = index.get(&fold(name)).cloned().unwrap_or_default();
645 for other in others {
646 // Only a name the head brought counts: one already in
647 // the base, or one the change has too, makes the
648 // collision the change's own.
649 let existing = join(parent, &other);
650 let in_base = self.trees.find(self.base, &existing)?;
651 let in_change = self.trees.find(self.theirs, &existing)?;
652 if in_base.entry().is_none() && in_change.entry().is_none() {
653 self.conflict(&path[..end], ConflictKind::Case { existing })?;
654 }
655 }
656 return Ok(());
657 }
658 }
659 }
660 }
661
662 /// The names of a directory of the head, by folded name.
663 fn folded_names(&mut self, dir: ObjectId, entries: &[Entry]) -> Rc<FoldedNames> {
664 Rc::clone(self.folded.entry(dir).or_insert_with(|| {
665 let mut index = FoldedNames::new();
666 for entry in entries {
667 index
668 .entry(fold(&entry.name))
669 .or_default()
670 .push(entry.name.clone());
671 }
672 Rc::new(index)
673 }))
674 }
675
676 /// The conflicts, sorted by path and kind, without repeats.
677 pub(crate) fn into_conflicts(self) -> Vec<Conflict> {
678 let mut conflicts = self.conflicts;
679 conflicts.sort_by(|a, b| {
680 a.path
681 .cmp(&b.path)
682 .then_with(|| a.kind.rank().cmp(&b.kind.rank()))
683 });
684 conflicts.dedup_by(|a, b| a.path == b.path && a.kind == b.kind);
685 conflicts
686 }
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692 use crate::commit::{admit, store_assembled};
693 use crate::diff::diff;
694 use crate::merge::HunkSide;
695 use crate::path::MAX_PATH_DEPTH;
696 use crate::testing::{Hinted, Repo, deep_path, delete, gitlink, signature, text_map};
697 use braid_format::Changes;
698
699 struct Setup {
700 repo: Repo,
701 base: ObjectId,
702 head: ObjectId,
703 change: ObjectId,
704 }
705
706 /// A base with `files`, a head that applies `ours` to it, and a change
707 /// that applies `theirs` to it.
708 fn setup(
709 files: &[(&str, &str)],
710 ours: impl FnOnce(&Repo) -> Vec<Change>,
711 theirs: impl FnOnce(&Repo) -> Vec<Change>,
712 ) -> Setup {
713 let repo = Repo::new();
714 let start: Vec<Change> = files.iter().map(|(p, c)| repo.set(p, c)).collect();
715 let base = repo.commit(&[], start);
716 let head = repo.commit(&[base], ours(&repo));
717 let change = repo.commit(&[base], theirs(&repo));
718 Setup {
719 repo,
720 base,
721 head,
722 change,
723 }
724 }
725
726 fn land_it(setup: &Setup) -> LandOutcome {
727 land(
728 &setup.repo.objects,
729 Some(setup.head),
730 setup.change,
731 signature("lander"),
732 )
733 .unwrap()
734 }
735
736 fn rebased(setup: &Setup) -> (ObjectId, Vec<Vec<u8>>) {
737 match land_it(setup) {
738 LandOutcome::Rebased {
739 changeset,
740 merged_paths,
741 } => {
742 // Whatever lands is admissible, and its list is the diff.
743 let objects = &setup.repo.objects;
744 admit(objects, changeset, |id| *id == setup.head).unwrap();
745 let new = read_changeset(objects, changeset).unwrap();
746 let list = read_changes(objects, changeset, &new).unwrap().into_owned();
747 let head_root = setup.repo.root(setup.head);
748 assert_eq!(list, diff(objects, head_root, new.root).unwrap());
749 (changeset, merged_paths)
750 }
751 other => panic!("expected a rebase, got {other:?}"),
752 }
753 }
754
755 fn conflicts(setup: &Setup) -> Vec<(String, &'static str)> {
756 match land_it(setup) {
757 LandOutcome::Conflicts(conflicts) => conflicts
758 .iter()
759 .map(|c| (String::from_utf8(c.path.clone()).unwrap(), c.kind.code()))
760 .collect(),
761 other => panic!("expected conflicts, got {other:?}"),
762 }
763 }
764
765 fn pairs(expected: &[(&str, &'static str)]) -> Vec<(String, &'static str)> {
766 expected
767 .iter()
768 .map(|(path, code)| (path.to_string(), *code))
769 .collect()
770 }
771
772 #[test]
773 fn fast_forward_when_the_base_is_the_head() {
774 let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new());
775 let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]);
776 assert_eq!(
777 land(&s.repo.objects, Some(s.head), on_head, signature("x")).unwrap(),
778 LandOutcome::FastForward(on_head)
779 );
780 // Even a change that changes nothing.
781 assert_eq!(
782 land(&s.repo.objects, Some(s.base), s.change, signature("x")).unwrap(),
783 LandOutcome::FastForward(s.change)
784 );
785 // The first changeset of an empty branch.
786 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
787 assert_eq!(
788 land(&s.repo.objects, None, root, signature("x")).unwrap(),
789 LandOutcome::FastForward(root)
790 );
791 }
792
793 #[test]
794 fn landing_again_is_already_applied() {
795 let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new());
796 let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]);
797 let objects = &s.repo.objects;
798 // The change is the head.
799 assert_eq!(
800 land(objects, Some(on_head), on_head, signature("x")).unwrap(),
801 LandOutcome::AlreadyApplied
802 );
803 // The change is further down the first-parent chain.
804 let later = s.repo.commit(&[on_head], vec![s.repo.set("b", "4")]);
805 assert_eq!(
806 land(objects, Some(later), on_head, signature("x")).unwrap(),
807 LandOutcome::AlreadyApplied
808 );
809 // A first changeset that is the head.
810 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
811 assert_eq!(
812 land(objects, Some(root), root, signature("x")).unwrap(),
813 LandOutcome::AlreadyApplied
814 );
815 }
816
817 #[test]
818 fn landing_again_after_a_rebase_is_already_applied() {
819 let s = setup(
820 &[("a", "1"), ("b", "1")],
821 |r| vec![r.set("a", "2")],
822 |r| vec![r.set("b", "2")],
823 );
824 let (rebased, _) = rebased(&s);
825 let objects = &s.repo.objects;
826 assert_eq!(
827 land(objects, Some(rebased), s.change, signature("x")).unwrap(),
828 LandOutcome::AlreadyApplied
829 );
830 // Neither a later edit of the same file nor putting it back makes
831 // the change land a second time.
832 for content in ["3", "1"] {
833 let later = s.repo.commit(&[rebased], vec![s.repo.set("b", content)]);
834 assert_eq!(
835 land(objects, Some(later), s.change, signature("x")).unwrap(),
836 LandOutcome::AlreadyApplied
837 );
838 }
839 }
840
841 #[test]
842 fn merges_that_change_no_file_keep_their_ancestry() {
843 let repo = Repo::new();
844 let base = repo.commit(&[], vec![repo.set("a", "1")]);
845 let head = repo.commit(&[base], vec![repo.set("h", "1")]);
846 let side = repo.commit(&[base], vec![repo.set("s", "1")]);
847 // Merges `side` but keeps none of its files: no change against `base`.
848 let merge = commit_with_extras(&repo, vec![base, side], Vec::new(), Vec::new());
849 let objects = &repo.objects;
850
851 let outcome = land(objects, Some(head), merge, signature("x")).unwrap();
852 let LandOutcome::Rebased {
853 changeset,
854 merged_paths,
855 } = outcome
856 else {
857 panic!("expected a rebase, got {outcome:?}");
858 };
859 assert!(merged_paths.is_empty());
860 let new = read_changeset(objects, changeset).unwrap();
861 assert_eq!(new.parents, [head, side]);
862 assert_eq!(new.root, repo.root(head));
863 assert_eq!(new.changes, Changes::Inline(Vec::new()));
864 admit(objects, changeset, |id| [head, side].contains(id)).unwrap();
865
866 // Landed again on the new head, the merge has nothing left to add.
867 assert_eq!(
868 land(objects, Some(changeset), merge, signature("x")).unwrap(),
869 LandOutcome::AlreadyApplied
870 );
871 // Nor has another merge of the same side, once `side` is in history.
872 let again = commit_with_extras(
873 &repo,
874 vec![base, side],
875 Vec::new(),
876 vec![(b"note".to_vec(), b"again".to_vec())],
877 );
878 assert_eq!(
879 land(objects, Some(changeset), again, signature("x")).unwrap(),
880 LandOutcome::AlreadyApplied
881 );
882 // A merge built on the head fast-forwards, changes or not.
883 let on_head = commit_with_extras(&repo, vec![head, side], Vec::new(), Vec::new());
884 assert_eq!(
885 land(objects, Some(head), on_head, signature("x")).unwrap(),
886 LandOutcome::FastForward(on_head)
887 );
888 }
889
890 #[test]
891 fn landing_respects_the_depth_limit() {
892 let deepest = deep_path(MAX_PATH_DEPTH);
893 let s = setup(
894 &[("a", "1")],
895 |r| vec![r.set("a", "2")],
896 |r| vec![r.set(&deepest, "c")],
897 );
898 let (id, _) = rebased(&s);
899 assert_eq!(
900 s.repo.files(s.repo.root(id)),
901 text_map(&[("a", "2"), (&deepest, "c")])
902 );
903
904 // A change one name deeper, made by hand since `commit` refuses it.
905 let forged = ChangesetParts {
906 parents: vec![s.base],
907 root: s.repo.root(s.base),
908 changes: vec![s.repo.set(&deep_path(MAX_PATH_DEPTH + 1), "c")],
909 author: signature("a"),
910 committer: signature("a"),
911 message: Vec::new(),
912 extras: Vec::new(),
913 git_origin: None,
914 }
915 .assemble()
916 .unwrap();
917 store_assembled(&s.repo.objects, &forged).unwrap();
918 let result = land(&s.repo.objects, Some(s.head), forged.id, signature("x"));
919 assert!(matches!(result, Err(Error::TooDeep { .. })), "{result:?}");
920 }
921
922 #[test]
923 fn base_must_be_on_the_branch() {
924 let s = setup(
925 &[("a", "1")],
926 |r| vec![r.set("a", "2")],
927 |r| vec![r.set("b", "1")],
928 );
929 let objects = &s.repo.objects;
930 // A change built on a changeset that is not on the branch.
931 let on_side = s.repo.commit(&[s.change], vec![s.repo.set("c", "1")]);
932 assert!(matches!(
933 land(objects, Some(s.head), on_side, signature("x")),
934 Err(Error::BaseNotOnBranch { .. })
935 ));
936 // A change with parents on an empty branch, and a root change on a
937 // branch with a head.
938 assert!(matches!(
939 land(objects, None, s.change, signature("x")),
940 Err(Error::BaseNotOnBranch { head: None, .. })
941 ));
942 let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]);
943 assert!(matches!(
944 land(objects, Some(s.head), root, signature("x")),
945 Err(Error::BaseNotOnBranch { base: None, .. })
946 ));
947 // A base further down the first-parent chain is fine.
948 let later = s.repo.commit(&[s.head], vec![s.repo.set("d", "1")]);
949 assert!(matches!(
950 land(objects, Some(later), s.change, signature("x")).unwrap(),
951 LandOutcome::Rebased { .. }
952 ));
953 }
954
955 #[test]
956 fn disjoint_changes_rebase_cleanly() {
957 let s = setup(
958 &[("a", "1"), ("d/b", "2")],
959 |r| vec![r.set("a", "head"), r.set("d/new", "h")],
960 |r| vec![r.set("d/b", "change"), r.set("e/f", "c")],
961 );
962 let (id, merged) = rebased(&s);
963 assert!(merged.is_empty());
964 assert_eq!(
965 s.repo.files(s.repo.root(id)),
966 text_map(&[
967 ("a", "head"),
968 ("d/b", "change"),
969 ("d/new", "h"),
970 ("e/f", "c")
971 ])
972 );
973 let new = read_changeset(&s.repo.objects, id).unwrap();
974 let original = read_changeset(&s.repo.objects, s.change).unwrap();
975 assert_eq!(new.parents, [s.head]);
976 assert_eq!(new.author, original.author);
977 assert_eq!(new.message, original.message);
978 assert_eq!(new.committer, signature("lander"));
979 assert_eq!(
980 new.extras,
981 [(REBASED_FROM.to_vec(), s.change.to_hex().into_bytes())]
982 );
983 assert_eq!(new.git_origin, None);
984 }
985
986 #[test]
987 fn rebasing_keeps_extra_parents_and_replaces_rebased_from() {
988 let repo = Repo::new();
989 let base = repo.commit(&[], vec![repo.set("a", "1")]);
990 let head = repo.commit(&[base], vec![repo.set("h", "1")]);
991 let other = repo.commit(&[base], vec![repo.set("o", "1")]);
992 let merge = commit_with_extras(
993 &repo,
994 vec![base, other],
995 vec![repo.set("m", "1")],
996 vec![
997 (b"keep".to_vec(), b"me".to_vec()),
998 (REBASED_FROM.to_vec(), b"old".to_vec()),
999 ],
1000 );
1001 let outcome = land(&repo.objects, Some(head), merge, signature("x")).unwrap();
1002 let LandOutcome::Rebased { changeset, .. } = outcome else {
1003 panic!("expected a rebase, got {outcome:?}");
1004 };
1005 let new = read_changeset(&repo.objects, changeset).unwrap();
1006 assert_eq!(new.parents, [head, other]);
1007 assert_eq!(
1008 new.extras,
1009 [
1010 (b"keep".to_vec(), b"me".to_vec()),
1011 (REBASED_FROM.to_vec(), merge.to_hex().into_bytes()),
1012 ]
1013 );
1014 }
1015
1016 fn commit_with_extras(
1017 repo: &Repo,
1018 parents: Vec<ObjectId>,
1019 changes: Vec<Change>,
1020 extras: Vec<(Vec<u8>, Vec<u8>)>,
1021 ) -> ObjectId {
1022 crate::commit::commit(
1023 &repo.objects,
1024 parents,
1025 changes,
1026 signature("author"),
1027 signature("author"),
1028 b"merge\n".to_vec(),
1029 extras,
1030 )
1031 .unwrap()
1032 }
1033
1034 #[test]
1035 fn a_merged_file_names_the_heads_version() {
1036 let objects = Hinted::default();
1037 let file = |path: &str, text: &str| Change {
1038 path: path.as_bytes().to_vec(),
1039 op: ChangeOp::File {
1040 blob: objects.put(Kind::Blob, text.as_bytes()).unwrap(),
1041 size: text.len() as u64,
1042 },
1043 };
1044 let commit = |parents: Vec<ObjectId>, changes| {
1045 crate::commit::commit(
1046 &objects,
1047 parents,
1048 changes,
1049 signature("author"),
1050 signature("author"),
1051 b"change\n".to_vec(),
1052 Vec::new(),
1053 )
1054 .unwrap()
1055 };
1056 let base = commit(Vec::new(), vec![file("f", "1\n2\n3\n4\n5\n")]);
1057 let head = commit(vec![base], vec![file("f", "ONE\n2\n3\n4\n5\n")]);
1058 let change = commit(vec![base], vec![file("f", "1\n2\n3\n4\nFIVE\n")]);
1059 objects.hints.take();
1060 let outcome = land(&objects, Some(head), change, signature("x")).unwrap();
1061 assert!(
1062 matches!(outcome, LandOutcome::Rebased { .. }),
1063 "{outcome:?}"
1064 );
1065 let merged = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\nFIVE\n");
1066 let heads = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\n5\n");
1067 let hints = objects.hints.take();
1068 assert!(hints.contains(&(merged, heads)), "{hints:?}");
1069 }
1070
1071 #[test]
1072 fn both_sides_editing_a_file_merge_line_by_line() {
1073 let s = setup(
1074 &[("f", "1\n2\n3\n4\n5\n")],
1075 |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
1076 |r| vec![r.set("f", "1\n2\n3\n4\nFIVE\n")],
1077 );
1078 let (id, merged) = rebased(&s);
1079 assert_eq!(merged, [b"f".to_vec()]);
1080 assert_eq!(
1081 s.repo.files(s.repo.root(id)),
1082 text_map(&[("f", "ONE\n2\n3\n4\nFIVE\n")])
1083 );
1084 }
1085
1086 #[test]
1087 fn executable_bit_and_content_merge_separately() {
1088 let s = setup(
1089 &[("run", "1\n2\n3\n")],
1090 |r| vec![r.exec("run", "1\n2\n3\n")],
1091 |r| vec![r.set("run", "1\n2\nthree\n")],
1092 );
1093 let (id, merged) = rebased(&s);
1094 assert_eq!(merged, [b"run".to_vec()]);
1095 assert_eq!(
1096 s.repo.files(s.repo.root(id)),
1097 text_map(&[("run", "exec:1\n2\nthree\n")])
1098 );
1099 }
1100
1101 #[test]
1102 fn already_applied() {
1103 let s = setup(
1104 &[("a", "1"), ("b", "2")],
1105 |r| vec![r.set("a", "new"), delete("b"), r.set("c", "3")],
1106 |r| vec![r.set("a", "new"), delete("b")],
1107 );
1108 assert_eq!(land_it(&s), LandOutcome::AlreadyApplied);
1109 // A merge that gives what the head has is nothing to do either.
1110 let s = setup(
1111 &[("f", "1\n2\n3\n4\n5\n")],
1112 |r| vec![r.set("f", "ONE\n2\n3\n4\nFIVE\n")],
1113 |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
1114 );
1115 assert_eq!(land_it(&s), LandOutcome::AlreadyApplied);
1116 }
1117
1118 #[test]
1119 fn content_conflict() {
1120 let s = setup(
1121 &[("f", "1\n2\n3\n")],
1122 |r| vec![r.set("f", "1\nours\n3\n")],
1123 |r| vec![r.set("f", "1\ntheirs\n3\n")],
1124 );
1125 let LandOutcome::Conflicts(found) = land_it(&s) else {
1126 panic!("expected conflicts");
1127 };
1128 assert_eq!(found.len(), 1);
1129 let conflict = &found[0];
1130 assert_eq!(conflict.path, b"f");
1131 assert_eq!(conflict.base, Some(s.repo.file_kind("1\n2\n3\n")));
1132 assert_eq!(conflict.ours, Some(s.repo.file_kind("1\nours\n3\n")));
1133 assert_eq!(conflict.theirs, Some(s.repo.file_kind("1\ntheirs\n3\n")));
1134 let ConflictKind::Content { hunks } = &conflict.kind else {
1135 panic!("expected a content conflict");
1136 };
1137 let side = |lines, text: &str| HunkSide {
1138 lines,
1139 text: text.as_bytes().to_vec(),
1140 };
1141 assert_eq!(
1142 hunks,
1143 &[ConflictHunk {
1144 base: side(1..2, "2\n"),
1145 ours: side(1..2, "ours\n"),
1146 theirs: side(1..2, "theirs\n"),
1147 }]
1148 );
1149
1150 // Both sides add the same path with different content.
1151 let s = setup(
1152 &[],
1153 |r| vec![r.set("n", "a\n")],
1154 |r| vec![r.set("n", "b\n")],
1155 );
1156 assert_eq!(conflicts(&s), pairs(&[("n", "CONTENT")]));
1157 // Two symlink targets, and two gitlink commits.
1158 let s = setup(
1159 &[("x", "1")],
1160 |r| vec![r.symlink("l", "one"), gitlink("g", 1)],
1161 |r| vec![r.symlink("l", "two"), gitlink("g", 2)],
1162 );
1163 assert_eq!(conflicts(&s), pairs(&[("g", "CONTENT"), ("l", "CONTENT")]));
1164 // Binary content.
1165 let s = setup(
1166 &[("bin", "\0base")],
1167 |r| vec![r.set("bin", "\0ours")],
1168 |r| vec![r.set("bin", "\0theirs")],
1169 );
1170 let LandOutcome::Conflicts(found) = land_it(&s) else {
1171 panic!("expected conflicts");
1172 };
1173 assert_eq!(found[0].kind, ConflictKind::Content { hunks: Vec::new() });
1174 }
1175
1176 #[test]
1177 fn modify_delete_conflict() {
1178 let s = setup(
1179 &[("f", "1"), ("g", "1")],
1180 |r| vec![r.set("f", "2"), delete("g")],
1181 |r| vec![delete("f"), r.set("g", "2")],
1182 );
1183 assert_eq!(
1184 conflicts(&s),
1185 pairs(&[("f", "MODIFY_DELETE"), ("g", "MODIFY_DELETE")])
1186 );
1187 }
1188
1189 #[test]
1190 fn mode_conflict() {
1191 // Both changed the kind, differently.
1192 let s = setup(
1193 &[("f", "1")],
1194 |r| vec![r.symlink("f", "target")],
1195 |r| vec![r.exec("f", "1")],
1196 );
1197 assert_eq!(conflicts(&s), pairs(&[("f", "MODE")]));
1198 // Added on both sides, executable on one only: the base cannot settle
1199 // the bit.
1200 let s = setup(
1201 &[],
1202 |r| vec![r.exec("n", "same")],
1203 |r| vec![r.set("n", "same")],
1204 );
1205 assert_eq!(conflicts(&s), pairs(&[("n", "MODE")]));
1206 }
1207
1208 #[test]
1209 fn directory_file_conflicts() {
1210 // The change sets a file where the head now has a directory.
1211 let s = setup(
1212 &[("a", "1")],
1213 |r| vec![r.set("x/y", "h")],
1214 |r| vec![r.set("x", "c")],
1215 );
1216 assert_eq!(conflicts(&s), pairs(&[("x", "DF")]));
1217 // The change sets something below a path the head made a file.
1218 let s = setup(
1219 &[("d/a", "1")],
1220 |r| vec![delete("d/a"), r.set("d", "file")],
1221 |r| vec![r.set("d/b", "c")],
1222 );
1223 assert_eq!(conflicts(&s), pairs(&[("d", "DF")]));
1224 // The change edits a file below a path the head made a file.
1225 let s = setup(
1226 &[("d/a", "1")],
1227 |r| vec![delete("d/a"), r.set("d", "file")],
1228 |r| vec![r.set("d/a", "2")],
1229 );
1230 assert_eq!(conflicts(&s), pairs(&[("d", "DF")]));
1231 // The change edits a file the head replaced with a directory.
1232 let s = setup(
1233 &[("f", "1")],
1234 |r| vec![delete("f"), r.set("f/inner", "h")],
1235 |r| vec![r.set("f", "2")],
1236 );
1237 assert_eq!(conflicts(&s), pairs(&[("f", "DF")]));
1238 // The change replaces a directory with a file, and the head added a
1239 // file to that directory.
1240 let s = setup(
1241 &[("p/x", "1")],
1242 |r| vec![r.set("p/new", "h")],
1243 |r| vec![delete("p/x"), r.set("p", "file")],
1244 );
1245 assert_eq!(conflicts(&s), pairs(&[("p", "DF")]));
1246 }
1247
1248 #[test]
1249 fn replacing_a_directory_the_head_also_emptied() {
1250 // The head deleted one file of `p`; the change deleted both and put a
1251 // file in its place. Nothing is left in the directory: no conflict.
1252 let s = setup(
1253 &[("p/x", "1"), ("p/y", "2")],
1254 |_| vec![delete("p/y")],
1255 |r| vec![delete("p/x"), delete("p/y"), r.set("p", "file")],
1256 );
1257 let (id, _) = rebased(&s);
1258 assert_eq!(s.repo.files(s.repo.root(id)), text_map(&[("p", "file")]));
1259 // The head replaced a file with a directory, and the change deleted
1260 // the file: both removed it, the directory stays.
1261 let s = setup(
1262 &[("f", "1"), ("g", "1")],
1263 |r| vec![delete("f"), r.set("f/inner", "h")],
1264 |r| vec![delete("f"), r.set("g", "2")],
1265 );
1266 let (id, _) = rebased(&s);
1267 assert_eq!(
1268 s.repo.files(s.repo.root(id)),
1269 text_map(&[("f/inner", "h"), ("g", "2")])
1270 );
1271 }
1272
1273 #[test]
1274 fn directory_removed_conflicts() {
1275 // The head removed `d`; the change adds a file in it.
1276 let s = setup(
1277 &[("d/a", "1"), ("k", "1")],
1278 |_| vec![delete("d/a")],
1279 |r| vec![r.set("d/b", "2")],
1280 );
1281 let LandOutcome::Conflicts(found) = land_it(&s) else {
1282 panic!("expected conflicts");
1283 };
1284 assert_eq!(found.len(), 1);
1285 assert_eq!(found[0].path, b"d/b");
1286 assert_eq!(
1287 found[0].kind,
1288 ConflictKind::DirectoryRemoved {
1289 directory: b"d".to_vec()
1290 }
1291 );
1292 // Also when the new file is deeper, in a directory the change creates.
1293 let s = setup(
1294 &[("d/e/a", "1"), ("k", "1")],
1295 |_| vec![delete("d/e/a")],
1296 |r| vec![r.set("d/e/new/f", "2")],
1297 );
1298 assert_eq!(conflicts(&s), pairs(&[("d/e/new/f", "DIR_REMOVED")]));
1299 // The other way: the change removed `d`, the head added a file in it.
1300 let s = setup(
1301 &[("d/a", "1"), ("k", "1")],
1302 |r| vec![r.set("d/b", "2")],
1303 |_| vec![delete("d/a")],
1304 );
1305 let LandOutcome::Conflicts(found) = land_it(&s) else {
1306 panic!("expected conflicts");
1307 };
1308 assert_eq!(found[0].path, b"d/b");
1309 assert_eq!(found[0].ours, Some(s.repo.file_kind("2")));
1310 assert_eq!(found[0].theirs, None);
1311 // A directory that keeps other files is not removed.
1312 let s = setup(
1313 &[("d/a", "1"), ("d/z", "1")],
1314 |_| vec![delete("d/a")],
1315 |r| vec![r.set("d/b", "2")],
1316 );
1317 let (id, _) = rebased(&s);
1318 assert_eq!(
1319 s.repo.files(s.repo.root(id)),
1320 text_map(&[("d/b", "2"), ("d/z", "1")])
1321 );
1322 }
1323
1324 #[test]
1325 fn case_conflicts() {
1326 let s = setup(
1327 &[("x", "1")],
1328 |r| vec![r.set("README", "h")],
1329 |r| vec![r.set("readme", "c")],
1330 );
1331 let LandOutcome::Conflicts(found) = land_it(&s) else {
1332 panic!("expected conflicts");
1333 };
1334 assert_eq!(found.len(), 1);
1335 assert_eq!(found[0].path, b"readme");
1336 assert_eq!(
1337 found[0].kind,
1338 ConflictKind::Case {
1339 existing: b"README".to_vec()
1340 }
1341 );
1342 // Unicode normalisation: precomposed and decomposed forms.
1343 let s = setup(
1344 &[("x", "1")],
1345 |r| vec![r.set("docs/caf\u{e9}.md", "h")],
1346 |r| vec![r.set("docs/cafe\u{301}.md", "c")],
1347 );
1348 assert_eq!(conflicts(&s), pairs(&[("docs/cafe\u{301}.md", "CASE")]));
1349 // A directory name that collides, reported once.
1350 let s = setup(
1351 &[("x", "1")],
1352 |r| vec![r.set("Docs/a", "h")],
1353 |r| vec![r.set("docs/b", "c"), r.set("docs/c", "c")],
1354 );
1355 assert_eq!(conflicts(&s), pairs(&[("docs", "CASE")]));
1356 // A collision with a name that was already in the base is the
1357 // change's own business.
1358 let s = setup(
1359 &[("README", "1")],
1360 |r| vec![r.set("x", "h")],
1361 |r| vec![r.set("readme", "c")],
1362 );
1363 rebased(&s);
1364 // Renaming by case alone is fine too.
1365 let s = setup(
1366 &[("README", "1")],
1367 |r| vec![r.set("x", "h")],
1368 |r| vec![delete("README"), r.set("Readme", "1")],
1369 );
1370 rebased(&s);
1371 // Two names on the head fold to the name the change adds: each
1372 // collision is reported once, however many files go through it.
1373 let s = setup(
1374 &[("x", "1")],
1375 |r| vec![r.set("Docs/a", "h"), r.set("DOCS/b", "h")],
1376 |r| vec![r.set("docs/c", "c"), r.set("docs/d", "c")],
1377 );
1378 let LandOutcome::Conflicts(found) = land_it(&s) else {
1379 panic!("expected conflicts");
1380 };
1381 let existing: Vec<&ConflictKind> = found.iter().map(|c| &c.kind).collect();
1382 assert_eq!(
1383 existing,
1384 [
1385 &ConflictKind::Case {
1386 existing: b"DOCS".to_vec()
1387 },
1388 &ConflictKind::Case {
1389 existing: b"Docs".to_vec()
1390 },
1391 ]
1392 );
1393 // Both sides create the directory `cafe\u{301}`, and the change also
1394 // adds `caf\u{e9}` next to it. That collision is the change's own,
1395 // whichever side lands first.
1396 let dir = |r: &Repo| vec![r.set("cafe\u{301}/z", "h")];
1397 let own = |r: &Repo| vec![r.set("cafe\u{301}/b", "c"), r.set("caf\u{e9}", "c")];
1398 rebased(&setup(&[("x", "1")], dir, own));
1399 rebased(&setup(&[("x", "1")], own, dir));
1400 }
1401
1402 #[test]
1403 fn several_conflicts_are_all_reported_in_order() {
1404 let s = setup(
1405 &[("a", "1\n"), ("b", "1"), ("c", "1")],
1406 |r| vec![r.set("a", "ours\n"), delete("b"), r.set("Z", "h")],
1407 |r| {
1408 vec![
1409 r.set("a", "theirs\n"),
1410 r.set("b", "2"),
1411 r.set("z", "c"),
1412 r.set("c", "2"),
1413 ]
1414 },
1415 );
1416 let stored = s.repo.objects.len();
1417 assert_eq!(
1418 conflicts(&s),
1419 pairs(&[("a", "CONTENT"), ("b", "MODIFY_DELETE"), ("z", "CASE")])
1420 );
1421 // A landing with conflicts stores nothing.
1422 assert_eq!(s.repo.objects.len(), stored);
1423 }
1424}