diff --git a/README.md b/README.md index 862136bb..b864045e 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ origin evolog # every revision of a change origin edit # switch the working copy to another change origin abandon --reason "Too slow" # give a change up, keeping it for others to see origin converge # end a change's divergence +origin resolve ... # accept conflicted files as they are origin index rebuild # rebuild the record index from the store origin annotate @ ci.test --pass --inputs src Cargo.toml # a statement about a revision @@ -40,6 +41,13 @@ else `origin` in `$XDG_CONFIG_HOME` or `~/.config`: set `user = ""` in its `config.toml` if `$USER` isn't the name you want. See [the design](docs/design.md) for the model. +`converge` merges the files of a change's heads. A text file two heads +changed holds both versions between conflict markers (`<<<<<<<`, `=======`, +`>>>>>>>`), and a binary one keeps one side. A `core.conflict` statement +records which files conflict and what the merge wrote there, until they +change: edit them, or accept a file as it is with `origin resolve `. `status` lists those left, and every new +revision, `describe` included, keeps them. + ## Development ```sh diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index d7cd1b76..0f26335f 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -78,6 +78,12 @@ enum WorkspaceCommand { /// The change. change: String, }, + /// Accept conflicted files as they are, resolving their conflicts. + Resolve { + /// The files, from the root of the repository. + #[arg(required = true)] + paths: Vec, + }, /// Show the working copy's changes and the target they're on. Log { /// Show this target's history instead. @@ -333,6 +339,7 @@ impl WorkspaceCommand { Self::Show { change } => workspace.show(change.as_deref())?, Self::New { description } => workspace.new_change(&description)?, Self::Describe { description } => workspace.describe(&description)?, + Self::Resolve { paths } => workspace.resolve(&paths)?, Self::Edit { change } => workspace.edit(&change)?, Self::Abandon { change, reason } => workspace.abandon(change.as_deref(), &reason)?, Self::Converge { change } => workspace.converge(&change)?, diff --git a/apps/origin-src/src/conflict.rs b/apps/origin-src/src/conflict.rs index e223541e..9a8e622c 100644 --- a/apps/origin-src/src/conflict.rs +++ b/apps/origin-src/src/conflict.rs @@ -1,6 +1,6 @@ //! Conflicts: what a merge leaves where both sides changed a file. //! -//! A [marked](crate::store::Store::merge_marked) merge writes both +//! A merge into a working copy, such as `origin converge`, writes both //! versions of each such text file, between markers naming the sides: //! //! ```text @@ -12,9 +12,28 @@ //! ``` //! //! A binary file, or a path a directory is on either side of, keeps one -//! side instead. +//! side instead. The merge then issues a `core.conflict` statement about +//! the new revision, as its author, a user, listing each conflicted path +//! and the entry it wrote there. That list is the conflict, not the +//! markers, which only help to edit the file: a path stays unresolved while +//! a revision has the entry written there. Changing the file resolves it, +//! and so does `origin resolve`, which accepts it as it is, such as the +//! side a binary file kept. +//! +//! Every revision made from one with unresolved paths, by a snapshot, +//! `describe`, a new change on top, or a merge, carries those it still has +//! the entries of over, in a `core.conflict` of its own, published before +//! the revision itself, so it's never found without it. + +use origin_platform::Platform; +use origin_shared::{ + EncodedObject, Kind, ObjectId, Principal, RecordId, RepoPath, Revision, Statement, StatementId, + TreeId, +}; -use origin_shared::{ObjectId, RepoPath}; +use crate::annotations::Claim; +use crate::store::{Store, StoreError}; +use crate::tree::Snapshots; /// A path a merge left conflicted, and the entry it wrote there. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -39,6 +58,17 @@ impl Conflicts { /// The line ending their side, then its label. const THEIRS: &str = ">>>>>>> "; + /// The conflicts of `conflicted`, the latest of each path counting. + #[must_use] + pub fn new(mut conflicted: Vec) -> Self { + // Stable, so the latest of each path comes last, and dedup keeps the + // first of equal ones: reverse around it. + conflicted.reverse(); + conflicted.sort_by(|a, b| a.path.cmp(&b.path)); + conflicted.dedup_by(|a, b| a.path == b.path); + Self(conflicted) + } + /// 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)); @@ -60,6 +90,27 @@ impl Conflicts { .collect() } + /// These conflicts, then `newer` ones, which replace those of the same + /// paths: what a merge of a revision with these conflicts leaves. + #[must_use] + pub fn with(mut self, newer: Self) -> Self { + self.0.extend(newer.0); + Self::new(self.0) + } + + /// Resolves the conflicts of `paths`, returning those it had. + pub fn resolve(&mut self, paths: &[RepoPath]) -> Vec { + let mut resolved = Vec::new(); + self.0.retain(|conflicted| { + let listed = paths.contains(&conflicted.path); + if listed { + resolved.push(conflicted.path.clone()); + } + !listed + }); + resolved + } + /// 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: @@ -83,12 +134,264 @@ impl Conflicts { marked.extend_from_slice(format!("{}{}\n", Self::THEIRS, labels[1]).as_bytes()); Some(marked) } + + /// The `core.conflict` statement about `subject`, from `issuer`, + /// listing these conflicts in its payload, and the payload: each one + /// as the id written, or `-` for none, a space and the path, ended by a + /// NUL byte, which no path holds. + #[must_use] + pub fn statement( + &self, + subject: RecordId, + issuer: Principal, + supersedes: Option, + ) -> (EncodedObject, Statement) { + let mut list = String::new(); + for conflicted in &self.0 { + match conflicted.written { + Some(id) => list.push_str(&id.to_string()), + None => list.push('-'), + } + list.push(' '); + list.push_str(conflicted.path.as_str()); + list.push('\0'); + } + let payload = EncodedObject::blob(list.as_bytes()); + let statement = Statement { + subject, + kind: Kind::CONFLICT, + verdict: None, + issuer, + inputs: None, + payload: Some(payload.id().into()), + supersedes, + promoted_from: None, + }; + (payload, statement) + } + + /// The conflicts a `core.conflict` statement lists. Its payload is the + /// list, which a repository always keeps, so one it lacks fails rather + /// than reading as no conflicts. + /// + /// # Errors + /// + /// Fails if the payload is missing or cannot be read. + pub fn listed( + store: &Store

