utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | 9e7f0f69e18ec65109aec8724462e7bb48d2ddcae263e600ea728db9022a8a77 |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 11:50 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 11:50 +02:00 |
| Parents | 2da7deeea818 |
6 files changed
modified Cargo.lock +1 −0
| @@ -511,6 +511,7 @@ | ||
| 511 | 511 | "elffuss-braid-repo", |
| 512 | 512 | "elffuss-braid-store", |
| 513 | 513 | "elffuss-braid-wc", |
| 514 | + "rustix", | |
| 514 | 515 | "rustls", |
| 515 | 516 | "rustls-native-certs", |
| 516 | 517 | "serde", |
modified crates/cli/Cargo.toml +4 −0
| @@ -32,6 +32,10 @@ | ||
| 32 | 32 | rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] } |
| 33 | 33 | rustls-native-certs = "0.8" |
| 34 | 34 | |
| 35 | +# `braid verify` kills a timed-out test command's whole process group. | |
| 36 | +[target.'cfg(unix)'.dependencies] | |
| 37 | +rustix = { version = "1.1.5", features = ["process"] } | |
| 38 | + | |
| 35 | 39 | [dev-dependencies] |
| 36 | 40 | tempfile.workspace = true |
| 37 | 41 |
modified crates/cli/src/main.rs +7 −0
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | mod hub; |
| 9 | 9 | mod revert; |
| 10 | 10 | mod sync; |
| 11 | +mod verify; | |
| 11 | 12 | mod work; |
| 12 | 13 | |
| 13 | 14 | use std::collections::HashMap; |
| @@ -318,6 +319,11 @@ | ||
| 318 | 319 | /// conflicts). |
| 319 | 320 | #[command(long_about = revert::REVERT_HELP)] |
| 320 | 321 | Revert(revert::RevertArgs), |
| 322 | + /// Run the tests on a branch's head, keep braid/green/<branch> at the | |
| 323 | + /// newest changeset that passed, and find what broke them (exit status | |
| 324 | + /// 4 when the branch is red). | |
| 325 | + #[command(long_about = verify::VERIFY_HELP)] | |
| 326 | + Verify(verify::VerifyArgs), | |
| 321 | 327 | } |
| 322 | 328 | |
| 323 | 329 | #[derive(Debug, Subcommand)] |
| @@ -521,6 +527,7 @@ | ||
| 521 | 527 | Command::Track { paths } => work::track(cli, paths), |
| 522 | 528 | Command::Change { action } => work::change(cli, action), |
| 523 | 529 | Command::Revert(args) => revert::revert(cli, args), |
| 530 | + Command::Verify(args) => verify::verify(cli, args), | |
| 524 | 531 | } |
| 525 | 532 | } |
| 526 | 533 |
added crates/cli/src/verify.rs +801 −0
| @@ -0,0 +1,801 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | + | |
| 4 | +//! `verify`: run a project's tests on a branch's head, keep a green ref at | |
| 5 | +//! the newest changeset that passed them, and when they fail, find the | |
| 6 | +//! changeset that broke them and, if asked, revert it. | |
| 7 | +//! | |
| 8 | +//! One pass per invocation. The tests run in a fresh copy of the | |
| 9 | +//! changeset's files outside the repository, with no shell, and with the | |
| 10 | +//! hub's credentials taken out of their environment. The green ref, | |
| 11 | +//! `braid/green/<branch>`, is in braid's own namespace, so it is never | |
| 12 | +//! exported to git or sent to a hub; it moves with a compare-and-swap, in | |
| 13 | +//! an operation of its own. The reverts verify landed are recorded in | |
| 14 | +//! `.braid/verify/<branch>.json`, which is what it trusts to tell its own | |
| 15 | +//! reverts, never the `reverts` field a changeset carries. | |
| 16 | + | |
| 17 | +use std::ffi::OsString; | |
| 18 | +use std::fs; | |
| 19 | +use std::io; | |
| 20 | +use std::path::{Path, PathBuf}; | |
| 21 | +use std::process::{Child, Command, ExitCode, ExitStatus, Stdio}; | |
| 22 | +use std::sync::atomic::{AtomicU32, Ordering}; | |
| 23 | +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | |
| 24 | + | |
| 25 | +use anyhow::{Context, Result, bail}; | |
| 26 | +use braid_format::ObjectId; | |
| 27 | +use braid_repo::Repo; | |
| 28 | +use braid_store::RefUpdate; | |
| 29 | +use braid_wc::RevertRequest; | |
| 30 | +use clap::Args; | |
| 31 | +use serde::{Deserialize, Serialize}; | |
| 32 | +use serde_json::{Value, json}; | |
| 33 | + | |
| 34 | +use crate::hub::{self, link::Link}; | |
| 35 | +use crate::revert::{branch_or_main, land_revert}; | |
| 36 | +use crate::work::{IdentityArgs, Report, hex, identity, print_conflicts, short}; | |
| 37 | +use crate::{Cli, open_repo, print_json, resolve_changeset}; | |
| 38 | + | |
| 39 | +/// The agent label of everything verify records: the green ref's moves, | |
| 40 | +/// and the reverts it makes and lands. | |
| 41 | +pub(crate) const AGENT: &str = "braid-verify"; | |
| 42 | + | |
| 43 | +/// Exit status of a pass that leaves the branch red: the tests fail on its | |
| 44 | +/// head, whether or not the culprit was found or reverted. | |
| 45 | +const RED: u8 = 4; | |
| 46 | + | |
| 47 | +/// The exit status of a revert that conflicts, as for every conflict. | |
| 48 | +const CONFLICTS: u8 = crate::work::CONFLICTS; | |
| 49 | + | |
| 50 | +/// The green ref of `branch`: the newest changeset of it that passed. | |
| 51 | +pub(crate) fn green_ref(branch: &str) -> String { | |
| 52 | + format!("braid/green/{branch}") | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// The long help of `verify`. | |
| 56 | +pub(crate) const VERIFY_HELP: &str = | |
| 57 | + "Run the project's tests on the head of a branch, once, and keep the | |
| 58 | +branch green: braid/green/<branch> points at the newest changeset of the | |
| 59 | +branch that passed. When the tests fail, find the changeset that broke | |
| 60 | +them, and with --revert, revert it. | |
| 61 | + | |
| 62 | +The command comes after `--` and runs as given, with no shell: write | |
| 63 | +`-- sh -c '...'` for one. It runs in a fresh copy of the changeset's files, | |
| 64 | +in a new directory under the system's temporary directory: outside the | |
| 65 | +repository, with no .braid file and no .git, so each run starts from | |
| 66 | +scratch and nothing it writes stays. Its output goes to standard error. It | |
| 67 | +gets BRAID_VERIFY_CHANGESET (the changeset's id) and BRAID_VERIFY_BRANCH, | |
| 68 | +and neither BRAID_TOKEN nor any BRAID_HUB variable. A run fails when the | |
| 69 | +command exits with a status other than 0, is killed, or runs longer than | |
| 70 | +--timeout (10m by default; s, m and h are the units), which kills it and | |
| 71 | +every process it started. | |
| 72 | + | |
| 73 | + - The head is the green changeset already: pass, and nothing runs. | |
| 74 | + - The tests pass: the green ref moves to the head, in an operation of | |
| 75 | + its own by braid-verify. A run that failed and passed when run again | |
| 76 | + (--reruns, 1 by default) is flaky, and moves it too. | |
| 77 | + - They fail, again on every rerun: verify bisects the changesets after | |
| 78 | + the green one along first parents, the head's changes and its | |
| 79 | + parents', to find the first that fails. With no green ref yet it does | |
| 80 | + not bisect unless --from names a changeset to take as passing. | |
| 81 | + Midpoints run as they are: an earlier revert in the range is not | |
| 82 | + undone first. | |
| 83 | + - With --revert, the culprit is reverted and the revert landed, as | |
| 84 | + `braid revert` does. Verify does not revert a merge, nor a revert it | |
| 85 | + made itself (it keeps those in .braid/verify/<branch>.json), nor more | |
| 86 | + than --max-reverts-per-hour (3 by default). The green ref does not move: | |
| 87 | + the next run tests the new head. | |
| 88 | + | |
| 89 | +--dry-run runs the tests but moves no ref, records nothing and lands | |
| 90 | +nothing. In a repository linked to a hub, verify fetches first and lands a | |
| 91 | +revert on the hub; --local, or BRAID_HUB=off, keeps it here. Run one verify | |
| 92 | +per branch at a time. | |
| 93 | + | |
| 94 | +With --json it prints branch; tip, the head it tested; green_before and | |
| 95 | +green, the green ref before and after; outcome, one of pass, flaky, red, | |
| 96 | +reverted, revert_conflicts, refused, no_culprit or error; culprit, the | |
| 97 | +first failing changeset, or null; revert, the revert made, or null; | |
| 98 | +tests_run, how many times the command ran; reason, why, in words, or null; | |
| 99 | +dry_run; and land, the landing report of the revert as `braid land --help` | |
| 100 | +describes it, or null. | |
| 101 | + | |
| 102 | +Exit status: 0 for pass and flaky; 4 for red, reverted, refused and | |
| 103 | +no_culprit; 2 for revert_conflicts; 1 for an error, with the report | |
| 104 | +printed when the tests had started."; | |
| 105 | + | |
| 106 | +#[derive(Debug, Args)] | |
| 107 | +pub(crate) struct VerifyArgs { | |
| 108 | + /// The branch to verify (default: main, master, or the repository's | |
| 109 | + /// only branch). | |
| 110 | + #[arg(long, value_name = "BRANCH")] | |
| 111 | + branch: Option<String>, | |
| 112 | + /// Revert the changeset that broke the tests, and land the revert. | |
| 113 | + #[arg(long)] | |
| 114 | + revert: bool, | |
| 115 | + /// Run the tests, but move no ref, record nothing and land nothing. | |
| 116 | + #[arg(long)] | |
| 117 | + dry_run: bool, | |
| 118 | + /// The most reverts verify lands on the branch in an hour. | |
| 119 | + #[arg(long, value_name = "N", default_value_t = 3)] | |
| 120 | + max_reverts_per_hour: usize, | |
| 121 | + /// How many times to run a failing command again before it counts as | |
| 122 | + /// failing. | |
| 123 | + #[arg(long, value_name = "N", default_value_t = 1)] | |
| 124 | + reruns: u32, | |
| 125 | + /// How long one run may take: a number with s, m or h. | |
| 126 | + #[arg(long, value_name = "DURATION", default_value = "10m", value_parser = parse_duration)] | |
| 127 | + timeout: Duration, | |
| 128 | + /// A changeset of the branch to take as passing, to bisect from instead | |
| 129 | + /// of the green one. | |
| 130 | + #[arg(long, value_name = "REV")] | |
| 131 | + from: Option<String>, | |
| 132 | + #[command(flatten)] | |
| 133 | + identity: IdentityArgs, | |
| 134 | + /// Stay in this repository even if it is linked to a hub. | |
| 135 | + #[arg(long)] | |
| 136 | + local: bool, | |
| 137 | + /// The test command and its arguments, after `--`. | |
| 138 | + #[arg(last = true, required = true, value_name = "COMMAND")] | |
| 139 | + command: Vec<OsString>, | |
| 140 | +} | |
| 141 | + | |
| 142 | +/// A duration: a whole number followed by `s`, `m` or `h`, or a number of | |
| 143 | +/// seconds; never zero. | |
| 144 | +fn parse_duration(text: &str) -> Result<Duration, String> { | |
| 145 | + let (digits, unit) = match text.char_indices().find(|(_, c)| !c.is_ascii_digit()) { | |
| 146 | + Some((at, _)) => text.split_at(at), | |
| 147 | + None => (text, "s"), | |
| 148 | + }; | |
| 149 | + let scale = match unit { | |
| 150 | + "s" => 1, | |
| 151 | + "m" => 60, | |
| 152 | + "h" => 3600, | |
| 153 | + _ => return Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")), | |
| 154 | + }; | |
| 155 | + match digits.parse::<u64>() { | |
| 156 | + Ok(n) if n > 0 => n | |
| 157 | + .checked_mul(scale) | |
| 158 | + .map(Duration::from_secs) | |
| 159 | + .ok_or_else(|| format!("{text:?} is too long")), | |
| 160 | + _ => Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")), | |
| 161 | + } | |
| 162 | +} | |
| 163 | + | |
| 164 | +/// What one pass found. | |
| 165 | +#[derive(Default)] | |
| 166 | +struct Verdict { | |
| 167 | + outcome: &'static str, | |
| 168 | + green: Option<ObjectId>, | |
| 169 | + culprit: Option<ObjectId>, | |
| 170 | + revert: Option<ObjectId>, | |
| 171 | + reason: Option<String>, | |
| 172 | + land: Option<Report>, | |
| 173 | +} | |
| 174 | + | |
| 175 | +impl Verdict { | |
| 176 | + fn exit_code(&self) -> ExitCode { | |
| 177 | + match self.outcome { | |
| 178 | + "pass" | "flaky" => ExitCode::SUCCESS, | |
| 179 | + "revert_conflicts" => ExitCode::from(CONFLICTS), | |
| 180 | + "error" => ExitCode::FAILURE, | |
| 181 | + _ => ExitCode::from(RED), | |
| 182 | + } | |
| 183 | + } | |
| 184 | +} | |
| 185 | + | |
| 186 | +/// The reverts verify landed on one branch, as `.braid/verify/<branch>.json` | |
| 187 | +/// keeps them. | |
| 188 | +#[derive(Debug, Default, Serialize, Deserialize)] | |
| 189 | +struct Record { | |
| 190 | + #[serde(default)] | |
| 191 | + reverts: Vec<Reverted>, | |
| 192 | +} | |
| 193 | + | |
| 194 | +/// One revert verify landed. | |
| 195 | +#[derive(Debug, Serialize, Deserialize)] | |
| 196 | +struct Reverted { | |
| 197 | + /// The changeset it reverted, in hex. | |
| 198 | + culprit: String, | |
| 199 | + /// The revert as verify made it, in hex. | |
| 200 | + revert: String, | |
| 201 | + /// The changeset that holds it on the branch: itself, or the rebased | |
| 202 | + /// one. | |
| 203 | + landed: Option<String>, | |
| 204 | + /// When it landed, in seconds since the Unix epoch. | |
| 205 | + time: u64, | |
| 206 | +} | |
| 207 | + | |
| 208 | +impl Record { | |
| 209 | + /// The file of `branch`. A branch name may hold `/` and other bytes a | |
| 210 | + /// file name should not, so all but letters, digits, `.`, `_` and `-` | |
| 211 | + /// are written as `%XX`. | |
| 212 | + fn path(repo: &Repo, branch: &str) -> PathBuf { | |
| 213 | + let mut name = String::new(); | |
| 214 | + for byte in branch.bytes() { | |
| 215 | + if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-') { | |
| 216 | + name.push(byte as char); | |
| 217 | + } else { | |
| 218 | + name.push_str(&format!("%{byte:02X}")); | |
| 219 | + } | |
| 220 | + } | |
| 221 | + repo.root() | |
| 222 | + .join(braid_repo::DIR) | |
| 223 | + .join("verify") | |
| 224 | + .join(format!("{name}.json")) | |
| 225 | + } | |
| 226 | + | |
| 227 | + fn load(path: &Path) -> Result<Record> { | |
| 228 | + match fs::read(path) { | |
| 229 | + Ok(bytes) => serde_json::from_slice(&bytes) | |
| 230 | + .with_context(|| format!("{} is not verify's record", path.display())), | |
| 231 | + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Record::default()), | |
| 232 | + Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())), | |
| 233 | + } | |
| 234 | + } | |
| 235 | + | |
| 236 | + /// Writes the record whole, through a scratch file and a rename. | |
| 237 | + fn save(&self, path: &Path) -> Result<()> { | |
| 238 | + let dir = path.parent().context("the record has no directory")?; | |
| 239 | + fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?; | |
| 240 | + let scratch = path.with_extension("json.new"); | |
| 241 | + let mut text = serde_json::to_vec_pretty(self)?; | |
| 242 | + text.push(b'\n'); | |
| 243 | + fs::write(&scratch, text).with_context(|| format!("cannot write {}", scratch.display()))?; | |
| 244 | + fs::rename(&scratch, path).with_context(|| format!("cannot write {}", path.display()))?; | |
| 245 | + Ok(()) | |
| 246 | + } | |
| 247 | + | |
| 248 | + /// Whether verify made `id`: a revert of its own, as made or landed. | |
| 249 | + fn made(&self, id: ObjectId) -> bool { | |
| 250 | + let hex = id.to_hex(); | |
| 251 | + self.reverts | |
| 252 | + .iter() | |
| 253 | + .any(|r| r.revert == hex || r.landed.as_deref() == Some(hex.as_str())) | |
| 254 | + } | |
| 255 | + | |
| 256 | + /// How many reverts landed in the hour before `now`. | |
| 257 | + fn in_last_hour(&self, now: u64) -> usize { | |
| 258 | + self.reverts.iter().filter(|r| r.time + 3600 > now).count() | |
| 259 | + } | |
| 260 | +} | |
| 261 | + | |
| 262 | +fn now_seconds() -> u64 { | |
| 263 | + SystemTime::now() | |
| 264 | + .duration_since(UNIX_EPOCH) | |
| 265 | + .map_or(0, |since| since.as_secs()) | |
| 266 | +} | |
| 267 | + | |
| 268 | +/// Runs the test command on changesets, counting the runs. | |
| 269 | +struct Tester<'a> { | |
| 270 | + repo: &'a Repo, | |
| 271 | + branch: &'a str, | |
| 272 | + command: &'a [OsString], | |
| 273 | + timeout: Duration, | |
| 274 | + reruns: u32, | |
| 275 | + runs: usize, | |
| 276 | +} | |
| 277 | + | |
| 278 | +/// How one run ended. | |
| 279 | +enum RunEnd { | |
| 280 | + Exited(ExitStatus), | |
| 281 | + TimedOut, | |
| 282 | +} | |
| 283 | + | |
| 284 | +impl Tester<'_> { | |
| 285 | + /// Whether the tests pass on `changeset`: the first run, or one of the | |
| 286 | + /// reruns after it fails. Returns whether they passed, and whether a | |
| 287 | + /// run failed before one passed. | |
| 288 | + fn passes(&mut self, changeset: ObjectId) -> Result<(bool, bool)> { | |
| 289 | + for attempt in 0..=self.reruns { | |
| 290 | + if self.run(changeset)? { | |
| 291 | + return Ok((true, attempt > 0)); | |
| 292 | + } | |
| 293 | + } | |
| 294 | + Ok((false, false)) | |
| 295 | + } | |
| 296 | + | |
| 297 | + /// Runs the command once on a fresh copy of `changeset`. | |
| 298 | + fn run(&mut self, changeset: ObjectId) -> Result<bool> { | |
| 299 | + let dir = scratch_dir()?; | |
| 300 | + let result = self.run_in(changeset, &dir); | |
| 301 | + // Whatever the command left goes too. | |
| 302 | + let _ = fs::remove_dir_all(&dir); | |
| 303 | + // Only a command that ran counts. | |
| 304 | + let end = result?; | |
| 305 | + self.runs += 1; | |
| 306 | + let passed = matches!(&end, RunEnd::Exited(status) if status.success()); | |
| 307 | + let said = match &end { | |
| 308 | + RunEnd::Exited(status) if status.success() => "passed".to_owned(), | |
| 309 | + RunEnd::Exited(status) => format!("failed ({status})"), | |
| 310 | + RunEnd::TimedOut => format!("timed out after {:?} and was killed", self.timeout), | |
| 311 | + }; | |
| 312 | + eprintln!("braid verify: {} {said}", changeset.short()); | |
| 313 | + Ok(passed) | |
| 314 | + } | |
| 315 | + | |
| 316 | + fn run_in(&self, changeset: ObjectId, dir: &Path) -> Result<RunEnd> { | |
| 317 | + braid_wc::materialize(self.repo.store(), changeset, dir) | |
| 318 | + .with_context(|| format!("cannot write changeset {} to test it", changeset.short()))?; | |
| 319 | + let (program, args) = self.command.split_first().context("no command to run")?; | |
| 320 | + let mut command = Command::new(program); | |
| 321 | + command | |
| 322 | + .args(args) | |
| 323 | + .current_dir(dir) | |
| 324 | + .stdin(Stdio::null()) | |
| 325 | + .stdout(to_stderr()?) | |
| 326 | + .stderr(to_stderr()?) | |
| 327 | + .env("BRAID_VERIFY_CHANGESET", changeset.to_hex()) | |
| 328 | + .env("BRAID_VERIFY_BRANCH", self.branch); | |
| 329 | + for (name, _) in std::env::vars_os() { | |
| 330 | + if is_credential(&name) { | |
| 331 | + command.env_remove(&name); | |
| 332 | + } | |
| 333 | + } | |
| 334 | + #[cfg(unix)] | |
| 335 | + { | |
| 336 | + use std::os::unix::process::CommandExt; | |
| 337 | + // A group of its own, so that a timeout kills everything it | |
| 338 | + // started. | |
| 339 | + command.process_group(0); | |
| 340 | + } | |
| 341 | + let mut child = command | |
| 342 | + .spawn() | |
| 343 | + .with_context(|| format!("cannot run {}", program.to_string_lossy()))?; | |
| 344 | + let deadline = Instant::now() + self.timeout; | |
| 345 | + loop { | |
| 346 | + if let Some(status) = child.try_wait()? { | |
| 347 | + return Ok(RunEnd::Exited(status)); | |
| 348 | + } | |
| 349 | + let now = Instant::now(); | |
| 350 | + if now >= deadline { | |
| 351 | + kill(&mut child); | |
| 352 | + let _ = child.wait(); | |
| 353 | + return Ok(RunEnd::TimedOut); | |
| 354 | + } | |
| 355 | + std::thread::sleep((deadline - now).min(Duration::from_millis(20))); | |
| 356 | + } | |
| 357 | + } | |
| 358 | +} | |
| 359 | + | |
| 360 | +/// Whether an environment variable is one of the hub's credentials or | |
| 361 | +/// settings, which the tests never see: `BRAID_TOKEN` and every | |
| 362 | +/// `BRAID_HUB…`. | |
| 363 | +fn is_credential(name: &std::ffi::OsStr) -> bool { | |
| 364 | + let name = name.to_string_lossy(); | |
| 365 | + name == "BRAID_TOKEN" || name.starts_with("BRAID_HUB") | |
| 366 | +} | |
| 367 | + | |
| 368 | +/// Kills the command and every process in its group. | |
| 369 | +fn kill(child: &mut Child) { | |
| 370 | + #[cfg(unix)] | |
| 371 | + { | |
| 372 | + let group = rustix::process::Pid::from_child(child); | |
| 373 | + let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL); | |
| 374 | + } | |
| 375 | + let _ = child.kill(); | |
| 376 | +} | |
| 377 | + | |
| 378 | +/// Standard error, for the command's output, so that standard output keeps | |
| 379 | +/// only the report. | |
| 380 | +fn to_stderr() -> Result<Stdio> { | |
| 381 | + #[cfg(unix)] | |
| 382 | + { | |
| 383 | + use std::os::fd::AsFd; | |
| 384 | + Ok(Stdio::from(io::stderr().as_fd().try_clone_to_owned()?)) | |
| 385 | + } | |
| 386 | + #[cfg(windows)] | |
| 387 | + { | |
| 388 | + use std::os::windows::io::AsHandle; | |
| 389 | + Ok(Stdio::from(io::stderr().as_handle().try_clone_to_owned()?)) | |
| 390 | + } | |
| 391 | + #[cfg(not(any(unix, windows)))] | |
| 392 | + { | |
| 393 | + Ok(Stdio::inherit()) | |
| 394 | + } | |
| 395 | +} | |
| 396 | + | |
| 397 | +/// A new, empty directory under the system's temporary directory, readable | |
| 398 | +/// only by this user where the system has modes. | |
| 399 | +fn scratch_dir() -> Result<PathBuf> { | |
| 400 | + static COUNTER: AtomicU32 = AtomicU32::new(0); | |
| 401 | + let base = std::env::temp_dir(); | |
| 402 | + let nanos = SystemTime::now() | |
| 403 | + .duration_since(UNIX_EPOCH) | |
| 404 | + .map_or(0, |since| since.subsec_nanos()); | |
| 405 | + loop { | |
| 406 | + let n = COUNTER.fetch_add(1, Ordering::Relaxed); | |
| 407 | + let dir = base.join(format!( | |
| 408 | + "braid-verify-{}-{nanos:08x}-{n}", | |
| 409 | + std::process::id() | |
| 410 | + )); | |
| 411 | + let mut builder = fs::DirBuilder::new(); | |
| 412 | + #[cfg(unix)] | |
| 413 | + { | |
| 414 | + use std::os::unix::fs::DirBuilderExt; | |
| 415 | + builder.mode(0o700); | |
| 416 | + } | |
| 417 | + match builder.create(&dir) { | |
| 418 | + Ok(()) => return Ok(dir), | |
| 419 | + Err(err) if err.kind() == io::ErrorKind::AlreadyExists && n < 1000 => continue, | |
| 420 | + Err(err) => { | |
| 421 | + return Err(err).with_context(|| format!("cannot create {}", dir.display())); | |
| 422 | + } | |
| 423 | + } | |
| 424 | + } | |
| 425 | +} | |
| 426 | + | |
| 427 | +/// The changesets after `good` up to `tip`, along first parents, oldest | |
| 428 | +/// first, or `None` when `good` is not on the chain. | |
| 429 | +fn range(repo: &Repo, tip: ObjectId, good: ObjectId) -> Result<Option<Vec<ObjectId>>> { | |
| 430 | + let mut chain = Vec::new(); | |
| 431 | + let mut current = tip; | |
| 432 | + while current != good { | |
| 433 | + chain.push(current); | |
| 434 | + match braid_engine::read_changeset(repo.store(), current)? | |
| 435 | + .parents | |
| 436 | + .first() | |
| 437 | + { | |
| 438 | + Some(parent) => current = *parent, | |
| 439 | + None => return Ok(None), | |
| 440 | + } | |
| 441 | + } | |
| 442 | + chain.reverse(); | |
| 443 | + Ok(Some(chain)) | |
| 444 | +} | |
| 445 | + | |
| 446 | +/// Everything one pass needs. | |
| 447 | +struct Pass<'a> { | |
| 448 | + args: &'a VerifyArgs, | |
| 449 | + repo: &'a Repo, | |
| 450 | + link: Option<Link>, | |
| 451 | + branch: &'a str, | |
| 452 | + tip: ObjectId, | |
| 453 | + green_before: Option<ObjectId>, | |
| 454 | +} | |
| 455 | + | |
| 456 | +impl Pass<'_> { | |
| 457 | + fn run(&self, tester: &mut Tester<'_>) -> Result<Verdict> { | |
| 458 | + let mut verdict = Verdict { | |
| 459 | + green: self.green_before, | |
| 460 | + ..Verdict::default() | |
| 461 | + }; | |
| 462 | + if self.green_before == Some(self.tip) { | |
| 463 | + verdict.outcome = "pass"; | |
| 464 | + verdict.reason = Some("the head is the green changeset already".to_owned()); | |
| 465 | + return Ok(verdict); | |
| 466 | + } | |
| 467 | + let (passed, flaky) = tester.passes(self.tip)?; | |
| 468 | + if passed { | |
| 469 | + verdict.outcome = if flaky { "flaky" } else { "pass" }; | |
| 470 | + if flaky { | |
| 471 | + verdict.reason = Some("a run failed, and a rerun passed".to_owned()); | |
| 472 | + } | |
| 473 | + if self.args.dry_run { | |
| 474 | + let moved = format!("dry run: the green ref would move to {}", self.tip.short()); | |
| 475 | + verdict.reason = Some(match verdict.reason.take() { | |
| 476 | + Some(reason) => format!("{reason}; {moved}"), | |
| 477 | + None => moved, | |
| 478 | + }); | |
| 479 | + } else { | |
| 480 | + self.move_green()?; | |
| 481 | + verdict.green = Some(self.tip); | |
| 482 | + } | |
| 483 | + return Ok(verdict); | |
| 484 | + } | |
| 485 | + | |
| 486 | + verdict.outcome = "red"; | |
| 487 | + let good = match &self.args.from { | |
| 488 | + Some(revision) => Some(resolve_changeset(self.repo, revision)?), | |
| 489 | + None => self.green_before, | |
| 490 | + }; | |
| 491 | + let Some(good) = good else { | |
| 492 | + verdict.reason = Some( | |
| 493 | + "the tests fail on the head, and with no green changeset there is nothing to bisect from: --from names one" | |
| 494 | + .to_owned(), | |
| 495 | + ); | |
| 496 | + return Ok(verdict); | |
| 497 | + }; | |
| 498 | + let Some(range) = range(self.repo, self.tip, good)? else { | |
| 499 | + verdict.reason = Some(format!( | |
| 500 | + "{} is not on {}'s first-parent chain: there is nothing to bisect", | |
| 501 | + good.short(), | |
| 502 | + self.branch | |
| 503 | + )); | |
| 504 | + return Ok(verdict); | |
| 505 | + }; | |
| 506 | + if range.is_empty() { | |
| 507 | + verdict.outcome = "no_culprit"; | |
| 508 | + verdict.reason = Some(format!("the head is {}, which was to pass", good.short())); | |
| 509 | + return Ok(verdict); | |
| 510 | + } | |
| 511 | + // `range[lo]` passes (or is `good`, at -1), `range[hi]` fails. | |
| 512 | + let (mut lo, mut hi) = (-1_isize, range.len() as isize - 1); | |
| 513 | + while hi - lo > 1 { | |
| 514 | + let mid = lo + (hi - lo) / 2; | |
| 515 | + if tester.passes(range[mid as usize])?.0 { | |
| 516 | + lo = mid; | |
| 517 | + } else { | |
| 518 | + hi = mid; | |
| 519 | + } | |
| 520 | + } | |
| 521 | + let culprit = range[hi as usize]; | |
| 522 | + if lo < 0 && !tester.passes(good)?.0 { | |
| 523 | + // The changeset taken as passing fails now too: something | |
| 524 | + // outside the range broke the tests. | |
| 525 | + verdict.outcome = "no_culprit"; | |
| 526 | + verdict.reason = Some(format!( | |
| 527 | + "{} fails too, though it was to pass: the failure is not in the changesets after it", | |
| 528 | + good.short() | |
| 529 | + )); | |
| 530 | + return Ok(verdict); | |
| 531 | + } | |
| 532 | + verdict.culprit = Some(culprit); | |
| 533 | + self.revert(culprit, verdict) | |
| 534 | + } | |
| 535 | + | |
| 536 | + /// Moves the green ref from where it was to the tip, unless someone | |
| 537 | + /// moved it meanwhile. | |
| 538 | + fn move_green(&self) -> Result<()> { | |
| 539 | + let name = green_ref(self.branch); | |
| 540 | + let description = format!("verify: {name} at {}", self.tip.short()); | |
| 541 | + self.repo | |
| 542 | + .store() | |
| 543 | + .transact(AGENT, &description, |refs| { | |
| 544 | + let current = refs.get(&name); | |
| 545 | + if current != self.green_before { | |
| 546 | + return Err(format!( | |
| 547 | + "{name} moved while verify ran, to {}: is another verify running?", | |
| 548 | + short(current) | |
| 549 | + )); | |
| 550 | + } | |
| 551 | + Ok(vec![RefUpdate::new( | |
| 552 | + name.clone(), | |
| 553 | + self.green_before, | |
| 554 | + Some(self.tip), | |
| 555 | + )]) | |
| 556 | + }) | |
| 557 | + .map_err(|err| anyhow::anyhow!("{err}"))?; | |
| 558 | + Ok(()) | |
| 559 | + } | |
| 560 | + | |
| 561 | + /// Decides whether to revert `culprit`, and does. | |
| 562 | + fn revert(&self, culprit: ObjectId, mut verdict: Verdict) -> Result<Verdict> { | |
| 563 | + let first = format!( | |
| 564 | + "the tests fail from {}, the first changeset that fails", | |
| 565 | + culprit.short() | |
| 566 | + ); | |
| 567 | + if !self.args.revert { | |
| 568 | + verdict.reason = Some(format!("{first}; --revert would revert it")); | |
| 569 | + return Ok(verdict); | |
| 570 | + } | |
| 571 | + let parents = braid_engine::read_changeset(self.repo.store(), culprit)? | |
| 572 | + .parents | |
| 573 | + .len(); | |
| 574 | + let path = Record::path(self.repo, self.branch); | |
| 575 | + let mut record = Record::load(&path)?; | |
| 576 | + let now = now_seconds(); | |
| 577 | + let refusal = if parents > 1 { | |
| 578 | + Some(format!( | |
| 579 | + "{first}, and it is a merge: verify does not revert merges" | |
| 580 | + )) | |
| 581 | + } else if record.made(culprit) { | |
| 582 | + Some(format!( | |
| 583 | + "{first}, and it is a revert verify made: verify does not revert its own reverts" | |
| 584 | + )) | |
| 585 | + } else if record.in_last_hour(now) >= self.args.max_reverts_per_hour { | |
| 586 | + Some(format!( | |
| 587 | + "{first}, but verify landed {} on {} in the last hour, the most --max-reverts-per-hour allows", | |
| 588 | + crate::work::count(record.in_last_hour(now), "revert"), | |
| 589 | + self.branch | |
| 590 | + )) | |
| 591 | + } else { | |
| 592 | + None | |
| 593 | + }; | |
| 594 | + if let Some(reason) = refusal { | |
| 595 | + verdict.outcome = "refused"; | |
| 596 | + verdict.reason = Some(reason); | |
| 597 | + return Ok(verdict); | |
| 598 | + } | |
| 599 | + if self.args.dry_run { | |
| 600 | + verdict.reason = Some(format!("{first}; dry run: verify would revert it")); | |
| 601 | + return Ok(verdict); | |
| 602 | + } | |
| 603 | + let author = identity(&self.args.identity, self.repo)?; | |
| 604 | + let change = braid_wc::create_revert( | |
| 605 | + self.repo.store(), | |
| 606 | + &RevertRequest { | |
| 607 | + culprit, | |
| 608 | + allow_merge: false, | |
| 609 | + author: author.clone(), | |
| 610 | + agent: AGENT.to_owned(), | |
| 611 | + }, | |
| 612 | + )?; | |
| 613 | + verdict.revert = Some(change); | |
| 614 | + let mut report = land_revert( | |
| 615 | + self.repo, | |
| 616 | + self.link.as_ref(), | |
| 617 | + self.branch, | |
| 618 | + change, | |
| 619 | + AGENT, | |
| 620 | + &author, | |
| 621 | + )?; | |
| 622 | + match report.outcome.as_str() { | |
| 623 | + "fast-forward" | "rebased" => { | |
| 624 | + record.reverts.push(Reverted { | |
| 625 | + culprit: culprit.to_hex(), | |
| 626 | + revert: change.to_hex(), | |
| 627 | + landed: report.head.map(|id| id.to_hex()), | |
| 628 | + time: now, | |
| 629 | + }); | |
| 630 | + record.save(&path)?; | |
| 631 | + verdict.outcome = "reverted"; | |
| 632 | + verdict.reason = Some(format!("{first}; its revert landed on {}", self.branch)); | |
| 633 | + } | |
| 634 | + "conflicts" => { | |
| 635 | + verdict.outcome = "revert_conflicts"; | |
| 636 | + verdict.reason = Some(format!( | |
| 637 | + "{first}; its revert conflicts with what landed since, so {} did not move: revert it by hand in a workspace", | |
| 638 | + self.branch | |
| 639 | + )); | |
| 640 | + report.next = None; | |
| 641 | + } | |
| 642 | + "already-applied" => { | |
| 643 | + verdict.outcome = "refused"; | |
| 644 | + verdict.reason = Some(format!( | |
| 645 | + "{first}, but {} has what its revert would change already", | |
| 646 | + self.branch | |
| 647 | + )); | |
| 648 | + } | |
| 649 | + other => bail!("the revert's landing ended with {other}"), | |
| 650 | + } | |
| 651 | + verdict.land = Some(report); | |
| 652 | + Ok(verdict) | |
| 653 | + } | |
| 654 | +} | |
| 655 | + | |
| 656 | +pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> { | |
| 657 | + let repo = open_repo(cli)?; | |
| 658 | + let branch = branch_or_main(&repo, args.branch.as_deref())?; | |
| 659 | + if !braid_repo::is_branch(&branch) { | |
| 660 | + bail!("{branch:?} is in one of braid's own namespaces, not a branch"); | |
| 661 | + } | |
| 662 | + let link = hub::linked(&repo, args.local)?; | |
| 663 | + if let Some(link) = &link | |
| 664 | + && !args.dry_run | |
| 665 | + { | |
| 666 | + let hub = hub::connect(link)?; | |
| 667 | + let remote = hub.repo(link.repo.clone()); | |
| 668 | + hub::fetch::fetch(&repo, &remote, link, AGENT, None).context( | |
| 669 | + "cannot fetch from the hub before verifying (--local verifies the local branch as it is)", | |
| 670 | + )?; | |
| 671 | + } | |
| 672 | + let refs = repo.store().refs()?; | |
| 673 | + let Some(tip) = refs.get(&branch) else { | |
| 674 | + bail!("there is no branch {branch:?} to verify"); | |
| 675 | + }; | |
| 676 | + let green_before = refs.get(&green_ref(&branch)); | |
| 677 | + let pass = Pass { | |
| 678 | + args, | |
| 679 | + repo: &repo, | |
| 680 | + link, | |
| 681 | + branch: &branch, | |
| 682 | + tip, | |
| 683 | + green_before, | |
| 684 | + }; | |
| 685 | + let mut tester = Tester { | |
| 686 | + repo: &repo, | |
| 687 | + branch: &branch, | |
| 688 | + command: &args.command, | |
| 689 | + timeout: args.timeout, | |
| 690 | + reruns: args.reruns, | |
| 691 | + runs: 0, | |
| 692 | + }; | |
| 693 | + let verdict = match pass.run(&mut tester) { | |
| 694 | + Ok(verdict) => verdict, | |
| 695 | + // Before anything ran, an error is only an error. | |
| 696 | + Err(err) if tester.runs == 0 => return Err(err), | |
| 697 | + Err(err) => { | |
| 698 | + eprintln!("braid: error: {err:#}"); | |
| 699 | + Verdict { | |
| 700 | + outcome: "error", | |
| 701 | + green: green_before, | |
| 702 | + reason: Some(format!("{err:#}")), | |
| 703 | + ..Verdict::default() | |
| 704 | + } | |
| 705 | + } | |
| 706 | + }; | |
| 707 | + if cli.json { | |
| 708 | + print_json(&json!({ | |
| 709 | + "branch": branch, | |
| 710 | + "tip": tip.to_hex(), | |
| 711 | + "green_before": hex(green_before), | |
| 712 | + "green": hex(verdict.green), | |
| 713 | + "outcome": verdict.outcome, | |
| 714 | + "culprit": hex(verdict.culprit), | |
| 715 | + "revert": hex(verdict.revert), | |
| 716 | + "tests_run": tester.runs, | |
| 717 | + "reason": verdict.reason, | |
| 718 | + "dry_run": args.dry_run, | |
| 719 | + "land": verdict.land.as_ref().map_or(Value::Null, Report::json), | |
| 720 | + }))?; | |
| 721 | + } else { | |
| 722 | + print_text(&branch, tip, &verdict, tester.runs); | |
| 723 | + } | |
| 724 | + Ok(verdict.exit_code()) | |
| 725 | +} | |
| 726 | + | |
| 727 | +fn print_text(branch: &str, tip: ObjectId, verdict: &Verdict, runs: usize) { | |
| 728 | + let ran = crate::work::count(runs, "run"); | |
| 729 | + match verdict.outcome { | |
| 730 | + "pass" | "flaky" => println!( | |
| 731 | + "{branch} is green at {} ({}, {ran})", | |
| 732 | + tip.short(), | |
| 733 | + verdict.outcome | |
| 734 | + ), | |
| 735 | + outcome => println!("{branch} at {}: {outcome} ({ran})", tip.short()), | |
| 736 | + } | |
| 737 | + if let Some(reason) = &verdict.reason { | |
| 738 | + println!("{reason}"); | |
| 739 | + } | |
| 740 | + if let Some(report) = &verdict.land | |
| 741 | + && report.conflicted() | |
| 742 | + { | |
| 743 | + print_conflicts(&report.conflicts); | |
| 744 | + } | |
| 745 | +} | |
| 746 | + | |
| 747 | +#[cfg(test)] | |
| 748 | +mod tests { | |
| 749 | + use super::*; | |
| 750 | + | |
| 751 | + #[test] | |
| 752 | + fn durations() { | |
| 753 | + assert_eq!(parse_duration("10m"), Ok(Duration::from_secs(600))); | |
| 754 | + assert_eq!(parse_duration("30s"), Ok(Duration::from_secs(30))); | |
| 755 | + assert_eq!(parse_duration("2h"), Ok(Duration::from_secs(7200))); | |
| 756 | + assert_eq!(parse_duration("45"), Ok(Duration::from_secs(45))); | |
| 757 | + for bad in ["", "0s", "m", "10x", "1.5m", "-1s", "10 m"] { | |
| 758 | + assert!(parse_duration(bad).is_err(), "{bad}"); | |
| 759 | + } | |
| 760 | + } | |
| 761 | + | |
| 762 | + #[test] | |
| 763 | + fn credentials_are_recognised() { | |
| 764 | + for name in [ | |
| 765 | + "BRAID_TOKEN", | |
| 766 | + "BRAID_HUB", | |
| 767 | + "BRAID_HUB_URL", | |
| 768 | + "BRAID_HUB_MAX_BODY", | |
| 769 | + ] { | |
| 770 | + assert!(is_credential(name.as_ref()), "{name}"); | |
| 771 | + } | |
| 772 | + for name in ["BRAID_AGENT", "BRAID_AUTHOR", "PATH", "BRAID_TOKENS"] { | |
| 773 | + assert!(!is_credential(name.as_ref()), "{name}"); | |
| 774 | + } | |
| 775 | + } | |
| 776 | + | |
| 777 | + #[test] | |
| 778 | + fn record_paths_escape_branch_names() { | |
| 779 | + let temp = tempfile::tempdir().unwrap(); | |
| 780 | + let repo = Repo::init(temp.path()).unwrap(); | |
| 781 | + let path = Record::path(&repo, "feature/x y"); | |
| 782 | + assert_eq!(path.file_name().unwrap(), "feature%2Fx%20y.json"); | |
| 783 | + assert_eq!( | |
| 784 | + Record::path(&repo, "main").file_name().unwrap(), | |
| 785 | + "main.json" | |
| 786 | + ); | |
| 787 | + let mut record = Record::default(); | |
| 788 | + record.reverts.push(Reverted { | |
| 789 | + culprit: "c".repeat(64), | |
| 790 | + revert: "a".repeat(64), | |
| 791 | + landed: Some("b".repeat(64)), | |
| 792 | + time: 10_000, | |
| 793 | + }); | |
| 794 | + let landed: ObjectId = "b".repeat(64).parse().unwrap(); | |
| 795 | + assert!(record.made(landed)); | |
| 796 | + assert_eq!(record.in_last_hour(10_000 + 3599), 1); | |
| 797 | + assert_eq!(record.in_last_hour(10_000 + 3600), 0); | |
| 798 | + record.save(&path).unwrap(); | |
| 799 | + assert_eq!(Record::load(&path).unwrap().reverts.len(), 1); | |
| 800 | + } | |
| 801 | +} |
modified crates/cli/src/work.rs +8 −0
| @@ -84,6 +84,8 @@ | ||
| 84 | 84 | branch the branch it lands on and updates from |
| 85 | 85 | base the changeset its working copy is at, or null |
| 86 | 86 | head the branch's head, or null when the branch does not exist |
| 87 | + green the newest changeset of the branch that passed `braid | |
| 88 | + verify`, braid/green/<branch>, or null | |
| 87 | 89 | behind whether the branch has changesets the workspace does not |
| 88 | 90 | behind_by how many: the changesets from the branch's head down to |
| 89 | 91 | the one the workspace's own start from, along first |
| @@ -564,12 +566,18 @@ | ||
| 564 | 566 | })).collect::<Vec<_>>(), |
| 565 | 567 | }) |
| 566 | 568 | }); |
| 569 | + let green = target | |
| 570 | + .repo | |
| 571 | + .store() | |
| 572 | + .refs()? | |
| 573 | + .get(&crate::verify::green_ref(&state.branch)); | |
| 567 | 574 | print_json(&json!({ |
| 568 | 575 | "workspace": workspace.name(), |
| 569 | 576 | "path": workspace.dir().to_string_lossy(), |
| 570 | 577 | "branch": state.branch, |
| 571 | 578 | "base": hex(state.base), |
| 572 | 579 | "head": hex(report.head), |
| 580 | + "green": hex(green), | |
| 573 | 581 | "behind": report.behind(), |
| 574 | 582 | "behind_by": report.behind_by, |
| 575 | 583 | "clean": status.is_clean(), |
added crates/cli/tests/verify.rs +466 −0
| @@ -0,0 +1,466 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | + | |
| 4 | +//! `braid verify` end to end, on small repositories whose test is a script | |
| 5 | +//! of their own, `check.sh`, which fails while a file named `broken` is | |
| 6 | +//! there: the green ref, bisecting to the changeset that broke the tests, | |
| 7 | +//! reverting it, and the limits on reverting. | |
| 8 | + | |
| 9 | +use std::path::{Path, PathBuf}; | |
| 10 | +use std::process::{Command, Output}; | |
| 11 | + | |
| 12 | +use serde_json::Value; | |
| 13 | + | |
| 14 | +/// The project's test, committed in every repository here. | |
| 15 | +const CHECK: &str = "test ! -f broken\n"; | |
| 16 | + | |
| 17 | +fn braid_with(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> Output { | |
| 18 | + Command::new(env!("CARGO_BIN_EXE_braid")) | |
| 19 | + .current_dir(dir) | |
| 20 | + .args(args) | |
| 21 | + .env("BRAID_AGENT", "tester") | |
| 22 | + .env("BRAID_AUTHOR", "Ada <ada@example.org>") | |
| 23 | + .env("BRAID_HUB", "off") | |
| 24 | + .envs(envs.iter().copied()) | |
| 25 | + .output() | |
| 26 | + .unwrap() | |
| 27 | +} | |
| 28 | + | |
| 29 | +/// Runs braid with `--json`, expecting exit status `code`. | |
| 30 | +fn run(dir: &Path, args: &[&str], code: i32) -> Value { | |
| 31 | + let mut all = vec!["--json"]; | |
| 32 | + all.extend_from_slice(args); | |
| 33 | + let out = braid_with(dir, &all, &[]); | |
| 34 | + assert_eq!( | |
| 35 | + out.status.code(), | |
| 36 | + Some(code), | |
| 37 | + "braid {args:?}: {}{}", | |
| 38 | + String::from_utf8_lossy(&out.stdout), | |
| 39 | + String::from_utf8_lossy(&out.stderr) | |
| 40 | + ); | |
| 41 | + serde_json::from_slice(&out.stdout).unwrap_or(Value::Null) | |
| 42 | +} | |
| 43 | + | |
| 44 | +fn id(value: &Value) -> String { | |
| 45 | + value.as_str().unwrap().to_owned() | |
| 46 | +} | |
| 47 | + | |
| 48 | +struct Repo { | |
| 49 | + _temp: tempfile::TempDir, | |
| 50 | + /// A directory outside the repository, for the tests' own files. | |
| 51 | + outside: PathBuf, | |
| 52 | + dir: PathBuf, | |
| 53 | +} | |
| 54 | + | |
| 55 | +impl Repo { | |
| 56 | + /// A repository whose `main` holds `check.sh` and a notes file. | |
| 57 | + fn new() -> Repo { | |
| 58 | + let temp = tempfile::tempdir().unwrap(); | |
| 59 | + let base = std::fs::canonicalize(temp.path()).unwrap(); | |
| 60 | + let dir = base.join("repo"); | |
| 61 | + let outside = base.join("outside"); | |
| 62 | + std::fs::create_dir(&outside).unwrap(); | |
| 63 | + run(&base, &["init", dir.to_str().unwrap()], 0); | |
| 64 | + let repo = Repo { | |
| 65 | + _temp: temp, | |
| 66 | + outside, | |
| 67 | + dir, | |
| 68 | + }; | |
| 69 | + repo.land(&[("check.sh", CHECK), ("notes", "1\n2\n3\n")], &[], "Seed"); | |
| 70 | + repo | |
| 71 | + } | |
| 72 | + | |
| 73 | + /// Lands a change on `main` that sets and deletes paths, and returns | |
| 74 | + /// the changeset that holds it on `main`. | |
| 75 | + fn land(&self, sets: &[(&str, &str)], deletes: &[&str], message: &str) -> String { | |
| 76 | + let base = self.head().unwrap_or_else(|| "none".to_owned()); | |
| 77 | + let mut args = vec!["change", "create", "--base", &base, "-m", message]; | |
| 78 | + let mut owned = Vec::new(); | |
| 79 | + for (n, (path, text)) in sets.iter().enumerate() { | |
| 80 | + let file = self.outside.join(format!("{message}-{n}")); | |
| 81 | + std::fs::write(&file, text).unwrap(); | |
| 82 | + owned.push(format!("{path}=@{}", file.display())); | |
| 83 | + } | |
| 84 | + for set in &owned { | |
| 85 | + args.extend(["--set", set]); | |
| 86 | + } | |
| 87 | + for path in deletes { | |
| 88 | + args.extend(["--delete", path]); | |
| 89 | + } | |
| 90 | + args.extend(["--land", "main"]); | |
| 91 | + let out = run(&self.dir, &args, 0); | |
| 92 | + id(&out["land"]["head"]) | |
| 93 | + } | |
| 94 | + | |
| 95 | + fn head(&self) -> Option<String> { | |
| 96 | + self.reference("main") | |
| 97 | + } | |
| 98 | + | |
| 99 | + fn green(&self) -> Option<String> { | |
| 100 | + self.reference("braid/green/main") | |
| 101 | + } | |
| 102 | + | |
| 103 | + fn reference(&self, name: &str) -> Option<String> { | |
| 104 | + let refs = run(&self.dir, &["refs"], 0); | |
| 105 | + refs["refs"][name].as_str().map(str::to_owned) | |
| 106 | + } | |
| 107 | + | |
| 108 | + /// Runs `braid verify` with `flags`, then `--` and `command`, expecting | |
| 109 | + /// exit status `code`. | |
| 110 | + fn verify_env( | |
| 111 | + &self, | |
| 112 | + flags: &[&str], | |
| 113 | + command: &[&str], | |
| 114 | + envs: &[(&str, &str)], | |
| 115 | + code: i32, | |
| 116 | + ) -> Value { | |
| 117 | + let mut args = vec!["--json", "verify"]; | |
| 118 | + args.extend_from_slice(flags); | |
| 119 | + args.push("--"); | |
| 120 | + args.extend_from_slice(command); | |
| 121 | + let out = braid_with(&self.dir, &args, envs); | |
| 122 | + assert_eq!( | |
| 123 | + out.status.code(), | |
| 124 | + Some(code), | |
| 125 | + "braid {args:?}: {}{}", | |
| 126 | + String::from_utf8_lossy(&out.stdout), | |
| 127 | + String::from_utf8_lossy(&out.stderr) | |
| 128 | + ); | |
| 129 | + serde_json::from_slice(&out.stdout).unwrap() | |
| 130 | + } | |
| 131 | + | |
| 132 | + fn verify(&self, flags: &[&str], code: i32) -> Value { | |
| 133 | + self.verify_env(flags, &["sh", "check.sh"], &[], code) | |
| 134 | + } | |
| 135 | + | |
| 136 | + /// The test command of a repository whose failing changesets are listed | |
| 137 | + /// in a file outside it: a changeset fails when its id is in the list. | |
| 138 | + fn listed(&self) -> (PathBuf, Vec<String>) { | |
| 139 | + let list = self.outside.join("failing"); | |
| 140 | + std::fs::write(&list, "").unwrap(); | |
| 141 | + let script = self.outside.join("listed.sh"); | |
| 142 | + std::fs::write( | |
| 143 | + &script, | |
| 144 | + "if grep -qx \"$BRAID_VERIFY_CHANGESET\" \"$1\"; then exit 1; fi\n", | |
| 145 | + ) | |
| 146 | + .unwrap(); | |
| 147 | + let command = vec![ | |
| 148 | + "sh".to_owned(), | |
| 149 | + script.display().to_string(), | |
| 150 | + list.display().to_string(), | |
| 151 | + ]; | |
| 152 | + (list, command) | |
| 153 | + } | |
| 154 | + | |
| 155 | + fn has_record(&self) -> bool { | |
| 156 | + self.dir.join(".braid/verify/main.json").is_file() | |
| 157 | + } | |
| 158 | +} | |
| 159 | + | |
| 160 | +/// A repository where `main` was verified green at the seed, then had four | |
| 161 | +/// changesets landed, the second of which broke the tests. Returns the | |
| 162 | +/// seed and the four. | |
| 163 | +fn broken_after_green() -> (Repo, String, Vec<String>) { | |
| 164 | + let r = Repo::new(); | |
| 165 | + let seed = r.head().unwrap(); | |
| 166 | + let out = r.verify(&[], 0); | |
| 167 | + assert_eq!(out["outcome"], "pass"); | |
| 168 | + let ids = vec![ | |
| 169 | + r.land(&[("a", "a\n")], &[], "Add a"), | |
| 170 | + r.land(&[("broken", "x\n")], &[], "Break the tests"), | |
| 171 | + r.land(&[("b", "b\n")], &[], "Add b"), | |
| 172 | + r.land(&[("c", "c\n")], &[], "Add c"), | |
| 173 | + ]; | |
| 174 | + (r, seed, ids) | |
| 175 | +} | |
| 176 | + | |
| 177 | +#[test] | |
| 178 | +fn a_pass_moves_the_green_ref_and_status_shows_it() { | |
| 179 | + let r = Repo::new(); | |
| 180 | + let tip = r.head().unwrap(); | |
| 181 | + let out = r.verify(&[], 0); | |
| 182 | + assert_eq!(out["outcome"], "pass"); | |
| 183 | + assert_eq!(out["branch"], "main"); | |
| 184 | + assert_eq!(out["tip"], tip.as_str()); | |
| 185 | + assert_eq!(out["green_before"], Value::Null); | |
| 186 | + assert_eq!(out["green"], tip.as_str()); | |
| 187 | + assert_eq!(out["tests_run"], 1); | |
| 188 | + assert_eq!(out["culprit"], Value::Null); | |
| 189 | + assert_eq!(out["revert"], Value::Null); | |
| 190 | + assert_eq!(r.green().as_deref(), Some(tip.as_str())); | |
| 191 | + | |
| 192 | + // The move is an operation of its own, by braid-verify. | |
| 193 | + let log = run(&r.dir, &["op", "log", "-n", "1"], 0); | |
| 194 | + assert_eq!(log[0]["agent"], "braid-verify"); | |
| 195 | + assert_eq!(log[0]["updates"][0]["name"], "braid/green/main"); | |
| 196 | + | |
| 197 | + // Nothing to run while the head is green. | |
| 198 | + let again = r.verify(&[], 0); | |
| 199 | + assert_eq!(again["outcome"], "pass"); | |
| 200 | + assert_eq!(again["tests_run"], 0); | |
| 201 | + | |
| 202 | + run(&r.dir, &["workspace", "add", "w"], 0); | |
| 203 | + let status = run(&r.dir, &["status", "--workspace", "w"], 0); | |
| 204 | + assert_eq!(status["green"], tip.as_str()); | |
| 205 | + | |
| 206 | + let text = braid_with(&r.dir, &["verify", "--", "sh", "check.sh"], &[]); | |
| 207 | + assert!(text.status.success()); | |
| 208 | + let text = String::from_utf8(text.stdout).unwrap(); | |
| 209 | + assert!(text.starts_with("main is green at"), "{text}"); | |
| 210 | +} | |
| 211 | + | |
| 212 | +#[test] | |
| 213 | +fn a_dry_run_moves_no_green_ref() { | |
| 214 | + let r = Repo::new(); | |
| 215 | + let out = r.verify(&["--dry-run"], 0); | |
| 216 | + assert_eq!(out["outcome"], "pass"); | |
| 217 | + assert_eq!(out["dry_run"], true); | |
| 218 | + assert_eq!(out["green"], Value::Null); | |
| 219 | + assert!(id(&out["reason"]).contains("dry run")); | |
| 220 | + assert_eq!(r.green(), None); | |
| 221 | +} | |
| 222 | + | |
| 223 | +#[test] | |
| 224 | +fn red_on_the_head_bisects_to_the_changeset_that_broke_it() { | |
| 225 | + let (r, seed, ids) = broken_after_green(); | |
| 226 | + let out = r.verify(&["--reruns", "0"], 4); | |
| 227 | + assert_eq!(out["outcome"], "red"); | |
| 228 | + assert_eq!(out["tip"], ids[3].as_str()); | |
| 229 | + assert_eq!(out["culprit"], ids[1].as_str()); | |
| 230 | + assert_eq!(out["green_before"], seed.as_str()); | |
| 231 | + assert_eq!(out["green"], seed.as_str()); | |
| 232 | + assert_eq!(out["revert"], Value::Null); | |
| 233 | + // The head, then the second and the first changesets after green. | |
| 234 | + assert_eq!(out["tests_run"], 3); | |
| 235 | + assert!(id(&out["reason"]).contains("--revert")); | |
| 236 | + assert_eq!(r.green(), Some(seed)); | |
| 237 | + assert_eq!(r.head().as_deref(), Some(ids[3].as_str())); | |
| 238 | +} | |
| 239 | + | |
| 240 | +#[test] | |
| 241 | +fn without_a_green_ref_only_the_head_is_tested_unless_from_says() { | |
| 242 | + let r = Repo::new(); | |
| 243 | + let seed = r.head().unwrap(); | |
| 244 | + let culprit = r.land(&[("broken", "x\n")], &[], "Break"); | |
| 245 | + r.land(&[("a", "a\n")], &[], "Add a"); | |
| 246 | + let out = r.verify(&[], 4); | |
| 247 | + assert_eq!(out["outcome"], "red"); | |
| 248 | + assert_eq!(out["culprit"], Value::Null); | |
| 249 | + // The head, and the rerun. | |
| 250 | + assert_eq!(out["tests_run"], 2); | |
| 251 | + assert!(id(&out["reason"]).contains("--from")); | |
| 252 | + | |
| 253 | + let out = r.verify(&["--from", &seed, "--reruns", "0"], 4); | |
| 254 | + assert_eq!(out["culprit"], culprit.as_str()); | |
| 255 | + assert_eq!(r.green(), None); | |
| 256 | +} | |
| 257 | + | |
| 258 | +#[test] | |
| 259 | +fn a_revert_lands_and_the_green_ref_stays_until_the_next_pass() { | |
| 260 | + let (r, seed, ids) = broken_after_green(); | |
| 261 | + let out = r.verify(&["--revert", "--reruns", "0"], 4); | |
| 262 | + assert_eq!(out["outcome"], "reverted"); | |
| 263 | + assert_eq!(out["culprit"], ids[1].as_str()); | |
| 264 | + let revert = id(&out["revert"]); | |
| 265 | + assert_eq!(out["land"]["outcome"], "rebased"); | |
| 266 | + assert_eq!(out["green"], seed.as_str()); | |
| 267 | + assert_eq!(r.green().as_deref(), Some(seed.as_str())); | |
| 268 | + let head = r.head().unwrap(); | |
| 269 | + assert_eq!(out["land"]["head"], head.as_str()); | |
| 270 | + assert!(r.has_record()); | |
| 271 | + | |
| 272 | + // The revert names its culprit, and braid-verify made it. | |
| 273 | + let shown = run(&r.dir, &["show", "main"], 0); | |
| 274 | + assert_eq!(shown["agent"], "braid-verify"); | |
| 275 | + assert!( | |
| 276 | + shown["extras"] | |
| 277 | + .as_array() | |
| 278 | + .unwrap() | |
| 279 | + .contains(&serde_json::json!(["rebased-from", revert])) | |
| 280 | + ); | |
| 281 | + assert!( | |
| 282 | + shown["changes"] | |
| 283 | + .as_array() | |
| 284 | + .unwrap() | |
| 285 | + .iter() | |
| 286 | + .any(|c| c["path"] == "broken" && c["op"] == "delete") | |
| 287 | + ); | |
| 288 | + | |
| 289 | + // The next pass tests the new head, which passes. | |
| 290 | + let next = r.verify(&["--revert"], 0); | |
| 291 | + assert_eq!(next["outcome"], "pass"); | |
| 292 | + assert_eq!(next["green"], head.as_str()); | |
| 293 | +} | |
| 294 | + | |
| 295 | +#[test] | |
| 296 | +fn a_dry_run_finds_the_culprit_and_reverts_nothing() { | |
| 297 | + let (r, seed, ids) = broken_after_green(); | |
| 298 | + let out = r.verify(&["--revert", "--dry-run", "--reruns", "0"], 4); | |
| 299 | + assert_eq!(out["outcome"], "red"); | |
| 300 | + assert_eq!(out["culprit"], ids[1].as_str()); | |
| 301 | + assert_eq!(out["revert"], Value::Null); | |
| 302 | + assert!(id(&out["reason"]).contains("dry run")); | |
| 303 | + assert_eq!(r.head().as_deref(), Some(ids[3].as_str())); | |
| 304 | + assert_eq!(r.green(), Some(seed)); | |
| 305 | + assert!(!r.has_record()); | |
| 306 | +} | |
| 307 | + | |
| 308 | +#[test] | |
| 309 | +fn reverts_stop_at_the_hourly_cap() { | |
| 310 | + let (r, _, ids) = broken_after_green(); | |
| 311 | + let none = r.verify( | |
| 312 | + &["--revert", "--reruns", "0", "--max-reverts-per-hour", "0"], | |
| 313 | + 4, | |
| 314 | + ); | |
| 315 | + assert_eq!(none["outcome"], "refused"); | |
| 316 | + assert!(id(&none["reason"]).contains("--max-reverts-per-hour")); | |
| 317 | + assert_eq!(r.head().as_deref(), Some(ids[3].as_str())); | |
| 318 | + | |
| 319 | + let first = r.verify( | |
| 320 | + &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"], | |
| 321 | + 4, | |
| 322 | + ); | |
| 323 | + assert_eq!(first["outcome"], "reverted"); | |
| 324 | + // Green again, then broken again: the cap of one an hour is spent. | |
| 325 | + assert_eq!(r.verify(&[], 0)["outcome"], "pass"); | |
| 326 | + let again = r.land(&[("broken", "again\n")], &[], "Break again"); | |
| 327 | + let second = r.verify( | |
| 328 | + &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"], | |
| 329 | + 4, | |
| 330 | + ); | |
| 331 | + assert_eq!(second["outcome"], "refused"); | |
| 332 | + assert!(id(&second["reason"]).contains("1 revert on main in the last hour")); | |
| 333 | + assert_eq!(r.head(), Some(again)); | |
| 334 | + assert_eq!(second["revert"], Value::Null); | |
| 335 | +} | |
| 336 | + | |
| 337 | +#[test] | |
| 338 | +fn verify_does_not_revert_its_own_revert() { | |
| 339 | + let r = Repo::new(); | |
| 340 | + let (list, command) = r.listed(); | |
| 341 | + let command: Vec<&str> = command.iter().map(String::as_str).collect(); | |
| 342 | + let seed = r.head().unwrap(); | |
| 343 | + let green = r.verify_env(&[], &command, &[], 0); | |
| 344 | + assert_eq!(green["green"], seed.as_str()); | |
| 345 | + | |
| 346 | + let culprit = r.land(&[("a", "a\n")], &[], "Change a"); | |
| 347 | + std::fs::write(&list, format!("{culprit}\n")).unwrap(); | |
| 348 | + let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4); | |
| 349 | + assert_eq!(out["outcome"], "reverted"); | |
| 350 | + let revert = r.head().unwrap(); | |
| 351 | + | |
| 352 | + // Now the revert fails and the change it undid passes: the culprit is | |
| 353 | + // the revert, which verify leaves alone. | |
| 354 | + std::fs::write(&list, format!("{revert}\n")).unwrap(); | |
| 355 | + let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4); | |
| 356 | + assert_eq!(out["outcome"], "refused"); | |
| 357 | + assert_eq!(out["culprit"], revert.as_str()); | |
| 358 | + assert!(id(&out["reason"]).contains("its own reverts")); | |
| 359 | + assert_eq!(r.head(), Some(revert)); | |
| 360 | +} | |
| 361 | + | |
| 362 | +#[test] | |
| 363 | +fn a_failure_before_every_changeset_in_range_has_no_culprit() { | |
| 364 | + let r = Repo::new(); | |
| 365 | + let (list, command) = r.listed(); | |
| 366 | + let command: Vec<&str> = command.iter().map(String::as_str).collect(); | |
| 367 | + let seed = r.head().unwrap(); | |
| 368 | + r.verify_env(&[], &command, &[], 0); | |
| 369 | + let change = r.land(&[("a", "a\n")], &[], "Change a"); | |
| 370 | + // Something outside the repository broke: the green changeset fails too. | |
| 371 | + std::fs::write(&list, format!("{seed}\n{change}\n")).unwrap(); | |
| 372 | + let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4); | |
| 373 | + assert_eq!(out["outcome"], "no_culprit"); | |
| 374 | + assert_eq!(out["culprit"], Value::Null); | |
| 375 | + assert_eq!(out["tests_run"], 2); | |
| 376 | + assert_eq!(r.head(), Some(change)); | |
| 377 | +} | |
| 378 | + | |
| 379 | +#[test] | |
| 380 | +fn a_revert_that_conflicts_exits_with_2_and_moves_nothing() { | |
| 381 | + let r = Repo::new(); | |
| 382 | + r.verify(&[], 0); | |
| 383 | + r.land(&[("notes", "1\nbad\n3\n"), ("broken", "x\n")], &[], "Break"); | |
| 384 | + let later = r.land(&[("notes", "1\nworse\n3\n")], &[], "Edit the same line"); | |
| 385 | + let out = r.verify(&["--revert", "--reruns", "0"], 2); | |
| 386 | + assert_eq!(out["outcome"], "revert_conflicts"); | |
| 387 | + assert_eq!(out["land"]["outcome"], "conflicts"); | |
| 388 | + assert_eq!(out["land"]["conflicts"][0]["path"], "notes"); | |
| 389 | + assert_eq!(r.head(), Some(later)); | |
| 390 | +} | |
| 391 | + | |
| 392 | +#[test] | |
| 393 | +fn a_run_that_fails_then_passes_is_flaky() { | |
| 394 | + let r = Repo::new(); | |
| 395 | + let marker = r.outside.join("ran-once"); | |
| 396 | + let script = format!( | |
| 397 | + "if [ -f '{0}' ]; then exit 0; fi; touch '{0}'; exit 1", | |
| 398 | + marker.display() | |
| 399 | + ); | |
| 400 | + let out = r.verify_env(&[], &["sh", "-c", &script], &[], 0); | |
| 401 | + assert_eq!(out["outcome"], "flaky"); | |
| 402 | + assert_eq!(out["tests_run"], 2); | |
| 403 | + assert_eq!(out["green"], r.head().unwrap().as_str()); | |
| 404 | +} | |
| 405 | + | |
| 406 | +#[test] | |
| 407 | +fn the_tests_get_a_clean_copy_and_no_credentials() { | |
| 408 | + let r = Repo::new(); | |
| 409 | + let tip = r.head().unwrap(); | |
| 410 | + let script = format!( | |
| 411 | + "test -z \"$BRAID_TOKEN\" && test -z \"$BRAID_HUB_URL\" && test -z \"$BRAID_HUB\" \ | |
| 412 | + && test \"$BRAID_VERIFY_CHANGESET\" = {tip} && test \"$BRAID_VERIFY_BRANCH\" = main \ | |
| 413 | + && test -f check.sh && test -f notes && test ! -e .braid && test ! -e .git" | |
| 414 | + ); | |
| 415 | + let envs = [ | |
| 416 | + ("BRAID_TOKEN", "brd_secret"), | |
| 417 | + ("BRAID_HUB_URL", "https://hub.example.org"), | |
| 418 | + ]; | |
| 419 | + let out = r.verify_env(&["--dry-run"], &["sh", "-c", &script], &envs, 0); | |
| 420 | + assert_eq!(out["outcome"], "pass"); | |
| 421 | + // Braid's other variables reach the tests. | |
| 422 | + let leak = "test -n \"$BRAID_AGENT\""; | |
| 423 | + let out = r.verify_env(&["--dry-run"], &["sh", "-c", leak], &envs, 0); | |
| 424 | + assert_eq!(out["outcome"], "pass"); | |
| 425 | + // A command that cannot run is an error, not a red branch. | |
| 426 | + let out = braid_with(&r.dir, &["verify", "--", "no-such-command-for-braid"], &[]); | |
| 427 | + assert_eq!(out.status.code(), Some(1)); | |
| 428 | + assert!(out.stdout.is_empty()); | |
| 429 | +} | |
| 430 | + | |
| 431 | +#[cfg(unix)] | |
| 432 | +#[test] | |
| 433 | +fn a_timeout_kills_the_command_and_what_it_started() { | |
| 434 | + let r = Repo::new(); | |
| 435 | + let pid_file = r.outside.join("pid"); | |
| 436 | + let script = format!( | |
| 437 | + "sleep 120 > /dev/null 2>&1 & echo $! > '{}'; wait", | |
| 438 | + pid_file.display() | |
| 439 | + ); | |
| 440 | + let out = r.verify_env( | |
| 441 | + &["--timeout", "1s", "--reruns", "0"], | |
| 442 | + &["sh", "-c", &script], | |
| 443 | + &[], | |
| 444 | + 4, | |
| 445 | + ); | |
| 446 | + assert_eq!(out["outcome"], "red"); | |
| 447 | + assert_eq!(out["tests_run"], 1); | |
| 448 | + let pid = std::fs::read_to_string(&pid_file).unwrap(); | |
| 449 | + let pid = pid.trim(); | |
| 450 | + // The background sleep went with its group: gone, or a zombie waiting | |
| 451 | + // to be reaped. | |
| 452 | + let mut alive = true; | |
| 453 | + for _ in 0..100 { | |
| 454 | + let ps = Command::new("ps") | |
| 455 | + .args(["-o", "stat=", "-p", pid]) | |
| 456 | + .output() | |
| 457 | + .unwrap(); | |
| 458 | + let state = String::from_utf8_lossy(&ps.stdout).trim().to_owned(); | |
| 459 | + if state.is_empty() || state.starts_with('Z') { | |
| 460 | + alive = false; | |
| 461 | + break; | |
| 462 | + } | |
| 463 | + std::thread::sleep(std::time::Duration::from_millis(50)); | |
| 464 | + } | |
| 465 | + assert!(!alive, "the background process {pid} outlived the timeout"); | |
| 466 | +} |