diff --git a/README.md b/README.md index 703924bc..07f93de3 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,9 @@ origin pull # follow your change where it went, or onto origin workspace new [--change ] [] # another working copy, sharing the repository origin workspace list | rm + +origin op log [-n ] # what this node did, operation by operation, in every workspace +origin undo # move this workspace's working copy back one operation ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -67,6 +70,12 @@ 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). +Every node keeps an op log of what it did: records written, landings left +waiting and working copies moved, numbered in order. `origin undo` only +moves the working copy of the workspace it runs in back to where it was +before its latest operation; records and targets stay as they are, so an +undone landing still landed. + 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 the revision's id. Your name and node key live in `$ORIGIN_CONFIG_DIR`, or diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index babdb6ba..b6d1d6f0 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -148,6 +148,22 @@ enum WorkspaceCommand { /// Manage workspaces: working copies sharing this repository. #[command(subcommand)] Workspace(WorkspacesCommand), + /// Show the op log: what this node did, in every workspace. + #[command(subcommand)] + Op(OpCommand), + /// Move this workspace's working copy back to where it was before its + /// latest operation. Records and targets stay as they are. + Undo, +} + +#[derive(Debug, Subcommand)] +enum OpCommand { + /// List the latest operations, newest first. + Log { + /// Show at most this many operations. + #[arg(short = 'n', long)] + limit: Option, + }, } #[derive(Debug, Args)] @@ -456,6 +472,8 @@ impl WorkspaceCommand { } Self::Workspace(WorkspacesCommand::List) => workspace.list_workspaces()?, Self::Workspace(WorkspacesCommand::Rm { path }) => workspace.remove_workspace(&path)?, + Self::Op(OpCommand::Log { limit }) => workspace.op_log(limit)?, + Self::Undo => workspace.undo()?, } Ok(()) } diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index a6b5cd91..5f908607 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -11,7 +11,8 @@ //! //! Each entry has a sequence number, one more than the entry before it, //! which never changes. The entries one command run appends form an -//! operation, numbered by its first entry's sequence number. +//! operation, numbered by its first entry's sequence number, which `origin +//! op log` shows and `origin undo` takes back. //! //! ```text //! .origin/oplog/ diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index 70593ffc..aa16061c 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -234,6 +234,23 @@ impl Store