, + statement: &Statement, + ) -> Result { + let Some(payload) = statement.payload else { + return Ok(Self::default()); + }; + let content = store + .try_blob(payload.into())? + .ok_or(StoreError::NotFound(payload.into()))?; + let conflicted = String::from_utf8_lossy(&content) + .split_terminator('\0') + .filter_map(|line| { + let (written, path) = line.split_once(' ')?; + let written = match written { + "-" => None, + id => Some(id.parse().ok()?), + }; + let path = RepoPath::new(path).ok()?; + Some(Conflicted { path, written }) + }) + .collect(); + Ok(Self::new(conflicted)) + } + + /// The unresolved conflicts of `revision`, from `claims`, those about it + /// that hold: of the latest `core.conflict` from its author, if that's + /// a user, the paths where it still has the entry written. A node's + /// says only that a landing queue could not rebase it. + /// + /// # Errors + /// + /// Fails if the statement's payload is missing, or it or a tree on the + /// way to a path cannot be read. + pub fn of( + store: &Store

, + claims: &[Claim], + revision: &Revision, + ) -> Result { + if matches!(revision.author, Principal::Node(_)) { + return Ok(Self::default()); + } + let Some(claim) = claims.iter().rev().find(|claim| { + claim.statement().kind == Kind::CONFLICT && claim.statement().issuer == revision.author + }) else { + return Ok(Self::default()); + }; + Self::listed(store, claim.statement())?.remaining(store, revision.snapshot) + } + + /// Those of these conflicts `snapshot` still has: where it has the + /// entry written. + /// + /// # Errors + /// + /// Fails if a tree on the way to a path cannot be read. + pub fn remaining( + mut self, + store: &Store

