From b9489034f4d2a7be10d9d016baf3bc1a562fb0bf Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 13:57:30 +0100 Subject: [PATCH] feat(workspaces): add copy-on-write workspaces `origin workspace new [--change X] [path]`, `list` and `rm` give a repository several working copies, like git worktrees, so agents can work side by side. Each workspace has its own current change, `.origin/workspace` pointer and stat cache, and shares the main working copy's store and index: its `.origin/repository` names the main `.origin`, which lists the other workspaces in `workspaces/`. Records are immutable and the index and target chains lock, so commands in different workspaces run concurrently. Every checkout clones files from the other working copies, copying where the file system cannot clone, when their stat caches prove the files unmodified. Landing moves only the working copy of the workspace it runs in. A new workspace's pointer is published last, so a crash never leaves partial files for a snapshot to record. Removing a workspace snapshots it first, so its work stays a revision of its change. --- README.md | 10 + apps/origin-src/src/cli.rs | 29 +++ apps/origin-src/src/config.rs | 2 +- apps/origin-src/src/store/mod.rs | 6 + apps/origin-src/src/workspace/mod.rs | 123 +++++++++-- apps/origin-src/src/workspace/registry.rs | 237 ++++++++++++++++++++++ apps/origin-src/tests/cli.rs | 182 ++++++++++++++++- 7 files changed, 565 insertions(+), 24 deletions(-) create mode 100644 apps/origin-src/src/workspace/registry.rs diff --git a/README.md b/README.md index 20ba3d05..3f2f3d9c 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,9 @@ 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 workspace new [--change ] [] # another working copy, sharing the repository +origin workspace list | rm ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -49,6 +52,13 @@ target's authority. A landing that conflicts or lacks evidence waits: issue the statements, or a new revision, and run `origin land` again. Policy is a target too: edit it with `origin new --on policy`, then `origin land`. +Workspaces work like git worktrees: each has its own current change and +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. + 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 ae4c9c80..88090784 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, + /// Manage workspaces: working copies that share this repository. + #[command(subcommand)] + Workspace(WorkspacesCommand), } #[derive(Debug, Args)] @@ -334,6 +337,27 @@ enum IndexCommand { Rebuild, } +#[derive(Debug, Subcommand)] +enum WorkspacesCommand { + /// Create a workspace, with a new change on the same base as the working + /// copy's change. + New { + /// Check out this change's head instead of starting a new change. + #[arg(long)] + change: Option, + /// Where to create the workspace: by default, beside the main working + /// copy, named after the change. + path: Option, + }, + /// List the workspaces and their changes. + List, + /// Remove a workspace, keeping its work as a revision of its change. + Rm { + /// The workspace's path. + path: PathBuf, + }, +} + impl Cli { /// Parses the command line, then checks what parsing can't: an /// `annotate`'s arguments, whose meaning depends on `--on`. Exits as a @@ -416,6 +440,11 @@ impl WorkspaceCommand { workspace.target_new(&name, &from)?; } Self::Targets => workspace.targets()?, + Self::Workspace(WorkspacesCommand::New { change, path }) => { + workspace.add_workspace(change.as_deref(), path.as_deref())?; + } + Self::Workspace(WorkspacesCommand::List) => workspace.list_workspaces()?, + Self::Workspace(WorkspacesCommand::Rm { path }) => workspace.remove_workspace(&path)?, } Ok(()) } diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs index b88ced74..c8e9cdf4 100644 --- a/apps/origin-src/src/config.rs +++ b/apps/origin-src/src/config.rs @@ -20,7 +20,7 @@ use origin_shared::{InvalidName, NodeKey, Principal, PrincipalName}; use serde::Deserialize; /// The user's configuration. -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct UserConfig { dir: PathBuf, user: PrincipalName, diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 2a0a56cf..7cc81191 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -164,6 +164,12 @@ impl Store

