Watch
0
0
Fork
You've already forked hyperhive
0

hive-forge: ci-rerun takes repeatable --input key=value for workflow dispatch

The dispatch goes out as a raw API POST so a forge rejection of an input
reaches the caller with its response body.
This commit is contained in:
atlas 2026-11-19 10:26:32 +01:00 • committed by mara
commit 439cb28c8c
3 changed files with 378 additions and 19 deletions

View file

@ -212,6 +212,31 @@ impl Client {
})
}
/// POST a JSON body to `/api/v1<path>` and discard a 2xx response body.
/// Raw instead of through `forgejo-api` for endpoints where that crate
/// maps every non-2xx status except `404` to a bare "unexpected status
/// code", dropping the forge's explanation: here a non-2xx surfaces as a
/// [`WebStatusError`] carrying the response body. `path` starts with `/`.
///
/// # Errors
/// Returns an error on transport failure or a non-2xx response (body
/// included).
pub fn post_api_json<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
let url = format!("{}/api/v1{path}", self.base);
let resp = self
.web
.post(&url)
.json(body)
.timeout(JSON_TIMEOUT)
.send()
.map_err(|e| {
let ctx = http_context("POST", &e, JSON_TIMEOUT);
anyhow::Error::new(e).context(ctx)
})?;
check_status(resp, &format!("POST {url}"))?;
Ok(())
}
/// GET a raw (non-API) URL and return the response body as bytes.
/// Stays on the raw `reqwest` client because these are *web-router*
/// routes (`/attachments/<uuid>`, Actions artifact / persisted-log

View file

