Skip to content
Merged
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
11 changes: 6 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions crates/visualci-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
171 changes: 170 additions & 1 deletion crates/visualci-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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 {
Expand Down Expand Up @@ -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 };
Expand All @@ -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<i32> {
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()
Expand Down Expand Up @@ -1105,6 +1242,38 @@ mod tests {
assert_eq!(readable("Page 1 (changed), base:"), "Page 1 (changed), base:");
}

fn build(passed: Option<bool>, 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" }));
Expand Down
Loading