{ self.write_index(&[], &[]) } + /// The directory holding the store: a repository's `.origin`. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + pub(crate) fn sync_dir(&self, dir: &Path) -> Result<(), StoreError> { self.platform .sync_dir(dir) diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 49ab8b47..cbd22b06 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -3,10 +3,16 @@ //! ```text //! .origin/ //! objects/ targets/ index/ the store, see `store`, `targets` and `index` +//! 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, called workspaces, that share +//! its store. The main working copy's `.origin` holds the store. The others' +//! `.origin` holds only `workspace`, `state`, and a `repository` file that +//! names the main one's `.origin`. +//! //! The working copy is always on a revision of the current change. Every //! command that reads the working copy snapshots its files first. The files it //! finds are the draft. Commands that only read the working copy show the draft @@ -26,6 +32,7 @@ mod annotate; mod land; +mod registry; pub use annotate::{Annotated, Payload}; @@ -49,7 +56,7 @@ use crate::output::FileDiff; use crate::policy::PolicyError; use crate::queue::{LandError, Queue}; use crate::store::{Store, StoreError}; -use crate::worktree::{SnapshotError, StatCache, Worktree}; +use crate::worktree::{CloneSource, SnapshotError, StatCache, Worktree}; /// A working copy and its repository. #[derive(Debug)] @@ -98,6 +105,16 @@ impl Workspace { /// The metadata directory at the root of every working copy. pub const META_DIR: &str = ".origin"; + /// The file in [`Workspace::META_DIR`] that names the working copy's revision. + const POINTER: &str = "workspace"; + + /// The file in [`Workspace::META_DIR`] that holds the stat cache. + const STATE: &str = "state"; + + /// The file in a workspace's [`Workspace::META_DIR`] that names the main + /// working copy's, which holds the store. + const REPOSITORY: &str = "repository"; + /// `origin init`: creates a repository in `root`, with the `policy` /// target naming this node the authority of `policy` and `main`, an /// empty `main`, and a first change on top of it. @@ -179,32 +196,56 @@ impl Workspace { ) } - /// Opens the working copy containing `start`. + /// Opens the working copy that contains `start`. /// /// # Errors /// - /// Fails if neither `start` nor any parent has a repository, it is on a - /// network file system, or its working copy file is unreadable. + /// Fails if neither `start` nor any of its parents has a repository, or like + /// [`Workspace::open`]. pub fn discover(start: &Path, config: UserConfig) -> 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) + } + + /// Opens the working copy at `root`: either 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 { let meta = root.join(Self::META_DIR); - let path = meta.join("workspace"); - let revision = fs::read_to_string(&path) - .map_err(|source| WorkspaceError::io(&path, source))? - .trim_end() - .parse() - .map_err(|_| WorkspaceError::Malformed(path))?; + let repository = meta.join(Self::REPOSITORY); + let store = match Self::read_path(&repository) { + Ok(store) if store.is_dir() => store, + Ok(store) => return Err(WorkspaceError::MissingRepository(store)), + Err(WorkspaceError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => { + meta + } + Err(error) => return Err(error), + }; + let revision = + Self::read_pointer(root)?.ok_or_else(|| WorkspaceError::Incomplete(root.to_owned()))?; Ok(Self { root: root.to_owned(), - store: Store::open_writable(meta, Native::default())?, + store: Store::open_writable(store, Native::default())?, config, revision, }) } + /// Returns the revision of the working copy at `root`, if it has one. + fn read_pointer(root: &Path) -> Result, WorkspaceError> { + let path = root.join(Self::META_DIR).join(Self::POINTER); + let pointer = match fs::read_to_string(&path) { + Ok(pointer) => pointer, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(source) => return Err(WorkspaceError::io(&path, source)), + }; + let revision = pointer.trim_end().parse(); + Ok(Some(revision.map_err(|_| WorkspaceError::Malformed(path))?)) + } + fn meta(&self, name: &str) -> PathBuf { self.root.join(Self::META_DIR).join(name) } @@ -220,7 +261,7 @@ impl Workspace { fn snapshot(&mut self) -> Result { let held = self.store.hold_objects()?; let revision: Revision = self.store.get(self.revision)?; - let path = self.meta("state"); + let path = self.meta(Self::STATE); let loaded = StatCache::load(&path); let (files, cache) = Worktree::new(&self.root, &self.store).snapshot(&loaded)?; let cache = match cache { @@ -348,12 +389,18 @@ impl Workspace { /// 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 replaces a metadata file. + fn write_durably(&self, path: PathBuf, contents: &[u8]) -> Result<(), WorkspaceError> { let write = self.store.durable_write(); write - .stage(self.meta("workspace"), format!("{revision}\n").as_bytes()) + .stage(path, contents) .and_then(|()| write.commit()) .map_err(StoreError::from)?; - self.revision = revision; Ok(()) } @@ -391,9 +438,10 @@ impl Workspace { Ok(Worktree::new(&self.root, &self.store).restore(&changes)?) } - /// Makes the files match `to`, given that they match `from`, durably. With - /// `unchanged`, the stat cache of the snapshot that found `from`, it changes - /// nothing if a file it would change was edited since. + /// Makes the files match `to`, given that they match `from`, durably, cloning + /// the files other workspaces already have. With `unchanged`, the stat cache of + /// the snapshot that found `from`, it changes nothing if a file it would change + /// was edited since. fn checkout( &self, from: TreeId, @@ -401,7 +449,19 @@ impl Workspace { unchanged: Option<&StatCache>, ) -> Result<(), WorkspaceError> { let changes = self.store.diff(from, to)?; - Ok(Worktree::new(&self.root, &self.store).checkout(&changes, &[], unchanged)?) + if changes.is_empty() { + return Ok(()); + } + let sources: Vec<_> = self + .workspaces()? + .into_iter() + .filter(|root| *root != self.root) + .map(|root| { + let cache = root.join(Self::META_DIR).join(Self::STATE); + CloneSource::saved(root, cache) + }) + .collect(); + Ok(Worktree::new(&self.root, &self.store).checkout(&changes, &sources, unchanged)?) } /// `origin status`: prints the working copy's change, what it is on @@ -506,10 +566,10 @@ impl Workspace { Ok(()) } - /// Prints the changes `files` make to the snapshot of `base`. - fn print_diff(&self, base: Base, files: TreeId) -> Result<(), WorkspaceError> { + /// Prints the changes `snapshot` makes to `base`, line by line. + fn print_diff(&self, base: Base, snapshot: TreeId) -> Result<(), WorkspaceError> { let base = self.base_tree(base)?; - for change in self.store.diff(base, files)? { + for change in self.store.diff(base, snapshot)? { print!("{}", FileDiff::new(&self.store, &change)?); } Ok(()) @@ -1079,6 +1139,27 @@ pub enum WorkspaceError { /// The working copy file isn't a revision id. #[error("{} is not a revision id", .0.display())] Malformed(PathBuf), + /// A workspace's creation never finished. + #[error( + "the workspace at {} was never finished: remove it with `origin workspace rm`", + .0.display() + )] + Incomplete(PathBuf), + /// A workspace's repository is gone. + #[error("this workspace's repository, {}, is gone", .0.display())] + MissingRepository(PathBuf), + /// `workspace new` was given a path inside a working copy. + #[error("{} is inside a working copy", .0.display())] + Nested(PathBuf), + /// `workspace new` was given a directory with files in it. + #[error("{} is not empty", .0.display())] + NotEmpty(PathBuf), + /// `workspace rm` was given a path that isn't another workspace. + #[error("{} is not a workspace of this repository", .0.display())] + UnknownWorkspace(PathBuf), + /// `workspace rm` was given the main working copy, which holds the store. + #[error("{} is the main working copy, which holds the repository", .0.display())] + RemoveMain(PathBuf), /// A metadata file cannot be accessed. #[error("cannot access {}", path.display())] Io { diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs new file mode 100644 index 00000000..37b5e51d --- /dev/null +++ b/apps/origin-src/src/workspace/registry.rs @@ -0,0 +1,237 @@ +//! Workspaces: working copies that share a repository's store and index, like +//! git worktrees. Each has its own current change and stat cache. +//! +//! The main working copy's `.origin/workspaces/` holds a file for each other +//! workspace, named by the hash of its root and containing that root. Records +//! never change, and only target chains and the index are locked, so commands +//! run at the same time in different workspaces. +//! +//! Creating a workspace registers it and checks out its files, and only then +//! writes its `.origin/workspace`. So a crash never leaves partial files that a +//! command would record, only a workspace that `origin workspace rm` removes. +//! Removing a workspace records its draft first, so its work stays a revision +//! of its change. + +use std::ffi::OsStr; +use std::fs; +use std::io; +use std::os::unix::ffi::OsStrExt; +use std::path::{self, Path, PathBuf}; + +use origin_platform::DurableWrite; +use origin_shared::{ChangeId, Digest, EncodedObject, Record, Revision, Tree}; + +use super::{Workspace, WorkspaceError}; + +impl Workspace { + /// The directory in the store's `.origin` that holds a file for each workspace. + const REGISTRY: &str = "workspaces"; + + /// `origin workspace new [--change ] []`: creates a workspace at + /// `path`, by default next to the main working copy, and checks out the + /// change's head in it. Without a change, it starts a new change on the working + /// copy's base, next to the working copy's change. + /// + /// # Errors + /// + /// Fails if `path` is inside a working copy or has files, the change cannot be + /// found or has diverged, or the workspace cannot be written. + pub fn add_workspace( + &mut self, + change: Option<&str>, + path: Option<&Path>, + ) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let (id, revision, records) = if let Some(change) = change { + let change = working_copy.find_change(change)?; + let head = Self::single_head(&working_copy.index, change)?; + (head, self.store.get(head)?, Vec::new()) + } else { + let description = EncodedObject::blob(b""); + let base = working_copy.revision.base; + let revision = Revision { + change: ChangeId::random().map_err(WorkspaceError::Random)?, + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: self.base_tree(base)?, + description: description.id().into(), + author: self.config.user(), + }; + let encoded = revision.encode(); + let id = encoded.id().into(); + let conflicts = self.base_conflicts(base)?; + let layers = self.revision_layers(vec![description], &encoded, &conflicts); + (id, revision, layers) + }; + let root = self.new_root(path, revision.change)?; + self.write(&records)?; + self.write_durably(self.registered(&root), &Self::path_bytes(&root))?; + let mut workspace = Self { + root, + store: self.store.clone(), + config: self.config.clone(), + revision: id, + }; + 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)?; + println!("Created workspace {}", workspace.root.display()); + println!("Working copy: {}", workspace.headline(&revision)?); + println!("On top of: {}", workspace.describe_base(revision.base)?); + Ok(()) + } + + /// `origin workspace list`: prints each workspace's root and working copy as of + /// its last snapshot, marking this one. + /// + /// # Errors + /// + /// Fails if the workspaces cannot be listed, or the records they point at + /// cannot be read. + pub fn list_workspaces(&self) -> Result<(), WorkspaceError> { + for root in self.workspaces()? { + let marker = if root == self.root { '@' } else { ' ' }; + let state = if root.is_dir() { + match Self::read_pointer(&root)? { + Some(id) => self.headline(&self.store.get(id)?)?, + None => "(incomplete)".to_owned(), + } + } else { + "(missing)".to_owned() + }; + println!("{marker} {}: {state}", root.display()); + } + Ok(()) + } + + /// `origin workspace rm `: snapshots a workspace, so its work stays a + /// revision of its change, then deletes it. + /// + /// # Errors + /// + /// Fails if `path` is the main working copy or isn't a workspace, or if the + /// workspace cannot be snapshotted or deleted. + pub fn remove_workspace(&self, path: &Path) -> Result<(), WorkspaceError> { + let root = Self::canonical(path)?; + if root == self.main_root() { + return Err(WorkspaceError::RemoveMain(root)); + } + let registered = self.registered(&root); + if !registered.exists() { + return Err(WorkspaceError::UnknownWorkspace(root)); + } + if Self::read_pointer(&root)?.is_some() { + let mut workspace = Self::open(&root, self.config.clone())?; + let working_copy = workspace.refresh()?; + println!( + "Kept its working copy: {}", + workspace.headline(&working_copy.revision)? + ); + } + match fs::remove_dir_all(&root) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + return Err(WorkspaceError::io(&root, error)); + } + _ => {} + } + fs::remove_file(®istered).map_err(|source| WorkspaceError::io(®istered, source))?; + self.store + .sync_dir(&self.store.root().join(Self::REGISTRY))?; + println!("Removed workspace {}", root.display()); + Ok(()) + } + + /// Returns where to create a workspace for `change`: `path`, or by default a + /// directory next to the main working copy. It must be empty, and not inside a + /// working copy. + fn new_root(&self, path: Option<&Path>, change: ChangeId) -> Result { + let root = if let Some(path) = path { + Self::canonical(path)? + } else { + let main = self.main_root(); + let mut name = main.file_name().unwrap_or("workspace".as_ref()).to_owned(); + name.push(format!("-{}", change.short())); + main.with_file_name(name) + }; + if root + .ancestors() + .any(|dir| dir.join(Self::META_DIR).exists()) + { + return Err(WorkspaceError::Nested(root)); + } + match fs::read_dir(&root).map(|mut entries| entries.next().is_some()) { + Ok(true) => Err(WorkspaceError::NotEmpty(root)), + Err(error) if error.kind() != io::ErrorKind::NotFound => { + Err(WorkspaceError::io(&root, error)) + } + _ => Ok(root), + } + } + + /// Returns the roots of every workspace: the main working copy's first, then + /// the others' in order. + pub(super) fn workspaces(&self) -> Result, WorkspaceError> { + let dir = self.store.root().join(Self::REGISTRY); + let entries = match fs::read_dir(&dir) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return Ok(vec![self.main_root().to_owned()]); + } + Err(source) => return Err(WorkspaceError::io(&dir, source)), + }; + let mut roots = Vec::new(); + for entry in entries { + let entry = entry.map_err(|source| WorkspaceError::io(&dir, source))?; + if DurableWrite::<()>::is_temporary(&entry.file_name()) { + continue; + } + roots.push(Self::read_path(&entry.path())?); + } + roots.sort(); + roots.insert(0, self.main_root().to_owned()); + Ok(roots) + } + + /// Returns the root of the main working copy, whose `.origin` holds the store. + fn main_root(&self) -> &Path { + self.store.root().parent().unwrap_or(Path::new("/")) + } + + /// Returns the registry file of the workspace at `root`. + fn registered(&self, root: &Path) -> PathBuf { + let name = Digest::of(root.as_os_str().as_bytes()).to_hex(); + self.store.root().join(Self::REGISTRY).join(name) + } + + /// Encodes a path as a line of a file, which [`Workspace::read_path`] reads. + fn path_bytes(path: &Path) -> Vec { + let mut bytes = path.as_os_str().as_bytes().to_vec(); + bytes.push(b'\n'); + bytes + } + + /// Returns the path in a file written with [`Workspace::path_bytes`]. + pub(super) fn read_path(file: &Path) -> Result { + let bytes = fs::read(file).map_err(|source| WorkspaceError::io(file, source))?; + let path = bytes.strip_suffix(b"\n").unwrap_or(&bytes); + Ok(PathBuf::from(OsStr::from_bytes(path))) + } + + /// Returns `path` made absolute, without symlinks or `..`. The path may not + /// exist, but its parent must. + 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 (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 e53acb5f..3fa6b3a0 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -1,4 +1,5 @@ -//! End-to-end tests of the change workflow, driving the real `origin` binary. +//! End-to-end tests of the change workflow and workspaces, driving the real +//! `origin` binary. use std::fs; use std::io::Write; @@ -43,7 +44,12 @@ impl Repo { /// Runs a command that must succeed, returning its output. fn ok(&self, args: &[&str]) -> String { - let output = self.run(self.dir.path(), args); + self.ok_in(self.dir.path(), args) + } + + /// Runs a command in `cwd` that must succeed, returning its output. + fn ok_in(&self, cwd: &Path, args: &[&str]) -> String { + let output = self.run(cwd, args); assert!( output.status.success(), "`origin {}` failed: {}", @@ -85,6 +91,15 @@ impl Repo { let headline = line.strip_prefix("Working copy: ").unwrap(); headline.split(' ').next().unwrap().to_owned() } + + /// Creates a workspace at `path` and returns its change. + fn workspace(&self, path: &Path, args: &[&str]) -> String { + let path = path.to_str().unwrap(); + let output = self.ok(&[&["workspace", "new", path], args].concat()); + let line = output.lines().nth(1).unwrap(); + let headline = line.strip_prefix("Working copy: ").unwrap(); + headline.split(' ').next().unwrap().to_owned() + } } #[test] @@ -973,6 +988,49 @@ fn statements_are_promoted_where_their_inputs_are_unchanged() { ); } +#[test] +fn workspaces_share_the_repository_with_changes_of_their_own() { + let repo = Repo::new(); + repo.write("shared", "base\n"); + repo.write("dir/run.sh", "#!/bin/sh\n"); + fs::set_permissions(repo.path("dir/run.sh"), fs::Permissions::from_mode(0o755)).unwrap(); + repo.ok(&["describe", "Base"]); + repo.ok(&["new", "Main work"]); + let others = tempfile::tempdir().unwrap(); + let ws = others.path().join("ws"); + + // A new change beside the working copy's, on the same base. + let change = repo.workspace(&ws, &[]); + assert_eq!(fs::read_to_string(ws.join("shared")).unwrap(), "base\n"); + let mode = fs::metadata(ws.join("dir/run.sh")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o111, 0o111, "still executable"); + fs::write(ws.join("shared"), "agent\n").unwrap(); + repo.ok_in(&ws.join("dir"), &["describe", "Agent work"]); + let status = repo.ok_in(&ws, &["status"]); + assert!( + status.starts_with(&format!("Working copy: {change} Agent work\nOn top of: ")), + "{status}" + ); + assert!(status.ends_with("M shared\n"), "{status}"); + + // Main sees the workspace's records, and keeps its own files. + assert_eq!(repo.read("shared"), "base\n"); + assert!(repo.ok(&["show", &change]).contains("+agent\n")); + let list = repo.ok(&["workspace", "list"]); + let lines: Vec<_> = list.lines().collect(); + assert_eq!(lines.len(), 2, "{list}"); + assert!(lines[0].starts_with("@ ") && lines[0].ends_with(" Main work")); + assert!(lines[1].starts_with(" ") && lines[1].ends_with(" Agent work")); + + // Another workspace on the same change. + let same = others.path().join("same"); + assert_eq!(repo.workspace(&same, &["--change", &change]), change); + assert_eq!(fs::read_to_string(same.join("shared")).unwrap(), "agent\n"); +} + #[test] fn a_move_that_fails_takes_its_files_back() { let repo = Repo::new(); @@ -998,6 +1056,42 @@ fn a_move_that_fails_takes_its_files_back() { assert!(status.ends_with("A extra\nD ro/new\n"), "{status}"); } +#[test] +fn removing_a_workspace_keeps_its_work() { + let repo = Repo::new(); + let others = tempfile::tempdir().unwrap(); + let ws = others.path().join("ws"); + let change = repo.workspace(&ws, &[]); + fs::write(ws.join("unsaved"), "not snapshotted yet\n").unwrap(); + + let removed = repo.ok(&["workspace", "rm", ws.to_str().unwrap()]); + assert!(removed.starts_with(&format!("Kept its working copy: {change} "))); + assert!(!ws.exists()); + assert_eq!(repo.ok(&["workspace", "list"]).lines().count(), 1); + assert!( + repo.ok(&["show", &change]) + .contains("+not snapshotted yet\n") + ); + + assert!( + repo.fails(&["workspace", "rm", "."]) + .contains("is the main working copy") + ); + assert!( + repo.fails(&["workspace", "rm", ws.to_str().unwrap()]) + .contains("is not a workspace of this repository") + ); + assert!( + repo.fails(&["workspace", "new", "nested"]) + .contains("is inside a working copy") + ); + fs::write(others.path().join("file"), "").unwrap(); + assert!( + repo.fails(&["workspace", "new", others.path().to_str().unwrap()]) + .contains("is not empty") + ); +} + #[test] fn landing_moves_the_working_copy_onto_the_target() { let repo = Repo::new(); @@ -1266,3 +1360,87 @@ fn converge_labels_the_side_holding_merged_heads() { let file = repo.read("file"); assert!(file.starts_with("<<<<<<< merged heads\n<<<<<<< "), "{file}"); } + +#[test] +fn commands_in_different_workspaces_run_concurrently() { + const WORKSPACES: usize = 4; + const EDITS: usize = 5; + let repo = Repo::new(); + let others = tempfile::tempdir().unwrap(); + let workspaces: Vec<_> = (0..WORKSPACES) + .map(|i| { + let root = others.path().join(format!("ws{i}")); + let change = repo.workspace(&root, &[]); + (root, change) + }) + .collect(); + + std::thread::scope(|scope| { + for (root, _) in &workspaces { + let repo = &repo; + scope.spawn(move || { + for edit in 0..EDITS { + fs::write(root.join("file"), edit.to_string()).unwrap(); + repo.ok_in(root, &["describe", "Edit"]); + } + }); + } + }); + + // Each change has its first revision, then two per edit, recording it + // and describing it, whichever order the index received them in. + let revisions = |change: &str| repo.ok(&["evolog", change]).lines().count() - 1; + for (_, change) in &workspaces { + assert_eq!(revisions(change), 1 + 2 * EDITS); + } + repo.ok(&["index", "rebuild"]); + for (_, change) in &workspaces { + assert_eq!(revisions(change), 1 + 2 * EDITS); + } +} + +#[test] +fn workspaces_land_their_own_changes() { + let repo = Repo::new(); + repo.write("unlanded", "main's own work\n"); + let others = tempfile::tempdir().unwrap(); + let (one, two) = (others.path().join("one"), others.path().join("two")); + let first = repo.workspace(&one, &[]); + let second = repo.workspace(&two, &[]); + fs::write(one.join("a"), "a\n").unwrap(); + fs::write(two.join("b"), "b\n").unwrap(); + + let land = repo.ok_in(&one, &["land"]); + assert!( + land.starts_with(&format!("Landed change {first}, revision ")), + "{land}" + ); + assert!(land.contains(" on main #1\nWorking copy: "), "{land}"); + // Made on main #0, the second change lands rebased onto main #1: a new + // revision of it, by the queue. + let land = repo.ok_in(&two, &["land"]); + assert!(land.contains(" on main #2\nWorking copy: "), "{land}"); + assert!(repo.ok(&["show", &first]).contains(" by user:ada\n")); + assert!(repo.ok(&["show", &second]).contains(" by node:ada\n")); + + // Each landing moved its own workspace onto the tip it made. + let status = repo.ok_in(&two, &["status"]); + assert!( + status.ends_with("On top of: main #2\nNo changes.\n"), + "{status}" + ); + assert_eq!(fs::read_to_string(two.join("a")).unwrap(), "a\n"); + let status = repo.ok_in(&one, &["status"]); + assert!( + status.ends_with("On top of: main #1\nNo changes.\n"), + "{status}" + ); + assert!(!one.join("b").exists()); + // The main working copy's change didn't land, so it stays. + let status = repo.ok(&["status"]); + assert!( + status.ends_with("On top of: main #0\nA unlanded\n"), + "{status}" + ); + assert!(!repo.path("a").exists()); +}