Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 37.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The reference model: a deliberately simple, executable specification of
5//! landing.
6//!
7//! A repository state is a map from path to file. Landing a change built on a
8//! base looks at each path the change touches: if the head left the path as
9//! it was in the base, the change's file is taken; if the head already has the
10//! change's file, there is nothing to do; otherwise both sides changed it, and
11//! only two regular files can still be merged, line by line. Around those
12//! files come the structural rules of `docs/design.md`: a file against a
13//! directory, a directory removed under a file added on the other side, and
14//! names that differ only in letter case or Unicode normalisation.
15//!
16//! Everything here works on the flat map, with naive scans over it, and none
17//! of it calls the engine. Tree ids come from [`Oracle`], which builds trees
18//! from scratch with the format crate, as the engine's property tests do.
19//!
20//! The line merge expects what the simulation's edits guarantee: no line
21//! appears twice in one version of a file, and lines never move. Under that
22//! condition every line diff has a single answer, so the model can predict
23//! the engine's merges exactly, conflicts and hunks included.
24
25use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
26use std::fmt;
27use std::ops::Range;
28use std::rc::Rc;
29
30use braid_format::{Change, ChangeOp, Entry, EntryKind, Kind, ObjectId, build_directory};
31use unicode_normalization::UnicodeNormalization;
32
33/// Content with a NUL byte among this many leading bytes is binary.
34const BINARY_SNIFF_BYTES: usize = 8000;
35
36/// What kind of file a value is.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub enum Mode {
39 /// A regular file.
40 File,
41 /// An executable file.
42 Exec,
43 /// A symlink; the content is its target.
44 Link,
45}
46
47/// A file: its mode, its content, and the id of the content as a blob.
48#[derive(Clone)]
49pub struct Value {
50 mode: Mode,
51 content: Rc<[u8]>,
52 blob: ObjectId,
53}
54
55impl Value {
56 /// A file of this mode and content.
57 pub fn new(mode: Mode, content: Vec<u8>) -> Self {
58 let blob = ObjectId::hash(Kind::Blob, &content);
59 Value {
60 mode,
61 content: content.into(),
62 blob,
63 }
64 }
65
66 /// Its mode.
67 pub fn mode(&self) -> Mode {
68 self.mode
69 }
70
71 /// Its content.
72 pub fn content(&self) -> &[u8] {
73 &self.content
74 }
75
76 /// The same content with another mode.
77 pub fn with_mode(&self, mode: Mode) -> Self {
78 Value {
79 mode,
80 content: Rc::clone(&self.content),
81 blob: self.blob,
82 }
83 }
84
85 /// Whether it is a regular file, executable or not.
86 pub fn is_regular(&self) -> bool {
87 matches!(self.mode, Mode::File | Mode::Exec)
88 }
89
90 /// Whether it is a regular file whose content can be edited line by line.
91 pub fn is_text(&self) -> bool {
92 self.is_regular() && !is_binary(&self.content)
93 }
94
95 /// The tree entry for this file.
96 pub fn entry(&self) -> EntryKind {
97 let (blob, size) = (self.blob, self.content.len() as u64);
98 match self.mode {
99 Mode::File => EntryKind::File { blob, size },
100 Mode::Exec => EntryKind::Executable { blob, size },
101 Mode::Link => EntryKind::Symlink { blob, size },
102 }
103 }
104
105 /// The change that sets a path to this file.
106 pub fn op(&self) -> ChangeOp {
107 ChangeOp::from_entry(&self.entry()).expect("a file is never a directory")
108 }
109}
110
111impl PartialEq for Value {
112 fn eq(&self, other: &Self) -> bool {
113 self.mode == other.mode && self.blob == other.blob
114 }
115}
116
117impl Eq for Value {}
118
119impl fmt::Debug for Value {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 let mode = match self.mode {
122 Mode::File => "file",
123 Mode::Exec => "exec",
124 Mode::Link => "link",
125 };
126 if is_binary(&self.content) {
127 write!(f, "{mode} of {} binary bytes", self.content.len())
128 } else {
129 write!(f, "{mode} {:?}", String::from_utf8_lossy(&self.content))
130 }
131 }
132}
133
134/// A repository state: every file, by path. No path is inside another.
135pub type Files = BTreeMap<Vec<u8>, Value>;
136
137/// A change list in the model's terms: each changed path with its new file,
138/// or `None` where the file is deleted, sorted by path.
139pub type Edits = Vec<(Vec<u8>, Option<Value>)>;
140
141/// Whether content is binary: a NUL byte among its first bytes.
142pub fn is_binary(content: &[u8]) -> bool {
143 content
144 .iter()
145 .take(BINARY_SNIFF_BYTES)
146 .any(|byte| *byte == 0)
147}
148
149/// `dir/name`, or `name` when `dir` is the root.
150pub fn join(dir: &[u8], name: &[u8]) -> Vec<u8> {
151 let mut path = dir.to_vec();
152 if !path.is_empty() {
153 path.push(b'/');
154 }
155 path.extend_from_slice(name);
156 path
157}
158
159/// The lengths of the proper prefixes of a path: 1 and 3 for `a/b/c`.
160pub fn prefix_lengths(path: &[u8]) -> impl Iterator<Item = usize> + '_ {
161 path.iter()
162 .enumerate()
163 .filter(|(_, byte)| **byte == b'/')
164 .map(|(at, _)| at)
165}
166
167/// Whether `path` is inside the directory `dir`.
168pub fn inside(dir: &[u8], path: &[u8]) -> bool {
169 path.len() > dir.len() && path.starts_with(dir) && path[dir.len()] == b'/'
170}
171
172/// Whether two paths are the same, or one is inside the other.
173pub fn related(a: &[u8], b: &[u8]) -> bool {
174 a == b || inside(a, b) || inside(b, a)
175}
176
177/// The files below the directory `dir`, which is not the root.
178pub fn files_below<'a>(
179 files: &'a Files,
180 dir: &[u8],
181) -> impl Iterator<Item = (&'a Vec<u8>, &'a Value)> + 'a {
182 let mut from = dir.to_vec();
183 from.push(b'/');
184 let mut to = dir.to_vec();
185 to.push(b'/' + 1);
186 files.range(from..to)
187}
188
189/// Whether `dir` is a directory: some file is below it.
190pub fn is_dir(files: &Files, dir: &[u8]) -> bool {
191 files_below(files, dir).next().is_some()
192}
193
194/// What is at a path.
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum Found<'a> {
197 /// This file.
198 File(&'a Value),
199 /// A directory.
200 Dir,
201 /// Nothing, and no prefix of the path is a file.
202 Absent,
203 /// Nothing, because the prefix of this many bytes is a file.
204 Blocked(usize),
205}
206
207/// What is at `path`.
208pub fn find<'a>(files: &'a Files, path: &[u8]) -> Found<'a> {
209 if let Some(len) = prefix_lengths(path).find(|&len| files.contains_key(&path[..len])) {
210 return Found::Blocked(len);
211 }
212 match files.get(path) {
213 Some(value) => Found::File(value),
214 None if is_dir(files, path) => Found::Dir,
215 None => Found::Absent,
216 }
217}
218
219/// Whether there is a file or a directory at `path`.
220fn has_entry(files: &Files, path: &[u8]) -> bool {
221 matches!(find(files, path), Found::File(_) | Found::Dir)
222}
223
224/// The names in the directory `dir` (the root when empty).
225fn names_in(files: &Files, dir: &[u8]) -> BTreeSet<Vec<u8>> {
226 let skip = if dir.is_empty() { 0 } else { dir.len() + 1 };
227 let first_name = |path: &Vec<u8>| {
228 let rest = &path[skip..];
229 let end = rest
230 .iter()
231 .position(|byte| *byte == b'/')
232 .unwrap_or(rest.len());
233 rest[..end].to_vec()
234 };
235 if dir.is_empty() {
236 files.keys().map(first_name).collect()
237 } else {
238 files_below(files, dir)
239 .map(|(path, _)| first_name(path))
240 .collect()
241 }
242}
243
244/// The shortest proper prefix of `path` that does not exist, when every
245/// shorter one is a directory.
246fn first_missing_dir(files: &Files, path: &[u8]) -> Option<usize> {
247 for len in prefix_lengths(path) {
248 let prefix = &path[..len];
249 if files.contains_key(prefix) {
250 return None;
251 }
252 if !is_dir(files, prefix) {
253 return Some(len);
254 }
255 }
256 None
257}
258
259/// A name as file systems that ignore case and normalisation compare it:
260/// Unicode NFC, lowercased letter by letter, NFC again. A name that is not
261/// UTF-8 is lowercased as ASCII.
262pub fn fold(name: &[u8]) -> Vec<u8> {
263 if name.is_ascii() {
264 // Normalisation leaves ASCII as it is.
265 return name.to_ascii_lowercase();
266 }
267 match std::str::from_utf8(name) {
268 Ok(text) => {
269 let composed: String = text.nfc().collect();
270 let lower: String = composed.chars().flat_map(char::to_lowercase).collect();
271 lower.nfc().collect::<String>().into_bytes()
272 }
273 Err(_) => name.to_ascii_lowercase(),
274 }
275}
276
277/// The edits that turn `old` into `new`, sorted by path.
278pub fn change_list(old: &Files, new: &Files) -> Edits {
279 let mut edits = Vec::new();
280 let mut a = old.iter().peekable();
281 let mut b = new.iter().peekable();
282 loop {
283 match (a.peek(), b.peek()) {
284 (None, None) => return edits,
285 (Some((path, _)), None) => {
286 edits.push(((*path).clone(), None));
287 a.next();
288 }
289 (None, Some((path, value))) => {
290 edits.push(((*path).clone(), Some((*value).clone())));
291 b.next();
292 }
293 (Some((old_path, old_value)), Some((new_path, new_value))) => {
294 if old_path < new_path {
295 edits.push(((*old_path).clone(), None));
296 a.next();
297 } else if new_path < old_path {
298 edits.push(((*new_path).clone(), Some((*new_value).clone())));
299 b.next();
300 } else {
301 if old_value != new_value {
302 edits.push(((*new_path).clone(), Some((*new_value).clone())));
303 }
304 a.next();
305 b.next();
306 }
307 }
308 }
309 }
310}
311
312/// Applies edits: deletes, then sets.
313pub fn apply_edits(files: &mut Files, edits: &Edits) {
314 for (path, value) in edits {
315 if value.is_none() {
316 files.remove(path);
317 }
318 }
319 for (path, value) in edits {
320 if let Some(value) = value {
321 files.insert(path.clone(), value.clone());
322 }
323 }
324}
325
326/// The engine's form of a change list.
327pub fn to_changes(edits: &Edits) -> Vec<Change> {
328 edits
329 .iter()
330 .map(|(path, value)| Change {
331 path: path.clone(),
332 op: value.as_ref().map_or(ChangeOp::Delete, Value::op),
333 })
334 .collect()
335}
336
337/// One region of a text that the two sides changed differently: a range of
338/// lines and their text, in the base, ours and theirs.
339#[derive(Clone, Debug, PartialEq, Eq)]
340pub struct Hunk {
341 /// The region in the base.
342 pub base: (Range<usize>, Vec<u8>),
343 /// What ours has instead.
344 pub ours: (Range<usize>, Vec<u8>),
345 /// What theirs has instead.
346 pub theirs: (Range<usize>, Vec<u8>),
347}
348
349/// The result of merging two versions of a text.
350#[derive(Clone, Debug, PartialEq, Eq)]
351pub enum TextMerge {
352 /// The merged text.
353 Clean(Vec<u8>),
354 /// The regions changed differently; none for binary content.
355 Conflict(Vec<Hunk>),
356}
357
358/// Lines end after each `\n`; a last line without one is a line too.
359fn lines(text: &[u8]) -> Vec<&[u8]> {
360 if text.is_empty() {
361 return Vec::new();
362 }
363 text.split_inclusive(|byte| *byte == b'\n').collect()
364}
365
366/// One change of one side: base lines `base` replaced by side lines `side`.
367#[derive(Clone, Debug)]
368struct SideHunk {
369 base: Range<usize>,
370 side: Range<usize>,
371}
372
373/// The changes that turn `base` into `side`. Lines must be distinct within
374/// each, and the lines both have must be in the same order; the diff then has
375/// a single answer: every shared line is kept.
376fn side_hunks(base: &[&[u8]], side: &[&[u8]]) -> Result<Vec<SideHunk>, String> {
377 let in_base: HashSet<&[u8]> = base.iter().copied().collect();
378 let in_side: HashSet<&[u8]> = side.iter().copied().collect();
379 if in_base.len() != base.len() || in_side.len() != side.len() {
380 return Err("a line appears twice in one version".to_owned());
381 }
382 let (mut i, mut j) = (0, 0);
383 let mut hunks = Vec::new();
384 while i < base.len() || j < side.len() {
385 if i < base.len() && j < side.len() && base[i] == side[j] {
386 i += 1;
387 j += 1;
388 continue;
389 }
390 let (i0, j0) = (i, j);
391 while i < base.len() && !in_side.contains(base[i]) {
392 i += 1;
393 }
394 while j < side.len() && !in_base.contains(side[j]) {
395 j += 1;
396 }
397 let aligned = match (base.get(i), side.get(j)) {
398 (Some(a), Some(b)) => a == b,
399 (None, None) => true,
400 _ => false,
401 };
402 if !aligned || (i, j) == (i0, j0) {
403 return Err("a line moved between versions".to_owned());
404 }
405 hunks.push(SideHunk {
406 base: i0..i,
407 side: j0..j,
408 });
409 }
410 Ok(hunks)
411}
412
413/// Merges `ours` and `theirs`, two versions of `base`, line by line.
414///
415/// Changes of the two sides whose base ranges overlap or touch, counting an
416/// insertion at the edge of a change, form one region; a region changed by
417/// one side takes that side's lines, one changed identically by both takes
418/// them once, and any other is a conflict. Binary content merges only when
419/// one side kept the base or both agree.
420///
421/// Fails when the inputs break the model's assumptions: a repeated line, or a
422/// line that moved.
423pub fn merge_text(base: &[u8], ours: &[u8], theirs: &[u8]) -> Result<TextMerge, String> {
424 if ours == theirs || theirs == base {
425 return Ok(TextMerge::Clean(ours.to_vec()));
426 }
427 if ours == base {
428 return Ok(TextMerge::Clean(theirs.to_vec()));
429 }
430 if is_binary(base) || is_binary(ours) || is_binary(theirs) {
431 return Ok(TextMerge::Conflict(Vec::new()));
432 }
433 let (b, o, t) = (lines(base), lines(ours), lines(theirs));
434 let sides = [side_hunks(&b, &o)?, side_hunks(&b, &t)?];
435
436 // Every change of either side, by where it starts in the base; ours
437 // first on a tie.
438 let mut order: Vec<(usize, usize, usize)> = Vec::new();
439 for (side, hunks) in sides.iter().enumerate() {
440 for (index, hunk) in hunks.iter().enumerate() {
441 order.push((hunk.base.start, side, index));
442 }
443 }
444 order.sort();
445
446 // Regions: a change joins the region before it when it starts at or
447 // before the region's end.
448 struct Region {
449 start: usize,
450 end: usize,
451 members: [Vec<usize>; 2],
452 }
453 let mut regions: Vec<Region> = Vec::new();
454 for (start, side, index) in order {
455 let end = sides[side][index].base.end;
456 match regions.last_mut() {
457 Some(region) if start <= region.end => {
458 region.end = region.end.max(end);
459 region.members[side].push(index);
460 }
461 _ => {
462 let mut members = [Vec::new(), Vec::new()];
463 members[side].push(index);
464 regions.push(Region {
465 start,
466 end,
467 members,
468 });
469 }
470 }
471 }
472
473 let texts = [&o, &t];
474 let mut out = Vec::new();
475 let mut hunks = Vec::new();
476 let mut copied = 0;
477 // Lines each side has gained before the current region.
478 let mut shift = [0isize; 2];
479 for region in &regions {
480 let mut ranges = [0..0, 0..0];
481 for side in 0..2 {
482 let growth: isize = region.members[side]
483 .iter()
484 .map(|&index| {
485 let hunk = &sides[side][index];
486 hunk.side.len() as isize - hunk.base.len() as isize
487 })
488 .sum();
489 let start = region.start as isize + shift[side];
490 let end = region.end as isize + shift[side] + growth;
491 ranges[side] = start as usize..end as usize;
492 shift[side] += growth;
493 }
494 for line in &b[copied..region.start] {
495 out.extend_from_slice(line);
496 }
497 copied = region.end;
498 let changed = [!region.members[0].is_empty(), !region.members[1].is_empty()];
499 let take = |side: usize, out: &mut Vec<u8>| {
500 for line in &texts[side][ranges[side].clone()] {
501 out.extend_from_slice(line);
502 }
503 };
504 match changed {
505 [true, false] => take(0, &mut out),
506 [false, true] => take(1, &mut out),
507 _ if o[ranges[0].clone()] == t[ranges[1].clone()] => take(0, &mut out),
508 _ => {
509 let text = |lines: &[&[u8]]| lines.concat();
510 hunks.push(Hunk {
511 base: (region.start..region.end, text(&b[region.start..region.end])),
512 ours: (ranges[0].clone(), text(&o[ranges[0].clone()])),
513 theirs: (ranges[1].clone(), text(&t[ranges[1].clone()])),
514 });
515 }
516 }
517 }
518 for line in &b[copied..] {
519 out.extend_from_slice(line);
520 }
521 Ok(if hunks.is_empty() {
522 TextMerge::Clean(out)
523 } else {
524 TextMerge::Conflict(hunks)
525 })
526}
527
528/// A conflict as the model sees it.
529#[derive(Clone, Debug, PartialEq, Eq)]
530pub struct ModelConflict {
531 /// Where it is.
532 pub path: Vec<u8>,
533 /// The engine's code for its kind: `CONTENT`, `MODIFY_DELETE`, `MODE`,
534 /// `DF`, `DIR_REMOVED` or `CASE`.
535 pub code: &'static str,
536 /// The removed directory of a `DIR_REMOVED`, the name already on the
537 /// head of a `CASE`; empty otherwise.
538 pub detail: Vec<u8>,
539 /// The conflicting regions of a text `CONTENT` conflict.
540 pub hunks: Vec<Hunk>,
541}
542
543impl ModelConflict {
544 fn new(path: &[u8], code: &'static str) -> Self {
545 ModelConflict {
546 path: path.to_vec(),
547 code,
548 detail: Vec::new(),
549 hunks: Vec::new(),
550 }
551 }
552}
553
554/// A text merge the model made while rebasing, kept so that it can be
555/// compared with the engine's `merge3` on the same inputs.
556#[derive(Clone, Debug)]
557pub struct MergeCase {
558 /// The file.
559 pub path: Vec<u8>,
560 /// The base text: empty when the base had no regular file there.
561 pub base: Vec<u8>,
562 /// The head's text.
563 pub ours: Vec<u8>,
564 /// The change's text.
565 pub theirs: Vec<u8>,
566 /// What the model made of them.
567 pub result: TextMerge,
568}
569
570/// What landing a change on a head that moved since its base gives.
571#[derive(Clone, Debug)]
572pub enum Rebase {
573 /// The change lands.
574 Clean {
575 /// The new state.
576 state: Files,
577 /// The change list against the head; empty when the head already
578 /// has everything the change does.
579 resolved: Edits,
580 /// The paths both sides changed and that were merged.
581 merged: Vec<Vec<u8>>,
582 },
583 /// The change conflicts with the head.
584 Conflicts(Vec<ModelConflict>),
585}
586
587/// Rebases the change that turns `base` into `theirs` onto `ours`, a head
588/// that descends from `base`. Text merges are added to `merges`.
589pub fn rebase(
590 base: &Files,
591 ours: &Files,
592 theirs: &Files,
593 merges: &mut Vec<MergeCase>,
594) -> Result<Rebase, String> {
595 let mut work = Work::default();
596 for (path, value) in change_list(base, theirs) {
597 work.path(base, ours, path, value, merges)?;
598 }
599 work.removed_under_added(base, ours);
600 work.added_under_removed(base, ours, theirs);
601 let sets: Vec<Vec<u8>> = work
602 .resolved
603 .iter()
604 .filter(|(_, value)| value.is_some())
605 .map(|(path, _)| path.clone())
606 .collect();
607 let mut checked = BTreeSet::new();
608 for path in sets {
609 work.check_case(base, ours, theirs, &path, &mut checked);
610 }
611 let mut state = ours.clone();
612 apply_edits(&mut state, &work.resolved);
613 work.file_against_directory(&state);
614
615 if work.conflicts.is_empty() {
616 return Ok(Rebase::Clean {
617 state,
618 resolved: work.resolved,
619 merged: work.merged,
620 });
621 }
622 let mut conflicts = work.conflicts;
623 conflicts.sort_by(|a, b| (&a.path, a.code, &a.detail).cmp(&(&b.path, b.code, &b.detail)));
624 conflicts.dedup();
625 Ok(Rebase::Conflicts(conflicts))
626}
627
628/// The names of one directory of the head, by folded name.
629type FoldedNames = BTreeMap<Vec<u8>, Vec<Vec<u8>>>;
630
631/// The state of one rebase.
632#[derive(Default)]
633struct Work {
634 resolved: Edits,
635 merged: Vec<Vec<u8>>,
636 conflicts: Vec<ModelConflict>,
637 /// Paths where the change adds a file and neither the base nor the head
638 /// had one.
639 added: Vec<Vec<u8>>,
640 /// Paths the change deletes.
641 deleted: Vec<Vec<u8>>,
642 /// Directories of the head whose names were folded already.
643 folded: BTreeMap<Vec<u8>, FoldedNames>,
644}
645
646impl Work {
647 /// The per-path rule for one path the change touches.
648 fn path(
649 &mut self,
650 base: &Files,
651 ours: &Files,
652 path: Vec<u8>,
653 theirs: Option<Value>,
654 merges: &mut Vec<MergeCase>,
655 ) -> Result<(), String> {
656 if theirs.is_none() {
657 self.deleted.push(path.clone());
658 }
659 let b = base.get(&path);
660 let o = ours.get(&path);
661 if theirs.as_ref() == o {
662 return Ok(());
663 }
664 if b == o {
665 if b.is_none() {
666 self.added.push(path.clone());
667 }
668 self.resolved.push((path, theirs));
669 return Ok(());
670 }
671 match (o, theirs) {
672 (Some(o), Some(t)) => self.merge(path, b, o, &t, merges)?,
673 (None, Some(_)) => {
674 let conflict = match find(ours, &path) {
675 Found::Dir => ModelConflict::new(&path, "DF"),
676 Found::Blocked(len) => ModelConflict::new(&path[..len], "DF"),
677 _ => ModelConflict::new(&path, "MODIFY_DELETE"),
678 };
679 self.conflicts.push(conflict);
680 }
681 _ => self
682 .conflicts
683 .push(ModelConflict::new(&path, "MODIFY_DELETE")),
684 }
685 Ok(())
686 }
687
688 /// Both sides changed the file at `path` to different files.
689 fn merge(
690 &mut self,
691 path: Vec<u8>,
692 base: Option<&Value>,
693 ours: &Value,
694 theirs: &Value,
695 merges: &mut Vec<MergeCase>,
696 ) -> Result<(), String> {
697 if !ours.is_regular() || !theirs.is_regular() {
698 let code = if ours.mode() == theirs.mode() {
699 "CONTENT"
700 } else {
701 "MODE"
702 };
703 self.conflicts.push(ModelConflict::new(&path, code));
704 return Ok(());
705 }
706 let base = base.filter(|value| value.is_regular());
707 let (o, t) = (ours.mode() == Mode::Exec, theirs.mode() == Mode::Exec);
708 // A side that kept the base's bit yields to the other.
709 let exec = if o == t {
710 Some(o)
711 } else {
712 base.map(|base| {
713 if (base.mode() == Mode::Exec) == o {
714 t
715 } else {
716 o
717 }
718 })
719 };
720 let content = if ours.content() == theirs.content() {
721 TextMerge::Clean(ours.content().to_vec())
722 } else {
723 let base_text = base.map_or(&[][..], Value::content);
724 let result = merge_text(base_text, ours.content(), theirs.content())
725 .map_err(|why| format!("cannot merge {}: {why}", show(&path)))?;
726 merges.push(MergeCase {
727 path: path.clone(),
728 base: base_text.to_vec(),
729 ours: ours.content().to_vec(),
730 theirs: theirs.content().to_vec(),
731 result: result.clone(),
732 });
733 result
734 };
735 if exec.is_none() {
736 self.conflicts.push(ModelConflict::new(&path, "MODE"));
737 }
738 match (exec, content) {
739 (_, TextMerge::Conflict(hunks)) => self.conflicts.push(ModelConflict {
740 hunks,
741 ..ModelConflict::new(&path, "CONTENT")
742 }),
743 (Some(exec), TextMerge::Clean(text)) => {
744 let mode = if exec { Mode::Exec } else { Mode::File };
745 let value = Value::new(mode, text);
746 if value != *ours {
747 self.resolved.push((path.clone(), Some(value)));
748 self.merged.push(path);
749 }
750 }
751 (None, TextMerge::Clean(_)) => {}
752 }
753 Ok(())
754 }
755
756 /// A file the change adds under a directory of the base that the head
757 /// removed.
758 fn removed_under_added(&mut self, base: &Files, ours: &Files) {
759 for path in &self.added {
760 let deepest = prefix_lengths(path)
761 .filter(|&len| is_dir(base, &path[..len]))
762 .last();
763 if let Some(len) = deepest
764 && find(ours, &path[..len]) == Found::Absent
765 {
766 self.conflicts.push(ModelConflict {
767 detail: path[..len].to_vec(),
768 ..ModelConflict::new(path, "DIR_REMOVED")
769 });
770 }
771 }
772 }
773
774 /// A file the head added under a directory of the base that the change
775 /// removed.
776 fn added_under_removed(&mut self, base: &Files, ours: &Files, theirs: &Files) {
777 let removed: BTreeSet<Vec<u8>> = self
778 .deleted
779 .iter()
780 .filter_map(|path| first_missing_dir(theirs, path).map(|len| path[..len].to_vec()))
781 .collect();
782 for dir in removed {
783 if find(base, &dir) != Found::Dir || find(ours, &dir) != Found::Dir {
784 continue;
785 }
786 for (path, _) in files_below(ours, &dir) {
787 if !base.contains_key(path) {
788 self.conflicts.push(ModelConflict {
789 detail: dir.clone(),
790 ..ModelConflict::new(path, "DIR_REMOVED")
791 });
792 }
793 }
794 }
795 }
796
797 /// The change sets `path`: the first name on it that the head does not
798 /// have must not fold to a name the head added.
799 fn check_case(
800 &mut self,
801 base: &Files,
802 ours: &Files,
803 theirs: &Files,
804 path: &[u8],
805 checked: &mut BTreeSet<Vec<u8>>,
806 ) {
807 let mut start = 0;
808 loop {
809 let end = path[start..]
810 .iter()
811 .position(|byte| *byte == b'/')
812 .map_or(path.len(), |at| start + at);
813 let prefix = &path[..end];
814 let last = end == path.len();
815 if ours.contains_key(prefix) {
816 return;
817 }
818 if is_dir(ours, prefix) {
819 if last {
820 return;
821 }
822 start = end + 1;
823 continue;
824 }
825 if !checked.insert(prefix.to_vec()) {
826 return;
827 }
828 let parent = &path[..start.saturating_sub(1)];
829 let index = self.folded.entry(parent.to_vec()).or_insert_with(|| {
830 let mut index = FoldedNames::new();
831 for name in names_in(ours, parent) {
832 index.entry(fold(&name)).or_default().push(name);
833 }
834 index
835 });
836 let others = index
837 .get(&fold(&path[start..end]))
838 .cloned()
839 .unwrap_or_default();
840 for other in others {
841 let existing = join(parent, &other);
842 // Only a name the head brought counts.
843 if !has_entry(base, &existing) && !has_entry(theirs, &existing) {
844 self.conflicts.push(ModelConflict {
845 detail: existing,
846 ..ModelConflict::new(prefix, "CASE")
847 });
848 }
849 }
850 return;
851 }
852 }
853
854 /// In the result, a file where another file needs a directory.
855 fn file_against_directory(&mut self, state: &Files) {
856 let mut clashes = BTreeSet::new();
857 for path in state.keys() {
858 for len in prefix_lengths(path) {
859 if state.contains_key(&path[..len]) {
860 clashes.insert(path[..len].to_vec());
861 }
862 }
863 }
864 for path in clashes {
865 self.conflicts.push(ModelConflict::new(&path, "DF"));
866 }
867 }
868}
869
870/// Builds tree ids from scratch from a state, with the format crate's
871/// `build_directory`, remembering directories it has built already.
872#[derive(Default)]
873pub struct Oracle {
874 built: HashMap<Vec<Entry>, ObjectId>,
875}
876
877impl fmt::Debug for Oracle {
878 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879 f.debug_struct("Oracle")
880 .field("directories", &self.built.len())
881 .finish()
882 }
883}
884
885/// How many directories the oracle remembers before it starts again.
886const ORACLE_MEMORY: usize = 20_000;
887
888impl Oracle {
889 /// The root tree id of `files`.
890 pub fn root(&mut self, files: &Files) -> ObjectId {
891 let items: Vec<(&[u8], &Value)> = files
892 .iter()
893 .map(|(path, value)| (path.as_slice(), value))
894 .collect();
895 self.build(&items)
896 }
897
898 /// The tree id of the directory `dir`, if there is one.
899 pub fn dir(&mut self, files: &Files, dir: &[u8]) -> Option<ObjectId> {
900 let skip = dir.len() + 1;
901 let items: Vec<(&[u8], &Value)> = files_below(files, dir)
902 .map(|(path, value)| (&path[skip..], value))
903 .collect();
904 (!items.is_empty()).then(|| self.build(&items))
905 }
906
907 /// The entry at `path`, as the engine would report it in a conflict.
908 pub fn entry_at(&mut self, files: &Files, path: &[u8]) -> Option<EntryKind> {
909 match find(files, path) {
910 Found::File(value) => Some(value.entry()),
911 Found::Dir => self.dir(files, path).map(|tree| EntryKind::Tree { tree }),
912 Found::Absent | Found::Blocked(_) => None,
913 }
914 }
915
916 fn build(&mut self, items: &[(&[u8], &Value)]) -> ObjectId {
917 let mut entries = Vec::new();
918 let mut below: BTreeMap<&[u8], Vec<(&[u8], &Value)>> = BTreeMap::new();
919 for (path, value) in items {
920 match path.iter().position(|byte| *byte == b'/') {
921 None => entries.push(Entry {
922 name: path.to_vec(),
923 kind: value.entry(),
924 }),
925 Some(slash) => below
926 .entry(&path[..slash])
927 .or_default()
928 .push((&path[slash + 1..], *value)),
929 }
930 }
931 for (name, sub) in below {
932 let tree = self.build(&sub);
933 entries.push(Entry {
934 name: name.to_vec(),
935 kind: EntryKind::Tree { tree },
936 });
937 }
938 entries.sort_by(|a, b| a.name.cmp(&b.name));
939 if let Some(id) = self.built.get(&entries) {
940 return *id;
941 }
942 let id = build_directory(entries.clone())
943 .expect("a state always forms valid directories")
944 .root();
945 if self.built.len() >= ORACLE_MEMORY {
946 self.built.clear();
947 }
948 self.built.insert(entries, id);
949 id
950 }
951}
952
953/// A path for messages: quoted, with combining marks escaped so that the
954/// two forms of a name tell apart.
955pub fn show(path: &[u8]) -> String {
956 format!("{:?}", String::from_utf8_lossy(path))
957}
958
959#[cfg(test)]
960mod tests {
961 use super::*;
962
963 fn text(lines: &[&str]) -> Vec<u8> {
964 lines
965 .iter()
966 .map(|line| format!("{line}\n"))
967 .collect::<String>()
968 .into_bytes()
969 }
970
971 fn clean(base: &[&str], ours: &[&str], theirs: &[&str]) -> Vec<u8> {
972 match merge_text(&text(base), &text(ours), &text(theirs)).unwrap() {
973 TextMerge::Clean(bytes) => bytes,
974 conflict => panic!("expected a clean merge, got {conflict:?}"),
975 }
976 }
977
978 fn conflict(base: &[&str], ours: &[&str], theirs: &[&str]) -> Vec<Hunk> {
979 match merge_text(&text(base), &text(ours), &text(theirs)).unwrap() {
980 TextMerge::Conflict(hunks) => hunks,
981 clean => panic!("expected a conflict, got {clean:?}"),
982 }
983 }
984
985 #[test]
986 fn line_merge_follows_the_rules() {
987 let base = ["1", "2", "3", "4", "5"];
988 // Separate edits, one unchanged line between them.
989 assert_eq!(
990 clean(
991 &base,
992 &["1", "A", "3", "4", "5"],
993 &["1", "2", "3", "B", "5"]
994 ),
995 text(&["1", "A", "3", "B", "5"])
996 );
997 // Adjacent edits touch.
998 let hunks = conflict(
999 &base,
1000 &["1", "A", "3", "4", "5"],
1001 &["1", "2", "B", "4", "5"],
1002 );
1003 assert_eq!(hunks.len(), 1);
1004 assert_eq!(hunks[0].base, (1..3, text(&["2", "3"])));
1005 assert_eq!(hunks[0].ours, (1..3, text(&["A", "3"])));
1006 assert_eq!(hunks[0].theirs, (1..3, text(&["2", "B"])));
1007 // An insertion at the edge of a change touches it.
1008 conflict(
1009 &base,
1010 &["1", "A", "3", "4", "5"],
1011 &["1", "2", "X", "3", "4", "5"],
1012 );
1013 // An insertion one line away does not.
1014 assert_eq!(
1015 clean(
1016 &base,
1017 &["1", "A", "3", "4", "5"],
1018 &["1", "2", "3", "X", "4", "5"]
1019 ),
1020 text(&["1", "A", "3", "X", "4", "5"])
1021 );
1022 // The same change on both sides is taken once.
1023 assert_eq!(
1024 clean(
1025 &base,
1026 &["1", "A", "3", "4", "5"],
1027 &["1", "A", "3", "4", "Z"]
1028 ),
1029 text(&["1", "A", "3", "4", "Z"])
1030 );
1031 // Insertions at the same place.
1032 conflict(&["a", "b"], &["a", "X", "b"], &["a", "Y", "b"]);
1033 // Line numbers on each side follow what came before.
1034 let base = ["1", "2", "3", "4", "5", "6"];
1035 let hunks = conflict(
1036 &base,
1037 &["1", "2", "n", "n2", "3", "4", "X", "6"],
1038 &["2", "3", "4", "Y", "6"],
1039 );
1040 assert_eq!(hunks.len(), 1);
1041 assert_eq!(hunks[0].base, (4..5, text(&["5"])));
1042 assert_eq!(hunks[0].ours, (6..7, text(&["X"])));
1043 assert_eq!(hunks[0].theirs, (3..4, text(&["Y"])));
1044 // An insertion right after a line the other side deletes touches it.
1045 conflict(
1046 &base,
1047 &["1", "n", "2", "3", "4", "5", "6"],
1048 &["2", "3", "4", "5", "6"],
1049 );
1050 // Binary content.
1051 assert_eq!(
1052 merge_text(b"\0a", b"\0b", b"\0c").unwrap(),
1053 TextMerge::Conflict(Vec::new())
1054 );
1055 // What the model cannot judge.
1056 assert!(merge_text(&text(&["a", "b"]), &text(&["b", "a", "c"]), &text(&["a"])).is_err());
1057 assert!(merge_text(&text(&["a"]), &text(&["a", "a"]), &text(&["b"])).is_err());
1058 }
1059
1060 fn files(entries: &[(&str, &str)]) -> Files {
1061 entries
1062 .iter()
1063 .map(|(path, content)| {
1064 (
1065 path.as_bytes().to_vec(),
1066 Value::new(Mode::File, content.as_bytes().to_vec()),
1067 )
1068 })
1069 .collect()
1070 }
1071
1072 fn codes(result: Rebase) -> Vec<(String, &'static str)> {
1073 match result {
1074 Rebase::Conflicts(conflicts) => conflicts
1075 .into_iter()
1076 .map(|c| (String::from_utf8(c.path).unwrap(), c.code))
1077 .collect(),
1078 Rebase::Clean { state, .. } => panic!("expected conflicts, got {state:?}"),
1079 }
1080 }
1081
1082 #[test]
1083 fn rebase_rules() {
1084 let base = files(&[("a", "1\n"), ("d/x", "1\n"), ("k", "1\n")]);
1085 let mut merges = Vec::new();
1086 // Disjoint edits.
1087 let ours = files(&[("a", "2\n"), ("d/x", "1\n"), ("k", "1\n")]);
1088 let theirs = files(&[("a", "1\n"), ("d/x", "1\n"), ("d/y", "1\n"), ("k", "1\n")]);
1089 match rebase(&base, &ours, &theirs, &mut merges).unwrap() {
1090 Rebase::Clean { state, .. } => assert_eq!(
1091 state,
1092 files(&[("a", "2\n"), ("d/x", "1\n"), ("d/y", "1\n"), ("k", "1\n")])
1093 ),
1094 other => panic!("{other:?}"),
1095 }
1096 // The head removed `d`; the change adds under it.
1097 let ours = files(&[("a", "1\n"), ("k", "1\n")]);
1098 assert_eq!(
1099 codes(rebase(&base, &ours, &theirs, &mut merges).unwrap()),
1100 [("d/y".to_owned(), "DIR_REMOVED")]
1101 );
1102 // A file against a directory, and a name twin.
1103 let ours = files(&[
1104 ("a", "1\n"),
1105 ("d/x", "1\n"),
1106 ("k", "1\n"),
1107 ("README", "h\n"),
1108 ]);
1109 let theirs = files(&[
1110 ("a/b", "1\n"),
1111 ("d/x", "1\n"),
1112 ("k", "1\n"),
1113 ("readme", "c\n"),
1114 ]);
1115 let ours_a_file = {
1116 let mut ours = ours.clone();
1117 ours.insert(b"a".to_vec(), Value::new(Mode::File, b"2\n".to_vec()));
1118 ours
1119 };
1120 // The change deleted `a`, which the head modified, and put `a/b` below
1121 // it: a modify/delete conflict, and the file the head keeps at `a`
1122 // stands where `a/b` needs a directory.
1123 assert_eq!(
1124 codes(rebase(&base, &ours_a_file, &theirs, &mut merges).unwrap()),
1125 [
1126 ("a".to_owned(), "DF"),
1127 ("a".to_owned(), "MODIFY_DELETE"),
1128 ("readme".to_owned(), "CASE")
1129 ]
1130 );
1131 }
1132
1133 #[test]
1134 fn oracle_matches_the_empty_tree_and_shares_directories() {
1135 let mut oracle = Oracle::default();
1136 assert_eq!(
1137 oracle.root(&Files::new()).to_hex(),
1138 "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf"
1139 );
1140 let state = files(&[("d/x", "1\n"), ("e/x", "1\n")]);
1141 assert_eq!(oracle.dir(&state, b"d"), oracle.dir(&state, b"e"));
1142 assert_eq!(oracle.dir(&state, b"f"), None);
1143 }
1144
1145 #[test]
1146 fn folding() {
1147 assert_eq!(fold(b"README"), fold(b"readme"));
1148 assert_eq!(fold("caf\u{e9}".as_bytes()), fold("cafe\u{301}".as_bytes()));
1149 assert_eq!(fold("CAF\u{c9}".as_bytes()), fold("cafe\u{301}".as_bytes()));
1150 assert_ne!(fold(b"a"), fold(b"b"));
1151 assert_eq!(fold(b"\xffA"), b"\xffa");
1152 }
1153}