, + snapshot: TreeId, + ) -> Result { + let mut snapshots = Snapshots::new(store); + let mut remaining = Vec::with_capacity(self.0.len()); + for conflicted in self.0.drain(..) { + let entry = snapshots.entry_at(snapshot, &conflicted.path)?; + if entry.map(|entry| entry.id) == conflicted.written { + remaining.push(conflicted); + } + } + Ok(Self(remaining)) + } } #[cfg(test)] mod tests { + use origin_platform::Native; + use origin_shared::{EntryKind, EntryName, Record, Tree, TreeEntry}; + use super::*; + fn path(path: &str) -> RepoPath { + RepoPath::new(path).unwrap() + } + + #[test] + fn a_path_resolves_once_its_entry_changes() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let marked = EncodedObject::blob(b"<<<<<<< a\nours\n=======\ntheirs\n>>>>>>> b\n"); + let resolved = EncodedObject::blob(b"Heading\n=======\nresolved\n"); + let snapshot = |file: &EncodedObject| { + let mut tree = Tree::default(); + tree.insert( + EntryName::new("file").unwrap(), + TreeEntry { + kind: EntryKind::File, + id: file.id(), + }, + ); + let tree = tree.encode(); + store.write_all(&[file.clone(), tree.clone()]).unwrap(); + TreeId::from(tree.id()) + }; + let conflicts = Conflicts::new(vec![ + Conflicted { + path: path("file"), + written: Some(marked.id()), + }, + Conflicted { + path: path("removed"), + written: None, + }, + ]); + let (payload, statement) = conflicts.statement( + RecordId::Snapshot(snapshot(&marked)), + "user:ada".parse().unwrap(), + None, + ); + // Without its payload, the statement lists nothing it can trust. + assert!(matches!( + Conflicts::listed(&store, &statement), + Err(StoreError::NotFound(id)) if id == payload.id() + )); + store.write_all(&[payload]).unwrap(); + assert_eq!(Conflicts::listed(&store, &statement).unwrap(), conflicts); + + let unchanged = conflicts.clone().remaining(&store, snapshot(&marked)); + assert_eq!(unchanged.unwrap(), conflicts); + // Even to content that looks like a marker. + let remaining = conflicts.remaining(&store, snapshot(&resolved)).unwrap(); + assert_eq!(remaining.paths(), [path("removed")]); + } + + #[test] + fn only_a_user_author_leaves_a_revision_unresolved() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let tree = Tree::default().encode(); + store.write_all(std::slice::from_ref(&tree)).unwrap(); + let revision = |author: &str| Revision { + change: origin_shared::ChangeId::from_bytes([1; 16]), + predecessors: Vec::new(), + base: origin_shared::Base::Acceptance(EncodedObject::blob(b"base").id().into()), + deps: Vec::new(), + snapshot: tree.id().into(), + description: EncodedObject::blob(b"").id().into(), + author: author.parse().unwrap(), + }; + let subject = RecordId::Revision(revision("user:ada").encode().id().into()); + let conflicts = Conflicts::new(vec![Conflicted { + path: path("file"), + written: None, + }]); + let claims = |issuer: &str| { + let (payload, statement) = conflicts.statement(subject, issuer.parse().unwrap(), None); + store.write_all(&[payload]).unwrap(); + let id = statement.encode().id().into(); + [store.claim(id, statement).unwrap().unwrap()] + }; + let ada = revision("user:ada"); + assert_eq!( + Conflicts::of(&store, &claims("user:ada"), &ada).unwrap(), + conflicts + ); + assert!( + Conflicts::of(&store, &claims("user:eve"), &ada) + .unwrap() + .is_empty() + ); + // A queue that rebased a revision, then could not rebase it elsewhere. + let queue = revision("node:queue"); + assert!( + Conflicts::of(&store, &claims("node:queue"), &queue) + .unwrap() + .is_empty() + ); + } + + #[test] + fn newer_conflicts_replace_older_ones() { + let older = Conflicts::new(vec![ + Conflicted { + path: path("a"), + written: None, + }, + Conflicted { + path: path("b"), + written: None, + }, + ]); + let id = EncodedObject::blob(b"newer").id(); + let newer = Conflicts::new(vec![Conflicted { + path: path("b"), + written: Some(id), + }]); + let mut both = older.with(newer); + assert_eq!( + both, + Conflicts::new(vec![ + Conflicted { + path: path("a"), + written: None, + }, + Conflicted { + path: path("b"), + written: Some(id), + }, + ]) + ); + assert_eq!(both.resolve(&[path("a"), path("c")]), [path("a")]); + assert_eq!(both.paths(), [path("b")]); + } + #[test] fn marks_both_sides() { let marked = Conflicts::mark(b"ours\n", b"theirs", ["a", "b"]).unwrap(); diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index cf08e897..7cee97d8 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -14,7 +14,9 @@ //! the files changed, they become a new revision of the change, which //! evolves from the previous one. Records are written before anything //! refers to them: the snapshot's objects, then the revision, then the -//! `workspace` file naming it. +//! `workspace` file naming it. Only the statements a new revision needs, +//! such as its unresolved conflicts, come before it, so it's never found +//! without them. mod annotate; @@ -27,12 +29,14 @@ use std::path::{self, Path, PathBuf}; use origin_platform::Native; use origin_shared::{ AcceptanceBody, AcceptanceId, Base, BlobId, ChangeId, EncodedObject, EntryKind, EntryName, - Kind, NodePublicKey, Principal, Record, RecordId, Revision, RevisionId, Source, Statement, - StatementId, TargetId, TargetName, Tree, TreeEntry, TreeId, + Kind, NodePublicKey, Principal, Record, RecordId, RepoPath, Revision, RevisionId, Source, + Statement, StatementId, TargetId, TargetName, Tree, TreeEntry, TreeId, }; -use crate::annotations::AnnotateError; +use crate::ancestry::Ancestry; +use crate::annotations::{AnnotateError, Annotations}; use crate::config::{ConfigError, UserConfig}; +use crate::conflict::Conflicts; use crate::index::{FindChangeError, FindError, Index}; use crate::output::FileDiff; use crate::store::{Store, StoreError}; @@ -58,6 +62,8 @@ struct WorkingCopy { /// The revision's record, if recording the draft made a new revision, /// which is not written yet. unsaved: Option, + /// The unresolved conflicts of the revision that the files still have. + conflicts: Conflicts, } impl WorkingCopy { @@ -232,11 +238,15 @@ impl Workspace { .save(&path) .map_err(|source| WorkspaceError::io(&path, source))?; } + let conflicts = self + .conflicts(self.revision, &revision)? + .remaining(&self.store, files)?; Ok(WorkingCopy { id: self.revision, revision, files, unsaved: None, + conflicts, }) } @@ -254,6 +264,10 @@ impl Workspace { ..working_copy.revision }; let encoded = revision.encode(); + if !working_copy.conflicts.is_empty() { + // Now, so the revision never exists without them. + self.write(&self.revision_layers(Vec::new(), &encoded, &working_copy.conflicts))?; + } Ok(WorkingCopy { id: encoded.id().into(), revision, @@ -262,6 +276,46 @@ impl Workspace { }) } + /// The unresolved conflicts of `revision`, `id`. + fn conflicts(&self, id: RevisionId, revision: &Revision) -> Result { + let annotations = Annotations::open(&self.store)?; + let claims = annotations.claims(RecordId::Revision(id))?; + Ok(Conflicts::of(&self.store, &claims, revision)?) + } + + /// The unresolved conflicts a new change on `base` starts with, from + /// the files of the revision it's on, if it's on one. + fn base_conflicts(&self, base: Base) -> Result { + match base { + Base::Revision(id) => self.conflicts(id, &self.store.get(id)?), + Base::Acceptance(_) => Ok(Conflicts::default()), + } + } + + /// The layers that write `revision`, a new one: `first`, objects it + /// refers to, then the statements published with it, then the revision + /// itself. The statements are a `core.conflict` about it listing + /// `conflicts`, its unresolved ones, if it has any (see + /// [`conflict`](crate::conflict)), and any a caller adds to the second + /// layer. Whoever finds the revision finds them: an error or a crash + /// never publishes it without them, as one batch could, publishing some + /// of its files. + fn revision_layers( + &self, + mut first: Vec, + revision: &EncodedObject, + conflicts: &Conflicts, + ) -> Vec> { + let mut statements = Vec::new(); + if !conflicts.is_empty() { + let subject = RecordId::Revision(revision.id().into()); + let (payload, statement) = conflicts.statement(subject, self.config.user(), None); + first.push(payload); + statements.push(statement.encode()); + } + vec![first, statements, vec![revision.clone()]] + } + /// Snapshots the working copy and saves its draft as a new revision if /// the files changed, for the commands that build on it. fn refresh(&mut self) -> Result { @@ -328,6 +382,9 @@ impl Workspace { ); println!("On top of: {}", self.describe_base(revision.base)?); Self::print_divergence(&index, revision.change); + if !working_copy.conflicts.is_empty() { + Self::print_conflicts(&working_copy.conflicts); + } let changes = self .store .diff(self.base_tree(revision.base)?, working_copy.files)?; @@ -441,7 +498,9 @@ impl Workspace { let id = encoded.id().into(); let recorded = working_copy.unsaved.is_some(); let first = working_copy.unsaved.into_iter().chain([description]); - self.save(&[first.collect(), vec![encoded]], id)?; + // It starts with the files of the one below, and their conflicts. + let layers = self.revision_layers(first.collect(), &encoded, &working_copy.conflicts); + self.save(&layers, id)?; // Edits recorded on a revision that is no longer its change's head // make that change diverge. if recorded { @@ -471,11 +530,43 @@ impl Workspace { let encoded = revision.encode(); let id = encoded.id().into(); let first = working_copy.unsaved.into_iter().chain([description]); - self.save(&[first.collect(), vec![encoded]], id)?; + let layers = self.revision_layers(first.collect(), &encoded, &working_copy.conflicts); + self.save(&layers, id)?; println!("Working copy: {}", self.headline(&revision)?); Ok(()) } + /// `origin resolve ...`: accepts the files at `paths` as they + /// are, resolving their conflicts, with a new revision of the change + /// that keeps the others. Paths without one are skipped. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted or the revision + /// cannot be written. + pub fn resolve(&mut self, paths: &[RepoPath]) -> Result<(), WorkspaceError> { + let mut working_copy = self.refresh()?; + let resolved = working_copy.conflicts.resolve(paths); + if resolved.is_empty() { + println!("No conflict to resolve there."); + return Ok(()); + } + let revision = Revision { + predecessors: vec![working_copy.id], + author: self.config.user(), + ..working_copy.revision + }; + let encoded = revision.encode(); + let id = encoded.id().into(); + let layers = self.revision_layers(Vec::new(), &encoded, &working_copy.conflicts); + self.save(&layers, id)?; + println!("Resolved {}", Self::list_paths(&resolved)); + if !working_copy.conflicts.is_empty() { + Self::print_conflicts(&working_copy.conflicts); + } + Ok(()) + } + /// `origin edit `: switches the working copy to the change's /// head. /// @@ -553,7 +644,11 @@ impl Workspace { author: self.config.user(), }; let encoded = revision.encode(); - self.write(&[vec![reason, empty], vec![statement, encoded.clone()]])?; + let conflicts = self.base_conflicts(revision.base)?; + let mut layers = self.revision_layers(vec![reason, empty], &encoded, &conflicts); + // Published before the revision that replaces the change. + layers[1].push(statement); + self.write(&layers)?; self.checkout(working_copy.revision.snapshot, revision.snapshot)?; self.point_at(encoded.id().into())?; println!("Abandoned change {}", change.short()); @@ -563,9 +658,14 @@ impl Workspace { } /// `origin converge `: ends a change's divergence with a - /// revision evolving from all its heads. It keeps the files and - /// description of the working copy, if it is one of the heads, or else - /// of the newest head. + /// revision evolving from all its heads. It merges their files, file by + /// file, with the changes each made since the latest revision they all + /// evolve from. It keeps the base and the description of the working + /// copy, if it is one of the heads, or else of the newest head. Where + /// heads changed the same text file, it holds each version between + /// conflict markers, and a `core.conflict` statement lists the files, + /// so the revision doesn't land until a snapshot without the markers: + /// see [`conflict`](crate::conflict). /// /// # Errors /// @@ -584,28 +684,87 @@ impl Workspace { } else { heads[heads.len() - 1] }; + let kept_revision: Revision = self.store.get(kept)?; + let base = self.merge_base(&heads)?; + let mut snapshot = kept_revision.snapshot; + let mut merged = Conflicts::default(); + for (merged_heads, &head) in heads.iter().filter(|&&head| head != kept).enumerate() { + // Past the first merge, our side holds every head merged so far. + let ours = if merged_heads == 0 { + kept.short() + } else { + "merged heads".to_owned() + }; + let merge = self.store.merge_marked( + base, + snapshot, + self.store.get(head)?.snapshot, + [&ours, &head.short()], + )?; + // The next merge reads this one's trees. + self.write(&[merge.files.into_iter().chain(merge.trees).collect()])?; + snapshot = merge.tree; + merged = merged.with(merge.conflicts); + } + // The heads' own, where the merge kept their side. + let mut conflicts = Conflicts::default(); + for &head in &heads { + let unresolved = self.conflicts(head, &self.store.get(head)?)?; + conflicts = conflicts.with(unresolved.remaining(&self.store, snapshot)?); + } + let conflicts = conflicts.with(merged); let revision = Revision { predecessors: heads.clone(), + snapshot, author: self.config.user(), - ..self.store.get(kept)? + ..kept_revision }; let encoded = revision.encode(); let id = encoded.id().into(); - self.write(&[vec![encoded]])?; + self.write(&self.revision_layers(Vec::new(), &encoded, &conflicts))?; if change == working_copy.revision.change { self.checkout(working_copy.revision.snapshot, revision.snapshot)?; self.point_at(id)?; } println!( - "Converged change {}: revision {} evolves from {}, with the files of {}", + "Converged change {}: revision {} evolves from {}, merging their files", change.short(), id.short(), Self::list(&heads), - kept.short() ); + if !conflicts.is_empty() { + Self::print_conflicts(&conflicts); + } Ok(()) } + /// Lists a revision's unresolved conflicts, and how to resolve them. + fn print_conflicts(conflicts: &Conflicts) { + println!( + "Conflicts: {} hold both versions between conflict markers, or one side for a \ + binary file. Edit them, or run `origin resolve ...` to accept them as they \ + are.", + Self::list_paths(&conflicts.paths()) + ); + } + + /// `paths`, separated by commas. + fn list_paths(paths: &[RepoPath]) -> String { + let paths: Vec<_> = paths.iter().map(ToString::to_string).collect(); + paths.join(", ") + } + + /// The snapshot to merge `heads`, revisions of one change, from: that of + /// the newest revision they all evolve from, or the + /// [merge](Ancestry::merge_base) of several, if each lacks another. + fn merge_base(&self, heads: &[RevisionId]) -> Result, WorkspaceError> { + let ancestry = Ancestry::walk(heads, |id| { + let revision: Revision = self.store.get(id)?; + Ok::<_, StoreError>((revision.predecessors, revision.snapshot)) + })?; + Ok(ancestry.merge_base(&self.store, heads)?) + } + /// `origin log []`: prints the working copy's stack of changes /// down to the target it's on, then the target's acceptances, newest /// first. With a target, prints that target's acceptances instead, diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 219b9b43..6c763244 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -260,19 +260,114 @@ fn divergence_shows_until_converged() { converged.starts_with(&format!("Converged change {change}")), "{converged}" ); - assert_eq!( - repo.read("file"), - "right\n", - "the working copy's files are kept" + assert!( + converged.contains("Conflicts: file hold both versions"), + "{converged}" ); - assert!(!repo.ok(&["status"]).contains("divergent")); + // Both versions, the working copy's first, between markers. + let file = repo.read("file"); + assert!(file.starts_with("<<<<<<< "), "{file}"); + assert!(file.contains("\nright\n=======\nleft\n>>>>>>> "), "{file}"); + let status = repo.ok(&["status"]); + assert!(!status.contains("divergent"), "{status}"); + assert!(status.contains("Conflicts: file hold"), "{status}"); assert!(repo.ok(&["evolog"]).contains(" converges ")); + + // Describing it keeps the conflict, an edit resolves it, whatever the + // file then holds. + repo.ok(&["describe", "Shared work, converged"]); + assert!(repo.ok(&["status"]).contains("Conflicts: file hold")); + repo.write("file", "Heading\n=======\nboth\n"); + assert!(!repo.ok(&["status"]).contains("Conflicts")); assert!( repo.fails(&["converge", &change]) .contains("is not divergent") ); } +#[test] +fn binary_conflicts_resolve_only_when_accepted() { + let repo = Repo::new(); + repo.write("image", "base\0"); + repo.write("text", "base\n"); + repo.ok(&["describe", "Shared work"]); + let change = repo.change(); + let pointer = repo.path(".origin/workspace"); + let started = fs::read_to_string(&pointer).unwrap(); + repo.write("image", "left\0"); + repo.write("text", "left\n"); + repo.ok(&["describe", "Shared work"]); + fs::write(&pointer, started).unwrap(); + repo.write("image", "right\0"); + repo.write("text", "right\n"); + repo.ok(&["converge", &change]); + assert_eq!(repo.read("image"), "right\0", "the working copy's side"); + + // An edit elsewhere leaves it unresolved, even without markers. + repo.write("unrelated", "docs\n"); + assert!(repo.ok(&["status"]).contains("Conflicts: image, text hold")); + let resolved = repo.ok(&["resolve", "image", "unrelated"]); + assert!(resolved.starts_with("Resolved image\n"), "{resolved}"); + assert!(resolved.contains("Conflicts: text hold"), "{resolved}"); + let status = repo.ok(&["status"]); + assert!(status.contains("\nConflicts: text hold"), "{status}"); + repo.ok(&["resolve", "text"]); + assert!(!repo.ok(&["status"]).contains("Conflicts")); +} + +#[test] +fn a_revision_is_published_only_after_its_conflicts() { + use origin_shared::{EncodedObject, Record, RecordId, Revision, RevisionId}; + use origin_src::{annotations::Annotations, conflict::Conflicts, store::Store}; + + let repo = Repo::new(); + repo.write("file", "base\n"); + repo.ok(&["describe", "Shared work"]); + let change = repo.change(); + let pointer = repo.path(".origin/workspace"); + let started = fs::read_to_string(&pointer).unwrap(); + repo.write("file", "left\n"); + repo.ok(&["describe", "Shared work"]); + fs::write(&pointer, started).unwrap(); + repo.write("file", "right\n"); + repo.ok(&["converge", &change]); + + // The `core.conflict` statement `describe` issues about its revision. + let store = Store::new(repo.path(".origin"), origin_platform::Native::default()); + let converged: RevisionId = fs::read_to_string(&pointer) + .unwrap() + .trim() + .parse() + .unwrap(); + let revision: Revision = store.get(converged).unwrap(); + let claims = Annotations::open(&store) + .unwrap() + .claims(RecordId::Revision(converged)) + .unwrap(); + let conflicts = Conflicts::of(&store, &claims, &revision).unwrap(); + let issuer = revision.author.clone(); + let described = Revision { + predecessors: vec![converged], + description: EncodedObject::blob(b"Described").id().into(), + ..revision + } + .encode(); + let subject = RecordId::Revision(described.id().into()); + let (_, statement) = conflicts.statement(subject, issuer, None); + let hex = statement.encode().id().to_hex(); + + // Writing it fails: its directory is read-only. + let dir = repo.path(&format!(".origin/objects/loose/{}", &hex[..2])); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o555)).unwrap(); + repo.fails(&["describe", "Described"]); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + + // So the revision, which would hide the conflict, wasn't written. + assert!(!store.contains(described.id()).unwrap()); + assert!(repo.ok(&["status"]).contains("Conflicts: file hold")); +} + #[test] fn abandoning_the_current_change_restores_its_base() { let repo = Repo::new(); @@ -823,3 +918,58 @@ fn statements_are_promoted_where_their_inputs_are_unchanged() { ); assert!(repo.fails(&["annotate", "@", "ci.lint"]).contains("--pass")); } + +#[test] +fn converge_merges_the_files_of_every_head() { + let repo = Repo::new(); + for path in ["a", "b", "c"] { + repo.write(path, "base\n"); + } + repo.ok(&["describe", "Shared work"]); + let change = repo.change(); + // Three agents revise the same revision, each changing its own file. + let pointer = repo.path(".origin/workspace"); + let started = fs::read_to_string(&pointer).unwrap(); + for changed in ["a", "b", "c"] { + fs::write(&pointer, &started).unwrap(); + for path in ["a", "b", "c"] { + repo.write( + path, + if path == changed { + "changed\n" + } else { + "base\n" + }, + ); + } + repo.ok(&["describe", "Shared work"]); + } + // Merging a third head reads the tree merging the first two. + let converged = repo.ok(&["converge", &change]); + assert!( + converged.ends_with(", merging their files\n"), + "{converged}" + ); + for path in ["a", "b", "c"] { + assert_eq!(repo.read(path), "changed\n", "{path}"); + } +} + +#[test] +fn converge_labels_the_side_holding_merged_heads() { + let repo = Repo::new(); + repo.write("file", "base\n"); + repo.ok(&["describe", "Shared work"]); + let change = repo.change(); + let pointer = repo.path(".origin/workspace"); + let started = fs::read_to_string(&pointer).unwrap(); + for side in ["one", "two", "three"] { + fs::write(&pointer, &started).unwrap(); + repo.write("file", &format!("{side}\n")); + repo.ok(&["describe", "Shared work"]); + } + repo.ok(&["converge", &change]); + // The third head merges into both versions of the first two. + let file = repo.read("file"); + assert!(file.starts_with("<<<<<<< merged heads\n<<<<<<< "), "{file}"); +}