From a533160be0384e02b65b879e9bf6f12501386f9b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 18:07:40 +1300 Subject: [PATCH] CLI 0.2.10 (sc-8795): visualci test -- creates a build, runs the tests with VISUALCI_BUILD_ID set, and finalizes it when they end (failed, empty or interrupted too: Ctrl-C stops the tests, not the finalize), waits and prints the result; local runs are subsets; --upload sends visualci.yml's uploads after; the command's failure is the exit code --- Cargo.lock | 11 +- Cargo.toml | 2 +- crates/visualci-cli/Cargo.toml | 3 + crates/visualci-cli/src/main.rs | 171 +++++++++++++++++++++++++++++++- 4 files changed, 180 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1263c998..a020bf7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5195,13 +5195,14 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "visualci-cli" -version = "0.2.9" +version = "0.2.10" dependencies = [ "anyhow", "base64 0.22.1", "clap", "image", "keyring", + "libc", "reqwest", "serde", "serde_json", @@ -5211,7 +5212,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.9" +version = "0.2.10" dependencies = [ "globset", "hex", @@ -5228,7 +5229,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.9" +version = "0.2.10" dependencies = [ "anyhow", "image", @@ -5242,7 +5243,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.9" +version = "0.2.10" dependencies = [ "image", "serde", @@ -5252,7 +5253,7 @@ dependencies = [ [[package]] name = "visualci_server" -version = "0.2.9" +version = "0.2.10" dependencies = [ "aes-gcm", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 72fc1579..35fe60a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*", "server", "server/migration"] [workspace.package] -version = "0.2.9" +version = "0.2.10" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/crates/visualci-cli/Cargo.toml b/crates/visualci-cli/Cargo.toml index 2fd554eb..3098d53e 100644 --- a/crates/visualci-cli/Cargo.toml +++ b/crates/visualci-cli/Cargo.toml @@ -23,5 +23,8 @@ reqwest = { workspace = true, features = ["blocking"] } # macOS keeps `visualci login`'s token in the Keychain; elsewhere a 0600 file (the static Linux builds can't link D-Bus # for the Secret Service). +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [target.'cfg(target_os = "macos")'.dependencies] keyring = { version = "3", default-features = false, features = ["apple-native"] } diff --git a/crates/visualci-cli/src/main.rs b/crates/visualci-cli/src/main.rs index 411e7c63..4d2eaffb 100644 --- a/crates/visualci-cli/src/main.rs +++ b/crates/visualci-cli/src/main.rs @@ -178,6 +178,34 @@ enum Command { #[command(flatten)] connection: Connection, }, + /// Run a test command inside one build: create the build, run the command with VISUALCI_BUILD_ID set (so every + /// test, process or worker that sends snapshots adds them to this build), then finalize it when the command ends, + /// even when the tests fail or are interrupted (Ctrl-C), wait for the result and print what changed. A local run + /// is a subset: what it didn't send isn't "removed". Exits with the command's status when it failed, else 0 when + /// CI should pass, 1 when it shouldn't, 3 when the result didn't come in time and 4 when out of credits. + /// + /// visualci test -- cargo test + /// visualci test --upload -- npx jest -u + Test { + /// The test command and its arguments, after `--`. + #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true, value_name = "COMMAND")] + command: Vec, + /// After the command, also send visualci.yml's `uploads` (for test runners that write snapshot files). + #[arg(long)] + upload: bool, + /// Finalize and exit with the command's status, without waiting for the result. + #[arg(long)] + no_wait: bool, + /// Seconds to wait for the result. + #[arg(long, default_value_t = 900)] + timeout: u64, + #[command(flatten)] + options: BuildOptions, + #[command(flatten)] + snapshot: SnapshotOptions, + #[command(flatten)] + connection: Connection, + }, /// One-shot local check: create a local build, upload, wait, and print what changed. Renders happen on the /// server, so a laptop gets the same pixels as CI. Check { @@ -642,6 +670,34 @@ fn run() -> Result<()> { let (_, uploaded) = client.add_snapshots(&build_id(build)?, &[s])?; eprintln!("1 snapshot, {uploaded} uploaded"); } + Command::Test { command, upload, no_wait, timeout, mut options, snapshot, connection } => { + let client = + Client::from_env(connection.api_url.clone(), connection.token.clone(), connection.project.clone())?; + // A local run usually runs some of the tests: what it didn't send isn't removed. + let local = + options.mode.as_deref() == Some("local") || (options.mode.is_none() && !client::running_in_ci()); + options.subset |= local; + let build = create_build(&client, &options)?; + eprintln!("Build #{} for {}: {}", build.number, build.project, build.url); + if let Some(message) = build.blocked_message() { + eprintln!("visualci: {message}"); + } + let status = run_tests(&command, &build.id, &connection)?; + if upload { + let snapshots = configured_uploads(&snapshot)?; + if !snapshots.is_empty() { + let (registered, uploaded) = client.add_snapshots(&build.id, &snapshots)?; + eprintln!("{registered} snapshots, {uploaded} uploaded"); + } + } + // Finalized whatever happened to the tests: a run that sent nothing (it failed before any snapshot) too. + let mut build = client.finalize(&build.id, None, true)?; + if !no_wait { + build = client.wait(&build.id, Duration::from_secs(timeout))?; + } + print_build(&client, &build)?; + std::process::exit(test_exit_code(status, &build, no_wait)); + } Command::Check { paths, snapshot, name, timeout, connection } => { let client = Client::from_env(connection.api_url, connection.token, connection.project)?; let options = BuildOptions { mode: Some("local".to_string()), name, shards: 1, subset: true, nonce: None }; @@ -668,7 +724,88 @@ fn run() -> Result<()> { Ok(()) } -/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the +/// Run the test command with VISUALCI_BUILD_ID (and the connection's options, when given on the command line) in its +/// environment, and return its exit status: its code, or 128 + the signal that ended it. While it runs this process +/// ignores Ctrl-C (the command, in the same process group, still gets it), so an interrupted run is still finalized. +fn run_tests(command: &[String], build_id: &str, connection: &Connection) -> Result { + let (program, args) = command.split_first().context("give the test command after --")?; + let mut child = std::process::Command::new(program); + child.args(args).env("VISUALCI_BUILD_ID", build_id); + if let Some(url) = &connection.api_url { + child.env("VISUALCI_API_URL", url); + } + if let Some(token) = &connection.token { + child.env("VISUALCI_TOKEN", token); + } + if let Some(project) = &connection.project { + child.env("VISUALCI_PROJECT", project); + } + // Started before Ctrl-C is ignored here: an ignored signal stays ignored in a program started after, and the + // tests must still stop on it. + let mut child = child.spawn().with_context(|| format!("running {program}"))?; + let _interrupts = IgnoreInterrupts::new(); + let status = child.wait().with_context(|| format!("running {program}"))?; + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt as _; + if let Some(signal) = status.signal() { + return Ok(128 + signal); + } + } + Ok(status.code().unwrap_or(1)) +} + +/// `visualci test`'s exit code: the command's when it failed (the build is still finalized and printed); otherwise 4 +/// when the organization is out of credits, else what the build says for CI (0 pass, 1 fail, 3 no result yet). +fn test_exit_code(status: i32, build: &client::Build, no_wait: bool) -> i32 { + if status != 0 { + return status; + } + if build.blocked_message().is_some() { + return BLOCKED; + } + if no_wait { + return 0; + } + match build.passed { + Some(true) => 0, + Some(false) => 1, + None => 3, + } +} + +/// While it's alive, Ctrl-C (SIGINT) and SIGQUIT don't end this process; dropping it restores what they did before. +struct IgnoreInterrupts { + #[cfg(unix)] + previous: [(libc::c_int, libc::sighandler_t); 2], +} + +impl IgnoreInterrupts { + fn new() -> Self { + #[cfg(unix)] + { + // SAFETY: setting a signal's disposition to SIG_IGN is async-signal-safe and touches no Rust state. + let previous = [libc::SIGINT, libc::SIGQUIT].map(|sig| (sig, unsafe { libc::signal(sig, libc::SIG_IGN) })); + Self { previous } + } + #[cfg(not(unix))] + Self {} + } +} + +impl Drop for IgnoreInterrupts { + fn drop(&mut self) { + #[cfg(unix)] + for (sig, handler) in self.previous { + // SAFETY: restores the disposition saved in `new`. + unsafe { + libc::signal(sig, handler); + } + } + } +} + +/// The device-code sign-in:/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the /// browser, then keep the personal access token it gives. fn login(api: &str, no_browser: bool) -> Result<()> { let http = reqwest::blocking::Client::builder() @@ -1105,6 +1242,38 @@ mod tests { assert_eq!(readable("Page 1 (changed), base:"), "Page 1 (changed), base:"); } + fn build(passed: Option, blocked: bool) -> client::Build { + serde_json::from_value(json!({ + "id": "b", "number": 1, "project": "acme/web", "state": "completed", "review_state": "none", + "conclusion": null, "ci_mode": "review", "passed": passed, "stats": {}, "error": null, "url": "u", + "blocked": if blocked { json!({ "message": "Out of credits", "resolved": false }) } else { json!(null) }, + })) + .unwrap() + } + + #[test] + fn test_exits_with_the_commands_failure_first() { + assert_eq!(test_exit_code(101, &build(Some(true), false), false), 101); + assert_eq!(test_exit_code(0, &build(Some(true), false), false), 0); + assert_eq!(test_exit_code(0, &build(Some(false), false), false), 1); + assert_eq!(test_exit_code(0, &build(None, false), false), 3); + assert_eq!(test_exit_code(0, &build(None, false), true), 0); + assert_eq!(test_exit_code(0, &build(Some(true), true), false), BLOCKED); + } + + #[cfg(unix)] + #[test] + fn runs_the_test_command_with_the_build() { + let connection = Connection { api_url: None, token: None, project: Some("acme/web".into()) }; + let sh = |script: &str| vec!["sh".to_string(), "-c".to_string(), script.to_string()]; + let ok = r#"[ "$VISUALCI_BUILD_ID" = b-1 ] && [ "$VISUALCI_PROJECT" = acme/web ]"#; + assert_eq!(run_tests(&sh(ok), "b-1", &connection).unwrap(), 0); + assert_eq!(run_tests(&sh("exit 7"), "b-1", &connection).unwrap(), 7); + // Interrupted: 128 + SIGINT, and this process is still here to finalize. The command itself still stops on + // Ctrl-C (an ignored SIGINT would leave it running). + assert_eq!(run_tests(&sh("kill -INT $$; sleep 5"), "b-1", &connection).unwrap(), 130); + } + #[test] fn leaves_out_null_arguments() { assert_eq!(without_nulls(json!({ "build": "12", "only": null })), json!({ "build": "12" }));