From 144bb8621b274f49e9fe12acf6476c1f805540da Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(cli): run plugins as `origin ` origin's extensions, CI first, live outside the `origin` binary, and should run as `origin ` the way cargo and git run theirs. Any command that isn't built in now replaces the `origin` process with `origin-` from `PATH`, so its standard streams, exit code and signals are the command's. Run in a working copy, origin records its draft first and passes the plugin `ORIGIN_REPOSITORY`, `ORIGIN_REVISION` and `ORIGIN_REMOTE`, which `Context::from_env` reads back. Outside one, none of them is set, even if an outer plugin had them. The end-to-end helpers now find `origin` beside the test binary when another package's tests include them, and put the plugins built with it on `PATH`. --- AGENTS.md | 7 +- README.md | 10 ++ apps/origin-src/src/cli.rs | 20 +++- apps/origin-src/src/lib.rs | 1 + apps/origin-src/src/plugin.rs | 152 +++++++++++++++++++++++++++ apps/origin-src/src/workspace/mod.rs | 16 +++ apps/origin-src/tests/cli.rs | 48 +++++++++ apps/origin-src/tests/common/mod.rs | 41 +++++++- 8 files changed, 287 insertions(+), 8 deletions(-) create mode 100644 apps/origin-src/src/plugin.rs diff --git a/AGENTS.md b/AGENTS.md index 9c8837c1..dfb25128 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,8 @@ review bots read and write at the same time, written in Rust. same calls over the SDK or, for a local path, in-process. Every call takes a `Caller`, authenticated by `auth.rs`; `permissions.rs` filters what it reads and checks what it writes, by the rights `policy.rs` - resolves from `policy.toml`. + resolves from `policy.toml`. `plugin.rs` runs `origin ` as + `origin-` from `PATH`, passing the repository in the environment. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). @@ -54,7 +55,9 @@ 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. The sync tests clone, push and land through `origin serve` and through local paths; -`tests/common` holds the helpers every end-to-end test shares. +`apps/origin-src/tests/common` holds the helpers every end-to-end test +shares, plugins' included, which run `origin` from the target directory +their own binary is built in. ## Commits & Pull Requests diff --git a/README.md b/README.md index 5c7f04b8..6e0952ac 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,16 @@ send each server under `[tokens]`, by its URL (`"http://127.0.0.1:7878" = ""`), or in `$ORIGIN_TOKEN`. See [the design](docs/design.md) for the model. +## Plugins + +`origin ` runs `origin-` from `PATH` when `` isn't a +built-in command, with its arguments; its output and exit code are the +command's. Run in a working copy, whose draft it records first, it passes +the plugin `ORIGIN_REPOSITORY`, the directory holding the repository's store, +`ORIGIN_REVISION`, the working copy's revision, and `ORIGIN_REMOTE`, the +remote, if there's one. Plugins use origin's public API only: a server's +over HTTP, or for a local path, the same service in-process. + ## Permissions What each user may do lives in `policy.toml`, so changing it is a landing diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index ef22947d..9820d7cc 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -3,6 +3,7 @@ use std::convert::Infallible; use std::env; +use std::ffi::OsString; use std::path::PathBuf; use std::str::FromStr; @@ -17,8 +18,9 @@ use origin_shared::{ use crate::config::UserConfig; use crate::oplog::Actor; +use crate::plugin::Plugin; use crate::server::ServerConfig; -use crate::workspace::{Annotated, Payload, Workspace}; +use crate::workspace::{Annotated, Payload, Workspace, WorkspaceError}; /// A modern, git-compatible source control system. #[derive(Debug, Parser)] @@ -62,6 +64,10 @@ enum Command { Token(TokenCommand), #[command(flatten)] Workspace(WorkspaceCommand), + /// Any other command runs the plugin `origin-` from `PATH`, + /// such as `origin ci` for `origin-ci`. + #[command(external_subcommand)] + Plugin(Vec), } #[derive(Debug, Subcommand)] @@ -536,7 +542,8 @@ impl Cli { Command::Init { .. } | Command::Clone { .. } | Command::Token(_) - | Command::Workspace(_) => {} + | Command::Workspace(_) + | Command::Plugin(_) => {} } let config = UserConfig::load()?; // The op log records the command line, without the program's name, @@ -555,6 +562,15 @@ impl Cli { Workspace::clone(&url, path.as_deref(), &target, config, &actor)?; } Command::Workspace(command) => command.run(config, &actor)?, + Command::Plugin(args) => { + let cwd = env::current_dir().context("cannot read the current directory")?; + let context = match Workspace::discover(&cwd, config, &actor) { + Ok(mut workspace) => Some(workspace.plugin_context()?), + Err(WorkspaceError::NotFound(_)) => None, + Err(error) => return Err(error.into()), + }; + match Plugin(args).exec(context.as_ref())? {} + } Command::Token(TokenCommand::Issue { scope, ttl, .. }) => { let cwd = env::current_dir().context("cannot read the current directory")?; Workspace::discover(&cwd, config, &actor)?.issue_token(scope, ttl)?; diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index f61ef6f0..aa3fdf4d 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -16,6 +16,7 @@ pub mod index; pub mod oplog; pub mod output; pub mod permissions; +pub mod plugin; pub mod policy; pub mod queue; pub mod remote; diff --git a/apps/origin-src/src/plugin.rs b/apps/origin-src/src/plugin.rs new file mode 100644 index 00000000..a9308a3e --- /dev/null +++ b/apps/origin-src/src/plugin.rs @@ -0,0 +1,152 @@ +//! Plugins: `origin ` runs `origin-` from `PATH` when `` +//! isn't a built-in command, as cargo and git do with theirs. The plugin +//! replaces the `origin` process, so its standard streams, exit code and +//! signals are the command's. +//! +//! Run in a working copy, the plugin gets the repository's [`Context`] in +//! its environment, after its draft is recorded: +//! +//! - `ORIGIN_REPOSITORY`: the directory holding the repository's store, its +//! main working copy's `.origin`, which a remote on a local path accepts; +//! - `ORIGIN_REVISION`: the revision the working copy is, in full; +//! - `ORIGIN_REMOTE`: the repository's remote, if it has one. +//! +//! Outside a working copy, none of them is set. + +use std::convert::Infallible; +use std::env; +use std::ffi::OsString; +use std::io; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::Command; + +use origin_shared::RevisionId; + +use crate::remote::{RemoteError, RemoteUrl}; + +/// What a plugin learns of the repository it runs in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Context { + /// The directory holding the repository's store. + pub repository: PathBuf, + /// The revision the working copy is. + pub revision: RevisionId, + /// The repository's remote, if it has one. + pub remote: Option, +} + +impl Context { + /// The variable naming [`Context::repository`]. + pub const REPOSITORY: &str = "ORIGIN_REPOSITORY"; + /// The variable naming [`Context::revision`]. + pub const REVISION: &str = "ORIGIN_REVISION"; + /// The variable naming [`Context::remote`]. + pub const REMOTE: &str = "ORIGIN_REMOTE"; + + /// The context `origin` gave this process, if it ran it in a working + /// copy. + /// + /// # Errors + /// + /// Fails if a variable is set but malformed. + pub fn from_env() -> Result, ContextError> { + let Some(repository) = env::var_os(Self::REPOSITORY) else { + return Ok(None); + }; + let read = |name: &'static str| { + env::var(name).map_err(|source| ContextError::Variable { name, source }) + }; + let revision = read(Self::REVISION)?; + let revision = revision + .parse() + .map_err(|_| ContextError::Revision(revision))?; + let remote = match env::var_os(Self::REMOTE) { + Some(_) => Some(RemoteUrl::parse(&read(Self::REMOTE)?)?), + None => None, + }; + Ok(Some(Self { + repository: repository.into(), + revision, + remote, + })) + } + + /// Sets the context in the environment of `command`. + fn apply(&self, command: &mut Command) { + command + .env(Self::REPOSITORY, &self.repository) + .env(Self::REVISION, self.revision.to_string()); + match &self.remote { + Some(remote) => command.env(Self::REMOTE, remote.to_string()), + None => command.env_remove(Self::REMOTE), + }; + } +} + +/// A command that isn't built in: the plugin's name, then its arguments. +#[derive(Debug)] +pub struct Plugin(pub Vec); + +impl Plugin { + /// Replaces this process with the plugin, giving it `context`. + /// + /// # Errors + /// + /// Fails if no `origin-` is on `PATH`, or it cannot be run. + pub fn exec(self, context: Option<&Context>) -> Result { + let mut args = self.0.into_iter(); + let name = args.next().unwrap_or_default(); + let mut program = OsString::from("origin-"); + program.push(&name); + let mut command = Command::new(&program); + command.args(args); + // A plugin run from another's working copy gets only its own. + for variable in [Context::REPOSITORY, Context::REVISION, Context::REMOTE] { + command.env_remove(variable); + } + if let Some(context) = context { + context.apply(&mut command); + } + let name = name.to_string_lossy().into_owned(); + Err(match command.exec() { + error if error.kind() == io::ErrorKind::NotFound => PluginError::NotFound(name), + source => PluginError::Exec { name, source }, + }) + } +} + +/// A plugin that cannot run. +#[derive(Debug, thiserror::Error)] +pub enum PluginError { + /// Neither a built-in command nor a plugin has the name. + #[error("`{0}` is not an origin command, and no `origin-{0}` is on PATH")] + NotFound(String), + /// The plugin cannot be run. + #[error("cannot run `origin-{name}`")] + Exec { + /// The plugin's name. + name: String, + /// Why. + source: io::Error, + }, +} + +/// A context in the environment that cannot be read. +#[derive(Debug, thiserror::Error)] +pub enum ContextError { + /// A variable isn't UTF-8. + #[error("${name} is not valid")] + Variable { + /// Its name. + name: &'static str, + /// What is wrong. + source: env::VarError, + }, + /// `ORIGIN_REVISION` isn't a revision id. + #[error("$ORIGIN_REVISION is not a revision id: {0:?}")] + Revision(String), + /// `ORIGIN_REMOTE` isn't a remote. + #[error(transparent)] + Remote(#[from] RemoteError), +} diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 2902af6f..135ae308 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -98,6 +98,7 @@ use crate::conflict::Conflicts; use crate::index::{FindChangeError, FindError, Index}; use crate::oplog::{Actor, Effect, Move, Why}; use crate::output::FileDiff; +use crate::plugin::Context; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; use crate::remote::{Remote, RemoteError}; @@ -462,6 +463,21 @@ impl Workspace { }) } + /// What a plugin run in this working copy learns of it, once its draft + /// is recorded. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted, or the remote's URL + /// cannot be read. + pub fn plugin_context(&mut self) -> Result { + Ok(Context { + repository: self.store.root().to_owned(), + revision: self.refresh()?.id, + remote: Self::remote_url(&self.store)?, + }) + } + /// This node, with its key. fn node(&self) -> Result { Self::node_of(&self.config) diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index dc4e4e8d..a115dbeb 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -853,6 +853,54 @@ fn a_repository_is_one_working_copy_however_init_spells_it() { } } +#[test] +fn other_commands_run_plugins_from_the_path() { + let repo = Repo::new(); + repo.write("file", "edited\n"); + let plugins = tempfile::tempdir().unwrap(); + let plugin = plugins.path().join("origin-hello"); + fs::write( + &plugin, + "#!/bin/sh\necho \"$@\"\necho \"$ORIGIN_REPOSITORY $ORIGIN_REVISION $ORIGIN_REMOTE\"\nexit 7\n", + ) + .unwrap(); + fs::set_permissions(&plugin, fs::Permissions::from_mode(0o755)).unwrap(); + let run = |cwd: &std::path::Path, args: &[&str]| { + let mut path = std::ffi::OsString::from(plugins.path()); + path.push(":"); + path.push(common::path_with_plugins()); + repo.user() + .command(cwd, args) + .env("PATH", path) + .output() + .unwrap() + }; + + let output = run(repo.root(), &["hello", "--loud", "world"]); + assert_eq!(output.status.code(), Some(7), "the plugin's exit code"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let revision = repo.revision(); + assert_eq!( + stdout, + format!( + "--loud world\n{} {revision} \n", + // As the command finds it: macOS's temporary directory is a link. + fs::canonicalize(repo.path(".origin")).unwrap().display() + ), + "the working copy, snapshotted first, and no remote" + ); + assert!(repo.ok(&["status"]).ends_with("A file\n")); + + let outside = tempfile::tempdir().unwrap(); + let output = run(outside.path(), &["hello"]); + assert_eq!(String::from_utf8(output.stdout).unwrap(), "\n \n"); + let error = repo.fails(&["nosuch"]); + assert!( + error.contains("`nosuch` is not an origin command, and no `origin-nosuch` is on PATH"), + "{error}" + ); +} + #[test] fn a_move_marker_that_cannot_be_read_is_kept_and_stops_moves() { let repo = Repo::new(); diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 8c5dfeef..ab8fffbc 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -1,9 +1,12 @@ //! Helpers for the end-to-end tests, which run the real `origin` binary. +//! The tests of plugins, in other packages, include them too. // Each test binary uses its own subset of the helpers, and the others would // warn as unused in it. #![allow(dead_code)] +use std::env; +use std::ffi::OsString; use std::fs::{self, OpenOptions}; use std::io::{BufRead, BufReader}; use std::os::unix::fs::PermissionsExt; @@ -14,6 +17,29 @@ use std::sync::mpsc; use std::thread; use std::time::{Duration, Instant}; +/// The `origin` binary: this package's, or for a plugin's tests, the one +/// built beside the plugin's, in the target directory holding the tests. +pub fn origin() -> PathBuf { + if let Some(origin) = option_env!("CARGO_BIN_EXE_origin") { + return PathBuf::from(origin); + } + let exe = env::current_exe().unwrap(); + let origin = exe.parent().unwrap().parent().unwrap().join("origin"); + assert!( + origin.exists(), + "build `origin` first, such as with `cargo build --bin origin`" + ); + origin +} + +/// `$PATH`, starting with the directory holding `origin` and the plugins +/// built with it. +pub fn path_with_plugins() -> OsString { + let bin = origin().parent().unwrap().to_owned(); + let paths = env::var_os("PATH").unwrap_or_default(); + env::join_paths([bin].into_iter().chain(env::split_paths(&paths))).unwrap() +} + /// A user, with a configuration directory, and so a node key, of their /// own, and the token they send servers, if any. Clones share it. #[derive(Clone)] @@ -59,13 +85,15 @@ impl User { self.config.path() } - /// `origin` with `args`, run in `cwd` as this user. + /// `origin` with `args`, run in `cwd` as this user, with the plugins + /// built with it on `$PATH`. pub fn command(&self, cwd: &Path, args: &[&str]) -> Command { - let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + let mut command = Command::new(origin()); command .args(args) .current_dir(cwd) .env("ORIGIN_CONFIG_DIR", self.config()) + .env("PATH", path_with_plugins()) .env_remove("ORIGIN_TOKEN"); if let Some(token) = &self.token { command.env("ORIGIN_TOKEN", token); @@ -118,6 +146,11 @@ impl Repo { self.user.config() } + /// The repository's user. + pub fn user(&self) -> &User { + &self.user + } + /// Runs `origin` in `cwd` as the repository's user. pub fn run(&self, cwd: &Path, args: &[&str]) -> Output { self.command(cwd, args).output().unwrap() @@ -318,7 +351,7 @@ impl Server { ) .unwrap(); let origin = |args: &[&str]| { - let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + let mut command = Command::new(origin()); command.args(args).arg("--config").arg(&config); command }; @@ -386,7 +419,7 @@ impl Server { /// Signs a token for `principal` with `scope` with the server's key. pub fn issue_token(&self, principal: &str, scope: &[&str]) -> String { - let mut command = Command::new(env!("CARGO_BIN_EXE_origin")); + let mut command = Command::new(origin()); command .args(["token", "issue", "--as", principal, "--config"]) .arg(self.dir().join("origin-server.toml"));