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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` as
`origin-<name>` 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`).

Expand Down Expand Up @@ -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

Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ send each server under `[tokens]`, by its URL
(`"http://127.0.0.1:7878" = "<token>"`), or in `$ORIGIN_TOKEN`. See
[the design](docs/design.md) for the model.

## Plugins

`origin <name>` runs `origin-<name>` from `PATH` when `<name>` 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
Expand Down
20 changes: 18 additions & 2 deletions apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::convert::Infallible;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use std::str::FromStr;

Expand All @@ -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)]
Expand Down Expand Up @@ -62,6 +64,10 @@ enum Command {
Token(TokenCommand),
#[command(flatten)]
Workspace(WorkspaceCommand),
/// Any other command runs the plugin `origin-<command>` from `PATH`,
/// such as `origin ci` for `origin-ci`.
#[command(external_subcommand)]
Plugin(Vec<OsString>),
}

#[derive(Debug, Subcommand)]
Expand Down Expand Up @@ -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,
Expand All @@ -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)?;
Expand Down
1 change: 1 addition & 0 deletions apps/origin-src/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
152 changes: 152 additions & 0 deletions apps/origin-src/src/plugin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//! Plugins: `origin <name>` runs `origin-<name>` from `PATH` when `<name>`
//! 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<RemoteUrl>,
}

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<Option<Self>, 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<OsString>);

impl Plugin {
/// Replaces this process with the plugin, giving it `context`.
///
/// # Errors
///
/// Fails if no `origin-<name>` is on `PATH`, or it cannot be run.
pub fn exec(self, context: Option<&Context>) -> Result<Infallible, PluginError> {
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),
}
16 changes: 16 additions & 0 deletions apps/origin-src/src/workspace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Context, WorkspaceError> {
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<Node, WorkspaceError> {
Self::node_of(&self.config)
Expand Down
48 changes: 48 additions & 0 deletions apps/origin-src/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading