diff --git a/apps/origin-src/src/conflict.rs b/apps/origin-src/src/conflict.rs new file mode 100644 index 00000000..e223541e --- /dev/null +++ b/apps/origin-src/src/conflict.rs @@ -0,0 +1,106 @@ +//! Conflicts: what a merge leaves where both sides changed a file. +//! +//! A [marked](crate::store::Store::merge_marked) merge writes both +//! versions of each such text file, between markers naming the sides: +//! +//! ```text +//! <<<<<<< 3f1c9a2e07b4 +//! our version +//! ======= +//! their version +//! >>>>>>> 8d02e5b1c4f9 +//! ``` +//! +//! A binary file, or a path a directory is on either side of, keeps one +//! side instead. + +use origin_shared::{ObjectId, RepoPath}; + +/// A path a merge left conflicted, and the entry it wrote there. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Conflicted { + /// The path. + pub path: RepoPath, + /// The id of the entry written there: both versions between markers, + /// or the side kept. `None` if the merge left nothing there. + pub written: Option, +} + +/// Conflicted paths, sorted, each at most once: those a merge left, or a +/// revision's unresolved ones. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Conflicts(Vec); + +impl Conflicts { + /// The line starting our side, then its label. + const OURS: &str = "<<<<<<< "; + /// The line between the sides. + const BETWEEN: &str = "======="; + /// The line ending their side, then its label. + const THEIRS: &str = ">>>>>>> "; + + /// Adds `conflicted`, which must come after every path listed. + pub(crate) fn push(&mut self, conflicted: Conflicted) { + debug_assert!(self.0.last().is_none_or(|last| last.path < conflicted.path)); + self.0.push(conflicted); + } + + /// Whether there are none. + #[must_use] + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The conflicted paths, sorted. + #[must_use] + pub fn paths(&self) -> Vec { + self.0 + .iter() + .map(|conflicted| conflicted.path.clone()) + .collect() + } + + /// The content of a file both sides changed: `ours`, then `theirs`, + /// between markers naming them with `labels`. A side that removed the + /// file is empty. `None` if either side is binary, holding a NUL byte: + /// markers would only corrupt it. + #[must_use] + pub fn mark(ours: &[u8], theirs: &[u8], labels: [&str; 2]) -> Option> { + if ours.contains(&0) || theirs.contains(&0) { + return None; + } + let mut marked = Vec::with_capacity(ours.len() + theirs.len() + 64); + let side = |marked: &mut Vec, content: &[u8]| { + marked.extend_from_slice(content); + if !content.is_empty() && !content.ends_with(b"\n") { + marked.push(b'\n'); + } + }; + marked.extend_from_slice(format!("{}{}\n", Self::OURS, labels[0]).as_bytes()); + side(&mut marked, ours); + marked.extend_from_slice(format!("{}\n", Self::BETWEEN).as_bytes()); + side(&mut marked, theirs); + marked.extend_from_slice(format!("{}{}\n", Self::THEIRS, labels[1]).as_bytes()); + Some(marked) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn marks_both_sides() { + let marked = Conflicts::mark(b"ours\n", b"theirs", ["a", "b"]).unwrap(); + assert_eq!( + String::from_utf8(marked).unwrap(), + "<<<<<<< a\nours\n=======\ntheirs\n>>>>>>> b\n" + ); + assert_eq!( + Conflicts::mark(b"", b"kept\n", ["a", "b"]).unwrap(), + b"<<<<<<< a\n=======\nkept\n>>>>>>> b\n", + "a removed side is empty" + ); + assert_eq!(Conflicts::mark(b"\0binary", b"text", ["a", "b"]), None); + } +} diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index f207edb9..e0c5c022 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -4,6 +4,7 @@ pub mod annotations; pub mod cli; pub mod config; +pub mod conflict; #[cfg(feature = "fixture")] pub mod fixture; pub mod index; diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 1e37cf63..16d5a6f3 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -1,11 +1,14 @@ -//! Comparing trees, and looking up what they hold. +//! Comparing trees, merging them, and looking up what they hold. use std::collections::HashMap; use std::collections::hash_map::Entry; use origin_platform::Platform; -use origin_shared::{Digest, EntryKind, EntryName, Inputs, RepoPath, Tree, TreeEntry, TreeId}; +use origin_shared::{ + Digest, EncodedObject, EntryKind, EntryName, Inputs, Record, RepoPath, Tree, TreeEntry, TreeId, +}; +use crate::conflict::{Conflicted, Conflicts}; use crate::store::{Store, StoreError}; /// A file that differs between two trees. @@ -82,6 +85,223 @@ impl Store

