Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 52.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub verify`: keeping a repository's default branch green, as
5//! section 25 of `docs/hub.md` says.
6//!
7//! - `status` shows how the branch stands; with `--fail-on-red` it exits 4
8//! while the branch is red or stuck.
9//! - `report` tells the hub how a suite went on a changeset: what a CI job
10//! runs, with a token that only reads and posts verdicts.
11//! - `policy` shows who reports on which suite, and changes it: a read, a
12//! merge of what the flags name, and a `PUT` of the whole policy, which
13//! keeps every field braid does not know as the hub gave it.
14//! - `log` shows what verification did; `reset` moves green, or dismisses
15//! the fails there are now.
16//!
17//! Each acts on `-R OWNER/NAME`, else on the repository this one is linked
18//! to, and asks `GET /v1` first: a hub that does not list the `verify`
19//! feature is called for nothing else. `--json` prints what the hub
20//! answered, whole. `report` and `reset` send an `Idempotency-Key`, and
21//! send the request once more with the same key when the answer was lost.
22//! Exit statuses: 0 done, 1 refused, 3 when the hub could not be reached or
23//! failed, 4 for `status --fail-on-red` on a red branch.
24
25use std::fmt::Write as _;
26use std::process::ExitCode;
27
28use anyhow::{Context, Result, bail};
29use braid_format::ObjectId;
30use braid_hubproto::RepoPath;
31use braid_hubproto::names::is_owner;
32use braid_hubproto::verify::{
33 FEATURE, LandVerify, MAX_REPORTERS, MODE_OFF, MODE_REPORT, SOURCE_REPORT, STATE_OFF, STATE_RED,
34 STATE_STUCK, VerifyEvents, VerifyPolicy, VerifyReport, VerifyReportAnswer, VerifyReset,
35 VerifyStatus, is_git_commit, is_suite,
36};
37use clap::{ArgGroup, Args, Subcommand, ValueEnum};
38use serde::de::DeserializeOwned;
39use serde_json::{Map, Value, json};
40
41use super::remote::{HubError, shown};
42use super::social_common::{DONE, HubRepoArg, exit_for, hub_repo, idempotency_key, print};
43use crate::work::{count, short};
44use crate::{Cli, open_repo, resolve_changeset};
45
46/// The exit status of `status --fail-on-red` on a branch that is red or
47/// stuck, as `braid verify` exits on a red branch.
48pub(crate) const RED: u8 = 4;
49
50/// The long help of `hub verify`.
51pub(crate) const VERIFY_HELP: &str =
52 "Keep a repository's default branch green, as section 25 of the hub's
53protocol says. A CI job reports how a suite of tests went on a changeset
54of the branch; the hub keeps braid/green/<branch> at the newest changeset
55with a pass it accepts and, while the branch is red, braid/red/<branch> at
56the changeset it blames, or at the first fail it cannot explain. It names
57a culprit only when a single changeset separates a pass from a fail. The
58hub runs no code of the repository: every verdict comes from a reporter.
59
60 status how the branch stands; --fail-on-red exits 4 while it is red
61 report how a suite went on a changeset, as a CI job says it
62 policy who reports, on which suite; its admins change it
63 log what verification did, newest first
64 reset move green, or dismiss the fails there are now (admins)
65
66The repository is -R OWNER/NAME, else the one this repository is linked
67to. A hub whose GET /v1 does not list the verify feature is asked nothing
68else. With --json each command prints what the hub answered.
69
70Exit statuses: 0 done; 1 refused, or the hub does not verify branches; 3
71the hub could not be reached, or failed; 4 for status --fail-on-red on a
72red or stuck branch. report and reset send an Idempotency-Key, and send
73the request once more with the same key when the answer was lost.";
74
75/// The long help of `hub verify status`.
76pub(crate) const STATUS_HELP: &str =
77 "Show how the repository's default branch stands on the hub: its state (off,
78unknown, green, pending, red or stuck, and any other a newer hub gives),
79why (its code), its head, green and red, the culprit and how it was named,
80since when it is red, and the window the culprit is looked for in. The
81repository's admins also see who landed the culprit.
82
83With --fail-on-red, the exit status is 4 while the branch is red or stuck,
84so that a script stops before it builds on a broken branch; it is 0 for
85every other state. With --json it prints the status as the hub answered
86it.";
87
88/// The long help of `hub verify report`.
89pub(crate) const REPORT_HELP: &str =
90 "Tell the hub how a suite of tests went on a changeset of the default
91branch, as a CI job does once it ran them: --outcome pass, fail, or flaky
92(it failed, then passed when run again). Name the changeset by the git
93commit the mirror holds (--git-commit, 40 hex digits, such as the commit a
94GitHub workflow ran on), or by its id (--changeset, 64 hex digits). --suite
95is the suite the repository's policy names.
96
97The token is one made for this alone: read and verify:<branch glob> on the
98repository and nothing more, of an account that may write to it and that
99the policy names as a reporter. A CI job passes it in BRAID_TOKEN, and the
100hub in BRAID_HUB_URL, from its secrets; it never signs in with `braid
101login`.
102
103It prints what the report did (green_moved, red_set, red_cleared,
104recorded, duplicate, or stale for a changeset at or below green) and how
105the branch stands. The report goes with an Idempotency-Key, and once more
106with the same key when the answer was lost, so that it counts once. With
107--json it prints {\"effect\", \"status\"} as the hub answered.";
108
109/// The long help of `hub verify policy`.
110pub(crate) const POLICY_HELP: &str =
111 "Show how the hub verifies the repository's default branch, or change it:
112its admins only. With no flag it prints the policy. With flags it reads
113the policy, changes what the flags name, keeps everything else as the hub
114gave it, and puts the whole of it back.
115
116 --mode off|report report takes the verdicts of the reporters; off
117 stops verifying, and the hub forgets green and red
118 --suite SUITE the suite reported on: 1 to 32 of a-z 0-9 . _ -,
119 starting with a letter or a digit
120 --reporter LOGIN an account whose reports count, in place of those
121 the policy names; give it again for each, up to 10
122 --green-from SOURCE a source whose passes move green, in place of those
123 the policy names: report, the default when the
124 policy names none
125
126With --json it prints the policy as the hub answered it.";
127
128/// The long help of `hub verify log`.
129pub(crate) const LOG_HELP: &str =
130 "Show what verification did on the repository, newest first: each event's
131id, when, what (policy, green, red, culprit, fixed, stuck, reset or flaky),
132the changeset it is about, what goes with it and, to the repository's
133admins, who did it. --limit takes 1 to 100 (30 by default), and --after ID
134shows the events before that one: the next of the page before. With
135--json it prints the page as the hub answered it, with next.";
136
137/// The long help of `hub verify reset`.
138pub(crate) const RESET_HELP: &str =
139 "Its admins only. With --green REV, move green to that changeset of the
140default branch, backward too: it must be on the first-parent chain of the
141branch's head. The verdicts given before the reset on the changesets above
142it are forgotten, so the reset holds: green moves on, and red comes back,
143only on verdicts given after it. Without --green, dismiss the fails there
144are now: they no longer count, and only a new one turns the branch red
145again. Either way red is cleared, and the log records who did it. A reset
146needs the policy on. REV is a changeset's id
147or, in a repository that holds it, any revision braid resolves there.
148
149The reset goes with an Idempotency-Key, and once more with the same key
150when the answer was lost. With --json it prints the status as the hub
151answered it.";
152
153/// The routes of section 25 for one repository: over HTTP for the
154/// commands, in memory for their tests. Each answer comes as the hub gave
155/// it, so that `--json` prints it whole.
156pub(crate) trait VerifyApi {
157 /// `GET /v1`: the features the hub lists.
158 fn features(&self) -> Result<Vec<String>, HubError>;
159
160 /// `GET …/verify`.
161 fn status(&self) -> Result<Value, HubError>;
162
163 /// `POST …/verify/report`, with the `Idempotency-Key` `key`.
164 fn report(&self, report: &VerifyReport, key: &str) -> Result<Value, HubError>;
165
166 /// `GET …/verify/policy`.
167 fn policy(&self) -> Result<Value, HubError>;
168
169 /// `PUT …/verify/policy`: the whole policy.
170 fn put_policy(&self, policy: &Value) -> Result<Value, HubError>;
171
172 /// `GET …/verify/log?after&limit`.
173 fn log(&self, after: Option<u64>, limit: Option<u32>) -> Result<Value, HubError>;
174
175 /// `POST …/verify/reset`, with the `Idempotency-Key` `key`.
176 fn reset(&self, reset: &VerifyReset, key: &str) -> Result<Value, HubError>;
177}
178
179/// `hub verify`.
180#[derive(Debug, Args)]
181pub(crate) struct VerifyArgs {
182 #[command(subcommand)]
183 pub(crate) action: VerifyAction,
184}
185
186/// What `hub verify` does.
187#[derive(Debug, Subcommand)]
188pub(crate) enum VerifyAction {
189 /// Show how the default branch stands: green, red and the culprit.
190 #[command(long_about = STATUS_HELP)]
191 Status(StatusArgs),
192 /// Tell the hub how a suite went on a changeset, as a CI job does.
193 #[command(long_about = REPORT_HELP)]
194 Report(ReportArgs),
195 /// Show who reports on which suite, or change it (its admins).
196 #[command(long_about = POLICY_HELP)]
197 Policy(PolicyArgs),
198 /// Show what verification did, newest first.
199 #[command(long_about = LOG_HELP)]
200 Log(LogArgs),
201 /// Move green, or dismiss the fails there are now (its admins).
202 #[command(long_about = RESET_HELP)]
203 Reset(ResetArgs),
204}
205
206/// `hub verify status`.
207#[derive(Debug, Args)]
208pub(crate) struct StatusArgs {
209 #[command(flatten)]
210 pub(crate) repo: HubRepoArg,
211 /// Exit with status 4 while the branch is red or stuck.
212 #[arg(long)]
213 pub(crate) fail_on_red: bool,
214}
215
216/// How a suite went.
217#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
218pub(crate) enum Outcome {
219 /// It passed.
220 Pass,
221 /// It failed.
222 Fail,
223 /// It failed, then passed when run again.
224 Flaky,
225}
226
227impl Outcome {
228 fn as_str(self) -> &'static str {
229 match self {
230 Outcome::Pass => braid_hubproto::verify::PASS,
231 Outcome::Fail => braid_hubproto::verify::FAIL,
232 Outcome::Flaky => braid_hubproto::verify::FLAKY,
233 }
234 }
235}
236
237/// `hub verify report`.
238#[derive(Debug, Args)]
239#[command(group(ArgGroup::new("tested").required(true).args(["git_commit", "changeset"])))]
240pub(crate) struct ReportArgs {
241 #[command(flatten)]
242 pub(crate) repo: HubRepoArg,
243 /// How the suite went.
244 #[arg(long, value_enum)]
245 pub(crate) outcome: Outcome,
246 /// The git commit tested, as the mirror holds it: 40 hex digits.
247 #[arg(long, value_name = "SHA")]
248 pub(crate) git_commit: Option<String>,
249 /// The changeset tested: 64 hex digits.
250 #[arg(long, value_name = "ID")]
251 pub(crate) changeset: Option<String>,
252 /// The suite, as the repository's policy names it.
253 #[arg(long, value_name = "SUITE")]
254 pub(crate) suite: String,
255}
256
257/// A policy's mode.
258#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
259pub(crate) enum Mode {
260 /// Verify nothing.
261 Off,
262 /// Take the verdicts of the reporters.
263 Report,
264}
265
266impl Mode {
267 fn as_str(self) -> &'static str {
268 match self {
269 Mode::Off => MODE_OFF,
270 Mode::Report => MODE_REPORT,
271 }
272 }
273}
274
275/// A source of verdicts.
276#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
277pub(crate) enum Source {
278 /// The verdicts the reporters post.
279 Report,
280}
281
282impl Source {
283 fn as_str(self) -> &'static str {
284 match self {
285 Source::Report => SOURCE_REPORT,
286 }
287 }
288}
289
290/// `hub verify policy`.
291#[derive(Debug, Args)]
292pub(crate) struct PolicyArgs {
293 #[command(flatten)]
294 pub(crate) repo: HubRepoArg,
295 /// Take the reporters' verdicts (report), or verify nothing (off).
296 #[arg(long, value_enum)]
297 pub(crate) mode: Option<Mode>,
298 /// The suite the reporters report on.
299 #[arg(long, value_name = "SUITE")]
300 pub(crate) suite: Option<String>,
301 /// An account whose reports count, in place of those named before;
302 /// give it again for each, up to 10.
303 #[arg(long = "reporter", value_name = "LOGIN")]
304 pub(crate) reporters: Vec<String>,
305 /// A source whose passes move green, in place of those named before.
306 #[arg(long = "green-from", value_enum, value_name = "SOURCE")]
307 pub(crate) green_from: Vec<Source>,
308}
309
310/// `hub verify log`.
311#[derive(Debug, Args)]
312pub(crate) struct LogArgs {
313 #[command(flatten)]
314 pub(crate) repo: HubRepoArg,
315 /// The most events to show, 1 to 100 (default: 30).
316 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))]
317 pub(crate) limit: Option<u32>,
318 /// Show the events before this one: the next of the page before.
319 #[arg(long, value_name = "ID")]
320 pub(crate) after: Option<u64>,
321}
322
323/// `hub verify reset`.
324#[derive(Debug, Args)]
325pub(crate) struct ResetArgs {
326 #[command(flatten)]
327 pub(crate) repo: HubRepoArg,
328 /// Move green to this changeset, backward too (default: dismiss the
329 /// fails there are now).
330 #[arg(long, value_name = "REV")]
331 pub(crate) green: Option<String>,
332}
333
334impl VerifyAction {
335 /// The repository `-R` names, if it names one.
336 fn hub_repo(&self) -> Option<&str> {
337 match self {
338 VerifyAction::Status(args) => args.repo.hub_repo.as_deref(),
339 VerifyAction::Report(args) => args.repo.hub_repo.as_deref(),
340 VerifyAction::Policy(args) => args.repo.hub_repo.as_deref(),
341 VerifyAction::Log(args) => args.repo.hub_repo.as_deref(),
342 VerifyAction::Reset(args) => args.repo.hub_repo.as_deref(),
343 }
344 }
345}
346
347/// What a command asks of the hub, its arguments checked, so that nothing
348/// the hub would refuse for them goes out.
349#[derive(Debug)]
350enum Asked {
351 Status {
352 fail_on_red: bool,
353 },
354 Report(VerifyReport),
355 Policy(PolicyChange),
356 Log {
357 after: Option<u64>,
358 limit: Option<u32>,
359 },
360 Reset(VerifyReset),
361}
362
363/// What `policy` changes: the fields its flags name, checked.
364#[derive(Debug, Default, PartialEq, Eq)]
365struct PolicyChange {
366 mode: Option<&'static str>,
367 suite: Option<String>,
368 reporters: Option<Vec<String>>,
369 green_from: Option<Vec<String>>,
370}
371
372impl PolicyChange {
373 fn of(args: &PolicyArgs) -> Result<PolicyChange> {
374 let suite = args.suite.as_deref().map(suite_arg).transpose()?;
375 let reporters = if args.reporters.is_empty() {
376 None
377 } else {
378 let mut logins: Vec<String> = Vec::new();
379 for login in &args.reporters {
380 if !is_owner(login) {
381 bail!(
382 "{login:?} is not a login: 1 to 39 letters, digits and hyphens, with no hyphen at either end and no two in a row"
383 );
384 }
385 let login = login.to_ascii_lowercase();
386 if !logins.contains(&login) {
387 logins.push(login);
388 }
389 }
390 if logins.len() > MAX_REPORTERS {
391 bail!("a policy names at most {MAX_REPORTERS} reporters");
392 }
393 Some(logins)
394 };
395 let green_from = (!args.green_from.is_empty()).then(|| {
396 let mut sources: Vec<String> = Vec::new();
397 for source in &args.green_from {
398 if !sources.iter().any(|known| known == source.as_str()) {
399 sources.push(source.as_str().to_owned());
400 }
401 }
402 sources
403 });
404 Ok(PolicyChange {
405 mode: args.mode.map(Mode::as_str),
406 suite,
407 reporters,
408 green_from,
409 })
410 }
411
412 /// Whether the flags name nothing: the policy is only read.
413 fn is_empty(&self) -> bool {
414 *self == PolicyChange::default()
415 }
416
417 /// `current`, the policy as the hub gave it, with the change made, and
418 /// everything else kept as it was, fields braid does not know
419 /// included. A policy that names no source takes `report` when it has
420 /// reporters. A policy in `report` mode without a suite or reporters is
421 /// refused here, as the hub would refuse it.
422 fn merged(&self, current: &Value) -> Result<Value> {
423 let Value::Object(current) = current else {
424 bail!("the hub's policy is not a JSON object");
425 };
426 let mut policy = current.clone();
427 if let Some(mode) = self.mode {
428 policy.insert("mode".to_owned(), json!(mode));
429 }
430 if self.suite.is_some() || self.reporters.is_some() {
431 let report = policy
432 .entry("report")
433 .or_insert_with(|| Value::Object(Map::new()));
434 if !report.is_object() {
435 *report = Value::Object(Map::new());
436 }
437 if let Some(suite) = &self.suite {
438 report["suite"] = json!(suite);
439 }
440 if let Some(reporters) = &self.reporters {
441 report["reporters"] = json!(reporters);
442 }
443 }
444 let has_report = policy.get("report").is_some_and(Value::is_object);
445 match &self.green_from {
446 Some(sources) => {
447 policy.insert("green_from".to_owned(), json!(sources));
448 }
449 None => {
450 let none = policy
451 .get("green_from")
452 .and_then(Value::as_array)
453 .is_none_or(Vec::is_empty);
454 if none && has_report {
455 policy.insert("green_from".to_owned(), json!([SOURCE_REPORT]));
456 }
457 }
458 }
459 let merged = Value::Object(policy);
460 let read: VerifyPolicy = serde_json::from_value(merged.clone())
461 .context("the hub's policy is not one braid can change")?;
462 if read.mode == MODE_REPORT {
463 let complete = read
464 .report
465 .as_ref()
466 .is_some_and(|report| !report.suite.is_empty() && !report.reporters.is_empty());
467 if !complete {
468 bail!(
469 "verifying in report mode needs the suite and the reporters: give --suite and --reporter"
470 );
471 }
472 }
473 Ok(merged)
474 }
475}
476
477/// `--suite`, checked.
478fn suite_arg(suite: &str) -> Result<String> {
479 if !is_suite(suite) {
480 bail!(
481 "{suite:?} is not a suite: 1 to 32 of a-z, 0-9, '.', '_' and '-', starting with a letter or a digit"
482 );
483 }
484 Ok(suite.to_owned())
485}
486
487/// A changeset's id, 64 hex digits, given as an argument.
488fn full_id(text: &str, flag: &str) -> Result<ObjectId> {
489 text.to_ascii_lowercase()
490 .parse()
491 .ok()
492 .with_context(|| format!("{flag} takes a changeset's id, 64 hex digits, not {text:?}"))
493}
494
495/// What the arguments of `action` ask of the hub, checked; `resolve` turns
496/// a revision into a changeset.
497fn asked(action: &VerifyAction, resolve: impl Fn(&str) -> Result<ObjectId>) -> Result<Asked> {
498 Ok(match action {
499 VerifyAction::Status(args) => Asked::Status {
500 fail_on_red: args.fail_on_red,
501 },
502 VerifyAction::Report(args) => {
503 let git_commit = match &args.git_commit {
504 Some(sha) => {
505 let sha = sha.to_ascii_lowercase();
506 if !is_git_commit(&sha) {
507 bail!("--git-commit takes a git commit, 40 hex digits, not {sha:?}");
508 }
509 Some(sha)
510 }
511 None => None,
512 };
513 let changeset = args
514 .changeset
515 .as_deref()
516 .map(|text| full_id(text, "--changeset"))
517 .transpose()?;
518 Asked::Report(VerifyReport {
519 git_commit,
520 changeset,
521 outcome: args.outcome.as_str().to_owned(),
522 suite: suite_arg(&args.suite)?,
523 })
524 }
525 VerifyAction::Policy(args) => Asked::Policy(PolicyChange::of(args)?),
526 VerifyAction::Log(args) => Asked::Log {
527 after: args.after,
528 limit: args.limit,
529 },
530 VerifyAction::Reset(args) => Asked::Reset(VerifyReset {
531 green: args.green.as_deref().map(resolve).transpose()?,
532 expect: None,
533 }),
534 })
535}
536
537/// What a command did: what `--json` prints, what it prints without, and
538/// its exit status.
539#[derive(Debug)]
540struct Done {
541 json: Value,
542 text: String,
543 code: u8,
544}
545
546/// Whether a state is red: `red` or `stuck`.
547pub(crate) fn is_red(state: &str) -> bool {
548 matches!(state, STATE_RED | STATE_STUCK)
549}
550
551/// `answer`, from `route`, read as `T`.
552fn typed<T: DeserializeOwned>(answer: &Value, route: &str) -> Result<T, HubError> {
553 T::deserialize(answer).map_err(|err| {
554 HubError::Protocol(format!(
555 "{route} answered with something that is not the hub protocol ({err})"
556 ))
557 })
558}
559
560/// Sends a request that changes something, and sends it once more when its
561/// answer was lost: with the same `Idempotency-Key`, the hub gives the
562/// first answer again rather than doing it twice.
563fn twice(send: impl Fn() -> Result<Value, HubError>) -> Result<Value, HubError> {
564 match send() {
565 Err(err) if err.may_have_happened() => send(),
566 answer => answer,
567 }
568}
569
570/// `err`, saying, when the answer was lost twice, that the hub may have
571/// done `what`, and that `look` shows whether it did.
572fn lost(err: HubError, what: &str, look: &str) -> anyhow::Error {
573 if err.may_have_happened() {
574 anyhow::Error::new(err).context(format!(
575 "the hub may have {what} before its answer was lost: {look} shows whether it did"
576 ))
577 } else {
578 err.into()
579 }
580}
581
582/// Runs what was asked against `api`, the repository `path` on the hub at
583/// `url`.
584fn run(api: &impl VerifyApi, url: &str, path: &RepoPath, asked: &Asked) -> Result<Done> {
585 if !api.features()?.iter().any(|feature| feature == FEATURE) {
586 bail!(
587 "the hub at {url} does not verify branches: its GET /v1 lists no `{FEATURE}` feature"
588 );
589 }
590 Ok(match asked {
591 Asked::Status { fail_on_red } => {
592 let answer = api.status()?;
593 let status: VerifyStatus = typed(&answer, "GET …/verify")?;
594 let code = if *fail_on_red && is_red(&status.state) {
595 RED
596 } else {
597 DONE
598 };
599 Done {
600 text: status_text(path, &status),
601 json: answer,
602 code,
603 }
604 }
605 Asked::Report(report) => {
606 let key = idempotency_key();
607 let answer = twice(|| api.report(report, &key)).map_err(|err| {
608 lost(
609 err,
610 "recorded the verdict",
611 &format!("`braid hub verify log -R {path}`"),
612 )
613 })?;
614 let said: VerifyReportAnswer = typed(&answer, "POST …/verify/report")?;
615 Done {
616 text: format!(
617 "{}\n{}",
618 report_text(report, &said.effect),
619 status_text(path, &said.status)
620 ),
621 json: answer,
622 code: DONE,
623 }
624 }
625 Asked::Policy(change) => {
626 let current = api.policy()?;
627 let answer = if change.is_empty() {
628 current
629 } else {
630 api.put_policy(&change.merged(&current)?)?
631 };
632 let policy: VerifyPolicy = typed(&answer, "…/verify/policy")?;
633 Done {
634 text: policy_text(path, &policy),
635 json: answer,
636 code: DONE,
637 }
638 }
639 Asked::Log { after, limit } => {
640 let answer = api.log(*after, *limit)?;
641 let events: VerifyEvents = typed(&answer, "GET …/verify/log")?;
642 Done {
643 text: log_text(&events),
644 json: answer,
645 code: DONE,
646 }
647 }
648 Asked::Reset(reset) => {
649 let key = idempotency_key();
650 let answer = twice(|| api.reset(reset, &key)).map_err(|err| {
651 lost(
652 err,
653 "reset the branch",
654 &format!("`braid hub verify log -R {path}`"),
655 )
656 })?;
657 let status: VerifyStatus = typed(&answer, "POST …/verify/reset")?;
658 Done {
659 text: format!("Reset.\n{}", status_text(path, &status)),
660 json: answer,
661 code: DONE,
662 }
663 }
664 })
665}
666
667/// The exit status of a command that failed with `err`, when the hub
668/// refused it or could not be reached; `None` for an error of braid's
669/// own, which exits with 1.
670fn hub_exit(err: &anyhow::Error) -> Option<u8> {
671 err.downcast_ref::<HubError>().map(exit_for)
672}
673
674pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> {
675 let asked = asked(&args.action, |rev| changeset_of(cli, rev))?;
676 let (hub, path) = hub_repo(cli, args.action.hub_repo())?;
677 let api = hub.repo(path.clone());
678 match run(&api, hub.url(), &path, &asked) {
679 Ok(done) => {
680 print(cli, &done.json, || done.text.clone())?;
681 Ok(ExitCode::from(done.code))
682 }
683 Err(err) => match hub_exit(&err) {
684 Some(code) => {
685 eprintln!("braid: error: {err:#}");
686 Ok(ExitCode::from(code))
687 }
688 None => Err(err),
689 },
690 }
691}
692
693/// The changeset `rev` names: its id, or a revision of the repository
694/// braid runs in.
695fn changeset_of(cli: &Cli, rev: &str) -> Result<ObjectId> {
696 if let Ok(id) = rev.to_ascii_lowercase().parse() {
697 return Ok(id);
698 }
699 let repo = open_repo(cli).with_context(|| {
700 format!(
701 "{rev:?} is not a changeset's id (64 hex digits), and there is no repository here to read it in"
702 )
703 })?;
704 resolve_changeset(&repo, rev)
705}
706
707/// How the branch stands, in words. What the hub says goes through
708/// [`shown`].
709fn status_text(path: &RepoPath, status: &VerifyStatus) -> String {
710 if status.state == STATE_OFF || status.mode == MODE_OFF {
711 return format!("{path}: verification is off");
712 }
713 let branch = status
714 .branch
715 .as_deref()
716 .map_or_else(|| "the default branch".to_owned(), shown);
717 let mut out = format!("{path} {branch}: {}", shown(&status.state));
718 if let Some(code) = &status.code {
719 let _ = write!(out, " ({})", shown(code));
720 }
721 if let Some(since) = &status.since {
722 let _ = write!(out, " since {}", shown(since));
723 }
724 let _ = write!(
725 out,
726 "\n head {}\n green {}\n red {}",
727 short(status.head),
728 short(status.green),
729 short(status.red)
730 );
731 if let Some(culprit) = status.culprit {
732 let _ = write!(out, "\n culprit {}", culprit.short());
733 if let Some(decided) = &status.decided_by {
734 let _ = write!(out, " ({})", shown(decided));
735 }
736 if let Some(lander) = status
737 .admin
738 .as_ref()
739 .and_then(|admin| admin.lander.as_ref())
740 {
741 let _ = write!(out, ", landed by {}", shown(lander));
742 }
743 }
744 if let Some(window) = &status.window {
745 let _ = write!(
746 out,
747 "\n window {} after {} ({}), up to {}",
748 count(window.candidates, "changeset"),
749 short(window.lower),
750 shown(&window.lower_kind),
751 short(window.upper)
752 );
753 }
754 out
755}
756
757/// What a report did, in words.
758fn report_text(report: &VerifyReport, effect: &str) -> String {
759 let on = match (&report.changeset, &report.git_commit) {
760 (Some(id), _) => id.short(),
761 (None, Some(sha)) => format!("git commit {}", &sha[..sha.len().min(12)]),
762 (None, None) => "the changeset".to_owned(),
763 };
764 let what = match effect {
765 "red_set" => "the branch turned red".to_owned(),
766 "green_moved" => "green moved".to_owned(),
767 "red_cleared" => "the branch is no longer red".to_owned(),
768 "recorded" => "recorded".to_owned(),
769 "duplicate" => "the hub had this verdict already".to_owned(),
770 "stale" => "it is at or below green: nothing was recorded".to_owned(),
771 other => shown(other),
772 };
773 format!(
774 "{} on {on}, suite {}: {what}",
775 shown(&report.outcome),
776 shown(&report.suite)
777 )
778}
779
780/// The policy, in words.
781fn policy_text(path: &RepoPath, policy: &VerifyPolicy) -> String {
782 let mut out = format!("{path}: verification {}", shown(&policy.mode));
783 let sources = if policy.green_from.is_empty() {
784 "none".to_owned()
785 } else {
786 shown(&policy.green_from.join(", "))
787 };
788 let _ = write!(
789 out,
790 "\n green from {sources}\n flaky moves green {}",
791 if policy.flaky_moves_green {
792 "yes"
793 } else {
794 "no"
795 }
796 );
797 if let Some(report) = &policy.report {
798 let _ = write!(
799 out,
800 "\n suite {}\n reporters {}",
801 shown(&report.suite),
802 shown(&report.reporters.join(", "))
803 );
804 }
805 out
806}
807
808/// A page of the log, in words: an event a line.
809fn log_text(events: &VerifyEvents) -> String {
810 if events.events.is_empty() {
811 return "No events.".to_owned();
812 }
813 let mut out = String::new();
814 for event in &events.events {
815 let _ = write!(
816 out,
817 "{:<6} {} {:<8} {}",
818 event.id,
819 shown(&event.at),
820 shown(&event.code),
821 event
822 .changeset
823 .map_or_else(|| "-".repeat(12), |id| id.short())
824 );
825 if let Some(other) = &event.other {
826 let _ = write!(out, " {}", shown(other));
827 }
828 if let Some(actor) = &event.actor {
829 let _ = write!(out, " by {}", shown(actor));
830 }
831 out.push('\n');
832 }
833 if let Some(next) = events.next {
834 let _ = write!(out, "Older events: --after {next}");
835 }
836 out.trim_end().to_owned()
837}
838
839/// What braid notes on standard error after a landing whose answer says
840/// that `branch` is red: one line, or `None` when there is nothing to say.
841/// `repo`, when given, is the repository to name with `-R` in the hint.
842pub(crate) fn land_note(
843 branch: &str,
844 verify: &LandVerify,
845 repo: Option<&RepoPath>,
846) -> Option<String> {
847 if !is_red(&verify.state) {
848 return None;
849 }
850 let blame = match (verify.culprit, verify.red) {
851 (Some(culprit), _) => format!(", culprit {}", culprit.short()),
852 (None, Some(red)) => format!(" at {}, no culprit named", red.short()),
853 (None, None) => String::new(),
854 };
855 let flag = repo.map_or_else(String::new, |repo| format!(" -R {repo}"));
856 Some(format!(
857 "note: {} is {} on the hub{blame}: `braid hub verify status{flag}` says more",
858 shown(branch),
859 shown(&verify.state)
860 ))
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866 use crate::hub::testing::{FakeHub, Refusal, ada_change, set_ref};
867 use braid_hubproto::verify::{
868 EFFECT_DUPLICATE, EFFECT_GREEN_MOVED, EFFECT_RED_CLEARED, EFFECT_RED_SET, EFFECT_STALE,
869 FAIL, PASS, STATE_GREEN, STATE_PENDING,
870 };
871 use clap::Parser;
872
873 const URL: &str = "http://127.0.0.1:9";
874
875 /// A hub that verifies branches, whose repository's main holds `a`,
876 /// `b` and `c`, and whose policy takes the reports of ci-bot on `ci`.
877 fn hub() -> (FakeHub, [ObjectId; 3]) {
878 let hub = FakeHub::new();
879 let a = ada_change(&hub.repo, None, &[("a.txt", "a\n")]);
880 let b = ada_change(&hub.repo, Some(a), &[("b.txt", "b\n")]);
881 let c = ada_change(&hub.repo, Some(b), &[("c.txt", "c\n")]);
882 set_ref(&hub.repo, "main", c);
883 hub.verify.borrow_mut().turn_on();
884 (hub, [a, b, c])
885 }
886
887 fn path() -> RepoPath {
888 "ada/demo".parse().unwrap()
889 }
890
891 fn report(outcome: &str, changeset: ObjectId) -> Asked {
892 Asked::Report(VerifyReport {
893 git_commit: None,
894 changeset: Some(changeset),
895 outcome: outcome.to_owned(),
896 suite: "ci".to_owned(),
897 })
898 }
899
900 fn status(fail_on_red: bool) -> Asked {
901 Asked::Status { fail_on_red }
902 }
903
904 #[test]
905 fn reports_move_the_refs_and_say_what_they_did() {
906 let (hub, [a, b, c]) = hub();
907 let done = run(&hub, URL, &path(), &report(PASS, a)).unwrap();
908 assert_eq!(done.code, DONE);
909 assert_eq!(done.json["effect"], EFFECT_GREEN_MOVED);
910 assert_eq!(done.json["status"]["green"], a.to_hex());
911 assert!(
912 done.text
913 .starts_with(&format!("pass on {}, suite ci: green moved", a.short()))
914 );
915 assert!(
916 done.text.contains("ada/demo main: pending"),
917 "{}",
918 done.text
919 );
920
921 // A fail right after green names its culprit.
922 let done = run(&hub, URL, &path(), &report(FAIL, b)).unwrap();
923 assert_eq!(done.json["effect"], EFFECT_RED_SET);
924 let said: VerifyStatus = serde_json::from_value(done.json["status"].clone()).unwrap();
925 assert_eq!((said.state.as_str(), said.culprit), (STATE_RED, Some(b)));
926 assert!(
927 done.text
928 .contains(&format!("culprit {} (single)", b.short()))
929 );
930 // The same verdict again changes nothing; one below green neither.
931 let again = run(&hub, URL, &path(), &report(FAIL, b)).unwrap();
932 assert_eq!(again.json["effect"], EFFECT_DUPLICATE);
933 let below = run(&hub, URL, &path(), &report(FAIL, a)).unwrap();
934 assert_eq!(below.json["effect"], EFFECT_STALE);
935 // A pass at the head ends the red.
936 let done = run(&hub, URL, &path(), &report(PASS, c)).unwrap();
937 assert_eq!(done.json["effect"], EFFECT_RED_CLEARED);
938 assert_eq!(done.json["status"]["state"], STATE_GREEN);
939 // Each report went with a key of its own.
940 let keys: Vec<String> = hub
941 .verify
942 .borrow()
943 .keyed
944 .iter()
945 .map(|(key, _)| key.clone())
946 .collect();
947 assert_eq!(keys.len(), 5);
948 assert!(keys.windows(2).all(|pair| pair[0] != pair[1]), "{keys:?}");
949 }
950
951 #[test]
952 fn status_and_its_exit_statuses() {
953 let (hub, [_, b, _]) = hub();
954 let done = run(&hub, URL, &path(), &status(true)).unwrap();
955 assert_eq!(
956 (done.code, done.json["state"].as_str()),
957 (DONE, Some("unknown"))
958 );
959 run(&hub, URL, &path(), &report(FAIL, b)).unwrap();
960 // Red: 4 with --fail-on-red, 0 without.
961 let red = run(&hub, URL, &path(), &status(true)).unwrap();
962 assert_eq!(red.code, RED);
963 assert_eq!(red.json["red"], b.to_hex());
964 assert_eq!(run(&hub, URL, &path(), &status(false)).unwrap().code, DONE);
965 // Stuck counts as red; a state braid does not know does not.
966 hub.verify.borrow_mut().status.state = STATE_STUCK.to_owned();
967 assert_eq!(run(&hub, URL, &path(), &status(true)).unwrap().code, RED);
968 hub.verify.borrow_mut().status.state = "held".to_owned();
969 assert_eq!(run(&hub, URL, &path(), &status(true)).unwrap().code, DONE);
970 // What the hub answered is printed whole, fields braid does not
971 // know included.
972 hub.verify.borrow_mut().extra = Some(json!({"later": [1, 2]}));
973 let done = run(&hub, URL, &path(), &status(false)).unwrap();
974 assert_eq!(done.json["later"], json!([1, 2]));
975 // With mode off, nothing more is said.
976 hub.verify.borrow_mut().status = VerifyStatus::default();
977 hub.verify.borrow_mut().extra = None;
978 let off = run(&hub, URL, &path(), &status(true)).unwrap();
979 assert_eq!(
980 (off.code, off.text.as_str()),
981 (DONE, "ada/demo: verification is off")
982 );
983 }
984
985 #[test]
986 fn a_lost_answer_is_sent_again_with_the_same_key() {
987 let (hub, [a, _, _]) = hub();
988 // The answer of the first try is lost once the hub recorded the
989 // verdict: the same report goes again, with the same key, and the
990 // hub gives its first answer again.
991 hub.verify.borrow_mut().lose = 1;
992 let done = run(&hub, URL, &path(), &report(PASS, a)).unwrap();
993 assert_eq!(done.json["effect"], EFFECT_GREEN_MOVED);
994 {
995 let verify = hub.verify.borrow();
996 assert_eq!(verify.keyed.len(), 2);
997 assert_eq!(verify.keyed[0], verify.keyed[1], "the same key and body");
998 assert_eq!(verify.verdicts.len(), 1, "recorded once");
999 }
1000 // Lost twice: an error that says the hub may have recorded it, as
1001 // a hub that cannot be reached.
1002 hub.verify.borrow_mut().lose = 2;
1003 let err = run(&hub, URL, &path(), &report(FAIL, a)).unwrap_err();
1004 assert_eq!(hub_exit(&err), Some(3));
1005 let said = format!("{err:#}");
1006 assert!(said.contains("may have recorded the verdict"), "{said}");
1007 assert!(said.contains("braid hub verify log -R ada/demo"), "{said}");
1008 // A reset too.
1009 hub.verify.borrow_mut().lose = 1;
1010 let reset = Asked::Reset(VerifyReset {
1011 green: Some(a),
1012 expect: None,
1013 });
1014 run(&hub, URL, &path(), &reset).unwrap();
1015 let verify = hub.verify.borrow();
1016 let n = verify.keyed.len();
1017 assert_eq!(verify.keyed[n - 1], verify.keyed[n - 2]);
1018 assert_eq!(
1019 verify.keyed[n - 1].1,
1020 json!({"green": a.to_hex(), "expect": null})
1021 );
1022 }
1023
1024 #[test]
1025 fn the_policy_is_read_merged_and_put_back_whole() {
1026 let (hub, _) = hub();
1027 let read = Asked::Policy(PolicyChange::default());
1028 let done = run(&hub, URL, &path(), &read).unwrap();
1029 assert_eq!(done.json, hub.verify.borrow().policy);
1030 assert!(
1031 done.text.contains("reporters ci-bot"),
1032 "{}",
1033 done.text
1034 );
1035 assert_eq!(hub.called("verify/policy put"), 0, "read only");
1036
1037 // A newer hub's field stays as it was, through a change of what
1038 // braid knows.
1039 hub.verify.borrow_mut().policy["github"] = json!({"sources": [{"workflow": "ci.yml"}]});
1040 let args = PolicyArgs {
1041 repo: HubRepoArg::default(),
1042 mode: None,
1043 suite: Some("unit".into()),
1044 reporters: vec!["CI-Bot".into(), "other".into(), "ci-bot".into()],
1045 green_from: Vec::new(),
1046 };
1047 let change = PolicyChange::of(&args).unwrap();
1048 let done = run(&hub, URL, &path(), &Asked::Policy(change)).unwrap();
1049 assert_eq!(
1050 done.json["report"],
1051 json!({"suite": "unit", "reporters": ["ci-bot", "other"]})
1052 );
1053 assert_eq!(
1054 done.json["github"],
1055 json!({"sources": [{"workflow": "ci.yml"}]})
1056 );
1057 assert_eq!(hub.called("verify/policy put"), 1);
1058
1059 // On a policy never set, the first change takes report as its
1060 // source; turning it off keeps the rest.
1061 hub.verify.borrow_mut().policy = serde_json::to_value(VerifyPolicy::default()).unwrap();
1062 let args = PolicyArgs {
1063 mode: Some(Mode::Report),
1064 suite: Some("ci".into()),
1065 reporters: vec!["ci-bot".into()],
1066 ..args
1067 };
1068 let done = run(
1069 &hub,
1070 URL,
1071 &path(),
1072 &Asked::Policy(PolicyChange::of(&args).unwrap()),
1073 )
1074 .unwrap();
1075 assert_eq!(done.json["green_from"], json!(["report"]));
1076 assert_eq!(done.json["mode"], "report");
1077 let off = PolicyChange {
1078 mode: Some(MODE_OFF),
1079 ..PolicyChange::default()
1080 };
1081 let done = run(&hub, URL, &path(), &Asked::Policy(off)).unwrap();
1082 assert_eq!(done.json["mode"], "off");
1083 assert_eq!(done.json["report"]["suite"], "ci");
1084 assert!(
1085 done.text.starts_with("ada/demo: verification off"),
1086 "{}",
1087 done.text
1088 );
1089
1090 // Report mode without reporters is refused before anything is put.
1091 hub.verify.borrow_mut().policy = serde_json::to_value(VerifyPolicy::default()).unwrap();
1092 let half = PolicyChange {
1093 mode: Some(MODE_REPORT),
1094 ..PolicyChange::default()
1095 };
1096 let puts = hub.called("verify/policy put");
1097 let err = run(&hub, URL, &path(), &Asked::Policy(half)).unwrap_err();
1098 assert_eq!(hub_exit(&err), None);
1099 assert!(err.to_string().contains("--suite and --reporter"), "{err}");
1100 assert_eq!(hub.called("verify/policy put"), puts);
1101 }
1102
1103 #[test]
1104 fn the_log_and_resets() {
1105 let (hub, [a, b, c]) = hub();
1106 for (outcome, id) in [(PASS, a), (FAIL, c)] {
1107 run(&hub, URL, &path(), &report(outcome, id)).unwrap();
1108 }
1109 // Newest first, a page at a time.
1110 let done = run(
1111 &hub,
1112 URL,
1113 &path(),
1114 &Asked::Log {
1115 after: None,
1116 limit: Some(1),
1117 },
1118 )
1119 .unwrap();
1120 let events: VerifyEvents = serde_json::from_value(done.json.clone()).unwrap();
1121 assert_eq!(events.events.len(), 1);
1122 assert!(
1123 done.text.lines().next().unwrap().contains("red"),
1124 "{}",
1125 done.text
1126 );
1127 let next = events.next.expect("a page that is not the last");
1128 assert!(
1129 done.text.ends_with(&format!("--after {next}")),
1130 "{}",
1131 done.text
1132 );
1133 let rest = run(
1134 &hub,
1135 URL,
1136 &path(),
1137 &Asked::Log {
1138 after: Some(next),
1139 limit: None,
1140 },
1141 )
1142 .unwrap();
1143 let older: VerifyEvents = serde_json::from_value(rest.json).unwrap();
1144 assert!(!older.events.is_empty());
1145 assert!(older.events.iter().all(|event| event.id < next));
1146 assert!(older.events.windows(2).all(|pair| pair[0].id > pair[1].id));
1147 assert_eq!(older.next, None);
1148
1149 // A dismissal clears red; green stays.
1150 let dismiss = Asked::Reset(VerifyReset::default());
1151 let done = run(&hub, URL, &path(), &dismiss).unwrap();
1152 assert_eq!(done.json["red"], Value::Null);
1153 assert_eq!(done.json["green"], a.to_hex());
1154 assert_eq!(done.json["state"], STATE_PENDING);
1155 assert!(
1156 done.text.starts_with("Reset.\nada/demo main: pending"),
1157 "{}",
1158 done.text
1159 );
1160 // Green moves where it is told, backward too.
1161 let to_b = Asked::Reset(VerifyReset {
1162 green: Some(b),
1163 expect: None,
1164 });
1165 let done = run(&hub, URL, &path(), &to_b).unwrap();
1166 assert_eq!(done.json["green"], b.to_hex());
1167 let log = run(
1168 &hub,
1169 URL,
1170 &path(),
1171 &Asked::Log {
1172 after: None,
1173 limit: None,
1174 },
1175 )
1176 .unwrap();
1177 assert!(
1178 log.text.lines().next().unwrap().contains("reset"),
1179 "{}",
1180 log.text
1181 );
1182 }
1183
1184 #[test]
1185 fn refusals_and_a_hub_out_of_reach() {
1186 let (hub, [a, _, _]) = hub();
1187 hub.verify.borrow_mut().refuse = Some(Refusal::Api(403, "forbidden"));
1188 let err = run(&hub, URL, &path(), &report(PASS, a)).unwrap_err();
1189 assert_eq!(hub_exit(&err), Some(1));
1190 hub.verify.borrow_mut().refuse = Some(Refusal::Unreachable);
1191 let err = run(&hub, URL, &path(), &status(false)).unwrap_err();
1192 assert_eq!(hub_exit(&err), Some(3));
1193 hub.verify.borrow_mut().refuse = None;
1194 // A suite the policy does not name, a commit the hub does not know,
1195 // and a changeset off the branch are refused by the hub.
1196 let other = Asked::Report(VerifyReport {
1197 suite: "other".into(),
1198 ..VerifyReport::default()
1199 });
1200 assert_eq!(
1201 hub_exit(&run(&hub, URL, &path(), &other).unwrap_err()),
1202 Some(1)
1203 );
1204 let unknown = Asked::Report(VerifyReport {
1205 git_commit: Some("0a".repeat(20)),
1206 changeset: None,
1207 outcome: PASS.into(),
1208 suite: "ci".into(),
1209 });
1210 let err = run(&hub, URL, &path(), &unknown).unwrap_err();
1211 assert!(matches!(
1212 err.downcast_ref::<HubError>(),
1213 Some(HubError::Api { status: 404, .. })
1214 ));
1215 let elsewhere = ada_change(&hub.repo, None, &[("z.txt", "z\n")]);
1216 let err = run(&hub, URL, &path(), &report(FAIL, elsewhere)).unwrap_err();
1217 assert_eq!(
1218 err.downcast_ref::<HubError>().and_then(HubError::code),
1219 Some("not_on_branch")
1220 );
1221 // A commit the hub knows is taken.
1222 hub.verify.borrow_mut().commits.insert("0a".repeat(20), a);
1223 let done = run(&hub, URL, &path(), &unknown).unwrap();
1224 assert!(
1225 done.text.starts_with("pass on git commit 0a0a0a0a0a0a"),
1226 "{}",
1227 done.text
1228 );
1229
1230 // A hub that does not verify is asked nothing more.
1231 hub.verify.borrow_mut().served = false;
1232 let calls = hub.calls.borrow().len();
1233 let err = run(&hub, URL, &path(), &status(false)).unwrap_err();
1234 assert_eq!(hub_exit(&err), None);
1235 assert!(
1236 err.to_string().contains("does not verify branches"),
1237 "{err}"
1238 );
1239 assert_eq!(
1240 hub.calls.borrow().len(),
1241 calls + 1,
1242 "{:?}",
1243 hub.calls.borrow()
1244 );
1245 }
1246
1247 /// `braid` with `args`, parsed.
1248 fn parse(args: &[&str]) -> Result<VerifyAction, clap::Error> {
1249 let cli = crate::Cli::try_parse_from(args)?;
1250 match cli.command {
1251 crate::Command::Hub {
1252 action: super::super::HubAction::Verify(args),
1253 } => Ok(args.action),
1254 other => panic!("{other:?}"),
1255 }
1256 }
1257
1258 #[test]
1259 fn arguments_are_checked_before_anything_is_sent() {
1260 let id = ObjectId::hash(braid_format::Kind::Changeset, b"x");
1261 let hex = id.to_hex();
1262 let upper = "0A".repeat(20);
1263 let no_rev = |rev: &str| -> Result<ObjectId> { bail!("no repository for {rev}") };
1264 let action = parse(&[
1265 "braid",
1266 "hub",
1267 "verify",
1268 "report",
1269 "-R",
1270 "ada/demo",
1271 "--outcome",
1272 "fail",
1273 "--git-commit",
1274 &upper,
1275 "--suite",
1276 "ci",
1277 ])
1278 .unwrap();
1279 assert_eq!(action.hub_repo(), Some("ada/demo"));
1280 match asked(&action, no_rev).unwrap() {
1281 Asked::Report(report) => {
1282 assert_eq!(report.git_commit, Some("0a".repeat(20)));
1283 assert_eq!(
1284 (report.outcome.as_str(), report.suite.as_str()),
1285 (FAIL, "ci")
1286 );
1287 }
1288 other => panic!("{other:?}"),
1289 }
1290 let action = parse(&[
1291 "braid",
1292 "hub",
1293 "verify",
1294 "report",
1295 "--outcome",
1296 "pass",
1297 "--changeset",
1298 &hex,
1299 "--suite",
1300 "ci",
1301 ])
1302 .unwrap();
1303 assert!(
1304 matches!(asked(&action, no_rev).unwrap(), Asked::Report(VerifyReport { changeset: Some(found), .. }) if found == id)
1305 );
1306 // Exactly one of the two is needed.
1307 for args in [
1308 &[
1309 "braid",
1310 "hub",
1311 "verify",
1312 "report",
1313 "--outcome",
1314 "pass",
1315 "--suite",
1316 "ci",
1317 ][..],
1318 &[
1319 "braid",
1320 "hub",
1321 "verify",
1322 "report",
1323 "--outcome",
1324 "pass",
1325 "--suite",
1326 "ci",
1327 "--changeset",
1328 "x",
1329 "--git-commit",
1330 "y",
1331 ],
1332 &[
1333 "braid",
1334 "hub",
1335 "verify",
1336 "report",
1337 "--outcome",
1338 "maybe",
1339 "--suite",
1340 "ci",
1341 "--changeset",
1342 "x",
1343 ],
1344 ] {
1345 assert!(parse(args).is_err(), "{args:?}");
1346 }
1347 // What the hub would refuse is refused here.
1348 for (args, said) in [
1349 (
1350 vec!["--git-commit", "abc", "--suite", "ci"],
1351 "40 hex digits",
1352 ),
1353 (vec!["--changeset", "abc", "--suite", "ci"], "64 hex digits"),
1354 (vec!["--changeset", &hex, "--suite", "CI"], "is not a suite"),
1355 ] {
1356 let mut line = vec!["braid", "hub", "verify", "report", "--outcome", "pass"];
1357 line.extend(args);
1358 let err = asked(&parse(&line).unwrap(), no_rev).unwrap_err();
1359 assert!(err.to_string().contains(said), "{line:?}: {err}");
1360 }
1361 let policy = parse(&[
1362 "braid",
1363 "hub",
1364 "verify",
1365 "policy",
1366 "--mode",
1367 "report",
1368 "--reporter",
1369 "Ada",
1370 "--green-from",
1371 "report",
1372 "--suite",
1373 "ci",
1374 ])
1375 .unwrap();
1376 match asked(&policy, no_rev).unwrap() {
1377 Asked::Policy(change) => assert_eq!(
1378 change,
1379 PolicyChange {
1380 mode: Some(MODE_REPORT),
1381 suite: Some("ci".into()),
1382 reporters: Some(vec!["ada".into()]),
1383 green_from: Some(vec![SOURCE_REPORT.into()]),
1384 }
1385 ),
1386 other => panic!("{other:?}"),
1387 }
1388 let bad = parse(&[
1389 "braid",
1390 "hub",
1391 "verify",
1392 "policy",
1393 "--reporter",
1394 "bad--login",
1395 ])
1396 .unwrap();
1397 assert!(asked(&bad, no_rev).is_err());
1398 let many: Vec<String> = (0..11).map(|n| format!("--reporter=r{n}")).collect();
1399 let mut line = vec!["braid", "hub", "verify", "policy"];
1400 line.extend(many.iter().map(String::as_str));
1401 assert!(
1402 asked(&parse(&line).unwrap(), no_rev)
1403 .unwrap_err()
1404 .to_string()
1405 .contains("at most 10")
1406 );
1407 assert!(parse(&["braid", "hub", "verify", "policy", "--mode", "auto"]).is_err());
1408 assert!(parse(&["braid", "hub", "verify", "log", "--limit", "0"]).is_err());
1409 assert!(parse(&["braid", "hub", "verify", "log", "--limit", "101"]).is_err());
1410 let log = parse(&[
1411 "braid", "hub", "verify", "log", "--limit", "5", "--after", "9",
1412 ])
1413 .unwrap();
1414 assert!(matches!(
1415 asked(&log, no_rev).unwrap(),
1416 Asked::Log {
1417 after: Some(9),
1418 limit: Some(5)
1419 }
1420 ));
1421 // A reset names a changeset through the resolver.
1422 let reset = parse(&["braid", "hub", "verify", "reset", "--green", "main~1"]).unwrap();
1423 let found = asked(&reset, |rev: &str| -> Result<ObjectId> {
1424 assert_eq!(rev, "main~1");
1425 Ok(id)
1426 })
1427 .unwrap();
1428 assert!(
1429 matches!(found, Asked::Reset(VerifyReset { green: Some(green), expect: None }) if green == id)
1430 );
1431 assert!(asked(&reset, no_rev).is_err());
1432 let status = parse(&[
1433 "braid",
1434 "hub",
1435 "verify",
1436 "status",
1437 "--fail-on-red",
1438 "--json",
1439 ])
1440 .unwrap();
1441 assert!(matches!(
1442 asked(&status, no_rev).unwrap(),
1443 Asked::Status { fail_on_red: true }
1444 ));
1445 }
1446
1447 #[test]
1448 fn a_landing_on_a_red_branch_says_so() {
1449 let id = ObjectId::hash(braid_format::Kind::Changeset, b"x");
1450 let mut verify = LandVerify {
1451 state: STATE_RED.into(),
1452 green: None,
1453 red: Some(id),
1454 culprit: Some(id),
1455 reverted: Vec::new(),
1456 };
1457 let note = land_note("main", &verify, None).unwrap();
1458 assert_eq!(
1459 note,
1460 format!(
1461 "note: main is red on the hub, culprit {}: `braid hub verify status` says more",
1462 id.short()
1463 )
1464 );
1465 verify.culprit = None;
1466 verify.state = STATE_STUCK.into();
1467 let note = land_note("main", &verify, Some(&path())).unwrap();
1468 assert!(note.contains("is stuck on the hub at"), "{note}");
1469 assert!(
1470 note.ends_with("`braid hub verify status -R ada/demo` says more"),
1471 "{note}"
1472 );
1473 for state in [STATE_GREEN, STATE_PENDING, "unknown", "later"] {
1474 verify.state = state.into();
1475 assert_eq!(land_note("main", &verify, None), None, "{state}");
1476 }
1477 // What the hub says is shown, never raw.
1478 verify.state = STATE_RED.into();
1479 let note = land_note("ma\u{1b}in", &verify, None).unwrap();
1480 assert!(!note.contains('\u{1b}'), "{note}");
1481 }
1482}