Skip to content

Commit 2bdf82a

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 7f6f1a3 commit 2bdf82a

9 files changed

Lines changed: 253 additions & 27 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

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
//! reads instead, such as `rust-toolchain.toml` in its `inputs`: then a
3939
//! new toolchain changes the inputs, and the check runs again.
4040
41+
use std::borrow::Cow;
4142
use std::collections::BTreeMap;
4243

4344
use origin_shared::{Digest, Inputs, InvalidName, Kind, RepoPath};
@@ -141,6 +142,45 @@ impl Checks {
141142
}
142143

143144
impl Check {
145+
/// Creates a check named `name` that is given rather than read from
146+
/// `checks.toml`. It runs `words`, each quoted for the shell, and reads
147+
/// `inputs`, or the whole snapshot if there are none.
148+
///
149+
/// # Errors
150+
///
151+
/// Fails if the name doesn't make a valid kind.
152+
pub fn adhoc(
153+
name: &str,
154+
words: &[String],
155+
inputs: Vec<RepoPath>,
156+
toolchain: Option<String>,
157+
external: bool,
158+
) -> Result<Self, InvalidName> {
159+
let words: Vec<_> = words.iter().map(|word| Self::quote(word)).collect();
160+
Ok(Self {
161+
kind: Checks::kind(name)?,
162+
command: words.join(" "),
163+
inputs: if inputs.is_empty() {
164+
vec![RepoPath::root()]
165+
} else {
166+
inputs
167+
},
168+
target_inputs: Vec::new(),
169+
toolchain,
170+
external,
171+
})
172+
}
173+
174+
/// Returns `word` quoted for the shell, or as it is if it needs no quotes.
175+
fn quote(word: &str) -> Cow<'_, str> {
176+
// Without `=`: a first word `A=1` would assign a variable.
177+
let plain = |byte: u8| byte.is_ascii_alphanumeric() || b"_-./:,+@%".contains(&byte);
178+
if !word.is_empty() && word.bytes().all(plain) {
179+
return Cow::Borrowed(word);
180+
}
181+
Cow::Owned(format!("'{}'", word.replace('\'', "'\\''")))
182+
}
183+
144184
/// Returns the inputs a result of the check declares it depended on,
145185
/// including the output of its toolchain command, if it has one.
146186
#[must_use]
@@ -275,4 +315,14 @@ mod tests {
275315
);
276316
assert_ne!(inputs, check("cargo test").inputs(b"rustc 1.100.0"));
277317
}
318+
319+
#[test]
320+
fn adhoc_checks_quote_their_words() {
321+
let words = ["A=1", "printf", "%s\\n", "a b", "it's", ""].map(String::from);
322+
let check = Check::adhoc("say", &words, Vec::new(), None, false).unwrap();
323+
assert_eq!(check.kind, Checks::kind("say").unwrap());
324+
assert_eq!(check.command, r"'A=1' printf '%s\n' 'a b' 'it'\''s' ''");
325+
assert_eq!(check.inputs, [RepoPath::root()], "the whole snapshot");
326+
assert_eq!(check.target_inputs, [], "no checks.toml");
327+
}
278328
}

‎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
@@ -72,6 +72,15 @@ pub struct Runner {
7272
snapshots: Mutex<Vec<Arc<Snapshot>>>,
7373
}
7474

75+
/// When a check runs.
76+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77+
enum Rerun {
78+
/// Only if no result by the issuer already covers the record.
79+
Uncovered,
80+
/// Always, because it was asked for.
81+
Always,
82+
}
83+
7584
/// What became of one check.
7685
#[derive(Clone, Debug, PartialEq, Eq)]
7786
pub enum Outcome {
@@ -195,10 +204,25 @@ impl Runner {
195204
external: check.external || foreign,
196205
..check.clone()
197206
})
198-
.map(|check| self.run(&snapshot, subject, &check, &statements))
207+
.map(|check| self.run(&snapshot, subject, &check, &statements, Rerun::Uncovered))
199208
.collect()
200209
}
201210

