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: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 [<rev>] # 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
Expand Down Expand Up @@ -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 <name> [--rev <rev>] [--inputs <path>...]
[--toolchain <cmd>] [--external] -- <command...>` runs a command as the
check `ci.<name>` 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
Expand Down
129 changes: 128 additions & 1 deletion apps/origin-ci/src/checks/mod.rs → apps/origin-ci/src/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<RepoPath>,
toolchain: Option<String>,
external: bool,
) -> Result<Self, InvalidName> {
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]
Expand Down Expand Up @@ -180,4 +219,92 @@ impl TryFrom<ChecksFile> 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");
}
}
77 changes: 0 additions & 77 deletions apps/origin-ci/src/checks/tests.rs

This file was deleted.

5 changes: 3 additions & 2 deletions apps/origin-ci/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
43 changes: 41 additions & 2 deletions apps/origin-ci/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.<name>`
/// 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>`.
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<RepoPath>,
/// A shell command whose output identifies the tools it runs with.
#[arg(long)]
toolchain: Option<String>,
/// 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<String>,
},
}

fn main() -> ExitCode {
Expand All @@ -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)?]))
}
}
}

Expand Down
33 changes: 29 additions & 4 deletions apps/origin-ci/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ pub struct Runner {
snapshots: Mutex<Vec<Arc<Snapshot>>>,
}

/// 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 {
Expand Down Expand Up @@ -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<Outcome, RunError> {
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<RecordId, RunError> {
let targets = self.remote.targets()?;
Expand Down Expand Up @@ -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<Outcome, RunError> {
let mut checkout = None;
let toolchain = match &check.toolchain {
Expand All @@ -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,
Expand Down
Loading