diff --git a/README.md b/README.md index 3f2f3d9c..703924bc 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ origin land --status # the landings waiting for evidence or a con origin targets # every target, its tip, authority and requirements origin target new --from origin new [description] --on # start a change on a target's tip +origin pull # follow your change where it went, or onto its target's tip origin workspace new [--change ] [] # another working copy, sharing the repository origin workspace list | rm @@ -57,7 +58,14 @@ shares the repository's records, so agents can work side by side. A new workspace clones its files from the other working copies where the file system can (Btrfs, XFS, APFS), and copies them otherwise. Landing moves only the working copy of the workspace it runs in, and no other command -moves your files on its own. +moves your files on its own. When your change lands from another +workspace, or the landing queue rebases it, `origin status` says so, and +`origin pull` follows it: onto a new change on the target's tip once it +landed, or onto the queue's rebase, with your edits since. Until then those +edits aren't recorded, and the commands that build on the working copy +refuse. `pull` also rebases the working copy onto its target's tip once it +moved. Where your edits conflict, both versions are kept between conflict +markers (see `converge` below). Changes are named by a unique prefix of their id, or `@` for the working copy's. A revision is `@`, a change (for its head), or a unique prefix of diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 88090784..27106f3a 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -142,6 +142,9 @@ enum WorkspaceCommand { Target(TargetCommand), /// List the targets with their tips, authorities and requirements. Targets, + /// Move the working copy to where its change went from another workspace, + /// or onto its target's new tip, keeping the edits made since. + Pull, /// Manage workspaces: working copies that share this repository. #[command(subcommand)] Workspace(WorkspacesCommand), @@ -440,6 +443,7 @@ impl WorkspaceCommand { workspace.target_new(&name, &from)?; } Self::Targets => workspace.targets()?, + Self::Pull => workspace.pull()?, Self::Workspace(WorkspacesCommand::New { change, path }) => { workspace.add_workspace(change.as_deref(), path.as_deref())?; } diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 24f3b3c8..8e961884 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -82,7 +82,8 @@ impl Session<'_, '_, P> { } }; let revision: Revision = self.store().get(head)?; - if self.has_landed(head, &revision)? { + let landing = self.store().landing(head, &revision)?; + if landing.is_some_and(|landing| landing.body().target == self.onto.id()) { break; } let claims = self.annotations.claims(RecordId::Revision(head))?; @@ -108,30 +109,6 @@ impl Session<'_, '_, P> { Ok(stack) } - /// Whether the revision `id` landed on the target. A revision only lands on - /// the tip it is based on, so this checks the acceptance after that tip. - fn has_landed(&self, id: RevisionId, revision: &Revision) -> Result { - let Base::Acceptance(base) = revision.base else { - return Ok(false); - }; - let base = self.store().get(base)?; - if base.body().target != self.onto.id() { - return Ok(false); - } - let Some(next) = self - .store() - .acceptance_at(&self.onto, base.body().seq + 1)? - else { - return Ok(false); - }; - Ok(self - .store() - .get(next)? - .body() - .landed - .contains(&Source::Revision(id))) - } - /// Rebases the revision `id` onto the tip and lands it, as part of the /// landing of `stack`. If it has to wait, the queue keeps `stack` waiting. pub(super) fn land_revision( diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index 5a0147c3..d7820763 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -25,7 +25,9 @@ use std::path::{Path, PathBuf}; use std::slice; use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; -use origin_shared::{Acceptance, AcceptanceId, Record, TargetId, TargetName}; +use origin_shared::{ + Acceptance, AcceptanceId, Base, Record, Revision, RevisionId, Source, TargetId, TargetName, +}; use crate::store::{Store, StoreError}; @@ -186,10 +188,10 @@ impl Store

