Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ origin pull # follow your change where it went, or onto

origin workspace new [--change <change>] [<path>] # another working copy, sharing the repository
origin workspace list | rm <path>

origin op log [-n <count>] # 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
Expand All @@ -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
Expand Down
18 changes: 18 additions & 0 deletions apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
},
}

#[derive(Debug, Args)]
Expand Down Expand Up @@ -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(())
}
Expand Down
3 changes: 2 additions & 1 deletion apps/origin-src/src/oplog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down
17 changes: 17 additions & 0 deletions apps/origin-src/src/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,23 @@ impl<P: Platform> Store<P> {
.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<Option<TargetName>, 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
Expand Down
17 changes: 13 additions & 4 deletions apps/origin-src/src/workspace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@

mod annotate;
mod land;
mod ops;
mod registry;

pub use annotate::{Annotated, Payload};
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -1468,9 +1470,7 @@ impl Workspace {

fn target_name(&self, id: TargetId) -> Result<TargetName, WorkspaceError> {
self.store
.targets()?
.into_iter()
.find(|target| target.id() == id)
.target_name(id)?
.ok_or(WorkspaceError::UnknownTargetId(id))
}
}
Expand Down Expand Up @@ -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 {
Expand Down
205 changes: 205 additions & 0 deletions apps/origin-src/src/workspace/ops.rs
Original file line number Diff line number Diff line change
@@ -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 <limit>]`: 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<usize>) -> Result<(), WorkspaceError> {
let limit = limit.unwrap_or(usize::MAX);
let mut ops: BTreeMap<u64, Vec<Entry>> = 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<String, WorkspaceError> {
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<String, WorkspaceError> {
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)
}
}
Loading