From 35be16856747e8edce0be4000580e3b99debc582 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] feat(cli): add clone, remote, fetch, push and pull A repository has at most one remote, named in `.origin/remote`, which its workspaces share. `origin clone [] [--target ]` creates a repository that follows `policy` and one target, and starts a change on its tip: only that snapshot is fetched. Whenever a command needs a snapshot the repository lacks, such as a checkout, a diff or a merge, it's fetched from the remote, skipping what the working copy already holds. A move fetches what it needs before it publishes its `moving` marker, so a move that cannot fetch changes nothing. `origin remote []` shows or sets the remote, `origin fetch [--target ]... [--change ]...` fetches the chains followed and the records of the changes that moved, `origin push []...` shares changes, and `origin pull` fetches first. The remote's event cursor as of the last fetch is kept in `.origin/remote-cursor`, with its op log's generation; setting a new remote forgets it. Fetching never changes the files under a workspace. A clone canonicalizes its root, creates missing parents, and on failure removes exactly what it created, or empties the directory it found empty, never a dangling symlink it was given. `show` prints a change's full id, which `fetch --change` takes. --- AGENTS.md | 3 +- README.md | 20 ++ apps/origin-src/src/cli.rs | 52 ++- apps/origin-src/src/sync.rs | 7 +- apps/origin-src/src/workspace/land.rs | 17 +- apps/origin-src/src/workspace/mod.rs | 137 +++++--- apps/origin-src/src/workspace/registry.rs | 17 +- apps/origin-src/src/workspace/remote.rs | 388 ++++++++++++++++++++++ apps/origin-src/tests/common/mod.rs | 21 ++ apps/origin-src/tests/sync.rs | 126 +++++++ 10 files changed, 722 insertions(+), 66 deletions(-) create mode 100644 apps/origin-src/src/workspace/remote.rs create mode 100644 apps/origin-src/tests/sync.rs diff --git a/AGENTS.md b/AGENTS.md index f3e68fd7..2b878a3a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,8 @@ benchmark, and its numbers in the pull request. End-to-end tests run the `origin` binary with `ORIGIN_CONFIG_DIR` set to a temporary directory, which holds the user's `config.toml` and node key. The HTTP tests drive every SDK method against a real server. One fails -while `docs/openapi.json` is stale: `just openapi` rewrites it. +while `docs/openapi.json` is stale: `just openapi` rewrites it. The sync +tests clone, push and fetch through `origin serve` and through local paths; `tests/common` holds the helpers every end-to-end test shares. ## Commits & Pull Requests diff --git a/README.md b/README.md index 1ce36801..a2a2260c 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,12 @@ 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 origin watch [--kind ] [--subject ] [--since ] # events, as they happen + +origin clone [] [--target ] # follow a remote's target, starting a change on its tip +origin remote [] # show or set the remote: http://host:port/, or a path +origin push [...] # share changes and the ones below them; lands nothing +origin fetch [--target ] [--change ] # new acceptances, and the records of known changes +origin pull # fetch, then move the working copy onto its target's tip ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -81,6 +87,20 @@ op log, one a line starting with a cursor: `statement.issued`, takes an event name or a statement kind (`core.conflict`, `ci.*`), and `--since` resumes after a cursor. +A repository can have one remote, a server or another repository's path, +shared by its workspaces. A clone holds the chains of the targets it +follows, `policy` and one other, verified against their authorities' keys, +and the records of the changes it knows, which each `fetch` brings as they +move: it asks the remote's events what moved since the last fetch, so a +fetch that brings nothing is quick however long the history. It fetches +snapshots only when a command reads them, starting with its target's tip. +`push` shares revisions, their files and statements, and refuses a change +the remote has a newer revision of, even one pushed while it sends: +`fetch`, then `converge` it. A statement that needs one the remote lacks +stays, and the push says so. Fetching never changes your files; `pull` +then moves the working copy onto its target's new tip, like a landing +elsewhere does. + 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 87d4a5a5..ade12417 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -10,7 +10,7 @@ use anyhow::{Context, Result}; use clap::error::ErrorKind; use clap::{Args, CommandFactory, Parser, Subcommand}; use origin_shared::policy::KindPattern; -use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; +use origin_shared::{ChangeId, Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; use crate::config::UserConfig; use crate::oplog::Actor; @@ -33,6 +33,18 @@ enum Command { #[arg(default_value = ".")] path: PathBuf, }, + /// Copy a remote repository: the chains of `policy` and a target, and + /// the target's tip, on which a new change starts. Other snapshots are + /// fetched when something reads them. + Clone { + /// The repository: `http://host[:port]/`, or a path. + url: String, + /// Where to create it: by default, named after the repository. + path: Option, + /// The target to follow and start on. + #[arg(short, long, default_value = "main")] + target: TargetName, + }, /// Serve repositories over HTTP, as their authority. Serve { /// The server configuration file. @@ -166,9 +178,6 @@ enum WorkspaceCommand { Target(TargetCommand), /// List the targets, with their tips, authorities and requirements. Targets, - /// Move the working copy where its change went from another - /// workspace, or onto its target's new tip, with the edits made since. - Pull, /// Manage workspaces: working copies sharing this repository. #[command(subcommand)] Workspace(WorkspacesCommand), @@ -178,6 +187,31 @@ enum WorkspaceCommand { /// Move this workspace's working copy back to where it was before its /// latest operation. Records and targets stay as they are. Undo, + /// Show the remote, or set it. + Remote { + /// The new remote: `http://host[:port]/`, or a path. + url: Option, + }, + /// Fetch the remote's new acceptances on the targets followed, and the + /// records of the changes this repository knows. Changes no files. + Fetch { + /// Follow this target too. + #[arg(long)] + target: Vec, + /// Fetch this change too, by its full id. + #[arg(long)] + change: Vec, + }, + /// Fetch, if there's a remote, then move the working copy where its + /// change went, or onto its target's new tip, with the edits made + /// since. + Pull, + /// Share changes with the remote, with the changes below them: their + /// revisions, files and statements. Lands nothing. + Push { + /// The changes: the working copy's by default. + changes: Vec, + }, /// Print events as they happen, one a line, starting with the cursor to /// resume from. Runs until interrupted. Watch { @@ -449,7 +483,7 @@ impl Cli { Command::Repo(RepoCommand::Create { path, config }) => { return ServerConfig::load(&config)?.create_repo(&path); } - Command::Init { .. } | Command::Workspace(_) => {} + Command::Init { .. } | Command::Clone { .. } | Command::Workspace(_) => {} } let config = UserConfig::load()?; // The op log records the command line, without the program's name, @@ -464,6 +498,9 @@ impl Cli { Command::Init { path } => { Workspace::init(&path, config, &actor)?; } + Command::Clone { url, path, target } => { + Workspace::clone(&url, path.as_deref(), &target, config, &actor)?; + } Command::Workspace(command) => command.run(config, &actor)?, Command::Serve { .. } | Command::Repo(_) => unreachable!("run above"), } @@ -513,7 +550,6 @@ 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())?; } @@ -521,6 +557,10 @@ impl WorkspaceCommand { Self::Workspace(WorkspacesCommand::Rm { path }) => workspace.remove_workspace(&path)?, Self::Op(OpCommand::Log { limit }) => workspace.op_log(limit)?, Self::Undo => workspace.undo()?, + Self::Remote { url } => workspace.set_remote(url.as_deref())?, + Self::Fetch { target, change } => workspace.fetch(&target, &change)?, + Self::Pull => workspace.pull()?, + Self::Push { changes } => workspace.push(&changes)?, Self::Watch { kind, subject, diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index 20e7c7de..52ea1c11 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -19,9 +19,10 @@ //! however long the history: only without a cursor, or once it expired, //! are all the changes this node knows compared. //! - Snapshots don't come with records: [`Sync::need`] fetches one when -//! something reads it, such as a checkout. A snapshot is marked while it's -//! fetched ([`Store::fetching`]), so one whose fetch was interrupted is -//! fetched again rather than taken for whole. +//! something reads it, such as a checkout, so a clone fetches one +//! snapshot, its target's tip. A snapshot is marked while it's fetched +//! ([`Store::fetching`]), so one whose fetch was interrupted is fetched +//! again rather than taken for whole. //! - **Pushing** shares revisions, with their snapshots, and statements. It //! never lands anything. It first compares each change's heads with the //! remote's, and refuses before uploading anything when the remote has a diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 0dc23738..fc42249f 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -171,17 +171,22 @@ impl Workspace { self.start_on(&mut working_copy, target, description, files) } - /// `origin pull`: moves the working copy where its change went without - /// it, merging the edits made since: onto the tip of the target it + /// `origin pull`: fetches, if the repository has a remote, then moves + /// the working copy where its change went without it, merging the edits + /// made since: onto the tip of the target it /// landed on, as a new change, or onto the landing queue's rebase of it. /// Otherwise rebases it onto the tip of the target its stack is on: /// once the change below it landed, or once the target it's on moved. /// /// # Errors /// - /// Fails if the working copy cannot be snapshotted, a file was edited - /// while it moved, or the records cannot be read or written. + /// Fails like [`Workspace::fetch`], or if the working copy cannot be + /// snapshotted, a file was edited while it moved, or the records cannot + /// be read or written. pub fn pull(&mut self) -> Result<(), WorkspaceError> { + if self.remote()?.is_some() { + self.fetch(&[], &[])?; + } let mut working_copy = self.save_draft()?; if self.follow(&mut working_copy)? { return Ok(()); @@ -218,6 +223,7 @@ impl Workspace { .head(target)? .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; let state = self.store.get(tip.acceptance)?.body().state; + self.need(&[state])?; let tip_label = format!("{target} #{}", tip.seq); let merge = self.store.merge_marked( Some(base), @@ -318,7 +324,7 @@ impl Workspace { /// Rebases the working copy, made on `base`, onto the tip of `onto`, as /// the module explains. - fn rebase_onto_tip( + pub(super) fn rebase_onto_tip( &mut self, working_copy: &mut WorkingCopy, base: TreeId, @@ -329,6 +335,7 @@ impl Workspace { .head(onto)? .ok_or_else(|| WorkspaceError::UnknownTarget(onto.clone()))?; let state = self.store.get(tip.acceptance)?.body().state; + self.need(&[state])?; let current = &working_copy.revision; let tip_label = format!("{onto} #{}", tip.seq); let merge = self.store.merge_marked( diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 0e2b31ae..4dfacb0e 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -67,6 +67,7 @@ mod annotate; mod land; mod ops; mod registry; +mod remote; pub use annotate::{Annotated, Payload}; @@ -75,7 +76,7 @@ use std::fs; use std::io; use std::mem; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use origin_platform::{LockedFile, Native}; use origin_shared::api::{LogQuery, RevisionEntry, Revisions}; @@ -94,8 +95,11 @@ use crate::oplog::{Actor, Effect, Move, Why}; use crate::output::FileDiff; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; +use crate::remote::{Remote, RemoteError}; use crate::service::{Caller, Node, OriginService, ServiceError}; use crate::store::{Store, StoreError}; +use crate::sync::SyncError; +use crate::tree::FileChange; use crate::worktree::{CloneSource, SnapshotError, StatCache, Worktree}; /// A working copy and its repository. @@ -112,6 +116,8 @@ pub struct Workspace { /// The `moving` of a move a crash cut short, which couldn't be read: /// the working copy doesn't move while it's there. unreadable_move: Option, + /// The repository's remote, once opened: see [`Workspace::remote`]. + remote: OnceLock>, } /// The working copy as of a snapshot. @@ -265,14 +271,7 @@ impl Workspace { author: config.user(), }; let encoded = revision.encode(); - let mut workspace = Self { - root, - store, - config, - revision: encoded.id().into(), - unlogged: None, - unreadable_move: None, - }; + let mut workspace = Self::at(root, store, config, encoded.id().into()); workspace.write(&[vec![empty_description], vec![encoded]])?; workspace.publish_pointer(None, workspace.revision, Why::Command)?; println!( @@ -319,17 +318,25 @@ impl Workspace { }; let revision = Self::read_pointer(root)?.ok_or_else(|| WorkspaceError::Incomplete(root.to_owned()))?; - let mut workspace = Self { - root: root.to_owned(), - store: Store::open_writable(store, Native::default())? - .with_actor(actor.in_workspace(root)), + let store = Store::open_writable(store, Native::default())?; + let store = store.with_actor(actor.in_workspace(root)); + let mut workspace = Self::at(root.to_owned(), store, config, revision); + workspace.finish_move()?; + Ok(workspace) + } + + /// The working copy at `root`, of the repository in `store`, which is + /// `revision`. + fn at(root: PathBuf, store: Store, config: UserConfig, revision: RevisionId) -> Self { + Self { + root, + store, config, revision, unlogged: None, unreadable_move: None, - }; - workspace.finish_move()?; - Ok(workspace) + remote: OnceLock::new(), + } } /// Finishes the move `moving` records, if a crash cut it short, as the @@ -423,17 +430,26 @@ impl Workspace { /// that the API also offers go through. It finds records through /// `index`, if the command just read it, or else reads it once needed. fn service(&self, index: Option) -> Result { - let node = Node { - name: self.config.node().clone(), - key: Arc::new(self.config.node_key()?), - }; - let service = OriginService::new(self.store.clone(), node); + let service = OriginService::new(self.store.clone(), self.node()?); Ok(match index { Some(index) => service.with_index(index), None => service, }) } + /// This node, with its key. + fn node(&self) -> Result { + Self::node_of(&self.config) + } + + /// The node `config` names, with its key. + fn node_of(config: &UserConfig) -> Result { + Ok(Node { + name: config.node().clone(), + key: Arc::new(config.node_key()?), + }) + } + /// Snapshots the working copy into a draft, recording nothing, for the /// commands that only read it. fn snapshot(&mut self) -> Result { @@ -744,8 +760,14 @@ impl Workspace { ) -> Result<(), WorkspaceError> { // Before changing any file. self.may_move()?; + // Fetched first, so a fetch that fails moves nothing. + let changes = if revision.snapshot == working_copy.files { + Vec::new() + } else { + self.changes(working_copy.files, revision.snapshot)? + }; // The files stay as they are: there's nothing to finish. - if revision.snapshot == working_copy.files { + if changes.is_empty() { self.write(unwritten)?; return self.point_at(to, why); } @@ -756,11 +778,7 @@ impl Workspace { why, }; self.publish_moving(&moving)?; - let checkout = self.checkout( - working_copy.files, - revision.snapshot, - Some(&working_copy.cache), - ); + let checkout = self.checkout(&changes, Some(&working_copy.cache)); if let Err(error) = checkout { // So a crash finishes taking the files back, not the move, whose // revision may exist. Best effort: the checkout's error says @@ -807,17 +825,34 @@ impl Workspace { Ok(Worktree::new(&self.root, &self.store).restore(&changes)?) } - /// Makes the files match `to`, given that they match `from`, durably, - /// cloning those the other workspaces have. With `unchanged`, the stat - /// cache of the snapshot that found `from`, it changes nothing if a - /// file it changes was edited since. + /// The changes that make the files of `from` those of `to`, after + /// fetching what the repository lacks of `to`. A move asks for them + /// before it publishes `moving`, so a fetch that fails moves nothing. + fn changes(&self, from: TreeId, to: TreeId) -> Result, WorkspaceError> { + self.need(&[to])?; + Ok(match self.store.diff(from, to) { + // A snapshot can lack trees its root names, if its fetch was + // cut short before fetches were marked: fetch it whole again. + Err(StoreError::NotFound(missing)) => match self.remote()? { + Some(remote) => { + self.sync(remote).repair(to)?; + self.store.diff(from, to)? + } + None => return Err(StoreError::NotFound(missing).into()), + }, + changes => changes?, + }) + } + + /// Makes the files match a snapshot, given `changes`, how they differ + /// from it, durably, cloning those the other workspaces have. With + /// `unchanged`, the stat cache of the snapshot `changes` start from, it + /// changes nothing if a file it changes was edited since. fn checkout( &self, - from: TreeId, - to: TreeId, + changes: &[FileChange], unchanged: Option<&StatCache>, ) -> Result<(), WorkspaceError> { - let changes = self.store.diff(from, to)?; if changes.is_empty() { return Ok(()); } @@ -830,7 +865,7 @@ impl Workspace { CloneSource::saved(root, cache) }) .collect(); - Ok(Worktree::new(&self.root, &self.store).checkout(&changes, &sources, unchanged)?) + Ok(Worktree::new(&self.root, &self.store).checkout(changes, &sources, unchanged)?) } /// `origin status`: prints the working copy's change, what it is on @@ -909,7 +944,7 @@ impl Workspace { let files = files.unwrap_or(revision.snapshot); println!( "Change {}{}", - revision.change.short(), + revision.change, self.flags(index, revision.change)? ); let edited = if files == revision.snapshot { @@ -939,6 +974,7 @@ impl Workspace { /// 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)?; + self.need(&[snapshot])?; for change in self.store.diff(base, snapshot)? { print!("{}", FileDiff::new(&self.store, &change)?); } @@ -1156,6 +1192,11 @@ impl Workspace { heads[heads.len() - 1] }; let kept_revision: Revision = self.store.get(kept)?; + let snapshots = heads + .iter() + .map(|&head| Ok(self.store.get(head)?.snapshot)) + .collect::, WorkspaceError>>()?; + self.need(&snapshots)?; let base = self.merge_base(&heads)?; let mut snapshot = kept_revision.snapshot; let mut merged = Conflicts::default(); @@ -1452,12 +1493,15 @@ impl Workspace { shorts.join(", ") } - /// The snapshot a revision was made on top of. + /// The snapshot a revision was made on top of, fetched if the + /// repository lacks it. fn base_tree(&self, base: Base) -> Result { - Ok(match base { + let tree = match base { Base::Acceptance(id) => self.store.get(id)?.body().state, Base::Revision(id) => self.store.get(id)?.snapshot, - }) + }; + self.need(&[tree])?; + Ok(tree) } fn describe_base(&self, base: Base) -> Result { @@ -1513,6 +1557,15 @@ pub enum WorkspaceError { /// No target has this name. #[error("no target is named `{0}`")] UnknownTarget(TargetName), + /// No revision of the change is known. + #[error("change {} has no revisions", .0.short())] + UnknownChange(ChangeId), + /// A command needs a remote, and the repository has none. + #[error("this repository has no remote: set one with `origin remote `")] + NoRemote, + /// `clone` was given no path, and the URL names no directory. + #[error("cannot tell the repository's name from its URL: pass a path")] + Unnamed, /// An acceptance belongs to a target this repository doesn't have. #[error("no target has the id {0}")] UnknownTargetId(TargetId), @@ -1627,6 +1680,12 @@ pub enum WorkspaceError { /// The repository's service refused a call. #[error(transparent)] Service(#[from] ServiceError), + /// The remote cannot be opened, or refused a call. + #[error(transparent)] + Remote(#[from] RemoteError), + /// Syncing with the remote failed. + #[error(transparent)] + Sync(#[from] SyncError), /// `undo` found no operation of this workspace to take back. #[error("nothing to undo: no operation moved this workspace's working copy")] NothingToUndo, diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index 201a0a6f..66bd3f8b 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -69,19 +69,12 @@ impl Workspace { 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 { - store: self - .store - .clone() - .with_actor(self.store.actor().in_workspace(&root)), - root, - config: self.config.clone(), - revision: id, - unlogged: None, - unreadable_move: None, - }; + let store = self.store.clone(); + let store = store.with_actor(self.store.actor().in_workspace(&root)); + let mut workspace = Self::at(root, store, self.config.clone(), id); let empty = Tree::default().encode().id().into(); - workspace.checkout(empty, revision.snapshot, None)?; + let changes = workspace.changes(empty, revision.snapshot)?; + workspace.checkout(&changes, None)?; let repository = Self::path_bytes(self.store.root()); workspace.write_durably(workspace.meta(Self::REPOSITORY), &repository)?; workspace.publish_pointer(None, id, Why::Command)?; diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs new file mode 100644 index 00000000..d012c787 --- /dev/null +++ b/apps/origin-src/src/workspace/remote.rs @@ -0,0 +1,388 @@ +//! The sync commands: `clone`, `remote`, `fetch`, `pull` and `push`, and +//! fetching the snapshots a lazy clone lacks. +//! +//! A repository has at most one remote, named in `.origin/remote`, which +//! its workspaces share. A clone holds the chains of the targets it +//! follows, the records of the changes it knows, and only the snapshots it +//! read: whenever a command needs one it lacks, such as a checkout, it is +//! fetched from the remote, skipping what the working copy already holds. +//! Syncing never changes files under a running workspace: `pull` is a +//! fetch, then a move of the working copy. +//! +//! The remote's event cursor as of the last fetch, and the generation of +//! the op log it's of, are kept in `.origin/remote-cursor`, so the next +//! fetch only compares the changes +//! that moved since (see [`Sync::moved`]). Every way this repository learns +//! of a change brings all the remote has of it, so the changes it knows are +//! whole as of that cursor. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::slice; +use std::sync::OnceLock; + +use origin_platform::Native; +use origin_shared::{ + Base, ChangeId, EncodedObject, Record, Revision, RevisionId, TargetName, Tree, TreeId, +}; + +use super::{Workspace, WorkspaceError}; +use crate::config::UserConfig; +use crate::index::Index; +use crate::oplog::{Actor, Why}; +use crate::remote::{Remote, RemoteUrl}; +use crate::store::Store; +use crate::sync::{Advanced, Cursor, Fetch, Sync}; + +impl Workspace { + /// The file in the repository's `.origin` naming its remote. + const REMOTE: &str = "remote"; + + /// `origin clone [] [--target ]`: creates a + /// repository in `path`, by default named after the remote's, which + /// follows `policy` and `target`, and starts a change on its tip. Only + /// that snapshot is fetched. + /// + /// # Errors + /// + /// Fails if `path` has files, the remote cannot be reached or has no + /// such target, or the repository cannot be written. A failed clone + /// leaves nothing behind, but the empty directory it was made in. + pub fn clone( + url: &str, + path: Option<&Path>, + target: &TargetName, + config: UserConfig, + actor: &Actor, + ) -> Result { + let url = RemoteUrl::parse(url)?; + let path = match path { + Some(path) => path.to_owned(), + None => PathBuf::from(url.name().ok_or(WorkspaceError::Unnamed)?), + }; + // Canonical, as `init` and every command opening it spell it. + let root = Self::canonical(&path)?; + if fs::read_dir(&root).is_ok_and(|mut entries| entries.next().is_some()) { + return Err(WorkspaceError::NotEmpty(root)); + } + // The topmost directory the clone creates, if `root` is missing: + // its parents may be too. Only where nothing is, not even a + // dangling symlink, which cleaning up would delete. + let created = root + .ancestors() + .take_while(|dir| dir.symlink_metadata().is_err()) + .last() + .map(Path::to_owned); + let remote = Remote::open(&url, Self::node_of(&config)?)?; + let cloned = Self::clone_into(root.clone(), &url, remote, target, config, actor); + if cloned.is_err() { + // Best effort: the error says what went wrong. + let _ = Self::undo_clone(&root, created.as_deref()); + } + cloned + } + + /// Removes what a failed clone into `root` left: the topmost directory + /// it `created`, with `root`, if it created any, or else everything in + /// `root`, which was empty, such as the files it checked out. + fn undo_clone(root: &Path, created: Option<&Path>) -> io::Result<()> { + if let Some(created) = created { + return fs::remove_dir_all(created); + } + for entry in fs::read_dir(root)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + fs::remove_dir_all(entry.path())?; + } else { + fs::remove_file(entry.path())?; + } + } + Ok(()) + } + + fn clone_into( + root: PathBuf, + url: &RemoteUrl, + remote: Remote, + target: &TargetName, + config: UserConfig, + actor: &Actor, + ) -> Result { + let meta = root.join(Self::META_DIR); + let store = Store::new(meta, Native::default()).with_actor(actor.in_workspace(&root)); + store.init()?; + let sync = Sync::new(&store, &remote, config.node().clone()); + let cursor = sync.moved(None)?.cursor; + sync.fetch_chains(slice::from_ref(target))?; + let tip = store + .head(target)? + .ok_or_else(|| WorkspaceError::UnknownTarget(target.clone()))?; + let state = store.get(tip.acceptance)?.body().state; + sync.need(state, &[])?; + + let empty_tree = Tree::default().encode(); + let empty_description = EncodedObject::blob(b""); + let revision = Revision { + change: ChangeId::random().map_err(WorkspaceError::Random)?, + predecessors: Vec::new(), + base: Base::Acceptance(tip.acceptance), + deps: Vec::new(), + snapshot: state, + description: empty_description.id().into(), + author: config.user(), + }; + let encoded = revision.encode(); + let id: RevisionId = encoded.id().into(); + let mut workspace = Self::at(root, store, config, id); + workspace.write(&[vec![empty_tree.clone(), empty_description], vec![encoded]])?; + workspace.write_durably( + workspace.store.root().join(Self::REMOTE), + format!("{url}\n").as_bytes(), + )?; + workspace.save_cursor(&cursor)?; + workspace.remote = OnceLock::from(Some(remote)); + let changes = workspace.changes(empty_tree.id().into(), state)?; + workspace.checkout(&changes, None)?; + workspace.publish_pointer(None, id, Why::Command)?; + println!( + "Cloned {url} into {}, following `{target}` at #{}", + workspace.root.display(), + tip.seq + ); + println!("Working copy: {}", workspace.headline(&revision)?); + println!("On top of: {}", workspace.describe_base(revision.base)?); + Ok(workspace) + } + + /// The file in the repository's `.origin` holding the remote's event + /// cursor as of the last fetch. + const CURSOR: &str = "remote-cursor"; + + /// The remote's event cursor as of the last fetch, if any, written + /// ` `. One that cannot be read is forgotten: the + /// next fetch compares every change. + fn cursor(&self) -> Option { + let path = self.store.root().join(Self::CURSOR); + let text = fs::read_to_string(path).ok()?; + let (generation, next) = text.trim_end().split_once(' ')?; + Some(Cursor { + generation: generation.to_owned(), + next: next.parse().ok()?, + }) + } + + /// Saves the remote's event cursor, without syncing: any older cursor, + /// or none, is as good, only slower to fetch from, and one torn by a + /// crash doesn't parse, or reads from earlier. + fn save_cursor(&self, cursor: &Cursor) -> Result<(), WorkspaceError> { + let path = self.store.root().join(Self::CURSOR); + let text = format!("{} {}\n", cursor.generation, cursor.next); + fs::write(&path, text).map_err(|source| WorkspaceError::io(&path, source)) + } + + /// Forgets the remote's event cursor: the next fetch compares every + /// change, for a new remote, or once the user sees more of it. + pub(super) fn forget_cursor(&self) -> Result<(), WorkspaceError> { + let path = self.store.root().join(Self::CURSOR); + match fs::remove_file(&path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + Err(WorkspaceError::io(&path, error)) + } + _ => Ok(()), + } + } + + /// The URL of the repository's remote, if it has one. + fn remote_url(&self) -> Result, WorkspaceError> { + let path = self.store.root().join(Self::REMOTE); + match fs::read_to_string(&path) { + Ok(url) => Ok(Some(RemoteUrl::parse(url.trim_end())?)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(WorkspaceError::io(&path, source)), + } + } + + /// The repository's remote, opened the first time it's needed, if it + /// has one. + pub(super) fn remote(&self) -> Result, WorkspaceError> { + if let Some(remote) = self.remote.get() { + return Ok(remote.as_ref()); + } + let remote = match self.remote_url()? { + Some(url) => Some(Remote::open(&url, self.node()?)?), + None => None, + }; + Ok(self.remote.get_or_init(|| remote).as_ref()) + } + + /// Syncs with `remote`, as this node. + pub(super) fn sync<'s>(&'s self, remote: &'s Remote) -> Sync<'s> { + Sync::new(&self.store, remote, self.config.node().clone()) + } + + /// The repository's remote, which the command needs. + fn require_remote(&self) -> Result<&Remote, WorkspaceError> { + self.remote()?.ok_or(WorkspaceError::NoRemote) + } + + /// `origin remote []`: prints the repository's remote, or sets it. + /// + /// # Errors + /// + /// Fails if the URL is invalid, or the file naming the remote cannot be + /// read or written. + pub fn set_remote(&self, url: Option<&str>) -> Result<(), WorkspaceError> { + let Some(url) = url else { + match self.remote_url()? { + Some(url) => println!("{url}"), + None => println!("No remote: set one with `origin remote `."), + } + return Ok(()); + }; + let url = RemoteUrl::parse(url)?; + self.forget_cursor()?; + self.write_durably( + self.store.root().join(Self::REMOTE), + format!("{url}\n").as_bytes(), + )?; + println!("Remote: {url}"); + Ok(()) + } + + /// `origin fetch [--target ]... [--change ]...`: + /// fetches the chains of the targets this repository follows and of + /// `targets`, then the records of `changes` and of the changes it knows + /// that moved since the last fetch (see [`Sync::fetch`]). Changes + /// nothing under the working copy. + /// + /// # Errors + /// + /// Fails if there's no remote, it lacks a target or change asked for, + /// or the remote or the store fails. + pub fn fetch( + &self, + targets: &[TargetName], + changes: &[ChangeId], + ) -> Result<(), WorkspaceError> { + let remote = self.require_remote()?; + // Changes landed on a target fetched for the first time are older + // than the cursor: forget it, so they're compared, by a retry too. + for target in targets { + if self.store.head(target)?.is_none() { + self.forget_cursor()?; + break; + } + } + let since = self.cursor(); + let Fetch { + advanced, + fetched, + cursor, + } = self.sync(remote).fetch(targets, changes, since.as_ref())?; + if since.as_ref() != Some(&cursor) { + self.save_cursor(&cursor)?; + } + if !changes.is_empty() { + let index = Index::open(&self.store)?; + if let Some(&missing) = changes + .iter() + .find(|&&change| index.revisions(change).is_empty()) + { + return Err(WorkspaceError::UnknownChange(missing)); + } + } + for Advanced { target, from, to } in &advanced { + match from { + Some(from) => println!("`{target}`: #{} -> #{}", from.seq, to.seq), + None => println!("`{target}`: now followed, at #{}", to.seq), + } + } + if fetched.revisions + fetched.statements > 0 { + println!( + "Fetched {} revisions and {} statements", + fetched.revisions, fetched.statements + ); + } + if advanced.is_empty() && fetched.revisions + fetched.statements == 0 { + println!("Already up to date."); + } + Ok(()) + } + + /// `origin push []...`: shares the changes, the working copy's + /// by default, with the ones below them, with the remote: their + /// revisions, snapshots and statements. Lands nothing. + /// + /// # Errors + /// + /// Fails if there's no remote, a change cannot be found, is stale or is + /// on a target the remote lacks, or the remote or the store fails. + pub fn push(&mut self, changes: &[String]) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let changes = if changes.is_empty() { + vec![working_copy.revision.change] + } else { + changes + .iter() + .map(|change| working_copy.find_change(change)) + .collect::>()? + }; + let pushed = self.sync(self.require_remote()?).push(&changes)?; + for statement in &pushed.unsent { + println!( + "Statement {} stays here: it needs a statement the remote doesn't have", + statement.short() + ); + } + if pushed.objects == 0 { + println!("Everything up to date."); + } else { + println!( + "Pushed {} revisions and {} statements ({} objects)", + pushed.revisions, pushed.statements, pushed.objects + ); + } + Ok(()) + } + + /// Fetches the snapshots of `trees` the repository lacks, if it has a + /// remote: a clone only holds the snapshots it read. Skips what the + /// working copy's revision and its base hold. Without a remote, reading + /// a missing snapshot fails later. + pub(super) fn need(&self, trees: &[TreeId]) -> Result<(), WorkspaceError> { + if self.store.held_whole(trees.iter().copied())?.len() == trees.len() { + return Ok(()); + } + let Some(remote) = self.remote()? else { + return Ok(()); + }; + let current = self.store.get(self.revision)?; + let base = match current.base { + Base::Acceptance(id) => self.store.get(id)?.body().state, + Base::Revision(id) => self.store.get(id)?.snapshot, + }; + let sync = self.sync(remote); + for &tree in trees { + sync.need(tree, &[current.snapshot, base])?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_failed_clone_empties_the_directory_it_found_empty() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join(".origin/objects")).unwrap(); + fs::create_dir(dir.path().join("src")).unwrap(); + fs::write(dir.path().join("src/lib.rs"), "fn lib() {}\n").unwrap(); + fs::write(dir.path().join("README.md"), "hello\n").unwrap(); + Workspace::undo_clone(dir.path(), None).unwrap(); + assert!(dir.path().is_dir()); + assert!(fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 0f19e2cb..4bbb0063 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -70,6 +70,14 @@ impl Repo { repo } + /// A clone of `url` by `user`, with more arguments for `clone`. + pub fn clone(user: &User, url: &str, args: &[&str]) -> Self { + let repo = Self::empty(user); + let root = repo.root().to_str().unwrap().to_owned(); + repo.ok(&[&["clone", url, &root], args].concat()); + repo + } + fn empty(user: &User) -> Self { Self { dir: tempfile::tempdir().unwrap(), @@ -178,6 +186,14 @@ impl Repo { headline.split(' ').next().unwrap().to_owned() } + /// The full id of the working copy's change. + pub fn full_change(&self) -> String { + let show = self.ok(&["show"]); + let line = show.lines().next().unwrap(); + let change = line.strip_prefix("Change ").unwrap(); + change.split(' ').next().unwrap().to_owned() + } + /// Creates a workspace at `path`, returning its change. pub fn workspace(&self, path: &Path, args: &[&str]) -> String { let path = path.to_str().unwrap(); @@ -297,6 +313,11 @@ impl Server { pub fn dir(&self) -> &Path { self.dir.path() } + + /// The URL of `demo`. + pub fn url(&self) -> String { + format!("{}/demo", self.base) + } } impl Drop for Server { diff --git a/apps/origin-src/tests/sync.rs b/apps/origin-src/tests/sync.rs new file mode 100644 index 00000000..c5e4f43d --- /dev/null +++ b/apps/origin-src/tests/sync.rs @@ -0,0 +1,126 @@ +//! End-to-end tests of sharing work: cloning, pushing, fetching and +//! pulling, over HTTP and through a local path. + +mod common; + +use std::fs; + +use common::{Repo, Server, User}; + +#[test] +fn pushing_a_change_that_moved_on_the_server_is_refused() { + let server = Server::start(); + let (ada, bob) = (User::new("ada"), User::new("bob")); + let alice = Repo::clone(&ada, &server.url(), &[]); + alice.write("file", "alice\n"); + alice.ok(&["describe", "Shared work"]); + alice.ok(&["push"]); + + // Bob takes the change over, and pushes a revision of it. + let bobs = Repo::clone(&bob, &server.url(), &[]); + let change = alice.full_change(); + bobs.ok(&["fetch", "--change", &change]); + bobs.ok(&["edit", &change]); + assert_eq!(bobs.read("file"), "alice\n"); + bobs.write("file", "bob\n"); + bobs.ok(&["push", &change]); + + // Alice's next revision is stale: she learns before sending anything. + alice.write("file", "alice again\n"); + let error = alice.fails(&["push"]); + assert!(error.contains("is stale"), "{error}"); + alice.ok(&["fetch"]); + assert!(alice.ok(&["status"]).contains("Divergent")); + alice.ok(&["converge", &change]); + assert!(alice.ok(&["push"]).starts_with("Pushed ")); +} + +#[test] +fn clones_make_the_directories_they_go_in() { + let ada = User::new("ada"); + let origin = Repo::init(&ada); + let url = origin.root().to_str().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let cloned = ada + .command(dir.path(), &["clone", url, "x/y/name"]) + .output() + .unwrap(); + assert!(cloned.status.success(), "{cloned:?}"); + let root = fs::canonicalize(dir.path().join("x/y/name")).unwrap(); + let undo = ada.command(&root, &["undo"]).output().unwrap(); + let error = String::from_utf8_lossy(&undo.stderr); + assert!( + error.contains("nothing to undo but the creation of"), + "{error}" + ); + + // A clone that fails leaves none of them behind. + let args = ["clone", url, "z/y/name", "--target", "nope"]; + assert!(!ada.command(dir.path(), &args).status().unwrap().success()); + assert!(!dir.path().join("z").exists()); + + // Nor does it take a dangling symlink it was told to clone into. + let link = dir.path().join("link"); + std::os::unix::fs::symlink("nowhere", &link).unwrap(); + assert!( + !ada.command(dir.path(), &["clone", url, "link"]) + .status() + .unwrap() + .success() + ); + assert!(link.symlink_metadata().is_ok(), "the symlink stays"); +} + +#[test] +fn clones_follow_one_target_and_fetch_others_on_demand() { + let ada = User::new("ada"); + let origin = Repo::init(&ada); + origin.write("README.md", "main\n"); + origin.ok(&["land"]); + origin.ok(&["target", "new", "release", "--from", "main"]); + origin.ok(&["new", "--on", "release"]); + origin.write("RELEASE.md", "v1\n"); + origin.ok(&["land"]); + + let url = origin.root().to_str().unwrap(); + let clone = Repo::clone(&User::new("bob"), url, &["--target", "release"]); + assert_eq!(clone.read("RELEASE.md"), "v1\n"); + assert!(clone.ok(&["log"]).contains("◆ release #1")); + let error = clone.fails(&["log", "main"]); + assert!(error.contains("main"), "not followed: {error}"); + let fetched = clone.ok(&["fetch", "--target", "main"]); + assert!(fetched.contains("`main`: now followed, at #1"), "{fetched}"); + assert!(clone.ok(&["log", "main"]).starts_with("◆ main #1")); + + let missing = clone.fails(&["clone", url, "elsewhere", "--target", "nope"]); + assert!(missing.contains("no target `nope`"), "{missing}"); + assert!( + !clone.path("elsewhere").exists(), + "a failed clone leaves nothing" + ); +} + +#[test] +fn a_move_that_cannot_fetch_moves_nothing() { + let ada = User::new("ada"); + let origin = Repo::init(&ada); + origin.write("x", "x\n"); + origin.ok(&["describe", "X"]); + let change = origin.full_change(); + let url = origin.root().to_str().unwrap(); + let clone = Repo::clone(&ada, url, &[]); + clone.ok(&["fetch", "--change", &change]); + + // The remote is gone while `edit` needs the change's files from it. + let away = origin.root().with_extension("away"); + fs::rename(origin.root(), &away).unwrap(); + let error = clone.fails(&["edit", &change]); + assert!(error.contains("remote"), "{error}"); + assert!(!clone.path(".origin/moving").exists()); + clone.write("notes", "mine\n"); + let status = clone.ok(&["status"]); + assert!(status.contains("A notes\n"), "{status}"); + fs::rename(&away, origin.root()).unwrap(); + clone.ok(&["edit", &change]); + assert_eq!(clone.read("x"), "x\n"); +}