{ } } +/// Two trees merged with the changes each made to a common one. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Merge { + /// The merged tree: both sides' changes, and `ours` where they conflict. + pub tree: TreeId, + /// The trees the merge made, which the store may not have yet. + pub trees: Vec, + /// The files with conflict markers a [marked](Store::merge_marked) + /// merge made, which the store may not have yet either. + pub files: Vec, + /// The paths both sides changed, each its own way, with what the merge + /// left there. + pub conflicts: Conflicts, +} + +/// What a merge leaves where both sides changed a path, each its own way. +#[derive(Clone, Copy, Debug)] +enum OnConflict<'l> { + /// `ours`. + KeepOurs, + /// Both versions between conflict markers naming the sides with these + /// labels, see [`Conflicts::mark`]. + Mark([&'l str; 2]), +} + +impl Store

{ + /// Merges `ours` and `theirs`, two trees made from `base`, file by file: + /// a path one side changed takes that side's version, and a path both + /// changed, each its own way, is a conflict, where the merge keeps + /// `ours`. A path is a file, so two sides that changed different files + /// of a directory merge cleanly. Without a base, every path either side + /// has counts as changed. Subtrees with equal ids are never read, so the + /// cost follows the size of the changes. + /// + /// # Errors + /// + /// Fails if a tree that differs cannot be read. + pub fn merge( + &self, + base: Option, + ours: TreeId, + theirs: TreeId, + ) -> Result { + self.merge_with(base, ours, theirs, OnConflict::KeepOurs) + } + + /// Merges like [`Store::merge`], but where both sides changed a text + /// file, the merged one holds both versions between conflict markers + /// naming the sides with `labels`, see [`Conflicts::mark`]. Binary files, + /// and paths a directory is on either side of, keep `ours`. + /// + /// # Errors + /// + /// Fails if a tree that differs, or a file that conflicts, cannot be + /// read. + pub fn merge_marked( + &self, + base: Option, + ours: TreeId, + theirs: TreeId, + labels: [&str; 2], + ) -> Result { + self.merge_with(base, ours, theirs, OnConflict::Mark(labels)) + } + + fn merge_with( + &self, + base: Option, + ours: TreeId, + theirs: TreeId, + on_conflict: OnConflict<'_>, + ) -> Result { + let mut merge = Merge { + tree: ours, + trees: Vec::new(), + files: Vec::new(), + conflicts: Conflicts::default(), + }; + let merged = self.merge_dir( + &RepoPath::root(), + base, + Some(ours), + Some(theirs), + on_conflict, + &mut merge, + )?; + merge.tree = if let Some(tree) = merged { + tree + } else { + let empty = Tree::default().encode(); + let id = empty.id().into(); + merge.trees.push(empty); + id + }; + merge.trees.sort_unstable_by_key(EncodedObject::id); + merge.trees.dedup_by_key(|tree| tree.id()); + merge.files.sort_unstable_by_key(EncodedObject::id); + merge.files.dedup_by_key(|file| file.id()); + Ok(merge) + } + + /// Merges three versions of the directory `dir`, `None` standing for one + /// that doesn't exist, returning the merged one, or `None` if it's + /// empty. + fn merge_dir( + &self, + dir: &RepoPath, + base: Option, + ours: Option, + theirs: Option, + on_conflict: OnConflict<'_>, + merge: &mut Merge, + ) -> Result, StoreError> { + if ours == theirs || base == theirs { + return Ok(ours); + } + if base == ours { + return Ok(theirs); + } + let read = |id: Option| id.map(|id| self.get(id)).transpose(); + let (base, ours, theirs): (Tree, Tree, Tree) = ( + read(base)?.unwrap_or_default(), + read(ours)?.unwrap_or_default(), + read(theirs)?.unwrap_or_default(), + ); + let mut names: Vec<&EntryName> = [&base, &ours, &theirs] + .into_iter() + .flat_map(|tree| tree.iter().map(|(name, _)| name)) + .collect(); + names.sort_unstable(); + names.dedup(); + let mut merged = Tree::default(); + for name in names { + let [base, ours, theirs] = + [&base, &ours, &theirs].map(|tree| tree.get(name.as_str()).copied()); + let entry = if ours == theirs || base == theirs { + ours + } else if base == ours { + theirs + } else if ours.is_none_or(|ours| ours.kind.is_tree()) + && theirs.is_none_or(|theirs| theirs.kind.is_tree()) + { + // Both sides changed a directory, or one changed it and the + // other removed it: merge it file by file. + let subtree = |entry: Option| entry.and_then(TreeEntry::subtree); + self.merge_dir( + &dir.join(name), + subtree(base), + subtree(ours), + subtree(theirs), + on_conflict, + merge, + )? + .map(|tree| TreeEntry { + kind: EntryKind::Tree, + id: tree.into(), + }) + } else { + let written = match on_conflict { + OnConflict::KeepOurs => ours, + OnConflict::Mark(labels) => self.mark(ours, theirs, labels, merge)?, + }; + // Paths come in order, each once. + merge.conflicts.push(Conflicted { + path: dir.join(name), + written: written.map(|entry| entry.id), + }); + written + }; + if let Some(entry) = entry { + merged.insert(name.clone(), entry); + } + } + if merged.is_empty() { + return Ok(None); + } + let encoded = merged.encode(); + let id = encoded.id().into(); + merge.trees.push(encoded); + Ok(Some(id)) + } + + /// The entry of a file both sides changed, `ours` and `theirs`, that + /// holds both versions between conflict markers: a file on the side + /// that removed it is empty. Keeps `ours` if either side isn't a + /// regular file, or is binary or missing from the store. + fn mark( + &self, + ours: Option, + theirs: Option, + labels: [&str; 2], + merge: &mut Merge, + ) -> Result, StoreError> { + let content = |entry: Option| match entry { + None => Ok(Some(Vec::new())), + Some(entry) if matches!(entry.kind, EntryKind::File | EntryKind::Executable) => { + self.try_blob(entry.id) + } + Some(_) => Ok(None), + }; + let (Some(our_content), Some(their_content)) = (content(ours)?, content(theirs)?) else { + return Ok(ours); + }; + let Some(marked) = Conflicts::mark(&our_content, &their_content, labels) else { + return Ok(ours); + }; + let file = EncodedObject::blob(&marked); + let kind = ours.or(theirs).map_or(EntryKind::File, |entry| entry.kind); + let entry = TreeEntry { + kind, + id: file.id(), + }; + merge.files.push(file); + Ok(Some(entry)) + } +} + /// Looks up the entries of snapshots by path, reading each tree once, /// however many snapshots share it. #[derive(Debug)] @@ -149,7 +369,7 @@ pub(crate) mod tests { use std::collections::BTreeMap; use origin_platform::Native; - use origin_shared::{EncodedObject, EntryKind, Record}; + use origin_shared::{EncodedObject, EntryKind, ObjectId, Record}; use super::*; @@ -271,6 +491,118 @@ pub(crate) mod tests { assert_eq!(store.diff(empty, old).unwrap().len(), 5); } + /// The files of `tree`, by path, with their contents' ids. + fn files(store: &Store, tree: TreeId) -> Vec<(String, ObjectId)> { + let empty = build(store, &[]); + store + .diff(empty, tree) + .unwrap() + .into_iter() + .map(|change| (change.path.as_str().to_owned(), change.new.unwrap().id)) + .collect() + } + + #[test] + fn merges_changes_to_different_files() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let base = build( + &store, + &[ + ("src/a", "a"), + ("src/b", "b"), + ("gone/x", "x"), + ("same", "s"), + ], + ); + // Ours edits a file and removes a directory; theirs edits another + // file of the same directory, adds one, and makes the same edit. + let ours = build(&store, &[("src/a", "a2"), ("src/b", "b"), ("same", "s2")]); + let theirs = build( + &store, + &[ + ("src/a", "a"), + ("src/b", "b2"), + ("gone/x", "x"), + ("new/deep", "n"), + ("same", "s2"), + ], + ); + let merge = store.merge(Some(base), ours, theirs).unwrap(); + assert_eq!(merge.conflicts, Conflicts::default()); + let expected = build( + &store, + &[ + ("src/a", "a2"), + ("src/b", "b2"), + ("new/deep", "n"), + ("same", "s2"), + ], + ); + assert_eq!(files(&store, merge.tree), files(&store, expected)); + assert_eq!(merge.tree, expected, "trees are canonical"); + assert!( + merge.trees.iter().any(|tree| tree.id() == expected.into()), + "the merged trees are returned to be written" + ); + + // Merging onto an unchanged base reads nothing and makes no tree. + let unchanged = store.merge(Some(base), ours, base).unwrap(); + assert_eq!((unchanged.tree, unchanged.trees), (ours, Vec::new())); + } + + #[test] + fn conflicts_keep_ours() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let base = build( + &store, + &[("edit", "1"), ("dir/removed", "r"), ("file", "f")], + ); + let ours = build( + &store, + &[("edit", "ours"), ("dir/removed", "r2"), ("file", "f")], + ); + let theirs = build( + &store, + &[("edit", "theirs"), ("file/now-dir", "d"), ("other", "o")], + ); + let merge = store.merge(Some(base), ours, theirs).unwrap(); + let paths: Vec<_> = merge + .conflicts + .paths() + .iter() + .map(ToString::to_string) + .collect(); + assert_eq!( + paths, + ["dir/removed", "edit"], + "both edited `edit`; ours edited what theirs removed" + ); + let expected = build( + &store, + &[ + ("edit", "ours"), + ("dir/removed", "r2"), + ("file/now-dir", "d"), + ("other", "o"), + ], + ); + assert_eq!(files(&store, merge.tree), files(&store, expected)); + + // Without a base, both sides added everything. + let unrelated = store.merge(None, ours, theirs).unwrap(); + let paths: Vec<_> = unrelated + .conflicts + .paths() + .iter() + .map(ToString::to_string) + .collect(); + assert_eq!(paths, ["edit", "file"]); + } + #[test] fn looks_entries_up_by_path() { let dir = tempfile::tempdir().unwrap();