{ /// Fails if the target's files cannot be read or are malformed. pub fn acceptance_at( &self, - target: &TargetName, + target: TargetId, seq: u64, ) -> Result, StoreError> { - let files = self.target_files(target.id()); + let files = self.target_files(target); let Some(head) = files.read_head()? else { return Ok(None); }; @@ -204,6 +206,33 @@ impl Store

{ Ok(files.parse_log(&line)?.first().copied()) } + /// Returns the acceptance that landed `revision`, whose id is `id`, if one + /// did. A revision can only land right after the acceptance it is based + /// on, so only the next acceptance is checked. + /// + /// # Errors + /// + /// Fails if the acceptances or the target's files cannot be read. + pub fn landing( + &self, + id: RevisionId, + revision: &Revision, + ) -> Result, StoreError> { + let Base::Acceptance(base) = revision.base else { + return Ok(None); + }; + let base = self.get(base)?; + let Some(next) = self.acceptance_at(base.body().target, base.body().seq + 1)? else { + return Ok(None); + }; + let next = self.get(next)?; + Ok(next + .body() + .landed + .contains(&Source::Revision(id)) + .then_some(next)) + } + /// The names of every target, in no particular order. /// /// # Errors @@ -396,9 +425,9 @@ mod tests { ); assert_eq!(store.log(&main).unwrap(), ids); for (seq, &id) in (0..).zip(&ids) { - assert_eq!(store.acceptance_at(&main, seq).unwrap(), Some(id)); + assert_eq!(store.acceptance_at(main.id(), seq).unwrap(), Some(id)); } - assert_eq!(store.acceptance_at(&main, 3).unwrap(), None); + assert_eq!(store.acceptance_at(main.id(), 3).unwrap(), None); let last = store.get(ids[2]).unwrap(); assert_eq!(last.body().prev, Some(ids[1])); last.verify(&key().public()).unwrap(); diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index dc98257a..3004d106 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -2,20 +2,30 @@ //! change on a target with `new --on`. //! //! The landing queue runs in this process, as this node. After a landing, the -//! working copy follows its change. If the change landed, or the target already -//! had it, the working copy starts a new change on the target's tip, so later -//! edits build on what the target has. If the queue rebased the change, the -//! working copy moves to the rebased revision. If the working copy is on top of -//! a change that landed, it is rebased onto the tip, if that merges cleanly. +//! working copy of the workspace that ran it follows its change. If the change +//! landed, or the target already had it, the working copy starts a new change +//! on the target's tip, so later edits build on what the target has. If the +//! queue rebased the change, the working copy moves to the rebased revision. If +//! the working copy is on top of a change that landed, it is rebased onto the +//! tip. +//! +//! Other workspaces don't move: they are behind their change until `origin +//! pull` moves them the same way, merging the edits made since. Where those +//! edits conflict, the files hold both versions between conflict markers, and a +//! `core.conflict` statement lists them. The working copy can't land until +//! those files change or `origin resolve` accepts them (see +//! [`conflict`](crate::conflict)). use origin_shared::{ - Base, ChangeId, EncodedObject, Record, RecordId, Revision, RevisionId, Source, TargetName, - TreeId, + Base, ChangeId, EncodedObject, Record, Revision, RevisionId, Source, TargetName, TreeId, }; -use super::{WorkingCopy, Workspace, WorkspaceError}; +use super::{Behind, WorkingCopy, Workspace, WorkspaceError}; +use crate::conflict::Conflicts; +use crate::index::Index; use crate::policy::Policy; use crate::queue::{Blocked, Landing, Pending, Proposal, Queue}; +use crate::tree::Merge; impl Workspace { /// `origin land [] [--onto ]`: lands a change, by default the @@ -31,7 +41,7 @@ impl Workspace { change: Option<&str>, onto: Option, ) -> Result<(), WorkspaceError> { - let working_copy = self.refresh()?; + let mut working_copy = self.save_draft()?; let change = working_copy.find_change(change.unwrap_or("@"))?; let onto = match onto { Some(onto) => onto, @@ -43,7 +53,19 @@ impl Workspace { for landing in &landings { self.print_landing(landing, &onto)?; } - self.follow(&working_copy, &onto, &landings) + working_copy.index = Index::open(&self.store)?; + working_copy.behind = + self.behind(&working_copy.index, working_copy.id, &working_copy.revision)?; + // A change the target already had is as good as landed, though no + // acceptance says so. + let unchanged = Landing::Unchanged(Proposal::Change(working_copy.revision.change)); + if landings.contains(&unchanged) { + let base = working_copy.revision.snapshot; + self.start_on(&working_copy, &onto, "", base)?; + } else { + self.follow(&working_copy)?; + } + Ok(()) } /// `origin land --from --onto `: lands the tip of one target @@ -131,46 +153,122 @@ impl Workspace { /// /// # Errors /// - /// Fails if the target doesn't exist, the working copy cannot be snapshotted, - /// or the change cannot be written or checked out. + /// Fails if the target doesn't exist, the working copy cannot be snapshotted or + /// is behind its change, or the change cannot be written or checked out. pub fn new_on(&mut self, target: &TargetName, description: &str) -> Result<(), WorkspaceError> { let working_copy = self.refresh()?; - self.start_on(&working_copy, target, description) + self.start_on(&working_copy, target, description, working_copy.files) } - /// Starts a change with `description` on the tip of `target`, and checks it out - /// over the working copy's files. + /// `origin pull`: moves the working copy to where its change went without it, + /// merging the edits made since. If the change landed, the working copy becomes + /// a new change on the tip of that target. If the landing queue rebased the + /// change, the working copy moves onto the rebase. Otherwise, once the change + /// below it landed or its target moved, rebases the working copy onto the tip + /// of the target its stack is on. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted, a file was edited during + /// the move, or the records cannot be read or written. + pub fn pull(&mut self) -> Result<(), WorkspaceError> { + let working_copy = self.save_draft()?; + if self.follow(&working_copy)? { + return Ok(()); + } + let Base::Acceptance(base) = working_copy.revision.base else { + println!("The working copy is on a stack of changes, which stays where it is."); + return Ok(()); + }; + let target = self.target_name(self.store.get(base)?.body().target)?; + let tip = self + .store + .head(&target)? + .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; + if tip.acceptance == base { + println!("The working copy is on the tip of `{target}`."); + return Ok(()); + } + let files = self.base_tree(working_copy.revision.base)?; + self.rebase_onto_tip(&working_copy, files, &target) + } + + /// Starts a change with `description` on the tip of `target`, carrying over the + /// edits that turned `base` into the working copy's files, and checks it out + /// over them. fn start_on( &mut self, working_copy: &WorkingCopy, target: &TargetName, description: &str, + base: TreeId, ) -> Result<(), WorkspaceError> { let tip = self .store .head(target)? .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; + let state = self.store.get(tip.acceptance)?.body().state; + let tip_label = format!("{target} #{}", tip.seq); + let merge = self.store.merge_marked( + Some(base), + working_copy.files, + state, + [Self::OURS, &tip_label], + )?; let description = EncodedObject::blob(description.as_bytes()); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, predecessors: Vec::new(), base: Base::Acceptance(tip.acceptance), deps: Vec::new(), - snapshot: self.store.get(tip.acceptance)?.body().state, + snapshot: merge.tree, description: description.id().into(), author: self.config.user(), }; let encoded = revision.encode(); - let id = encoded.id().into(); - self.switch_to( + let (conflicts, layers) = + self.write_merge(working_copy, merge, vec![description], &encoded)?; + self.move_to( working_copy, - id, + encoded.id().into(), &revision, - &[vec![description], vec![encoded]], - )?; - println!("Working copy: {}", self.headline(&revision)?); - println!("On top of: {}", self.describe_base(revision.base)?); - Ok(()) + &layers, + &conflicts, + ) + } + + /// The name conflict markers give the working copy's side. + const OURS: &str = "working copy"; + + /// Moves the working copy to where its change went without it, merging the + /// edits made since, or rebases it onto the tip once the change below it + /// landed. Returns whether it moved. + fn follow(&mut self, working_copy: &WorkingCopy) -> Result { + match &working_copy.behind { + Some(Behind::Landed { target, .. }) => { + let base = working_copy.revision.snapshot; + self.start_on(working_copy, &target.clone(), "", base)?; + return Ok(true); + } + Some(Behind::Rebased(rebased)) => { + self.move_onto(working_copy, *rebased)?; + return Ok(true); + } + None => {} + } + let Base::Revision(below) = working_copy.revision.base else { + return Ok(false); + }; + let below: Revision = self.store.get(below)?; + let [head] = working_copy.index.heads(below.change)[..] else { + return Ok(false); + }; + let Some(landing) = self.store.landing(head, &self.store.get(head)?)? else { + return Ok(false); + }; + let target = self.target_name(landing.body().target)?; + self.rebase_onto_tip(working_copy, below.snapshot, &target)?; + Ok(true) } /// Returns the target a revision's stack is on: the target of the acceptance at @@ -187,57 +285,41 @@ impl Workspace { } } - /// Moves the working copy after `landings` on `onto`. Starts a new change on - /// the tip if the working copy's change landed, moves to the rebased revision - /// if the queue rebased it, or rebases it onto the tip if the change below it - /// landed. - fn follow( + /// Moves the working copy onto `rebased`, the landing queue's rebase of it, + /// with the edits made since in a new revision that evolves from it. + fn move_onto( &mut self, working_copy: &WorkingCopy, - onto: &TargetName, - landings: &[Landing], + rebased: RevisionId, ) -> Result<(), WorkspaceError> { - let revision = &working_copy.revision; - // A change the target already had is as good as landed. - let landed = |change: ChangeId| { - landings.iter().any(|landing| match landing { - Landing::Landed { proposal, .. } | Landing::Unchanged(proposal) => { - *proposal == Proposal::Change(change) - } - Landing::Pending(_) => false, - }) - }; - if landed(revision.change) { - return self.start_on(working_copy, onto, ""); + let theirs: Revision = self.store.get(rebased)?; + if working_copy.files == working_copy.revision.snapshot { + return self.move_to(working_copy, rebased, &theirs, &[], &Conflicts::default()); } - for landing in landings { - if let Landing::Pending(Pending { - proposal: Proposal::Change(change), - subject: RecordId::Revision(rebased), - .. - }) = landing - && *change == revision.change - && *rebased != working_copy.id - { - let rebased = *rebased; - let revision: Revision = self.store.get(rebased)?; - self.switch_to(working_copy, rebased, &revision, &[])?; - println!("Working copy: {}", self.headline(&revision)?); - return Ok(()); - } - } - let Base::Revision(below) = revision.base else { - return Ok(()); + let merge = self.store.merge_marked( + Some(working_copy.revision.snapshot), + working_copy.files, + theirs.snapshot, + [Self::OURS, &rebased.short()], + )?; + let revision = Revision { + predecessors: vec![rebased], + snapshot: merge.tree, + author: self.config.user(), + ..theirs }; - let below = self.store.get(below)?; - if !landed(below.change) { - return Ok(()); - } - self.rebase_onto_tip(working_copy, below.snapshot, onto) + let encoded = revision.encode(); + let (conflicts, layers) = self.write_merge(working_copy, merge, Vec::new(), &encoded)?; + self.move_to( + working_copy, + encoded.id().into(), + &revision, + &layers, + &conflicts, + ) } - /// Rebases the working copy, made on `base`, onto the tip of `onto`, if that - /// merges cleanly. + /// Rebases the working copy, made on `base`, onto the tip of `onto`. fn rebase_onto_tip( &mut self, working_copy: &WorkingCopy, @@ -250,14 +332,13 @@ impl Workspace { .ok_or_else(|| WorkspaceError::UnknownTarget(onto.clone()))?; let state = self.store.get(tip.acceptance)?.body().state; let current = &working_copy.revision; - let merge = self.store.merge(Some(base), current.snapshot, state)?; - if !merge.conflicts.is_empty() { - println!( - "The working copy stays where it is: it conflicts with `{onto}` in {}", - Self::list_paths(&merge.conflicts.paths()) - ); - return Ok(()); - } + let tip_label = format!("{onto} #{}", tip.seq); + let merge = self.store.merge_marked( + Some(base), + current.snapshot, + state, + [Self::OURS, &tip_label], + )?; let revision = Revision { predecessors: vec![working_copy.id], base: Base::Acceptance(tip.acceptance), @@ -266,12 +347,56 @@ impl Workspace { ..current.clone() }; let encoded = revision.encode(); - // Checking the revision out reads its trees. - self.write(&[merge.trees])?; - let id = encoded.id().into(); - self.switch_to(working_copy, id, &revision, &[vec![encoded]])?; - println!("Working copy: {}", self.headline(&revision)?); + let (conflicts, layers) = self.write_merge(working_copy, merge, Vec::new(), &encoded)?; + self.move_to( + working_copy, + encoded.id().into(), + &revision, + &layers, + &conflicts, + ) + } + + /// Writes the objects that `merge` of the working copy's files made, for + /// `revision`, the revision the merge made. Returns the revision's unresolved + /// conflicts, those the merge left and the working copy's that remain, and the + /// layers that write the revision: `with`, a `core.conflict` statement listing + /// the conflicts, and the revision. The caller writes the layers once the + /// revision is checked out. + fn write_merge( + &self, + working_copy: &WorkingCopy, + merge: Merge, + with: Vec, + revision: &EncodedObject, + ) -> Result<(Conflicts, Vec>), WorkspaceError> { + // Finding the working copy's conflicts that remain reads its trees. + self.write(&[merge.files.into_iter().chain(merge.trees).collect()])?; + let conflicts = working_copy.conflicts.clone(); + let conflicts = conflicts + .remaining(&self.store, merge.tree)? + .with(merge.conflicts); + let layers = self.revision_layers(with, revision, &conflicts); + Ok((conflicts, layers)) + } + + /// Checks out `revision`, whose ID is `id`, over the working copy, writes + /// `unwritten`, the layers that write it if it's new, and makes it the working + /// copy. Then prints it, with its unresolved `conflicts`. + fn move_to( + &mut self, + working_copy: &WorkingCopy, + id: RevisionId, + revision: &Revision, + unwritten: &[Vec], + conflicts: &Conflicts, + ) -> Result<(), WorkspaceError> { + self.switch_to(working_copy, id, revision, unwritten)?; + println!("Working copy: {}", self.headline(revision)?); println!("On top of: {}", self.describe_base(revision.base)?); + if !conflicts.is_empty() { + Self::print_conflicts(conflicts); + } Ok(()) } diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index cbd22b06..98fbd5ea 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -29,6 +29,13 @@ //! since the snapshot, the checkout fails and puts back the files it changed. //! The working copy and its change stay where they were, so the command can run //! again. +//! +//! Another workspace can move the change on without this working copy: the +//! change can land, or the landing queue can rebase it. The working copy is +//! then behind its change. Only `origin pull` moves it to where the change +//! went, merging the edits made since (see [`land`]). Until then, edits stay +//! unrecorded so the change doesn't fork, commands that only read the working +//! copy say where the change went, and commands that build on it fail. mod annotate; mod land; @@ -75,7 +82,8 @@ struct WorkingCopy { /// The revision's record, if recording the draft made a new revision, /// which is not written yet. unsaved: Option, - /// The revision's unresolved conflicts that the files still have. + /// The revision's unresolved conflicts. The files still have them, unless the + /// working copy is behind its change. conflicts: Conflicts, /// The record index as of the snapshot. Once the draft is saved, it has the new /// revision. @@ -85,11 +93,24 @@ struct WorkingCopy { files: TreeId, /// The stat cache of the snapshot, which tells whether files were edited since. cache: StatCache, + /// Where the change went, if it moved on without the working copy. + behind: Option, /// Keeps garbage collection from removing the objects the snapshot found, until /// the command that saves the snapshot is done. _held: LockedFile, } +/// Where the working copy's change went after it moved on without the working +/// copy, such as from another workspace. `origin pull` follows it there. +#[derive(Clone, Debug)] +enum Behind { + /// The change's only head landed, at this position of the target. + Landed { target: TargetName, seq: u64 }, + /// The landing queue rebased the working copy into this revision, which waits + /// to land. + Rebased(RevisionId), +} + impl WorkingCopy { /// The change `prefix` names: `@` for the working copy's, or a unique /// prefix of its id. @@ -274,9 +295,11 @@ impl Workspace { None => loaded, }; let index = Index::open(&self.store)?; - let conflicts = self - .conflicts(self.revision, &revision)? - .remaining(&self.store, files)?; + let behind = self.behind(&index, self.revision, &revision)?; + let mut conflicts = self.conflicts(self.revision, &revision)?; + if behind.is_none() { + conflicts = conflicts.remaining(&self.store, files)?; + } Ok(WorkingCopy { id: self.revision, revision, @@ -285,15 +308,17 @@ impl Workspace { index, files, cache, + behind, _held: held, }) } - /// Snapshots the working copy and records its draft: a new revision if - /// the files changed, which still has to be saved. + /// Snapshots the working copy and records its draft: a new revision if the + /// files changed, which the caller still has to save. If the working copy is + /// behind its change, the edits stay unrecorded. fn record(&mut self) -> Result { let working_copy = self.snapshot()?; - if working_copy.files == working_copy.revision.snapshot { + if working_copy.files == working_copy.revision.snapshot || working_copy.behind.is_some() { return Ok(working_copy); } let revision = Revision { @@ -315,6 +340,70 @@ impl Workspace { }) } + /// Returns where the working copy's change went without the working copy, whose + /// ID is `id`, if it did: either the change's only head landed, or the landing + /// queue made a rebase of the working copy. The queue's rebases are made by + /// nodes, and evolve from the working copy, each from the one before. + fn behind( + &self, + index: &Index, + id: RevisionId, + revision: &Revision, + ) -> Result, WorkspaceError> { + let [head] = index.heads(revision.change)[..] else { + return Ok(None); + }; + let mut newest: Revision = self.store.get(head)?; + if let Some(landing) = self.store.landing(head, &newest)? { + let body = landing.body(); + return Ok(Some(Behind::Landed { + target: self.target_name(body.target)?, + seq: body.seq, + })); + } + let mut at = head; + while at != id && matches!(newest.author, Principal::Node(_)) { + let [predecessor] = newest.predecessors[..] else { + break; + }; + at = predecessor; + newest = self.store.get(at)?; + } + Ok((at == id && head != id).then_some(Behind::Rebased(head))) + } + + /// Describes where the working copy's change went, in words. + fn describe_behind(&self, change: ChangeId, behind: &Behind) -> Result { + Ok(match behind { + Behind::Landed { target, seq } => { + format!("change {} landed on {target} #{seq}", change.short()) + } + Behind::Rebased(rebased) => format!( + "the landing queue rebased change {} onto {}, as revision {}", + change.short(), + self.describe_base(self.store.get(*rebased)?.base)?, + rebased.short() + ), + }) + } + + /// Prints where the change went, if the working copy is behind it, and how to + /// follow it. + fn print_behind(&self, working_copy: &WorkingCopy) -> Result<(), WorkspaceError> { + if let Some(behind) = &working_copy.behind { + let edits = if working_copy.files == working_copy.revision.snapshot { + "" + } else { + ", with the edits made since" + }; + println!( + "Behind: {}. Run `origin pull` to follow it{edits}.", + self.describe_behind(working_copy.revision.change, behind)? + ); + } + Ok(()) + } + /// Returns the unresolved conflicts of `revision`, whose ID is `id`. fn conflicts(&self, id: RevisionId, revision: &Revision) -> Result { let annotations = Annotations::open(&self.store)?; @@ -354,9 +443,11 @@ impl Workspace { 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 { + /// Snapshots the working copy and saves its draft as a new revision, if the + /// files changed and the working copy isn't behind its change. For the commands + /// that build on the working copy even when it's behind, such as those that + /// follow the change. + fn save_draft(&mut self) -> Result { let mut working_copy = self.record()?; if let Some(unsaved) = working_copy.unsaved.take() { self.save(&[vec![unsaved]], working_copy.id, &mut working_copy.index)?; @@ -364,6 +455,23 @@ impl Workspace { Ok(working_copy) } + /// Snapshots the working copy like [`Workspace::save_draft`], for the commands + /// that build on it. Fails if the working copy is behind its change. + fn refresh(&mut self) -> Result { + let working_copy = self.save_draft()?; + self.following(working_copy) + } + + /// Returns `working_copy`, or fails if it's behind its change. + fn following(&self, working_copy: WorkingCopy) -> Result { + match &working_copy.behind { + None => Ok(working_copy), + Some(behind) => Err(WorkspaceError::Behind( + self.describe_behind(working_copy.revision.change, behind)?, + )), + } + } + /// Writes `layers` of objects and adds them to `index`, then makes `revision` /// the working copy. Flags the change as divergent if that made it diverge. fn save( @@ -481,6 +589,7 @@ impl Workspace { self.flags(index, revision.change)? ); println!("On top of: {}", self.describe_base(revision.base)?); + self.print_behind(&working_copy)?; Self::print_divergence(index, revision.change); if !working_copy.conflicts.is_empty() { Self::print_conflicts(&working_copy.conflicts); @@ -583,7 +692,8 @@ impl Workspace { /// Fails if the working copy cannot be snapshotted or the new change /// cannot be written. pub fn new_change(&mut self, description: &str) -> Result<(), WorkspaceError> { - let mut working_copy = self.record()?; + let working_copy = self.record()?; + let mut working_copy = self.following(working_copy)?; let description = EncodedObject::blob(description.as_bytes()); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, @@ -619,7 +729,8 @@ impl Workspace { /// Fails if the working copy cannot be snapshotted or the revision /// cannot be written. pub fn describe(&mut self, description: &str) -> Result<(), WorkspaceError> { - let mut working_copy = self.record()?; + let working_copy = self.record()?; + let mut working_copy = self.following(working_copy)?; let description = EncodedObject::blob(description.as_bytes()); let revision = Revision { predecessors: vec![working_copy.id], @@ -760,7 +871,7 @@ impl Workspace { /// of the working copy if it is one of the heads, or else of the newest head. /// Where heads changed the same text file, the file holds each version between /// conflict markers, and a `core.conflict` statement lists those files, so the - /// revision can't land until a snapshot without the markers (see + /// revision can't land until a later revision changes those files (see /// [`conflict`](crate::conflict)). /// /// # Errors @@ -933,7 +1044,7 @@ impl Workspace { } } } - Ok(()) + self.print_behind(&working_copy) } /// `origin evolog `: prints every revision of a change, newest @@ -1124,6 +1235,9 @@ pub enum WorkspaceError { /// Its heads. heads: Vec, }, + /// The working copy is behind its change, and the command would build on it. + #[error("{0}: run `origin pull` to follow it first")] + Behind(String), /// `converge` was given a change with a single head. #[error("change {} is not divergent", .0.short())] NotDivergent(ChangeId), diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index 37b5e51d..ee40727f 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -112,8 +112,9 @@ impl Workspace { /// /// # Errors /// - /// Fails if `path` is the main working copy or isn't a workspace, or if the - /// workspace cannot be snapshotted or deleted. + /// Fails if `path` is the main working copy or isn't a workspace, if the + /// workspace is behind its change and has edits, which no revision would then + /// hold, or if it cannot be snapshotted or deleted. pub fn remove_workspace(&self, path: &Path) -> Result<(), WorkspaceError> { let root = Self::canonical(path)?; if root == self.main_root() { @@ -125,7 +126,13 @@ impl Workspace { } if Self::read_pointer(&root)?.is_some() { let mut workspace = Self::open(&root, self.config.clone())?; - let working_copy = workspace.refresh()?; + let working_copy = workspace.save_draft()?; + // Only behind its change are its edits left unsaved. + let working_copy = if working_copy.files == working_copy.revision.snapshot { + working_copy + } else { + workspace.following(working_copy)? + }; println!( "Kept its working copy: {}", workspace.headline(&working_copy.revision)? diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 3fa6b3a0..31aebe03 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -61,7 +61,12 @@ impl Repo { /// Runs a command that must fail, returning its error. fn fails(&self, args: &[&str]) -> String { - let output = self.run(self.dir.path(), args); + self.fails_in(self.dir.path(), args) + } + + /// Runs `origin` in `cwd`, which must fail, and returns its errors. + fn fails_in(&self, cwd: &Path, args: &[&str]) -> String { + let output = self.run(cwd, args); assert!( !output.status.success(), "`origin {}` succeeded", @@ -1056,6 +1061,27 @@ fn a_move_that_fails_takes_its_files_back() { assert!(status.ends_with("A extra\nD ro/new\n"), "{status}"); } +#[test] +fn a_clean_workspace_behind_its_change_is_removed() { + let repo = Repo::new(); + repo.write("shared", "base\n"); + repo.ok(&["describe", "Shared"]); + let change = repo.change(); + let others = tempfile::tempdir().unwrap(); + let (clean, edited) = (others.path().join("clean"), others.path().join("edited")); + repo.workspace(&clean, &["--change", &change]); + repo.workspace(&edited, &["--change", &change]); + assert!(repo.ok(&["land"]).contains(" on main #1\n")); + + repo.ok(&["workspace", "rm", clean.to_str().unwrap()]); + assert!(!clean.exists()); + // Edits made since would be lost: no revision holds them. + fs::write(edited.join("notes"), "mine\n").unwrap(); + let refused = repo.fails(&["workspace", "rm", edited.to_str().unwrap()]); + assert!(refused.contains("`origin pull`"), "{refused}"); + assert!(edited.join("notes").exists()); +} + #[test] fn removing_a_workspace_keeps_its_work() { let repo = Repo::new(); @@ -1444,3 +1470,168 @@ fn workspaces_land_their_own_changes() { ); assert!(!repo.path("a").exists()); } + +#[test] +fn pull_follows_a_rebase_waiting_to_land() { + let repo = Repo::new(); + repo.write("own", "own\n"); + repo.ok(&["describe", "Feature"]); + let change = repo.change(); + let others = tempfile::tempdir().unwrap(); + let other = others.path().join("other"); + repo.workspace(&other, &["--change", &change]); + repo.ok(&["new", "--on", "main"]); + repo.write("upstream", "upstream\n"); + repo.ok(&["land"]); + // Landing on main now needs a check nobody runs. + repo.ok(&["new", "--on", "policy"]); + let policy = repo + .read("policy.toml") + .replace("# [groups]", "[groups]") + .replace("# runners", "runners") + .replace("# require", "require"); + repo.write("policy.toml", &policy); + repo.ok(&["land"]); + repo.ok(&["edit", &change]); + assert!(repo.ok(&["land"]).contains("waits for ci.test")); + + // The other workspace's edits stay unrecorded, rather than fork the + // change from the queue's rebase, until `pull` merges them onto it. + fs::write(other.join("own"), "edited\n").unwrap(); + let status = repo.ok_in(&other, &["status"]); + assert!( + status.contains(&format!( + "Behind: the landing queue rebased change {change} onto main #1" + )), + "{status}" + ); + repo.ok_in(&other, &["pull"]); + assert_eq!( + fs::read_to_string(other.join("upstream")).unwrap(), + "upstream\n" + ); + assert_eq!(fs::read_to_string(other.join("own")).unwrap(), "edited\n"); + let status = repo.ok_in(&other, &["status"]); + assert!(status.contains("On top of: main #1\n"), "{status}"); + assert!( + !status.contains("divergent") && !status.contains("Behind"), + "{status}" + ); +} + +#[test] +fn a_workspace_follows_its_change_once_it_lands_elsewhere() { + let repo = Repo::new(); + repo.write("shared", "base\n"); + repo.ok(&["describe", "Shared"]); + let change = repo.change(); + let others = tempfile::tempdir().unwrap(); + let (clean, conflicting) = ( + others.path().join("clean"), + others.path().join("conflicting"), + ); + repo.workspace(&clean, &["--change", &change]); + repo.workspace(&conflicting, &["--change", &change]); + let pointer = clean.join(".origin/workspace"); + let before = fs::read_to_string(&pointer).unwrap(); + + // The change lands from the main working copy, then main moves on. + assert!(repo.ok(&["land"]).contains(" on main #1\n")); + repo.write("shared", "main\n"); + assert!(repo.ok(&["land"]).contains(" on main #2\n")); + + // Reading the working copy never moves it: it says where the change + // went, and the commands that build on it refuse. + fs::write(clean.join("notes"), "mine\n").unwrap(); + let status = repo.ok_in(&clean, &["status"]); + assert!( + status.contains(&format!( + "Behind: change {change} landed on main #1. Run `origin pull` to follow it, \ + with the edits made since.\n" + )), + "{status}" + ); + assert!(status.contains("A notes\n"), "{status}"); + assert_eq!(fs::read_to_string(&pointer).unwrap(), before, "left alone"); + assert_eq!(fs::read_to_string(clean.join("shared")).unwrap(), "base\n"); + let refused = repo.fails_in(&clean, &["describe", "More"]); + assert!( + refused.contains("run `origin pull` to follow it first"), + "{refused}" + ); + + // `pull` starts a new change on the tip, with the edits. + let pulled = repo.ok_in(&clean, &["pull"]); + assert!(pulled.contains("On top of: main #2\n"), "{pulled}"); + assert_eq!(fs::read_to_string(clean.join("shared")).unwrap(), "main\n"); + assert!( + repo.ok_in(&clean, &["status"]) + .ends_with("On top of: main #2\nA notes\n") + ); + + // Edits that conflict with the tip are both kept, between markers, and + // block the new change until they're resolved. + fs::write(conflicting.join("shared"), "mine\n").unwrap(); + let pulled = repo.ok_in(&conflicting, &["pull"]); + assert!( + pulled.contains("Conflicts: shared hold both versions"), + "{pulled}" + ); + let shared = fs::read_to_string(conflicting.join("shared")).unwrap(); + assert!( + shared.contains("mine\n") && shared.contains("main\n") && shared.contains("<<<<<<<"), + "{shared}" + ); + let refused = repo.fails_in(&conflicting, &["land"]); + assert!(refused.contains("shared"), "{refused}"); + // Pulling again, once main moves on, keeps them unresolved. + repo.write("other", "main\n"); + assert!(repo.ok(&["land"]).contains(" on main #3\n")); + let pulled = repo.ok_in(&conflicting, &["pull"]); + assert!(pulled.contains("On top of: main #3\n"), "{pulled}"); + assert!( + pulled.contains("Conflicts: shared hold both versions"), + "{pulled}" + ); + assert!(repo.fails_in(&conflicting, &["land"]).contains("shared")); + fs::write(conflicting.join("shared"), "resolved\n").unwrap(); + assert!( + repo.ok_in(&conflicting, &["land"]) + .contains(" on main #4\n") + ); +} + +#[test] +fn a_refused_pull_writes_nothing() { + let repo = Repo::new(); + repo.write("own", "own\n"); + repo.ok(&["describe", "Feature"]); + let change = repo.change(); + let others = tempfile::tempdir().unwrap(); + let other = others.path().join("other"); + repo.workspace(&other, &["--change", &change]); + repo.ok(&["new", "--on", "main"]); + repo.write("upstream", "upstream\n"); + assert!(repo.ok(&["land"]).contains(" on main #1\n")); + + // A socket, which snapshots skip, where the pull writes a file. + fs::write(other.join("own"), "edited\n").unwrap(); + let socket = std::os::unix::net::UnixListener::bind(other.join("upstream")).unwrap(); + // Recorded first, as the pull would. + repo.ok_in(&other, &["describe", "Feature"]); + let evolog = repo.ok_in(&other, &["evolog", &change]); + let refused = repo.fails_in(&other, &["pull"]); + assert!( + refused.contains("changed while origin was moving"), + "{refused}" + ); + assert_eq!(repo.ok_in(&other, &["evolog", &change]), evolog); + assert_eq!(fs::read_to_string(other.join("own")).unwrap(), "edited\n"); + + drop(socket); + fs::remove_file(other.join("upstream")).unwrap(); + let pulled = repo.ok_in(&other, &["pull"]); + assert!(pulled.contains("On top of: main #1\n"), "{pulled}"); + let status = repo.ok_in(&other, &["status"]); + assert!(!status.contains("divergent"), "{status}"); +}