211+
/// Runs `check` on `subject`, the way [`Runner::check`] runs the checks of
212+
/// a `checks.toml`, for a check given rather than read from one. It always
213+
/// runs, even where a result by the issuer covers it, since it was asked
214+
/// for. The result supersedes the issuer's previous result of its kind.
215+
///
216+
/// # Errors
217+
///
218+
/// Fails if the subject has no snapshot, the command cannot be started,
219+
/// the toolchain command fails, or the remote refuses.
220+
pub fn exec(&self, subject: RecordId, check: &Check) -> Result<Outcome, RunError> {
221+
let snapshot = self.fetch_snapshot(subject)?;
222+
let statements = self.claims(subject)?;
223+
self.run(&snapshot, subject, check, &statements, Rerun::Always)
224+
}
225+
202226
/// Returns the acceptance at the tip of `target`.
203227
fn tip(&self, target: &TargetName) -> Result<RecordId, RunError> {
204228
let targets = self.remote.targets()?;
@@ -359,14 +383,15 @@ impl Runner {
359383
.collect()
360384
}
361385

362-
/// Runs `check` in a checkout of `snapshot`, unless one of `statements`
363-
/// about `subject` already covers it.
386+
/// Runs `check` in a checkout of `snapshot`. Skips it if `rerun` allows
387+
/// that and one of `statements` about `subject` already covers it.
364388
fn run(
365389
&self,
366390
snapshot: &Snapshot,
367391
subject: RecordId,
368392
check: &Check,
369393
statements: &[(Annotation, Statement)],
394+
rerun: Rerun,
370395
) -> Result<Outcome, RunError> {
371396
let mut checkout = None;
372397
let toolchain = match &check.toolchain {
@@ -382,7 +407,7 @@ impl Runner {
382407
let covering = statements.iter().find(|(_, claim)| {
383408
mine(claim) && !claim.withdraws() && claim.inputs.as_ref() == Some(&inputs)
384409
});
385-
if let Some((annotation, claim)) = covering {
410+
if let Some((annotation, claim)) = covering.filter(|_| rerun == Rerun::Uncovered) {
386411
return Ok(Outcome::Covered {
387412
kind: check.kind.clone(),
388413
verdict: claim.verdict,

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

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ use std::time::{Duration, Instant};
1111

1212
use common::Repo;
1313
use origin_platform::{Native, Processes};
14+
use origin_shared::{Digest, Inputs, RecordId};
15+
use origin_src::annotations::Annotations;
16+
use origin_src::store::Store;
1417

1518
/// Returns a `checks.toml` whose `test` check reads `src` (and, like every
1619
/// check, `checks.toml`), and appends a line to `log` each time it runs.
@@ -90,6 +93,107 @@ fn tool_mode_runs_checks_and_promotes_unchanged_results() {
9093
assert_eq!(fs::read_dir(runs).unwrap().count(), 0);
9194
}
9295

96+
/// Returns the inputs of the `kind` statement about `revision`, from the
97+
/// repository's records.
98+
fn inputs_of(repo: &Repo, revision: &str, kind: &str) -> Inputs {
99+
let store = Store::new(repo.path(".origin"), Native::default());
100+
let revision = RecordId::Revision(revision.parse().unwrap());
101+
let about = Annotations::open(&store).unwrap().about(revision).unwrap();
102+
let current = about
103+
.into_iter()
104+
.rev()
105+
.find(|annotation| annotation.statement.kind.as_str() == kind)
106+
.unwrap();
107+
current.statement.inputs.unwrap()
108+
}
109+
110+
#[test]
111+
fn exec_runs_a_command_as_a_check() {
112+
let repo = Repo::new();
113+
repo.write("src/lib.rs", "fn a() {}\n");
114+
repo.ok(&["describe", "First"]);
115+
let first = repo.revision();
116+
repo.ok(&["new"]);
117+
repo.write("src/lib.rs", "fn b() {}\n");
118+
let exec = |command: &[&str]| {
119+
let args = [
120+
&[
121+
"ci", "exec", "lint", "--rev", &first, "--inputs", "src", "--",
122+
],
123+
command,
124+
];
125+
let output = repo.run(repo.root(), &args.concat());
126+
let stdout = String::from_utf8(output.stdout).unwrap();
127+
(output.status.success(), stdout)
128+
};
129+
130+
// In a checkout of the revision, not of the files here.
131+
let reads = ["sh", "-c", "cat src/lib.rs; printf '%s\\n' \"$0\"", "a b"];
132+
let (passed, stdout) = exec(&reads);
133+
assert!(passed && stdout.starts_with("ci.lint pass in "), "{stdout}");
134+
let statements = repo.ok(&["statements", &first]);
135+
assert!(
136+
statements.contains("ci.lint pass by user:ada\n"),
137+
"{statements}"
138+
);
139+
assert!(statements.contains(" inputs: src\n"), "{statements}");
140+
assert!(
141+
statements.contains(" payload: fn a() {}\n"),
142+
"{statements}"
143+
);
144+
let definition = r#"sh -c 'cat src/lib.rs; printf '\''%s\n'\'' "$0"' 'a b'"#;
145+
let inputs = inputs_of(&repo, &first, "ci.lint");
146+
assert_eq!(inputs.definition, Digest::of(definition.as_bytes()));
147+
148+
// Asked again, it runs again; a failure supersedes the pass.
149+
assert!(exec(&reads).1.starts_with("ci.lint pass in "));
150+
let (passed, stdout) = exec(&["sh", "-c", "echo broken; exit 3"]);
151+
assert!(!passed, "{stdout}");
152+
assert!(stdout.starts_with("ci.lint fail in "), "{stdout}");
153+
assert!(stdout.ends_with("broken\n"), "its output: {stdout}");
154+
let statements = repo.ok(&["statements", &first]);
155+
assert_eq!(
156+
statements.matches(" (superseded by ").count(),
157+
2,
158+
"{statements}"
159+
);
160+
assert!(
161+
statements.contains("ci.lint fail by user:ada\n"),
162+
"{statements}"
163+
);
164+
165+
// Its inputs make it promotable where they're the same.
166+
repo.write("src/lib.rs", "fn a() {}\n");
167+
repo.ok(&["describe", "Same library"]);
168+
let promoted = repo.ok(&["promote"]);
169+
assert!(
170+
promoted.contains("Promoted ci.lint fail by user:ada"),
171+
"{promoted}"
172+
);
173+
}
174+
175+
#[test]
176+
fn a_failed_exec_wins_over_a_promoted_pass() {
177+
let repo = Repo::new();
178+
repo.require_tests();
179+
let exec = |command: &str| {
180+
let args = ["ci", "exec", "test", "--inputs", "src", "--", command];
181+
repo.run(repo.root(), &args).status.success()
182+
};
183+
repo.ok(&["new", "--on", "main", "Library"]);
184+
repo.write("src/lib.rs", "fn a() {}\n");
185+
assert!(exec("true"));
186+
assert!(repo.ok(&["land"]).contains(" on main #1\n"));
187+
188+
// The same `src` gets the pass promoted, then fails there.
189+
repo.ok(&["new", "--on", "main", "Docs"]);
190+
repo.write("docs.md", "docs\n");
191+
assert!(repo.ok(&["promote"]).contains("Promoted ci.test pass"));
192+
assert!(!exec("false"));
193+
let landing = repo.ok(&["land"]);
194+
assert!(landing.starts_with("The landing of change "), "{landing}");
195+
}
196+
93197
#[test]
94198
fn runs_replace_promotions_a_result_there_replaces() {
95199
let repo = Repo::new();

‎apps/origin-src/tests/cli.rs‎

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,26 +1285,10 @@ fn targets_fork_and_land_on_each_other() {
12851285
assert!(repo.ok(&["log", "main"]).contains("\n overhaul #1\n"));
12861286
}
12871287

1288-
/// Lands a policy that makes `main` require a passing `ci.test` result from
1289-
/// the `runners` group, which includes `ada`.
1290-
fn require_tests(repo: &Repo) {
1291-
repo.ok(&["new", "--on", "policy", "Require tests"]);
1292-
let policy = repo
1293-
.read("policy.toml")
1294-
.replace("# [groups]", "[groups]")
1295-
.replace(
1296-
"# runners = [\"node:ci-1\"]",
1297-
"runners = [\"node:ci-1\", \"user:ada\"]",
1298-
)
1299-
.replace("# require", "require");
1300-
repo.write("policy.toml", &policy);
1301-
assert!(repo.ok(&["land"]).contains(" on policy #1\n"));
1302-
}
1303-
13041288
#[test]
13051289
fn results_there_count_over_promoted_ones() {
13061290
let repo = Repo::new();
1307-
require_tests(&repo);
1291+
repo.require_tests();
13081292
repo.ok(&["new", "--on", "main", "Library"]);
13091293
repo.write("src/lib.rs", "fn a() {}\n");
13101294
repo.ok(&["annotate", "@", "ci.test", "--pass", "--inputs", "src"]);
@@ -1333,7 +1317,7 @@ fn results_there_count_over_promoted_ones() {
13331317
#[test]
13341318
fn landings_wait_for_the_evidence_policy_requires() {
13351319
let repo = Repo::new();
1336-
require_tests(&repo);
1320+
repo.require_tests();
13371321
assert!(
13381322
repo.ok(&["targets"])
13391323
.contains(" requires ci.test pass from group:runners\n")

0 commit comments

Comments
 (0)