diff --git a/README.md b/README.md index 8ffeef72..e8d919d6 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ origin whoami | permissions # who the remote thinks you are, and what yo origin token issue --scope "write src" [--ttl 1h] # a short-lived token for an agent origin ci run [] # run the checks of checks.toml, and issue their results +origin ci exec lint --inputs src -- cargo clippy # run a command as the check ci.lint, now ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -162,7 +163,11 @@ landing queue promotes results without running the toolchain command, so new tools with unchanged inputs don't stop old results from being promoted: pin the toolchain in an input, such as `rust-toolchain.toml`. `origin ci run` checks a revision of this repository as you, and fails if a -check fails. Its checkouts +check fails. `origin ci exec [--rev ] [--inputs ...] +[--toolchain ] [--external] -- ` runs a command as the +check `ci.` the same way, in a checkout of the revision, with the +command as its definition: always, even if a result covers it, superseding +your previous result of that kind. Its checkouts live in `$XDG_STATE_HOME/origin-ci/` (or `~/.local/state/`). ## Permissions diff --git a/apps/origin-ci/src/checks/mod.rs b/apps/origin-ci/src/checks.rs similarity index 55% rename from apps/origin-ci/src/checks/mod.rs rename to apps/origin-ci/src/checks.rs index 560f751a..2b807d77 100644 --- a/apps/origin-ci/src/checks/mod.rs +++ b/apps/origin-ci/src/checks.rs @@ -20,6 +20,7 @@ //! `checks.toml` is itself always an input, read from where the checks are in //! force (see [`Defined`]), so results of different definitions never match. +use std::borrow::Cow; use std::collections::BTreeMap; use origin_shared::{Digest, Inputs, InvalidName, Kind, RepoPath}; @@ -124,6 +125,44 @@ impl Checks { } impl Check { + /// Creates a check named `name` that is given rather than read from + /// `checks.toml`. It runs `words`, each quoted for the shell, and reads + /// `inputs`, or the whole snapshot if there are none. + /// + /// # Errors + /// + /// Fails if the name doesn't make a valid kind. + pub fn adhoc( + name: &str, + words: &[String], + inputs: Vec, + toolchain: Option, + external: bool, + ) -> Result { + let words: Vec<_> = words.iter().map(|word| Self::quote(word)).collect(); + Ok(Self { + kind: Checks::kind(name)?, + command: words.join(" "), + inputs: if inputs.is_empty() { + vec![RepoPath::root()] + } else { + inputs + }, + target_inputs: Vec::new(), + toolchain, + external, + }) + } + + /// Returns `word` quoted for the shell, or as it is if it needs no quotes. + fn quote(word: &str) -> Cow<'_, str> { + let plain = |byte: u8| byte.is_ascii_alphanumeric() || b"_-./:,+@%".contains(&byte); + if !word.is_empty() && word.bytes().all(plain) { + return Cow::Borrowed(word); + } + Cow::Owned(format!("'{}'", word.replace('\'', "'\\''"))) + } + /// Returns the inputs a result of the check declares it depended on, /// including the output of its toolchain command, if it has one. #[must_use] @@ -180,4 +219,92 @@ impl TryFrom for Checks { } #[cfg(test)] -mod tests; +mod tests { + use std::slice; + + use super::*; + + const LINT_AND_LINKS: &str = "[checks.lint]\ncommand = \"cargo clippy\"\n\ + inputs = [\"src\", \"Cargo.toml\"]\ntoolchain = \"rustc -V\"\n\ + [checks.links]\ncommand = \"lychee docs\"\nexternal = true\n"; + + #[test] + fn parses_checks_by_kind() { + let checks = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap(); + let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap(); + assert_eq!( + lint.inputs, + [ + RepoPath::new("src").unwrap(), + RepoPath::new("Cargo.toml").unwrap(), + RepoPath::new("checks.toml").unwrap(), + ], + "the checks are an input of each" + ); + assert_eq!(lint.target_inputs, []); + assert_eq!(lint.toolchain.as_deref(), Some("rustc -V")); + let links = checks.get(&Kind::new("ci.links").unwrap()).unwrap(); + assert_eq!(Checks::kind("links").unwrap(), links.kind); + assert_eq!(links.inputs, [RepoPath::root()], "the whole snapshot"); + assert!(links.external && links.inputs(b"").external); + assert_eq!(checks.iter().count(), 2); + + let parse = |text| Checks::parse(text, Defined::InSnapshot); + assert!( + parse("[checks.Lint]\ncommand = \"x\"\n").is_err(), + "not a kind" + ); + assert!( + parse("[checks.lint]\ncmd = \"x\"\n").is_err(), + "unknown key" + ); + assert_eq!(parse("").unwrap(), Checks::default()); + } + + #[test] + fn checks_in_force_on_a_target_read_it_there() { + let checks = Checks::parse(LINT_AND_LINKS, Defined::OnTarget).unwrap(); + let file = RepoPath::new(Checks::FILE).unwrap(); + for check in checks.iter() { + assert_eq!(check.target_inputs, slice::from_ref(&file), "{check:?}"); + assert!(!check.inputs.contains(&file), "{check:?}"); + } + let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap(); + let in_snapshot = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap(); + let ran = lint.inputs(b"rustc 1.99.0"); + assert_eq!(ran.target_paths, [file]); + assert_ne!( + ran, + in_snapshot.get(&lint.kind).unwrap().inputs(b"rustc 1.99.0") + ); + } + + #[test] + fn inputs_follow_the_command_and_toolchain() { + let check = |command: &str| Check { + kind: Kind::new("ci.test").unwrap(), + command: command.to_owned(), + inputs: vec![RepoPath::new("src").unwrap()], + target_inputs: Vec::new(), + toolchain: None, + external: false, + }; + let inputs = check("cargo test").inputs(b"rustc 1.99.0"); + assert_eq!(inputs, check("cargo test").inputs(b"rustc 1.99.0")); + assert_ne!( + inputs, + check("cargo test --release").inputs(b"rustc 1.99.0") + ); + assert_ne!(inputs, check("cargo test").inputs(b"rustc 1.100.0")); + } + + #[test] + fn adhoc_checks_quote_their_words() { + let words = ["A=1", "printf", "%s\\n", "a b", "it's", ""].map(String::from); + let check = Check::adhoc("say", &words, Vec::new(), None, false).unwrap(); + assert_eq!(check.kind, Checks::kind("say").unwrap()); + assert_eq!(check.command, r"'A=1' printf '%s\n' 'a b' 'it'\''s' ''"); + assert_eq!(check.inputs, [RepoPath::root()], "the whole snapshot"); + assert_eq!(check.target_inputs, [], "no checks.toml"); + } +} diff --git a/apps/origin-ci/src/checks/tests.rs b/apps/origin-ci/src/checks/tests.rs deleted file mode 100644 index f6e16a83..00000000 --- a/apps/origin-ci/src/checks/tests.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::slice; - -use super::*; - -const LINT_AND_LINKS: &str = "[checks.lint]\ncommand = \"cargo clippy\"\n\ - inputs = [\"src\", \"Cargo.toml\"]\ntoolchain = \"rustc -V\"\n\ - [checks.links]\ncommand = \"lychee docs\"\nexternal = true\n"; - -#[test] -fn parses_checks_by_kind() { - let checks = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap(); - let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap(); - assert_eq!( - lint.inputs, - [ - RepoPath::new("src").unwrap(), - RepoPath::new("Cargo.toml").unwrap(), - RepoPath::new("checks.toml").unwrap(), - ], - "the checks are an input of each" - ); - assert_eq!(lint.target_inputs, []); - assert_eq!(lint.toolchain.as_deref(), Some("rustc -V")); - let links = checks.get(&Kind::new("ci.links").unwrap()).unwrap(); - assert_eq!(Checks::kind("links").unwrap(), links.kind); - assert_eq!(links.inputs, [RepoPath::root()], "the whole snapshot"); - assert!(links.external && links.inputs(b"").external); - assert_eq!(checks.iter().count(), 2); - - let parse = |text| Checks::parse(text, Defined::InSnapshot); - assert!( - parse("[checks.Lint]\ncommand = \"x\"\n").is_err(), - "not a kind" - ); - assert!( - parse("[checks.lint]\ncmd = \"x\"\n").is_err(), - "unknown key" - ); - assert_eq!(parse("").unwrap(), Checks::default()); -} - -#[test] -fn checks_in_force_on_a_target_read_it_there() { - let checks = Checks::parse(LINT_AND_LINKS, Defined::OnTarget).unwrap(); - let file = RepoPath::new(Checks::FILE).unwrap(); - for check in checks.iter() { - assert_eq!(check.target_inputs, slice::from_ref(&file), "{check:?}"); - assert!(!check.inputs.contains(&file), "{check:?}"); - } - let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap(); - let in_snapshot = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap(); - let ran = lint.inputs(b"rustc 1.99.0"); - assert_eq!(ran.target_paths, [file]); - assert_ne!( - ran, - in_snapshot.get(&lint.kind).unwrap().inputs(b"rustc 1.99.0") - ); -} - -#[test] -fn inputs_follow_the_command_and_toolchain() { - let check = |command: &str| Check { - kind: Kind::new("ci.test").unwrap(), - command: command.to_owned(), - inputs: vec![RepoPath::new("src").unwrap()], - target_inputs: Vec::new(), - toolchain: None, - external: false, - }; - let inputs = check("cargo test").inputs(b"rustc 1.99.0"); - assert_eq!(inputs, check("cargo test").inputs(b"rustc 1.99.0")); - assert_ne!( - inputs, - check("cargo test --release").inputs(b"rustc 1.99.0") - ); - assert_ne!(inputs, check("cargo test").inputs(b"rustc 1.100.0")); -} diff --git a/apps/origin-ci/src/lib.rs b/apps/origin-ci/src/lib.rs index 75e005fe..5f4edd9f 100644 --- a/apps/origin-ci/src/lib.rs +++ b/apps/origin-ci/src/lib.rs @@ -3,8 +3,9 @@ //! landing queue takes as evidence. //! //! As a tool, `origin ci run` checks a revision of the repository it runs -//! in, as the user. It talks to origin only through the public API: the -//! SDK over HTTP, or for a repository on a local path, the same service +//! in, as the user, and `origin ci exec` runs a given command as a check +//! the same way. It talks to origin only through the public API: the SDK +//! over HTTP, or for a repository on a local path, the same service //! in-process. pub mod checks; diff --git a/apps/origin-ci/src/main.rs b/apps/origin-ci/src/main.rs index 5de0c69f..881885c1 100644 --- a/apps/origin-ci/src/main.rs +++ b/apps/origin-ci/src/main.rs @@ -4,16 +4,18 @@ use std::process::ExitCode; use anyhow::{Context as _, Result, bail}; use clap::{Parser, Subcommand}; +use origin_ci::checks::Check; use origin_ci::runner::{Outcome, Runner}; use origin_ci::state::State; use origin_shared::api::At; -use origin_shared::{ChangeId, RecordId, RevisionId}; +use origin_shared::{ChangeId, RecordId, RepoPath, RevisionId}; use origin_src::config::UserConfig; use origin_src::output; use origin_src::plugin::Context; use origin_src::remote::{Remote, RemoteUrl}; -/// Run the checks of `checks.toml` and issue their results. +/// Run the checks of `checks.toml`, or a command as a check, and issue +/// their results. #[derive(Debug, Parser)] #[command(name = "origin ci", version)] struct Cli { @@ -33,6 +35,31 @@ enum Command { #[arg(default_value = "@")] rev: String, }, + /// Run a command as a check of a revision, the way `run` runs the checks + /// of `checks.toml`: in a checkout of the revision, issuing a `ci.` + /// result as you that supersedes your previous one. Runs even if a result + /// already covers it. Fails if the check fails. + Exec { + /// The check's name: its results are of the kind `ci.`. + name: String, + /// The revision, as for `run`. + #[arg(long, default_value = "@")] + rev: String, + /// The files and directories the check reads: the whole snapshot by + /// default. Its result is promoted to revisions where they are the same. + #[arg(long, num_args = 1..)] + inputs: Vec, + /// A shell command whose output identifies the tools it runs with. + #[arg(long)] + toolchain: Option, + /// The check also reads something outside the snapshot, such as the + /// network, so its result is never promoted. + #[arg(long)] + external: bool, + /// The command, after `--`. Its words are quoted for `sh -c`. + #[arg(last = true, required = true)] + command: Vec, + }, } fn main() -> ExitCode { @@ -56,6 +83,18 @@ impl Cli { let outcomes = runner.check(subject, &At::Record(subject), None)?; Ok(Self::report(&outcomes)) } + Command::Exec { + name, + rev, + inputs, + toolchain, + external, + command, + } => { + let (runner, subject) = Self::here(context.as_ref(), &config, "exec", &rev)?; + let check = Check::adhoc(&name, &command, inputs, toolchain, external)?; + Ok(Self::report(&[runner.exec(subject, &check)?])) + } } } diff --git a/apps/origin-ci/src/runner.rs b/apps/origin-ci/src/runner.rs index f37a874c..abfd166a 100644 --- a/apps/origin-ci/src/runner.rs +++ b/apps/origin-ci/src/runner.rs @@ -45,6 +45,15 @@ pub struct Runner { snapshots: Mutex>>, } +/// When a check runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Rerun { + /// Only if no result by the issuer already covers the record. + Uncovered, + /// Always, because it was asked for. + Always, +} + /// What became of one check. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Outcome { @@ -166,10 +175,25 @@ impl Runner { external: check.external || foreign, ..check.clone() }) - .map(|check| self.run(&snapshot, subject, &check, &statements)) + .map(|check| self.run(&snapshot, subject, &check, &statements, Rerun::Uncovered)) .collect() } + /// Runs `check` on `subject`, the way [`Runner::check`] runs the checks of + /// a `checks.toml`, for a check given rather than read from one. It always + /// runs, even where a result by the issuer covers it, since it was asked + /// for. The result supersedes the issuer's previous result of its kind. + /// + /// # Errors + /// + /// Fails if the subject has no snapshot, the command cannot be started, + /// the toolchain command fails, or the remote refuses. + pub fn exec(&self, subject: RecordId, check: &Check) -> Result { + let snapshot = self.fetch_snapshot(subject)?; + let statements = self.claims(subject)?; + self.run(&snapshot, subject, check, &statements, Rerun::Always) + } + /// Returns the acceptance at the tip of `target`. fn tip(&self, target: &TargetName) -> Result { let targets = self.remote.targets()?; @@ -330,14 +354,15 @@ impl Runner { .collect() } - /// Runs `check` in a checkout of `snapshot`, unless one of `statements` - /// about `subject` already covers it. + /// Runs `check` in a checkout of `snapshot`. Skips it if `rerun` allows + /// that and one of `statements` about `subject` already covers it. fn run( &self, snapshot: &Snapshot, subject: RecordId, check: &Check, statements: &[(Annotation, Statement)], + rerun: Rerun, ) -> Result { let mut checkout = None; let toolchain = match &check.toolchain { @@ -352,7 +377,7 @@ impl Runner { let covering = statements.iter().find(|(_, claim)| { mine(claim) && !claim.withdraws() && claim.inputs.as_ref() == Some(&inputs) }); - if let Some((annotation, claim)) = covering { + if let Some((annotation, claim)) = covering.filter(|_| rerun == Rerun::Uncovered) { return Ok(Outcome::Covered { kind: check.kind.clone(), verdict: claim.verdict, diff --git a/apps/origin-ci/tests/ci.rs b/apps/origin-ci/tests/ci.rs index bad92eb5..3f35c872 100644 --- a/apps/origin-ci/tests/ci.rs +++ b/apps/origin-ci/tests/ci.rs @@ -11,6 +11,9 @@ use std::time::{Duration, Instant}; use common::Repo; use origin_platform::{Native, Processes}; +use origin_shared::{Digest, Inputs, RecordId}; +use origin_src::annotations::Annotations; +use origin_src::store::Store; /// Returns a `checks.toml` whose `test` check reads `src` (and, like every /// check, `checks.toml`), and appends a line to `log` each time it runs. @@ -85,6 +88,103 @@ fn tool_mode_runs_checks_and_promotes_unchanged_results() { assert_eq!(fs::read_dir(runs).unwrap().count(), 0); } +/// Returns the inputs of the `kind` statement about `revision`, from the +/// repository's records. +fn inputs_of(repo: &Repo, revision: &str, kind: &str) -> Inputs { + let store = Store::new(repo.path(".origin"), Native::default()); + let revision = RecordId::Revision(revision.parse().unwrap()); + let about = Annotations::open(&store).unwrap().about(revision).unwrap(); + let current = about + .into_iter() + .rev() + .find(|annotation| annotation.statement.kind.as_str() == kind) + .unwrap(); + current.statement.inputs.unwrap() +} + +#[test] +fn exec_runs_a_command_as_a_check() { + let repo = Repo::new(); + repo.write("src/lib.rs", "fn a() {}\n"); + repo.ok(&["describe", "First"]); + let first = repo.revision(); + repo.ok(&["new"]); + repo.write("src/lib.rs", "fn b() {}\n"); + let exec = |command: &[&str]| { + let args = [ + &[ + "ci", "exec", "lint", "--rev", &first, "--inputs", "src", "--", + ], + command, + ]; + let output = repo.run(repo.root(), &args.concat()); + let stdout = String::from_utf8(output.stdout).unwrap(); + (output.status.success(), stdout) + }; + + let reads = ["sh", "-c", "cat src/lib.rs; printf '%s\\n' \"$0\"", "a b"]; + let (passed, stdout) = exec(&reads); + assert!(passed && stdout.starts_with("ci.lint pass in "), "{stdout}"); + let statements = repo.ok(&["statements", &first]); + assert!( + statements.contains("ci.lint pass by user:ada\n"), + "{statements}" + ); + assert!(statements.contains(" inputs: src\n"), "{statements}"); + assert!( + statements.contains(" payload: fn a() {}\n"), + "{statements}" + ); + let definition = r#"sh -c 'cat src/lib.rs; printf '\''%s\n'\'' "$0"' 'a b'"#; + let inputs = inputs_of(&repo, &first, "ci.lint"); + assert_eq!(inputs.definition, Digest::of(definition.as_bytes())); + + assert!(exec(&reads).1.starts_with("ci.lint pass in ")); + let (passed, stdout) = exec(&["sh", "-c", "echo broken; exit 3"]); + assert!(!passed, "{stdout}"); + assert!(stdout.starts_with("ci.lint fail in "), "{stdout}"); + assert!(stdout.ends_with("broken\n"), "its output: {stdout}"); + let statements = repo.ok(&["statements", &first]); + assert_eq!( + statements.matches(" (superseded by ").count(), + 2, + "{statements}" + ); + assert!( + statements.contains("ci.lint fail by user:ada\n"), + "{statements}" + ); + + repo.write("src/lib.rs", "fn a() {}\n"); + repo.ok(&["describe", "Same library"]); + let promoted = repo.ok(&["promote"]); + assert!( + promoted.contains("Promoted ci.lint fail by user:ada"), + "{promoted}" + ); +} + +#[test] +fn a_failed_exec_wins_over_a_promoted_pass() { + let repo = Repo::new(); + repo.require_tests(); + let exec = |command: &str| { + let args = ["ci", "exec", "test", "--inputs", "src", "--", command]; + repo.run(repo.root(), &args).status.success() + }; + repo.ok(&["new", "--on", "main", "Library"]); + repo.write("src/lib.rs", "fn a() {}\n"); + assert!(exec("true")); + assert!(repo.ok(&["land"]).contains(" on main #1\n")); + + repo.ok(&["new", "--on", "main", "Docs"]); + repo.write("docs.md", "docs\n"); + assert!(repo.ok(&["promote"]).contains("Promoted ci.test pass")); + assert!(!exec("false")); + let landing = repo.ok(&["land"]); + assert!(landing.starts_with("The landing of change "), "{landing}"); +} + #[test] fn runs_replace_promotions_a_result_there_replaces() { let repo = Repo::new(); diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 1f50d6e2..b8d854c8 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -1282,26 +1282,10 @@ fn targets_fork_and_land_on_each_other() { assert!(repo.ok(&["log", "main"]).contains("\n overhaul #1\n")); } -/// Lands a policy that makes `main` require a passing `ci.test` result from -/// the `runners` group, which includes `ada`. -fn require_tests(repo: &Repo) { - repo.ok(&["new", "--on", "policy", "Require tests"]); - let policy = repo - .read("policy.toml") - .replace("# [groups]", "[groups]") - .replace( - "# runners = [\"node:ci-1\"]", - "runners = [\"node:ci-1\", \"user:ada\"]", - ) - .replace("# require", "require"); - repo.write("policy.toml", &policy); - assert!(repo.ok(&["land"]).contains(" on policy #1\n")); -} - #[test] fn results_there_count_over_promoted_ones() { let repo = Repo::new(); - require_tests(&repo); + repo.require_tests(); repo.ok(&["new", "--on", "main", "Library"]); repo.write("src/lib.rs", "fn a() {}\n"); repo.ok(&["annotate", "@", "ci.test", "--pass", "--inputs", "src"]); @@ -1330,7 +1314,7 @@ fn results_there_count_over_promoted_ones() { #[test] fn landings_wait_for_the_evidence_policy_requires() { let repo = Repo::new(); - require_tests(&repo); + repo.require_tests(); assert!( repo.ok(&["targets"]) .contains(" requires ci.test pass from group:runners\n") diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 4f5577ce..642de404 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -260,6 +260,22 @@ impl Repo { change.split(' ').next().unwrap().to_owned() } + /// Lands a policy that makes `main` require a passing `ci.test` result from + /// the `runners` group, which includes `ada`. + pub fn require_tests(&self) { + self.ok(&["new", "--on", "policy", "Require tests"]); + let policy = self + .read("policy.toml") + .replace("# [groups]", "[groups]") + .replace( + "# runners = [\"node:ci-1\"]", + "runners = [\"node:ci-1\", \"user:ada\"]", + ) + .replace("# require", "require"); + self.write("policy.toml", &policy); + assert!(self.ok(&["land"]).contains(" on policy #1\n")); + } + /// Creates a workspace at `path` and returns its change. pub fn workspace(&self, path: &Path, args: &[&str]) -> String { let path = path.to_str().unwrap(); diff --git a/docs/design.md b/docs/design.md index 261623ee..23b484ca 100644 --- a/docs/design.md +++ b/docs/design.md @@ -586,6 +586,8 @@ plugin can do nothing the API can't, which keeps the API complete. Official plugins live in `apps/origin-`. The first is `origin-ci`: - **Tool mode:** `origin ci run []` checks a revision as the user. + `origin ci exec [--rev ] -- ` runs a command as + the check `ci.` the same way, even if a result covers it. - **Worker mode:** `origin ci worker --remote ` answers `check.requested` with a token that can read the repository and annotate `ci.*`. It reconciles the waiting landings at start, every minute and after an