diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 17175734..babdb6ba 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -12,6 +12,7 @@ use clap::{Args, CommandFactory, Parser, Subcommand}; use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; use crate::config::UserConfig; +use crate::oplog::Actor; use crate::workspace::{Annotated, Payload, Workspace}; /// A modern, git-compatible source control system. @@ -389,20 +390,28 @@ impl Cli { /// Fails if the command fails; the error is meant for the user. pub fn run(self) -> Result<()> { let config = UserConfig::load()?; + // The op log records the command line, without the program's name, + // as text: an argument that isn't UTF-8, such as a path, is never + // an error here. + let args: Vec<_> = env::args_os() + .skip(1) + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + let actor = Actor::new(args.join(" ")); match self.command { Command::Init { path } => { - Workspace::init(&path, config)?; + Workspace::init(&path, config, &actor)?; } - Command::Workspace(command) => command.run(config)?, + Command::Workspace(command) => command.run(config, &actor)?, } Ok(()) } } impl WorkspaceCommand { - fn run(self, config: UserConfig) -> Result<()> { + fn run(self, config: UserConfig, actor: &Actor) -> Result<()> { let cwd = env::current_dir().context("cannot read the current directory")?; - let mut workspace = Workspace::discover(&cwd, config)?; + let mut workspace = Workspace::discover(&cwd, config, actor)?; match self { Self::Status => workspace.status()?, Self::Diff => workspace.diff()?, diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index fc2002a2..d2ea1ca2 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -6,7 +6,8 @@ //! - records written: revisions, statements and acceptances, with what the //! [index](crate::index) keeps of them, so also every landing on a target; //! - targets advanced: a head naming a new acceptance; -//! - landings left waiting in a queue. +//! - landings left waiting in a queue; +//! - working copies moved, by recording a draft or by a command. //! //! Each entry has a sequence number, one more than the entry before it, //! which never changes. The entries one command run appends form an @@ -25,20 +26,21 @@ //! of entries, and a cursor older than that has expired. //! //! **Writing.** The index comes from the entries, so every entry must be -//! durable before a reader moves past it: a power loss could drop it otherwise, -//! and the next entry would take its sequence number, behind a cursor already -//! handed out. Each write appends its entries as a writer +//! durable before a reader moves past it: a power loss could drop it +//! otherwise, and the next entry would take its sequence number, behind +//! a cursor already handed out. Each write appends its entries as a writer //! ([`Store::commit_logged`]): a lock file, `writers/`, `n` being the -//! sequence number of its first entry, which every entry names, and which is -//! created and locked before that entry is appended. The entries are appended -//! just before the write is committed, and synced with it +//! sequence number of its first entry, which every entry names, and which +//! is created and locked before that entry is appended. The entries are +//! appended just before the write is committed, and synced with it //! ([`DurableWrite::sync_with`]): records and waiting landings with their -//! files, and a target's head with its new acceptance. Once the write is -//! published, the writer removes its lock file. +//! files, and moves of a working copy with the `workspace` file naming the +//! new revision. Once the write is published, the writer removes its lock +//! file. //! //! A batch of records syncs the op log in place of the index, which catches -//! up from it, so logging costs little: on Linux, a batch of up to two -//! files syncs them at once. +//! up from it, and a move syncs it beside the `workspace` file, so logging +//! costs little: on Linux, a batch of up to two files syncs them at once. //! //! **Reading.** Readers read up to the entry before the first one whose //! writer still holds its lock ([`OpLog::settled`]): every entry up to there @@ -47,10 +49,10 @@ //! some of a batch's records were published, or none; an acceptance was //! written but the target's head didn't move to it (the next landing on the //! target publishes it, and logs the acceptance again); a waiting landing -//! wasn't kept. Its writer's lock file is then left behind, unlocked: -//! readers sync the segments holding its entries, which may not be durable, -//! remove the file, and take the entries' effects as what they find -//! published. So a crashed writer holds nothing back. +//! wasn't kept; a working copy didn't move. Its writer's lock file is then +//! left behind, unlocked: readers sync the segments holding its entries, +//! which may not be durable, remove the file, and take the entries' effects +//! as what they find published. So a crashed writer holds nothing back. //! //! **Damage.** A crash in the middle of an append leaves part of a frame at //! the end of the last segment. It never was an entry: readers skip it, and @@ -65,14 +67,14 @@ use std::ffi::OsStr; use std::fs::{self, File, OpenOptions}; use std::io; -use std::iter; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock}; +use std::{fmt, iter}; use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; use origin_shared::object::{DecodeError, Reader}; -use origin_shared::{AcceptanceId, ChangeId, ObjectId, TargetName}; +use origin_shared::{AcceptanceId, ChangeId, ObjectId, RevisionId, TargetName}; use crate::frames::{Frames, Tail, Writer}; use crate::index; @@ -208,6 +210,8 @@ pub enum Effect { /// What lands. proposal: Proposal, }, + /// The entry's workspace's working copy moved. + Moved(Move), /// A target's head named a new acceptance. Advanced { /// The target. @@ -219,9 +223,42 @@ pub enum Effect { }, } +/// A working copy moving. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Move { + /// The revision it was, or `None` for a new workspace. + pub from: Option, + /// The revision it became. + pub to: RevisionId, + /// What moved it. + pub why: Why, +} + +/// What moved a working copy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Why { + /// A command recorded the working copy's draft as a new revision. + Draft, + /// A command, such as `new` or `edit`. + Command, + /// `origin undo`, taking back this operation. + Undo(u64), +} + +impl fmt::Display for Why { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Draft => f.write_str("draft"), + Self::Command => f.write_str("command"), + Self::Undo(op) => write!(f, "undo {op}"), + } + } +} + impl Entry { const WROTE: u8 = 1; const WAITING: u8 = 2; + const MOVED: u8 = 3; const ADVANCED: u8 = 4; /// Encodes the entry's frame: its sequence number, operation, writer, @@ -288,6 +325,19 @@ impl Effect { } } } + Self::Moved(moved) => { + out.u8(Entry::MOVED); + out.option(moved.from.as_ref().map(RevisionId::as_bytes)); + out.bytes(moved.to.as_bytes()); + match moved.why { + Why::Draft => out.u8(0), + Why::Command => out.u8(1), + Why::Undo(op) => { + out.u8(2); + out.u64(op); + } + } + } Self::Advanced { target, seq, @@ -305,6 +355,7 @@ impl Effect { let target = |reader: &mut Reader<'_>| -> Result { Ok(TargetName::new(reader.prefixed_str()?.to_owned())?) }; + let revision = |bytes| RevisionId::from(ObjectId::from_bytes(bytes)); let unknown = |field, tag| Err(DecodeError::UnknownTag { field, tag }); Ok(match reader.u8()? { Entry::WROTE => { @@ -322,6 +373,16 @@ impl Effect { tag => return unknown("proposal", tag), }, }, + Entry::MOVED => Self::Moved(Move { + from: reader.option(Reader::array)?.map(revision), + to: revision(reader.array()?), + why: match reader.u8()? { + 0 => Why::Draft, + 1 => Why::Command, + 2 => Why::Undo(reader.u64()?), + tag => return unknown("move reason", tag), + }, + }), Entry::ADVANCED => Self::Advanced { target: target(reader)?, seq: reader.u64()?, @@ -925,6 +986,7 @@ mod tests { #[test] fn entries_round_trip() { + let revision = |seed| RevisionId::from(ObjectId::from_bytes([seed; 32])); let effects = [ wrote(1), Effect::Waiting { @@ -935,6 +997,16 @@ mod tests { onto: TargetName::new("release/v3").unwrap(), proposal: Proposal::Target(TargetName::MAIN), }, + Effect::Moved(Move { + from: None, + to: revision(4), + why: Why::Command, + }), + Effect::Moved(Move { + from: Some(revision(4)), + to: revision(5), + why: Why::Undo(7), + }), Effect::Advanced { target: TargetName::MAIN, seq: 3, diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 990f9334..d39a1adc 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -23,6 +23,7 @@ use origin_shared::{ use super::{Behind, WorkingCopy, Workspace, WorkspaceError}; use crate::conflict::Conflicts; use crate::index::Index; +use crate::oplog::Why; use crate::policy::Policy; use crate::queue::{Blocked, Landing, Pending, Proposal, Queue}; use crate::tree::Merge; @@ -393,7 +394,7 @@ impl Workspace { unwritten: &[Vec], conflicts: &Conflicts, ) -> Result<(), WorkspaceError> { - self.switch_to(working_copy, id, revision, unwritten)?; + self.switch_to(working_copy, id, revision, unwritten, Why::Command)?; println!("Working copy: {}", self.headline(revision)?); println!("On top of: {}", self.describe_base(revision.base)?); if !conflicts.is_empty() { diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index a38dcfe6..f08427e0 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -3,14 +3,16 @@ //! ```text //! .origin/ //! objects/ targets/ index/ the store, see `store`, `targets` and `index` +//! oplog/ what this node applied, see `oplog` //! workspaces/ the other workspaces, see `registry` //! workspace the revision the working copy is //! state the stat cache of the last snapshot //! ``` //! //! A repository can have several working copies, its workspaces, which -//! share its store. The others have only `workspace` and `state` in their -//! `.origin`, and a `repository` file naming the main one's. +//! share its store and op log. The others have only `workspace` and +//! `state` in their `.origin`, and a `repository` file naming the main +//! one's. //! //! The working copy is always on a revision of the current change. Every //! command that reads it snapshots it first. The files the snapshot finds @@ -36,6 +38,9 @@ //! own. Until then, edits stay unrecorded rather than fork the change, the //! commands that only read the working copy say where the change went, and //! the others refuse to build on it. +//! +//! Every move of the working copy is logged in the op log, in an entry made +//! durable with the `workspace` file naming the new revision. mod annotate; mod land; @@ -45,7 +50,7 @@ pub use annotate::{Annotated, Payload}; use std::fs; use std::io; -use std::path::{self, Path, PathBuf}; +use std::path::{Path, PathBuf}; use origin_platform::{LockedFile, Native}; use origin_shared::{ @@ -59,6 +64,7 @@ use crate::annotations::{AnnotateError, Annotations}; use crate::config::{ConfigError, UserConfig}; use crate::conflict::Conflicts; use crate::index::{FindChangeError, FindError, Index}; +use crate::oplog::{Actor, Effect, Move, Why}; use crate::output::FileDiff; use crate::policy::PolicyError; use crate::queue::{LandError, Queue}; @@ -73,6 +79,9 @@ pub struct Workspace { config: UserConfig, /// The revision the working copy was last recorded as. revision: RevisionId, + /// The move recording the draft made, saved with the command's own + /// records, which is logged with the command's own move. + unlogged: Option, } /// The working copy as of a snapshot. @@ -145,15 +154,17 @@ impl Workspace { /// /// Fails if `root` already has a repository, the node key cannot be /// loaded, or the repository cannot be written. - pub fn init(root: &Path, config: UserConfig) -> Result { - let root = path::absolute(root).map_err(|source| WorkspaceError::io(root, source))?; + pub fn init(root: &Path, config: UserConfig, actor: &Actor) -> Result { + // Canonical, as every command opening it spells it, so the op log + // names this working copy one way. + let root = Self::canonical(root)?; let meta = root.join(Self::META_DIR); if meta.exists() { return Err(WorkspaceError::AlreadyInitialized(root)); } // First, so a key that cannot be loaded leaves no repository behind. let key = config.node_key()?; - let store = Store::new(meta, Native::default()); + let store = Store::new(meta, Native::default()).with_actor(actor.in_workspace(&root)); store.init()?; let policy = Self::policy(&config, &key.public()); @@ -176,13 +187,10 @@ impl Workspace { store, config, revision: encoded.id().into(), + unlogged: None, }; - // A first revision makes no divergence, which an index would tell. - workspace.save( - &[vec![empty_description], vec![encoded]], - workspace.revision, - &mut Index::default(), - )?; + workspace.write(&[vec![empty_description], vec![encoded]])?; + workspace.publish_pointer(None, workspace.revision, Why::Command)?; println!( "Initialized a repository in {}: node:{} is the authority of `policy` and `main`", workspace.root.display(), @@ -218,24 +226,29 @@ impl Workspace { ) } - /// Opens the working copy containing `start`. + /// Opens the working copy containing `start`, for `actor` to write in. /// /// # Errors /// /// Fails if neither `start` nor any parent has a repository, or like /// [`Workspace::open`]. - pub fn discover(start: &Path, config: UserConfig) -> Result { + pub fn discover( + start: &Path, + config: UserConfig, + actor: &Actor, + ) -> Result { let root = start .ancestors() .find(|dir| dir.join(Self::META_DIR).is_dir()) .ok_or_else(|| WorkspaceError::NotFound(start.to_owned()))?; - Self::open(root, config) + Self::open(root, config, actor) } /// Opens the working copy at `root`: the main one, whose `.origin` holds /// the store, or another workspace, whose `.origin/repository` names /// the main one's. - fn open(root: &Path, config: UserConfig) -> Result { + fn open(root: &Path, config: UserConfig, actor: &Actor) -> Result { + let root = &Self::canonical(root)?; let meta = root.join(Self::META_DIR); let repository = meta.join(Self::REPOSITORY); let store = match Self::read_path(&repository) { @@ -250,9 +263,11 @@ impl Workspace { Self::read_pointer(root)?.ok_or_else(|| WorkspaceError::Incomplete(root.to_owned()))?; Ok(Self { root: root.to_owned(), - store: Store::open_writable(store, Native::default())?, + store: Store::open_writable(store, Native::default())? + .with_actor(actor.in_workspace(root)), config, revision, + unlogged: None, }) } @@ -451,7 +466,12 @@ impl Workspace { 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)?; + self.save( + &[vec![unsaved]], + working_copy.id, + Why::Draft, + &mut working_copy.index, + )?; } Ok(working_copy) } @@ -474,18 +494,32 @@ 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. + fn log_draft(&mut self, working_copy: &WorkingCopy) { + if working_copy.unsaved.is_some() { + self.unlogged = Some(Move { + from: Some(self.revision), + to: working_copy.id, + why: Why::Draft, + }); + self.revision = working_copy.id; + } + } + /// Writes `layers` of objects, adding them to `index`, then makes - /// `revision` the working copy, flagging its change if that made it - /// diverge. + /// `revision`, which has the working copy's files, the working copy, + /// flagging its change if that made it diverge. fn save( &mut self, layers: &[Vec], revision: RevisionId, + why: Why, index: &mut Index, ) -> Result<(), WorkspaceError> { self.write(layers)?; index.add(layers.iter().flatten())?; - self.point_at(revision)?; + self.point_at(revision, why)?; self.flag_divergence(index, revision) } @@ -498,20 +532,33 @@ impl Workspace { Ok(()) } - /// Durably records that the working copy is `revision`. - fn point_at(&mut self, revision: RevisionId) -> Result<(), WorkspaceError> { - self.write_durably(self.meta(Self::POINTER), format!("{revision}\n").as_bytes())?; - self.revision = revision; - Ok(()) + /// Durably records that the working copy, which has the files of + /// `revision`, is `revision`, and logs the move. + fn point_at(&mut self, revision: RevisionId, why: Why) -> Result<(), WorkspaceError> { + self.publish_pointer(Some(self.revision), revision, why) } - /// Durably replaces a metadata file. - fn write_durably(&self, path: PathBuf, contents: &[u8]) -> Result<(), WorkspaceError> { + /// Durably records that the working copy moved from `from`, or was + /// created, to `to`, with the op log entry saying so, after the move of + /// a snapshot the command saved: the entries are durable with + /// `workspace`. + fn publish_pointer( + &mut self, + from: Option, + to: RevisionId, + why: Why, + ) -> Result<(), WorkspaceError> { + // The draft's move stays to log until this commit logs it. + let mut moves: Vec<_> = self.unlogged.into_iter().collect(); + moves.push(Move { from, to, why }); let write = self.store.durable_write(); write - .stage(path, contents) - .and_then(|()| write.commit()) + .stage(self.meta(Self::POINTER), format!("{to}\n").as_bytes()) .map_err(StoreError::from)?; + let moves: Vec<_> = moves.into_iter().map(Effect::Moved).collect(); + self.store.commit_logged(write, &moves)?; + self.unlogged = None; + self.revision = to; Ok(()) } @@ -528,6 +575,7 @@ impl Workspace { to: RevisionId, revision: &Revision, unwritten: &[Vec], + why: Why, ) -> Result<(), WorkspaceError> { let checkout = self.checkout( working_copy.files, @@ -540,7 +588,17 @@ impl Workspace { return Err(error); } self.write(unwritten)?; - self.point_at(to) + self.point_at(to, why) + } + + /// Durably replaces a metadata file. + fn write_durably(&self, path: PathBuf, contents: &[u8]) -> Result<(), WorkspaceError> { + let write = self.store.durable_write(); + write + .stage(path, contents) + .and_then(|()| write.commit()) + .map_err(StoreError::from)?; + Ok(()) } /// Makes the files still as `from` has them match `to`, durably, and @@ -698,6 +756,7 @@ impl Workspace { pub fn new_change(&mut self, description: &str) -> Result<(), WorkspaceError> { let working_copy = self.record()?; let mut working_copy = self.following(working_copy)?; + self.log_draft(&working_copy); let description = EncodedObject::blob(description.as_bytes()); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, @@ -714,7 +773,7 @@ impl Workspace { let first = working_copy.unsaved.take().into_iter().chain([description]); // 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, &mut working_copy.index)?; + self.save(&layers, id, Why::Command, &mut working_copy.index)?; // Edits recorded on a revision that is no longer its change's head // make that change diverge. if recorded { @@ -735,6 +794,7 @@ impl Workspace { pub fn describe(&mut self, description: &str) -> Result<(), WorkspaceError> { let working_copy = self.record()?; let mut working_copy = self.following(working_copy)?; + self.log_draft(&working_copy); let description = EncodedObject::blob(description.as_bytes()); let revision = Revision { predecessors: vec![working_copy.id], @@ -746,7 +806,7 @@ impl Workspace { let id = encoded.id().into(); let first = working_copy.unsaved.take().into_iter().chain([description]); let layers = self.revision_layers(first.collect(), &encoded, &working_copy.conflicts); - self.save(&layers, id, &mut working_copy.index)?; + self.save(&layers, id, Why::Command, &mut working_copy.index)?; println!("Working copy: {}", self.headline(&revision)?); Ok(()) } @@ -774,7 +834,7 @@ impl Workspace { let encoded = revision.encode(); let id = encoded.id().into(); let layers = self.revision_layers(Vec::new(), &encoded, &working_copy.conflicts); - self.save(&layers, id, &mut working_copy.index)?; + self.save(&layers, id, Why::Command, &mut working_copy.index)?; println!("Resolved {}", Self::list_paths(&resolved)); if !working_copy.conflicts.is_empty() { Self::print_conflicts(&working_copy.conflicts); @@ -796,7 +856,7 @@ impl Workspace { let head = Self::single_head(index, change)?; let revision: Revision = self.store.get(head)?; if head != working_copy.id { - self.switch_to(&working_copy, head, &revision, &[])?; + self.switch_to(&working_copy, head, &revision, &[], Why::Command)?; } println!("Working copy: {}", self.headline(&revision)?); Ok(()) @@ -862,7 +922,8 @@ impl Workspace { let mut layers = self.revision_layers(vec![reason, empty], &encoded, &conflicts); // Published before the revision that replaces the change. layers[1].push(statement); - self.switch_to(&working_copy, encoded.id().into(), &revision, &layers)?; + let id = encoded.id().into(); + self.switch_to(&working_copy, id, &revision, &layers, Why::Command)?; println!("Abandoned change {}", change.short()); println!("Working copy: {}", self.headline(&revision)?); println!("On top of: {}", self.describe_base(revision.base)?); @@ -935,7 +996,7 @@ impl Workspace { let id = encoded.id().into(); let layers = self.revision_layers(Vec::new(), &encoded, &conflicts); if change == working_copy.revision.change { - self.switch_to(&working_copy, id, &revision, &layers)?; + self.switch_to(&working_copy, id, &revision, &layers, Why::Command)?; } else { self.write(&layers)?; } diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index e691a3be..66c31980 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -22,6 +22,7 @@ use origin_platform::DurableWrite; use origin_shared::{ChangeId, Digest, EncodedObject, Record, Revision, Tree}; use super::{Workspace, WorkspaceError}; +use crate::oplog::Why; impl Workspace { /// The directory in the store's `.origin` with a file per workspace. @@ -69,16 +70,20 @@ impl Workspace { self.write(&records)?; self.write_durably(self.registered(&root), &Self::path_bytes(&root))?; let mut workspace = Self { + store: self + .store + .clone() + .with_actor(self.store.actor().in_workspace(&root)), root, - store: self.store.clone(), config: self.config.clone(), revision: id, + unlogged: None, }; let empty = Tree::default().encode().id().into(); workspace.checkout(empty, revision.snapshot, None)?; let repository = Self::path_bytes(self.store.root()); workspace.write_durably(workspace.meta(Self::REPOSITORY), &repository)?; - workspace.point_at(id)?; + workspace.publish_pointer(None, id, Why::Command)?; println!("Created workspace {}", workspace.root.display()); println!("Working copy: {}", workspace.headline(&revision)?); println!("On top of: {}", workspace.describe_base(revision.base)?); @@ -126,7 +131,7 @@ impl Workspace { return Err(WorkspaceError::UnknownWorkspace(root)); } if Self::read_pointer(&root)?.is_some() { - let mut workspace = Self::open(&root, self.config.clone())?; + let mut workspace = Self::open(&root, self.config.clone(), self.store.actor())?; 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 { @@ -228,18 +233,34 @@ impl Workspace { Ok(PathBuf::from(OsStr::from_bytes(path))) } - /// `path` made absolute, without symlinks or `..`. It may not exist, - /// but its parent must. - fn canonical(path: &Path) -> Result { + /// `path` made absolute: its nearest ancestor that exists, resolved, + /// without symlinks or `..`, then the components that don't exist yet, + /// as given. A dangling symlink is one that doesn't exist, so it stays + /// as given too: creating anything under it then fails. Nothing is + /// created. + pub(super) fn canonical(path: &Path) -> Result { let absolute = path::absolute(path).map_err(|source| WorkspaceError::io(path, source))?; - if let Ok(resolved) = fs::canonicalize(&absolute) { - return Ok(resolved); + let mut missing = Vec::new(); + let mut existing = absolute.as_path(); + loop { + match fs::canonicalize(existing) { + Ok(resolved) => { + return Ok(missing + .iter() + .rev() + .fold(resolved, |resolved, name| resolved.join(name))); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // A missing `..` can't be resolved without its parent. + let (Some(parent), Some(name)) = (existing.parent(), existing.file_name()) + else { + return Err(WorkspaceError::io(path, error)); + }; + missing.push(name); + existing = parent; + } + Err(source) => return Err(WorkspaceError::io(existing, source)), + } } - let (Some(parent), Some(name)) = (absolute.parent(), absolute.file_name()) else { - return Err(WorkspaceError::io(path, io::ErrorKind::NotFound.into())); - }; - let parent = - fs::canonicalize(parent).map_err(|source| WorkspaceError::io(parent, source))?; - Ok(parent.join(name)) } } diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index f45b8028..c8165059 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -32,14 +32,19 @@ impl Repo { repo } - /// Runs `origin` in `cwd` as the configured user. - fn run(&self, cwd: &Path, args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_origin")) + /// `origin` in `cwd` as the configured user. + fn command(&self, cwd: &Path, args: &[&str]) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + command .args(args) .current_dir(cwd) - .env("ORIGIN_CONFIG_DIR", self.config.path()) - .output() - .unwrap() + .env("ORIGIN_CONFIG_DIR", self.config.path()); + command + } + + /// Runs `origin` in `cwd` as the configured user. + fn run(&self, cwd: &Path, args: &[&str]) -> Output { + self.command(cwd, args).output().unwrap() } /// Runs a command that must succeed, returning its output. @@ -889,6 +894,21 @@ fn annotating_a_statement_needs_one_and_no_inputs() { assert!(error.contains("\nUsage: origin annotate "), "{error}"); } +#[test] +fn an_argument_that_is_not_utf8_is_no_panic() { + use std::os::unix::ffi::OsStrExt; + let repo = Repo::new(); + let path = std::ffi::OsStr::from_bytes(b"gone\xff"); + let output = repo + .command(repo.dir.path(), &["workspace", "rm"]) + .arg(path) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert!(stderr.starts_with("error: "), "{stderr}"); +} + #[test] fn statements_are_promoted_where_their_inputs_are_unchanged() { let repo = Repo::new();