Skip to content

Commit 48a4e84

Browse files
committed
feat(ci): run a command as a check with origin ci exec
A check that isn't in `checks.toml` yet, or a rerun with another command, should still give a proper result: one that declares its inputs, so it can be promoted. `origin ci exec <name> [--rev <rev>] [--inputs ...] [--toolchain <cmd>] [--external] -- <command...>` runs a command exactly as `ci run` runs a check of `checks.toml`: in a checkout of the revision, with its output as the payload, its exit status as the verdict and its words, quoted for the shell, as the definition. It always runs, even where a result covers it, superseding your previous result of that kind. `require_tests` moves to the shared end-to-end helpers, so the plugin's tests can use it.
1 parent 54808c1 commit 48a4e84

10 files changed

Lines changed: 327 additions & 105 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ origin whoami | permissions # who the remote thinks you are, and what yo
5858
origin token issue --scope "write src" [--ttl 1h] # a short-lived token for an agent
5959

6060
origin ci run [<rev>] # run the checks of checks.toml, and issue their results
61+
origin ci exec lint --inputs src -- cargo clippy # run a command as the check ci.lint, now
6162
```
6263

6364
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
162163
new tools with unchanged inputs don't stop old results from being
163164
promoted: pin the toolchain in an input, such as `rust-toolchain.toml`.
164165
`origin ci run` checks a revision of this repository as you, and fails if a
165-
check fails. Its checkouts
166+
check fails. `origin ci exec <name> [--rev <rev>] [--inputs <path>...]
167+
[--toolchain <cmd>] [--external] -- <command...>` runs a command as the
168+
check `ci.<name>` the same way, in a checkout of the revision, with the
169+
command as its definition: always, even if a result covers it, superseding
170+
your previous result of that kind. Its checkouts
166171
live in `$XDG_STATE_HOME/origin-ci/` (or `~/.local/state/`).
167172

168173
## Permissions
Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
//! `checks.toml` is itself always an input, read from where the checks are in
2121
//! force (see [`Defined`]), so results of different definitions never match.
2222
23+
use std::borrow::Cow;
2324
use std::collections::BTreeMap;
2425

2526
use origin_shared::{Digest, Inputs, InvalidName, Kind, RepoPath};
@@ -124,6 +125,44 @@ impl Checks {
124125
}
125126

126127
impl Check {
128+
/// Creates a check named `name` that is given rather than read from
129+
/// `checks.toml`. It runs `words`, each quoted for the shell, and reads
130+
/// `inputs`, or the whole snapshot if there are none.
131+
///
132+
/// # Errors
133+
///
134+
/// Fails if the name doesn't make a valid kind.
135+
pub fn adhoc(
136+
name: &str,
137+
words: &[String],
138+
inputs: Vec<RepoPath>,
139+
toolchain: Option<String>,
140+
external: bool,
141+
) -> Result<Self, InvalidName> {
142+
let words: Vec<_> = words.iter().map(|word| Self::quote(word)).collect();
143+
Ok(Self {
144+
kind: Checks::kind(name)?,
145+
command: words.join(" "),
146+
inputs: if inputs.is_empty() {
147+
vec![RepoPath::root()]
148+
} else {
149+
inputs
150+
},
151+
target_inputs: Vec::new(),
152+
toolchain,
153+
external,
154+
})
155+
}
156+
157+
/// Returns `word` quoted for the shell, or as it is if it needs no quotes.
158+
fn quote(word: &str) -> Cow<'_, str> {
159+
let plain = |byte: u8| byte.is_ascii_alphanumeric() || b"_-./:,+@%".contains(&byte);
160+
if !word.is_empty() && word.bytes().all(plain) {
161+
return Cow::Borrowed(word);
162+
}
163+
Cow::Owned(format!("'{}'", word.replace('\'', "'\\''")))
164+
}
165+
127166
/// Returns the inputs a result of the check declares it depended on,
128167
/// including the output of its toolchain command, if it has one.
129168
#[must_use]
@@ -180,4 +219,92 @@ impl TryFrom<ChecksFile> for Checks {
180219
}
181220

182221
#[cfg(test)]
183-
mod tests;
222+
mod tests {
223+
use std::slice;
224+
225+
use super::*;
226+
227+
const LINT_AND_LINKS: &str = "[checks.lint]\ncommand = \"cargo clippy\"\n\
228+
inputs = [\"src\", \"Cargo.toml\"]\ntoolchain = \"rustc -V\"\n\
229+
[checks.links]\ncommand = \"lychee docs\"\nexternal = true\n";
230+
231+
#[test]
232+
fn parses_checks_by_kind() {
233+
let checks = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap();
234+
let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap();
235+
assert_eq!(
236+
lint.inputs,
237+
[
238+
RepoPath::new("src").unwrap(),
239+
RepoPath::new("Cargo.toml").unwrap(),
240+
RepoPath::new("checks.toml").unwrap(),
241+
],
242+
"the checks are an input of each"
243+
);
244+
assert_eq!(lint.target_inputs, []);
245+
assert_eq!(lint.toolchain.as_deref(), Some("rustc -V"));
246+
let links = checks.get(&Kind::new("ci.links").unwrap()).unwrap();
247+
assert_eq!(Checks::kind("links").unwrap(), links.kind);
248+
assert_eq!(links.inputs, [RepoPath::root()], "the whole snapshot");
249+
assert!(links.external && links.inputs(b"").external);
250+
assert_eq!(checks.iter().count(), 2);
251+
252+
let parse = |text| Checks::parse(text, Defined::InSnapshot);
253+
assert!(
254+
parse("[checks.Lint]\ncommand = \"x\"\n").is_err(),
255+
"not a kind"
256+
);
257+
assert!(
258+
parse("[checks.lint]\ncmd = \"x\"\n").is_err(),
259+
"unknown key"
260+
);
261+
assert_eq!(parse("").unwrap(), Checks::default());
262+
}
263+
264+
#[test]
265+
fn checks_in_force_on_a_target_read_it_there() {
266+
let checks = Checks::parse(LINT_AND_LINKS, Defined::OnTarget).unwrap();
267+
let file = RepoPath::new(Checks::FILE).unwrap();
268+
for check in checks.iter() {
269+
assert_eq!(check.target_inputs, slice::from_ref(&file), "{check:?}");
270+
assert!(!check.inputs.contains(&file), "{check:?}");
271+
}
272+
let lint = checks.get(&Kind::new("ci.lint").unwrap()).unwrap();
273+
let in_snapshot = Checks::parse(LINT_AND_LINKS, Defined::InSnapshot).unwrap();
274+
let ran = lint.inputs(b"rustc 1.99.0");
275+
assert_eq!(ran.target_paths, [file]);
276+
assert_ne!(
277+
ran,
278+
in_snapshot.get(&lint.kind).unwrap().inputs(b"rustc 1.99.0")
279+
);
280+
}
281+
282+
#[test]
283+
fn inputs_follow_the_command_and_toolchain() {
284+
let check = |command: &str| Check {
285+
kind: Kind::new("ci.test").unwrap(),
286+
command: command.to_owned(),
287+
inputs: vec![RepoPath::new("src").unwrap()],
288+
target_inputs: Vec::new(),
289+
toolchain: None,
290+
external: false,
291+
};
292+
let inputs = check("cargo test").inputs(b"rustc 1.99.0");
293+
assert_eq!(inputs, check("cargo test").inputs(b"rustc 1.99.0"));
294+
assert_ne!(
295+
inputs,
296+
check("cargo test --release").inputs(b"rustc 1.99.0")
297+
);
298+
assert_ne!(inputs, check("cargo test").inputs(b"rustc 1.100.0"));
299+
}
300+
301+
#[test]
302+
fn adhoc_checks_quote_their_words() {
303+
let words = ["A=1", "printf", "%s\\n", "a b", "it's", ""].map(String::from);
304+
let check = Check::adhoc("say", &words, Vec::new(), None, false).unwrap();
305+
assert_eq!(check.kind, Checks::kind("say").unwrap());
306+
assert_eq!(check.command, r"'A=1' printf '%s\n' 'a b' 'it'\''s' ''");
307+
assert_eq!(check.inputs, [RepoPath::root()], "the whole snapshot");
308+
assert_eq!(check.target_inputs, [], "no checks.toml");
309+
}
310+
}

‎apps/origin-ci/src/checks/tests.rs‎

Lines changed: 0 additions & 77 deletions
This file was deleted.

‎apps/origin-ci/src/lib.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
//! landing queue takes as evidence.
44
//!
55
//! As a tool, `origin ci run` checks a revision of the repository it runs
6-
//! in, as the user. It talks to origin only through the public API: the
7-
//! SDK over HTTP, or for a repository on a local path, the same service
6+
//! in, as the user, and `origin ci exec` runs a given command as a check
7+
//! the same way. It talks to origin only through the public API: the SDK
8+
//! over HTTP, or for a repository on a local path, the same service
89
//! in-process.
910
1011
pub mod checks;

‎apps/origin-ci/src/main.rs‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@ use std::process::ExitCode;
44

55
use anyhow::{Context as _, Result, bail};
66
use clap::{Parser, Subcommand};
7+
use origin_ci::checks::Check;
78
use origin_ci::runner::{Outcome, Runner};
89
use origin_ci::state::State;
910
use origin_shared::api::At;
10-
use origin_shared::{ChangeId, RecordId, RevisionId};
11+
use origin_shared::{ChangeId, RecordId, RepoPath, RevisionId};
1112
use origin_src::config::UserConfig;
1213
use origin_src::output;
1314
use origin_src::plugin::Context;
1415
use origin_src::remote::{Remote, RemoteUrl};
1516

16-
/// Run the checks of `checks.toml` and issue their results.
17+
/// Run the checks of `checks.toml`, or a command as a check, and issue
18+
/// their results.
1719
#[derive(Debug, Parser)]
1820
#[command(name = "origin ci", version)]
1921
struct Cli {
@@ -33,6 +35,31 @@ enum Command {
3335
#[arg(default_value = "@")]
3436
rev: String,
3537
},
38+
/// Run a command as a check of a revision, the way `run` runs the checks
39+
/// of `checks.toml`: in a checkout of the revision, issuing a `ci.<name>`
40+
/// result as you that supersedes your previous one. Runs even if a result
41+
/// already covers it. Fails if the check fails.
42+
Exec {
43+
/// The check's name: its results are of the kind `ci.<name>`.
44+
name: String,
45+
/// The revision, as for `run`.
46+
#[arg(long, default_value = "@")]
47+
rev: String,
48+
/// The files and directories the check reads: the whole snapshot by
49+
/// default. Its result is promoted to revisions where they are the same.
50+
#[arg(long, num_args = 1..)]
51+
inputs: Vec<RepoPath>,
52+
/// A shell command whose output identifies the tools it runs with.
53+
#[arg(long)]
54+
toolchain: Option<String>,
55+
/// The check also reads something outside the snapshot, such as the
56+
/// network, so its result is never promoted.
57+
#[arg(long)]
58+
external: bool,
59+
/// The command, after `--`. Its words are quoted for `sh -c`.
60+
#[arg(last = true, required = true)]
61+
command: Vec<String>,
62+
},
3663
}
3764

3865
fn main() -> ExitCode {
@@ -56,6 +83,18 @@ impl Cli {
5683
let outcomes = runner.check(subject, &At::Record(subject), None)?;
5784
Ok(Self::report(&outcomes))
5885
}
86+
Command::Exec {
87+
name,
88+
rev,
89+
inputs,
90+
toolchain,
91+
external,
92+
command,
93+
} => {
94+
let (runner, subject) = Self::here(context.as_ref(), &config, "exec", &rev)?;
95+
let check = Check::adhoc(&name, &command, inputs, toolchain, external)?;
96+
Ok(Self::report(&[runner.exec(subject, &check)?]))
97+
}
5998
}
6099
}
61100

‎apps/origin-ci/src/runner.rs‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ pub struct Runner {
4545
snapshots: Mutex<Vec<Arc<Snapshot>>>,
4646
}
4747

48+
/// When a check runs.
49+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50+
enum Rerun {
51+
/// Only if no result by the issuer already covers the record.
52+
Uncovered,
53+
/// Always, because it was asked for.
54+
Always,
55+
}
56+
4857
/// What became of one check.
4958
#[derive(Clone, Debug, PartialEq, Eq)]
5059
pub enum Outcome {
@@ -166,10 +175,25 @@ impl Runner {
166175
external: check.external || foreign,
167176
..check.clone()
168177
})
169-
.map(|check| self.run(&snapshot, subject, &check, &statements))
178+
.map(|check| self.run(&snapshot, subject, &check, &statements, Rerun::Uncovered))
170179
.collect()
171180
}
172181

182+
/// Runs `check` on `subject`, the way [`Runner::check`] runs the checks of
183+
/// a `checks.toml`, for a check given rather than read from one. It always
184+
/// runs, even where a result by the issuer covers it, since it was asked
185+
/// for. The result supersedes the issuer's previous result of its kind.
186+
///
187+
/// # Errors
188+
///
189+
/// Fails if the subject has no snapshot, the command cannot be started,
190+
/// the toolchain command fails, or the remote refuses.
191+
pub fn exec(&self, subject: RecordId, check: &Check) -> Result<Outcome, RunError> {
192+
let snapshot = self.fetch_snapshot(subject)?;
193+
let statements = self.claims(subject)?;
194+
self.run(&snapshot, subject, check, &statements, Rerun::Always)
195+
}
196+
173197
/// Returns the acceptance at the tip of `target`.
174198
fn tip(&self, target: &TargetName) -> Result<RecordId, RunError> {
175199
let targets = self.remote.targets()?;
@@ -330,14 +354,15 @@ impl Runner {
330354
.collect()
331355
}
332356

333-
/// Runs `check` in a checkout of `snapshot`, unless one of `statements`
334-
/// about `subject` already covers it.
357+
/// Runs `check` in a checkout of `snapshot`. Skips it if `rerun` allows
358+
/// that and one of `statements` about `subject` already covers it.
335359
fn run(
336360
&self,
337361
snapshot: &Snapshot,
338362
subject: RecordId,
339363
check: &Check,
340364
statements: &[(Annotation, Statement)],
365+
rerun: Rerun,
341366
) -> Result<Outcome, RunError> {
342367
let mut checkout = None;
343368
let toolchain = match &check.toolchain {
@@ -352,7 +377,7 @@ impl Runner {
352377
let covering = statements.iter().find(|(_, claim)| {
353378
mine(claim) && !claim.withdraws() && claim.inputs.as_ref() == Some(&inputs)
354379
});
355-
if let Some((annotation, claim)) = covering {
380+
if let Some((annotation, claim)) = covering.filter(|_| rerun == Rerun::Uncovered) {
356381
return Ok(Outcome::Covered {
357382
kind: check.kind.clone(),
358383
verdict: claim.verdict,

0 commit comments

Comments
 (0)