{ .then_some(next)) } + /// The name of the target `id`, or `None` if it doesn't exist. + /// + /// # Errors + /// + /// Fails if its name cannot be read or is malformed. + pub fn target_name(&self, id: TargetId) -> Result, StoreError> { + let path = self.target_files(id).name(); + TargetFiles::read(&path)? + .map(|bytes| { + String::from_utf8(bytes) + .ok() + .and_then(|name| TargetName::new(name).ok()) + .ok_or(StoreError::Malformed(path)) + }) + .transpose() + } + /// The names of every target, in no particular order. /// /// # Errors diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index ac3e8f1d..f6612cb4 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -65,6 +65,7 @@ mod annotate; mod land; +mod ops; mod registry; pub use annotate::{Annotated, Payload}; @@ -644,7 +645,8 @@ impl Workspace { } /// Logs the draft a command records with its own records as a move of - /// its own. It's logged with the command's move, which starts from it. + /// its own, so `undo` takes the command back to the edits it recorded. + /// It's logged with the command's move, which starts from it. fn log_draft(&mut self, working_copy: &WorkingCopy) { if working_copy.unsaved.is_some() { self.unlogged = Some(Move { @@ -1468,9 +1470,7 @@ impl Workspace { fn target_name(&self, id: TargetId) -> Result { self.store - .targets()? - .into_iter() - .find(|target| target.id() == id) + .target_name(id)? .ok_or(WorkspaceError::UnknownTargetId(id)) } } @@ -1618,6 +1618,15 @@ pub enum WorkspaceError { /// A landing failed. #[error(transparent)] Land(#[from] LandError), + /// `undo` found no operation of this workspace to take back. + #[error("nothing to undo: no operation moved this workspace's working copy")] + NothingToUndo, + /// `undo` reached the operation that created the workspace. + #[error( + "nothing to undo but the creation of {}: remove it with `origin workspace rm`", + .0.display() + )] + UndoCreation(PathBuf), } impl WorkspaceError { diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs new file mode 100644 index 00000000..4655e8f5 --- /dev/null +++ b/apps/origin-src/src/workspace/ops.rs @@ -0,0 +1,205 @@ +//! The op log commands: `op log` and `undo`. +//! +//! `undo` takes back the latest operation of the workspace it runs in that +//! moved its working copy, other than recording its draft: it moves the +//! working copy back to the revision it was before, and checks it out. +//! That is all it does. Records stay, since others may have them already: +//! an undone `abandon` still abandoned the change, and an undone `land` +//! still landed. Operations from other workspaces are never undone, and the +//! other workspaces' working copies never move: each undoes its own. +//! Undoing again takes back the operation before, and so on; undos +//! themselves are never undone. +//! +//! Recording a draft isn't undone on its own: the edits it recorded stay +//! revisions of their change. If the revision moved back to is no longer a +//! head of its change, because the operation made a newer revision of it, +//! as `describe` does, the working copy becomes a new revision with its +//! contents, evolving from the change's heads, so the change doesn't +//! diverge. + +use std::collections::{BTreeMap, HashSet}; + +use origin_shared::{Record, RecordId, Revision, RevisionId}; + +use super::{Workspace, WorkspaceError}; +use crate::index; +use crate::oplog::{Effect, Entry, Move, Why}; +use crate::queue::Proposal; + +impl Workspace { + /// `origin op log [-n ]`: prints the latest operations of every + /// workspace, newest first, each with what its entries record, marking + /// this workspace's. + /// + /// # Errors + /// + /// Fails if the op log or a record cannot be read. + pub fn op_log(&self, limit: Option) -> Result<(), WorkspaceError> { + let limit = limit.unwrap_or(usize::MAX); + let mut ops: BTreeMap> = BTreeMap::new(); + for entry in self.store.oplog().newest_first()? { + let entry = entry?; + let full = ops.len() >= limit; + // An operation's entries all come after its first. + if full && ops.keys().next().is_some_and(|&oldest| entry.seq < oldest) { + break; + } + if full && !ops.contains_key(&entry.op) { + continue; + } + ops.entry(entry.op).or_default().push(entry); + } + if ops.is_empty() { + println!("The op log is empty."); + } + for (op, entries) in ops.iter().rev() { + let first = &entries[entries.len() - 1]; + let (marker, workspace) = match &first.workspace { + Some(root) if *root == self.root => ('@', root.display().to_string()), + Some(root) => ('○', root.display().to_string()), + None => ('○', "(no workspace)".to_owned()), + }; + println!("{marker} #{op} {workspace}: origin {}", first.command); + for entry in entries.iter().rev() { + println!(" {}", self.describe_entry(entry)?); + } + } + Ok(()) + } + + /// What an entry records, in a line. + fn describe_entry(&self, entry: &Entry) -> Result { + Ok(match &entry.effect { + Effect::Wrote(records) => { + let mut described = Vec::new(); + for record in records.iter().map(index::Entry::record) { + let mut description = record.describe(); + if let RecordId::Acceptance(id) = record + && let Ok(landing) = self.describe_acceptance(id) + { + description = format!("{description}, {landing}"); + } + described.push(description); + } + format!("wrote {}", described.join(", ")) + } + Effect::Waiting { onto, proposal } => match proposal { + Proposal::Change(change) => { + format!("change {} waits to land on `{onto}`", change.short()) + } + Proposal::Target(target) => format!("`{target}` waits to land on `{onto}`"), + }, + Effect::Moved(Move { from, to, why }) => { + let to = self.describe_revision(*to)?; + let from = match from { + Some(from) => self.describe_revision(*from)?, + None => return Ok(format!("created the working copy at {to}")), + }; + match why { + Why::Draft => format!("recorded the working copy: {from} -> {to}"), + Why::Command => format!("moved the working copy: {from} -> {to}"), + Why::Undo(op) => format!("undid #{op}: {from} -> {to}"), + } + } + Effect::Advanced { + target, + seq, + acceptance, + } => format!( + "advanced `{target}` to #{seq}, acceptance {}", + acceptance.short() + ), + }) + } + + /// A revision and its change, such as `revision 1a2b of change 3c4d`. + fn describe_revision(&self, id: RevisionId) -> Result { + let revision = self.store.get(id)?; + Ok(format!( + "revision {} of change {}", + id.short(), + revision.change.short() + )) + } + + /// `origin undo`: moves the working copy back to where it was before + /// this workspace's latest operation, as the module explains. + /// + /// # Errors + /// + /// Fails if there is nothing to undo, the latest operation created the + /// workspace, or the working copy cannot be snapshotted or moved. + pub fn undo(&mut self) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let (op, command, from) = self.last_undoable(working_copy.id)?; + let revision: Revision = self.store.get(from)?; + let heads = working_copy.index.heads(revision.change); + let (to, restored, layers) = if heads.contains(&from) { + (from, revision, Vec::new()) + } else { + // A newer revision of the change exists: restore this one's + // contents, and its unresolved conflicts, in a revision after it. + let conflicts = self.conflicts(from, &revision)?; + let restored = Revision { + predecessors: heads, + author: self.config.user(), + ..revision + }; + let encoded = restored.encode(); + let layers = self.revision_layers(Vec::new(), &encoded, &conflicts); + (encoded.id().into(), restored, layers) + }; + self.switch_to(&working_copy, to, &restored, &layers, Why::Undo(op))?; + println!("Undid #{op}: origin {command}"); + println!("Working copy: {}", self.headline(&restored)?); + println!("On top of: {}", self.describe_base(restored.base)?); + Ok(()) + } + + /// The latest operation of this workspace to undo, its command, and the + /// revision the working copy was before it. An operation that left the + /// working copy where it was, `current`, moved nothing, so it's skipped. + fn last_undoable( + &self, + current: RevisionId, + ) -> Result<(u64, String, RevisionId), WorkspaceError> { + // This workspace's moves, newest first. + let mut moves = Vec::new(); + for entry in self.store.oplog().newest_first()? { + let entry = entry?; + if let Effect::Moved(moved) = entry.effect + && entry.workspace.as_ref() == Some(&self.root) + { + moves.push((entry.op, entry.command, moved)); + } + } + let mut skipped = HashSet::new(); + for (op, _, moved) in &moves { + if let Why::Undo(undone) = moved.why { + skipped.extend([*op, undone]); + } + } + let mut seen = HashSet::new(); + for (op, command, _) in &moves { + if skipped.contains(op) || !seen.insert(*op) { + continue; + } + // Where the operation's first move, other than a draft's, + // started. + let from = moves + .iter() + .rfind(|(other, _, moved)| other == op && moved.why == Why::Command) + .map(|(_, _, moved)| moved.from); + match from { + // Only snapshots, or it left the working copy where it is. + None => {} + Some(Some(from)) if from == current => {} + // Logged before a crash kept its revision from being written. + Some(Some(from)) if !self.store.contains(from.into())? => {} + Some(None) => return Err(WorkspaceError::UndoCreation(self.root.clone())), + Some(Some(from)) => return Ok((*op, command.clone(), from)), + } + } + Err(WorkspaceError::NothingToUndo) + } +} diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 5b0fa69f..b2f8885d 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -918,6 +918,29 @@ fn an_argument_that_is_not_utf8_is_no_panic() { assert!(stderr.starts_with("error: "), "{stderr}"); } +#[test] +fn a_repository_is_one_working_copy_however_init_spells_it() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("real")).unwrap(); + std::os::unix::fs::symlink("real", dir.path().join("link")).unwrap(); + // Into a directory that exists, or one whose parents don't yet. + for path in ["repo", "a/b/repo"] { + let init = repo + .command(dir.path(), &["init", &format!("link/{path}")]) + .output() + .unwrap(); + assert!(init.status.success(), "{init:?}"); + let real = fs::canonicalize(dir.path().join("real").join(path)).unwrap(); + let undo = repo.command(&real, &["undo"]).output().unwrap(); + let error = String::from_utf8_lossy(&undo.stderr); + assert!( + error.contains("nothing to undo but the creation of"), + "{error}" + ); + } +} + #[test] fn a_move_marker_that_cannot_be_read_is_kept_and_stops_moves() { let repo = Repo::new(); @@ -1708,6 +1731,98 @@ fn a_refused_pull_writes_nothing() { assert!(!status.contains("divergent"), "{status}"); } +#[test] +fn undo_moves_the_working_copy_back_one_operation_at_a_time() { + let repo = Repo::new(); + let first = repo.change(); + repo.write("a", "a\n"); + repo.ok(&["describe", "Add a"]); + repo.ok(&["new", "Second"]); + assert_ne!(repo.change(), first); + + let undone = repo.ok(&["undo"]); + assert!(undone.starts_with("Undid #"), "{undone}"); + assert!(undone.contains(": origin new Second\n"), "{undone}"); + assert_eq!(repo.change(), first); + + // Describing makes a newer revision of the change: undoing it restores + // the description in another one, so the change keeps a single head. + repo.ok(&["describe", "Renamed"]); + repo.ok(&["undo"]); + let status = repo.ok(&["status"]); + assert!( + status.starts_with(&format!("Working copy: {first} Add a\n")), + "{status}" + ); + assert!(!repo.ok(&["evolog", &first]).contains("divergent")); + + // Then the first description, back to the edits it was made on, and + // then nothing is left but creating the repository. + repo.ok(&["undo"]); + let status = repo.ok(&["status"]); + assert!(status.starts_with(&format!("Working copy: {first} (no description)\n"))); + assert!(status.ends_with("A a\n"), "the edits stay: {status}"); + assert!( + repo.fails(&["undo"]) + .contains("nothing to undo but the creation") + ); +} + +#[test] +fn undoing_a_resolution_restores_the_conflict() { + let repo = Repo::new(); + repo.write("image", "base\0"); + 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.ok(&["describe", "Shared work"]); + fs::write(&pointer, started).unwrap(); + repo.write("image", "right\0"); + repo.ok(&["converge", &change]); + repo.ok(&["resolve", "image"]); + assert!(!repo.ok(&["status"]).contains("Conflicts")); + + repo.ok(&["undo"]); + assert!(repo.ok(&["status"]).contains("Conflicts: image hold")); + assert!(repo.fails(&["land"]).contains("unresolved conflicts")); +} + +#[test] +fn undo_moves_only_its_own_workspace() { + let repo = Repo::new(); + let others = tempfile::tempdir().unwrap(); + let ws = others.path().join("ws"); + repo.workspace(&ws, &[]); + repo.ok_in(&ws, &["new", "Agent work"]); + repo.ok(&["new", "Main work"]); + let main = repo.change(); + + // The latest operation is main's, but the workspace undoes its own. + let agent = repo.ok_in(&ws, &["undo"]); + assert!(agent.contains(": origin new Agent work\n"), "{agent}"); + assert_eq!(repo.change(), main); + + let log = repo.ok(&["op", "log"]); + let headers: Vec<_> = log + .lines() + .filter(|line| !line.starts_with(" ")) + .collect(); + assert!( + headers[0].starts_with("○ #") && headers[0].ends_with(": origin undo"), + "{log}" + ); + assert!(headers[1].starts_with("@ #") && headers[1].ends_with(": origin new Main work")); + assert!(headers[1].contains(&repo.dir.path().display().to_string())); + assert!(log.contains(" undid #"), "{log}"); + assert_eq!( + repo.ok(&["op", "log", "-n", "1"]).lines().count(), + 2, + "the undo, and its move" + ); +} + impl Repo { /// The file the store keeps the object holding `content` in. fn stored_object(&self, content: &[u8]) -> PathBuf {