@ -158,6 +158,8 @@ enum Verb {
CiLog(verbs::ci_log::Args),
/// Re-run CI without an empty commit. Pass one of `--pr <n>`,
/// `--run <n>`, or `--branch <name>`; `--workflow` defaults to `ci.yml`.
/// `--input key=value` (repeatable) passes workflow inputs, for example one VM
/// test: `--workflow vm-nightly.yml --input test=<name>`.
CiRerun(verbs::ci_rerun::Args),
/// List CI Actions runs, newest first (`--workflow`, `--branch`,
/// `--limit`, `--page`) — the run numbers `ci-log`/`ci-rerun --run`/

View file

@ -23,7 +23,13 @@
//! pseudo-ref, not a real branch — that case refuses for the same reason
//! `--pr` does (same underlying run, same red check, same sha).
//!
//! Dispatch re-runs the whole workflow (no single-job variant).
//! Dispatch re-runs the whole workflow (no single-job variant). Repeatable
//! `--input key=value` flags travel as the dispatch body's `inputs` map, for
//! a workflow whose `workflow_dispatch` declares them (for example
//! `vm-nightly.yml`'s `test`); the forge's own rejection of an unknown input
//! is surfaced verbatim.
use std::collections::BTreeMap;
use anyhow::{Context as _, Result, bail};
use clap::Args as ClapArgs;
@ -53,6 +59,57 @@ pub struct Args {
/// which uses the run's own workflow.
#[arg(long, default_value = "ci.yml")]
workflow: String,
/// Workflow input for the dispatch, `key=value` (repeatable; the value
/// may be empty or contain `=`). The workflow lists its inputs under
/// `on.workflow_dispatch.inputs`; for an unknown input the forge's own
/// error comes back unchanged. Example: `--workflow vm-nightly.yml
/// --input test=k8s-swarm-images` runs one VM test instead of all of
/// them.
#[arg(long = "input", value_name = "KEY=VALUE", value_parser = parse_input)]
inputs: Vec<(String, String)>,
}
/// Parse one `--input key=value`: split at the first `=`, so a value may
/// itself contain `=`. The key must be non-empty and have no surrounding
/// whitespace; the value may be empty (`test=` is how `vm-nightly.yml` asks
/// for every test).
fn parse_input(raw: &str) -> Result<(String, String), String> {
let Some((key, value)) = raw.split_once('=') else {
return Err(format!("`{raw}` is not key=value"));
};
if key.is_empty() || key.trim() != key {
return Err(format!(
"`{raw}`: the key before `=` must be non-empty, without surrounding whitespace"
));
}
Ok((key.to_string(), value.to_string()))
}
/// The dispatch request body: `ref` plus the `inputs` map, `None` when no
/// `--input` was given so the request is the same as before inputs existed.
/// Errors on a key given twice rather than letting the later one win
/// silently.
fn dispatch_body(branch: &str, inputs: &[(String, String)]) -> Result<DispatchWorkflowOption> {
let mut map = BTreeMap::new();
for (key, value) in inputs {
if map.insert(key.clone(), value.clone()).is_some() {
bail!("ci-rerun: --input {key} given more than once");
}
}
Ok(DispatchWorkflowOption {
inputs: (!map.is_empty()).then_some(map),
r#ref: branch.to_string(),
return_run_info: None,
})
}
/// `k=v k2=v2` for the confirmation line, in the order given.
fn render_inputs(inputs: &[(String, String)]) -> String {
inputs
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect::<Vec<_>>()
.join(" ")
}
/// # Errors
@ -60,9 +117,10 @@ pub struct Args {
/// Returns an error if none of `--pr` / `--run` / `--branch` is given, if
/// `--pr` is given or `--run` names a PR-triggered run (refuses before
/// dispatching — see the module doc), if a `--run` handle can't otherwise
/// be resolved (unknown run, or a run missing its ref), or if the dispatch
/// POST fails (network, or a non-2xx such as `404` for an unknown workflow
/// file or branch).
/// be resolved (unknown run, or a run missing its ref), if an `--input` key
/// is repeated, or if the dispatch POST fails (network, or a non-2xx such as
/// `404` for an unknown workflow file or branch, or the forge's rejection of
/// an input the workflow doesn't declare).
pub fn run(client: &Client, args: Args) -> Result<()> {
if let Some(pr) = args.pr {
bail!(pr_refusal_message(pr));
@ -78,23 +136,29 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
};
let (owner, name) = client.owner_repo()?;
let body = DispatchWorkflowOption {
inputs: None,
r#ref: branch.clone(),
return_run_info: None,
};
let body = dispatch_body(&branch, &args.inputs)?;
client
.api()
.dispatch_workflow(owner, name, &workflow, body)
.send()
.post_api_json(
&format!("/repos/{owner}/{name}/actions/workflows/{workflow}/dispatches"),
&body,
)
.with_context(|| {
format!(
"dispatch workflow {workflow} on {branch} ({repo}) — the workflow \
file or the branch may not exist"
file or the branch may not exist, or an --input is not one the \
workflow declares"
)
})?;
println!("dispatched a fresh run of {workflow} on {branch} ({repo})");
if args.inputs.is_empty() {
println!("dispatched a fresh run of {workflow} on {branch} ({repo})");
} else {
println!(
"dispatched a fresh run of {workflow} on {branch} ({repo}) with inputs: {}",
render_inputs(&args.inputs)
);
}
println!("follow it: hive-forge -r {repo} ci-runs --workflow {workflow} --branch {branch}");
Ok(())
}
@ -164,7 +228,10 @@ fn pr_number_from_run_ref(value: &str) -> Option<u64> {
#[cfg(test)]
mod tests {
use super::{ActionRun, pr_number_from_run_ref, pr_refusal_message, run_dispatch_target};
use super::{
ActionRun, dispatch_body, parse_input, pr_number_from_run_ref, pr_refusal_message,
render_inputs, run_dispatch_target,
};
use serde_json::json;
/// Build a typed run record from an API-shaped JSON fixture. The
@ -265,4 +332,83 @@ mod tests {
.expect("a PR-triggered run's dispatch target is a PR pseudo-ref");
assert_eq!(pr_refusal_message(pr), pr_refusal_message(4199)); // lint:allow: PR-shaped test fixture, not a tracker reference
}
#[test]
fn input_splits_at_the_first_equals() {
assert_eq!(
parse_input("test=k8s-swarm-images"),
Ok(("test".to_string(), "k8s-swarm-images".to_string()))
);
assert_eq!(
parse_input("flags=a=b"),
Ok(("flags".to_string(), "a=b".to_string()))
);
assert_eq!(
parse_input("test="),
Ok(("test".to_string(), String::new()))
);
}
#[test]
fn malformed_inputs_are_rejected() {
assert!(parse_input("test").is_err());
assert!(parse_input("=value").is_err());
assert!(parse_input(" test=x").is_err());
assert!(parse_input("test =x").is_err());
assert!(parse_input("").is_err());
}
#[test]
fn body_carries_ref_and_inputs_map() {
let body = dispatch_body(
"k8s/v1",
&[
("test".to_string(), "k8s-swarm-images".to_string()),
("other".to_string(), String::new()),
],
)
.unwrap();
assert_eq!(
serde_json::to_value(&body).unwrap(),
json!({
"ref": "k8s/v1",
"inputs": { "test": "k8s-swarm-images", "other": "" },
"return_run_info": null,
})
);
}
#[test]
fn body_without_inputs_has_none() {
let body = dispatch_body("main", &[]).unwrap();
assert_eq!(body.inputs, None);
assert_eq!(body.r#ref, "main");
}
#[test]
fn repeated_input_key_is_refused() {
let err = dispatch_body(
"main",
&[
("test".to_string(), "a".to_string()),
("test".to_string(), "b".to_string()),
],
)
.unwrap_err();
assert!(
err.to_string()
.contains("--input test given more than once")
);
}
#[test]
fn inputs_render_in_given_order() {
assert_eq!(
render_inputs(&[
("b".to_string(), "1".to_string()),
("a".to_string(), "2".to_string())
]),
"b=1 a=2"
);
}
}