Elffuss BraidHub

utopia-ia/elffuss-braid public

9e7f0f69e18e · 28.7 KiBRawPermalink
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
17use std::ffi::OsString;
18use std::fs;
19use std::io;
20use std::path::{Path, PathBuf};
21use std::process::{Child, Command, ExitCode, ExitStatus, Stdio};
22use std::sync::atomic::{AtomicU32, Ordering};
23use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
24
25use anyhow::{Context, Result, bail};
26use braid_format::ObjectId;
27use braid_repo::Repo;
28use braid_store::RefUpdate;
29use braid_wc::RevertRequest;
30use clap::Args;
31use serde::{Deserialize, Serialize};
32use serde_json::{Value, json};
33
34use crate::hub::{self, link::Link};
35use crate::revert::{branch_or_main, land_revert};
36use crate::work::{IdentityArgs, Report, hex, identity, print_conflicts, short};
37use 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.
41pub(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.
45const RED: u8 = 4;
46
47/// The exit status of a revert that conflicts, as for every conflict.
48const CONFLICTS: u8 = crate::work::CONFLICTS;
49
50/// The green ref of `branch`: the newest changeset of it that passed.
51pub(crate) fn green_ref(branch: &str) -> String {
52 format!("braid/green/{branch}")
53}
54
55/// The long help of `verify`.
56pub(crate) const VERIFY_HELP: &str =
57 "Run the project's tests on the head of a branch, once, and keep the
58branch green: braid/green/<branch> points at the newest changeset of the
59branch that passed. When the tests fail, find the changeset that broke
60them, and with --revert, revert it.
61
62The 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,
64in a new directory under the system's temporary directory: outside the
65repository, with no .braid file and no .git, so each run starts from
66scratch and nothing it writes stays. Its output goes to standard error. It
67gets BRAID_VERIFY_CHANGESET (the changeset's id) and BRAID_VERIFY_BRANCH,
68and neither BRAID_TOKEN nor any BRAID_HUB variable. A run fails when the
69command 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
71every 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
90nothing. In a repository linked to a hub, verify fetches first and lands a
91revert on the hub; --local, or BRAID_HUB=off, keeps it here. Run one verify
92per branch at a time.
93
94With --json it prints branch; tip, the head it tested; green_before and
95green, the green ref before and after; outcome, one of pass, flaky, red,
96reverted, revert_conflicts, refused, no_culprit or error; culprit, the
97first failing changeset, or null; revert, the revert made, or null;
98tests_run, how many times the command ran; reason, why, in words, or null;
99dry_run; and land, the landing report of the revert as `braid land --help`
100describes it, or null.
101
102Exit status: 0 for pass and flaky; 4 for red, reverted, refused and
103no_culprit; 2 for revert_conflicts; 1 for an error, with the report
104printed when the tests had started.";
105
106#[derive(Debug, Args)]
107pub(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.
144fn 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)]
166struct 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
175impl 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)]
189struct Record {
190 #[serde(default)]
191 reverts: Vec<Reverted>,
192}
193
194/// One revert verify landed.
195#[derive(Debug, Serialize, Deserialize)]
196struct 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
208impl 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
262fn 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.
269struct 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.
279enum RunEnd {
280 Exited(ExitStatus),
281 TimedOut,
282}
283
284impl 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…`.
363fn 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.
369fn 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.
380fn 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.
399fn 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.
429fn 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.
447struct 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
456impl 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
656pub(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
727fn 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)]
748mod 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}