fallow_output/baseline_staleness.rs
1//! The machine-readable view of a loaded baseline's staleness.
2//!
3//! One shape for every command that accepts `--baseline`, so a consumer reads
4//! the same member names whether the envelope came from `dead-code`, `dupes` or
5//! `health`. Carried as `baseline_staleness` at the dead-code and duplication
6//! roots and inside `summary` on health, absent whenever no baseline was loaded.
7//!
8//! Every member is a projection of the run's
9//! `fallow_engine::baseline::BaselineStaleness`, so nothing here restates a rule
10//! that lives in the engine. `gate_trips` in particular is computed by the same
11//! function the `--fail-on-stale-baseline` exit gate calls, which is why a CI
12//! integration can read one boolean instead of reimplementing the condition in
13//! jq.
14
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16
17/// One channel that narrows a run, or that differs between a run and a saved
18/// baseline.
19///
20/// Serialized as kebab-case inside `scope_reasons` and published as an open
21/// set, the same tolerate-unknown contract `gate_outcomes` keys carry: a name
22/// this build does not emit means "some narrowing", not an error.
23///
24/// Which names a command can emit differs per command, because the three
25/// narrowing predicates see different state. `dead-code` reads the flags
26/// themselves and can name every channel. `dupes` and `health` see an already
27/// resolved changed-file set and report `changed-files`, because at that point
28/// the flag that produced it is gone. `health` reports `workspace` for both
29/// `--workspace` and `--changed-workspaces` for the same reason. A consumer
30/// must therefore not assume a given command emits a given name.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33#[serde(rename_all = "kebab-case")]
34pub enum ScopeReason {
35 /// A diff index reached the analysis, from `--diff-file`, `--diff-stdin`,
36 /// `FALLOW_DIFF_FILE` or the shared index a CI format installs.
37 Diff,
38 /// `--changed-since`.
39 ChangedSince,
40 /// The per-package refs of `workspaces.changedSince` in the config.
41 /// `--no-package-baselines` turns them off for one run.
42 PackageBaselines,
43 /// A resolved changed-file set, on the commands that see the set rather
44 /// than the flag that produced it.
45 ChangedFiles,
46 /// `--workspace`. On `health` this also covers `--changed-workspaces`,
47 /// which it cannot distinguish.
48 Workspace,
49 /// `--changed-workspaces`.
50 ChangedWorkspaces,
51 /// `--scope`.
52 Scope,
53 /// One or more `--file`.
54 File,
55 /// An active issue-type filter such as `--unused-exports`, which drops
56 /// whole baseline categories before the comparison.
57 IssueTypeFilter,
58 /// Production mode, from the flag or the resolved project config. It drops
59 /// test, story and dev files at discovery.
60 Production,
61 /// `--include-entry-exports` or the `includeEntryExports` config key. It
62 /// changes which exports `unused-exports` reports, so the run judges a
63 /// different export surface than a run without it.
64 IncludeEntryExports,
65}
66
67impl ScopeReason {
68 /// Every reason, in the declaration order `scope_reasons` serializes in.
69 const ALL: [Self; 11] = [
70 Self::Diff,
71 Self::ChangedSince,
72 Self::PackageBaselines,
73 Self::ChangedFiles,
74 Self::Workspace,
75 Self::ChangedWorkspaces,
76 Self::Scope,
77 Self::File,
78 Self::IssueTypeFilter,
79 Self::Production,
80 Self::IncludeEntryExports,
81 ];
82
83 /// The kebab-case name this reason serializes as, for prose that has to
84 /// name it outside the JSON envelope.
85 #[must_use]
86 pub const fn as_str(self) -> &'static str {
87 match self {
88 Self::Diff => "diff",
89 Self::ChangedSince => "changed-since",
90 Self::PackageBaselines => "package-baselines",
91 Self::ChangedFiles => "changed-files",
92 Self::Workspace => "workspace",
93 Self::ChangedWorkspaces => "changed-workspaces",
94 Self::Scope => "scope",
95 Self::File => "file",
96 Self::IssueTypeFilter => "issue-type-filter",
97 Self::Production => "production",
98 Self::IncludeEntryExports => "include-entry-exports",
99 }
100 }
101
102 /// Whether repeating the run without this channel judges the same project.
103 ///
104 /// A channel the caller added for one run, a diff, a base ref, a path or an
105 /// issue-type filter, is removable: dropping it widens the run to the whole
106 /// project, which is exactly what judging a whole-project baseline needs.
107 /// Production mode and workspace scoping are the caller's own statement
108 /// about what the project is, and they resolve from the project config and
109 /// the environment as well as from a flag, so repeating the command without
110 /// the flag analyzes something nobody asked about and, on the config and
111 /// environment routes, is not even narrower. The package map is the one
112 /// config channel that is removable: `--no-package-baselines` turns it off
113 /// for the repeated run.
114 ///
115 /// This is the rule the GitHub Action and the GitLab template already apply
116 /// before re-reading a baseline unscoped, and the one the `scope_reasons`
117 /// documentation states.
118 #[must_use]
119 pub const fn is_removable_by_rerun(self) -> bool {
120 match self {
121 Self::Diff
122 | Self::ChangedSince
123 | Self::PackageBaselines
124 | Self::ChangedFiles
125 | Self::Scope
126 | Self::File
127 | Self::IssueTypeFilter => true,
128 Self::Workspace
129 | Self::ChangedWorkspaces
130 | Self::Production
131 | Self::IncludeEntryExports => false,
132 }
133 }
134
135 const fn bit(self) -> u16 {
136 1 << (self as u16)
137 }
138}
139
140/// The set of channels that narrowed one run.
141///
142/// A bitset rather than a `Vec` so [`BaselineStaleness`] keeps `Copy`, which
143/// the gate builder's `const fn` and three envelope structs that hold the
144/// object by value rely on. Serializes as an array of [`ScopeReason`] in
145/// declaration order, so two identical runs produce identical bytes.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
147pub struct BaselineScopeReasons(u16);
148
149/// The bitset holds one bit per reason, so a seventeenth variant would alias
150/// the first in release builds.
151const _: () = assert!(ScopeReason::ALL.len() <= u16::BITS as usize);
152
153impl BaselineScopeReasons {
154 /// A run that was not narrowed.
155 #[must_use]
156 pub const fn empty() -> Self {
157 Self(0)
158 }
159
160 /// This set plus `reason`.
161 #[must_use]
162 pub const fn with(self, reason: ScopeReason) -> Self {
163 Self(self.0 | reason.bit())
164 }
165
166 /// This set plus `reason` when `active`, unchanged otherwise.
167 #[must_use]
168 pub const fn insert_if(self, active: bool, reason: ScopeReason) -> Self {
169 if active { self.with(reason) } else { self }
170 }
171
172 /// True when nothing narrowed the run, which is exactly when
173 /// `change_scoped` is false.
174 #[must_use]
175 pub const fn is_empty(&self) -> bool {
176 self.0 == 0
177 }
178
179 /// This set without `reason`.
180 #[must_use]
181 pub const fn without(self, reason: ScopeReason) -> Self {
182 Self(self.0 & !reason.bit())
183 }
184
185 /// Whether `reason` narrowed the run.
186 #[must_use]
187 pub const fn contains(self, reason: ScopeReason) -> bool {
188 self.0 & reason.bit() != 0
189 }
190
191 /// The reasons in wire order.
192 pub fn iter(self) -> impl Iterator<Item = ScopeReason> {
193 ScopeReason::ALL
194 .into_iter()
195 .filter(move |reason| self.contains(*reason))
196 }
197
198 /// True when repeating the run without every channel in this set judges
199 /// the same project, so a command that drops them all is worth suggesting.
200 ///
201 /// Vacuously true for an empty set; callers that mean "this run was
202 /// narrowed and can be widened" check [`Self::is_empty`] first.
203 #[must_use]
204 pub fn all_removable_by_rerun(self) -> bool {
205 self.iter().all(ScopeReason::is_removable_by_rerun)
206 }
207
208 /// The reasons as a comma-joined list of kebab-case names, for prose.
209 /// Empty when the run was not narrowed.
210 #[must_use]
211 pub fn join(self) -> String {
212 self.iter()
213 .map(ScopeReason::as_str)
214 .collect::<Vec<_>>()
215 .join(", ")
216 }
217}
218
219impl Serialize for BaselineScopeReasons {
220 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
221 serializer.collect_seq(self.iter())
222 }
223}
224
225impl<'de> Deserialize<'de> for BaselineScopeReasons {
226 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
227 let reasons = Vec::<ScopeReason>::deserialize(deserializer)?;
228 Ok(reasons
229 .into_iter()
230 .fold(Self::empty(), |set, reason| set.with(reason)))
231 }
232}
233
234/// The two channels that a saved reason describes completely.
235///
236/// A saved `production` or `include-entry-exports` says all there is to know
237/// about that channel, so a run and a file can compare on it. A saved `diff` or
238/// `workspace` names the channel and not its value, so those stay out of this
239/// type. Dead-code files can record both channels. Health and duplication files
240/// can record production only.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
242pub struct BaselineMode {
243 /// The run or the file used production mode.
244 pub production: bool,
245 /// The run or the file used `--include-entry-exports`.
246 pub include_entry_exports: bool,
247}
248
249impl BaselineMode {
250 /// The mode that a set of reasons names.
251 #[must_use]
252 pub const fn from_reasons(reasons: BaselineScopeReasons) -> Self {
253 Self {
254 production: reasons.contains(ScopeReason::Production),
255 include_entry_exports: reasons.contains(ScopeReason::IncludeEntryExports),
256 }
257 }
258
259 /// The mode that the `scope_reasons` of a saved file names.
260 #[must_use]
261 pub fn from_saved_names(names: &[String]) -> Self {
262 let has = |reason: ScopeReason| names.iter().any(|name| name == reason.as_str());
263 Self {
264 production: has(ScopeReason::Production),
265 include_entry_exports: has(ScopeReason::IncludeEntryExports),
266 }
267 }
268
269 /// True when neither channel is on.
270 #[must_use]
271 pub const fn is_empty(self) -> bool {
272 !self.production && !self.include_entry_exports
273 }
274
275 /// The channels that are on in this mode and off in `other`.
276 #[must_use]
277 pub const fn minus(self, other: Self) -> Self {
278 Self {
279 production: self.production && !other.production,
280 include_entry_exports: self.include_entry_exports && !other.include_entry_exports,
281 }
282 }
283
284 /// The channels that are on in this mode or in `other`.
285 #[must_use]
286 pub const fn union(self, other: Self) -> Self {
287 Self {
288 production: self.production || other.production,
289 include_entry_exports: self.include_entry_exports || other.include_entry_exports,
290 }
291 }
292
293 /// The flags that select this mode, each with a leading space, for a
294 /// printed command. Empty when neither channel is on.
295 #[must_use]
296 pub const fn flags(self) -> &'static str {
297 match (self.production, self.include_entry_exports) {
298 (false, false) => "",
299 (true, false) => " --production",
300 (false, true) => " --include-entry-exports",
301 (true, true) => " --production --include-entry-exports",
302 }
303 }
304
305 /// The flags as prose, for example `--production`.
306 #[must_use]
307 pub const fn flags_prose(self) -> &'static str {
308 match (self.production, self.include_entry_exports) {
309 (false, false) => "",
310 (true, false) => "--production",
311 (false, true) => "--include-entry-exports",
312 (true, true) => "--production and --include-entry-exports",
313 }
314 }
315
316 /// The channels as prose, for a file that does not record them.
317 #[must_use]
318 pub const fn unrecorded_prose(self) -> &'static str {
319 match (self.production, self.include_entry_exports) {
320 (false, false) => "",
321 (true, false) => "production mode",
322 (false, true) => "--include-entry-exports",
323 (true, true) => "production mode and --include-entry-exports",
324 }
325 }
326}
327
328/// Which advisory a loaded baseline earned on this run.
329///
330/// Mirrors `fallow_engine::baseline::BaselineStalenessWarning` so a consumer can
331/// render the same distinction the stderr warning makes, instead of inferring it
332/// from counts.
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
334#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
335#[serde(rename_all = "kebab-case")]
336pub enum BaselineStalenessAdvisory {
337 /// Nothing to say: the baseline is fresh enough, or this run cannot judge
338 /// it (a narrowed scope, an empty baseline, or a run with no findings to
339 /// match against).
340 None,
341 /// Nothing in the baseline matched and there were findings to match, so the
342 /// paths likely moved or the baseline was saved elsewhere.
343 ZeroOverlap,
344 /// A quarter or more of the baseline matched nothing, so it protects
345 /// meaningfully less than what was saved.
346 Partial,
347}
348
349/// One run's machine-readable view of a loaded baseline.
350///
351/// `stale` and `gate_trips` answer different questions and legitimately
352/// disagree. `stale` mirrors the unasked-for stderr advisory, which stays silent
353/// below a quarter of the baseline and on a run that produced no findings at
354/// all, because a cleaned project and a rotted baseline look identical from
355/// there. `gate_trips` mirrors the opt-in `--fail-on-stale-baseline` rule, which
356/// a repository asks for precisely to catch those cases, so it fires on any
357/// stale entry. A rotted baseline on a cleaned project reports
358/// `stale: false` with `gate_trips: true`; that is the contract, not a defect.
359///
360/// `change_scoped` is the member a consumer must read before dividing
361/// `matched_entries` by `baseline_entries`. A run whose scope differs from the
362/// file compares the file against another set of findings and can report
363/// `matched_entries: 0` while the baseline is perfectly healthy, so both `stale`
364/// and `gate_trips` are false there by construction. The remedy for a tripped
365/// gate is always the same: remove the stale entries with
366/// `fallow baselines prune`, or re-save the baseline in the same mode with
367/// `--save-baseline`.
368#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
369#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
370pub struct BaselineStaleness {
371 /// Entries carried by the loaded baseline file. On health these are the
372 /// complexity and CRAP finding entries; runtime-coverage suppressions and
373 /// refactoring target keys carried by the same file are not counted.
374 pub baseline_entries: usize,
375 /// Entries that matched a current finding on this run and were filtered out
376 /// of the report. On health this includes entries matched through a
377 /// followed file move.
378 pub matched_entries: usize,
379 /// Entries that matched no current finding on this run:
380 /// `baseline_entries - matched_entries`.
381 pub stale_entries: usize,
382 /// Findings this run produced before the baseline filtered them. Zero means
383 /// there was nothing to compare, either because the project is clean or
384 /// because the scope was empty, which is why `stale` stays false there even
385 /// when every entry went unmatched.
386 pub current_findings: usize,
387 /// Health only: the number of functions above a complexity threshold that
388 /// the baseline does not accept. This is a count of functions, like
389 /// `summary.functions_above_threshold`, not a count of baseline entries,
390 /// and it is the value before `--top`. A run that does not list the
391 /// complexity findings (for example `--score`) still reports it, so a
392 /// reader can tell the new functions from the accepted ones.
393 ///
394 /// `dead-code` and `dupes` do not emit it. An envelope from a fallow
395 /// version before this member does not carry it either.
396 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub remaining_findings: Option<usize>,
398 /// True when this run cannot judge the loaded baseline, because its scope
399 /// differs from the scope the file records. `scope_reasons` names each
400 /// channel that differs, so on `dead-code` production can appear when only
401 /// the file used production mode. On `dupes` and `health` this is true when
402 /// the run analyzed only part of the project, and production mode always
403 /// counts. The channels differ per command and include a diff, a base ref,
404 /// `--changed-since`, `--workspace`, `--changed-workspaces`, `--scope`,
405 /// `--file`, an issue-type filter, and production mode. Both `stale` and
406 /// `gate_trips` are false whenever this is true.
407 pub change_scoped: bool,
408 /// True exactly when the advisory stderr warning fired: not change-scoped,
409 /// at least one current finding before baseline filtering, and either
410 /// nothing matched or `stale_entries` reached a quarter of
411 /// `baseline_entries`.
412 pub stale: bool,
413 /// Which advisory this run earned, so a consumer can render the same
414 /// distinction the stderr warning makes instead of inferring it from the
415 /// counts. `none` whenever `stale` is false.
416 pub warning: BaselineStalenessAdvisory,
417 /// True exactly when `unrecognised_format` is true, or
418 /// `!change_scoped && baseline_entries > 0 && matched_entries < baseline_entries`.
419 /// That is the rule `--fail-on-stale-baseline` applies. Deliberately
420 /// stricter than `stale`: any unmatched entry counts, and so does a file
421 /// this command could not read as its own, which protects nothing at all.
422 /// The second half is suppressed by `change_scoped` and the first is not:
423 /// which command wrote a file does not depend on how much of the project
424 /// the run looked at.
425 ///
426 /// It describes the baseline, not the run's exit code: `health
427 /// --report-only` is an explicit request never to fail, so that run exits 0
428 /// and says so on stderr while still reporting `gate_trips: true` here, and
429 /// `fallow audit` never judges a baseline at all, so its
430 /// `gate_outcomes["stale-baseline"]` stands down beside a section that
431 /// reports `true`.
432 pub gate_trips: bool,
433 /// Entries that matched only by following a file move. Only `health` can
434 /// follow one, in its identity baseline mode; `dead-code` and `dupes` match
435 /// entries by fingerprint and never classify one as moved, so they report
436 /// `0`. Always `0` in health's count mode too.
437 pub moved_entries: usize,
438 /// True when the loaded file is not a baseline of the command that read it:
439 /// it names another command in its top-level `kind`, or it names none and
440 /// carries no key this command's own format writes. Read this, not
441 /// `baseline_entries == 0`, before telling anyone their baseline is the
442 /// wrong file: a baseline saved from a project that had nothing to record
443 /// is legitimately empty and is not a mistake.
444 ///
445 /// Present only when true, so an envelope from a run that loaded its own
446 /// baseline is unchanged. All three commands set it, including `dead-code`,
447 /// which classifies the file before its required fields could reject it.
448 /// A file with no `kind` is the reading a baseline saved before that member
449 /// existed gets, which is why the keys remain the fallback.
450 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
451 pub unrecognised_format: bool,
452 /// The command that saved the loaded file, when `unrecognised_format` is
453 /// true and the file names a writer this version knows: `dead-code`,
454 /// `dupes` or `health`, the token the file carries in its top-level `kind`.
455 ///
456 /// Absent, never null, for this command's own baseline, for a file that
457 /// names no writer (an empty file, or a baseline saved before `kind`
458 /// existed) and for a `kind` token this version does not know. The value
459 /// set is open: a later release can add a writer, so treat an unknown value
460 /// as "another command". The CLI computes it once per loaded baseline and
461 /// uses the same value for its stderr note.
462 #[serde(
463 default,
464 skip_serializing_if = "Option::is_none",
465 deserialize_with = "crate::static_str::deserialize_option"
466 )]
467 #[cfg_attr(feature = "schema", schemars(with = "String"))]
468 pub saved_by: Option<crate::static_str::StaticStr>,
469 /// `legacy` when the loaded baseline uses an old key form. For dead-code,
470 /// the file has no `identity`, so some entries hold a line. For `dupes`,
471 /// some entries use the clone key that older versions shared between
472 /// unrelated groups whose code did not parse on its own. The run still
473 /// applies the file. `--save-baseline` rewrites it with current keys.
474 /// Absent for a current baseline and on `health`. The value set is open.
475 #[serde(
476 default,
477 skip_serializing_if = "Option::is_none",
478 deserialize_with = "crate::static_str::deserialize_option"
479 )]
480 #[cfg_attr(feature = "schema", schemars(with = "String"))]
481 pub format: Option<crate::static_str::StaticStr>,
482 /// Which channels stop this run from judging the file, present and
483 /// non-empty exactly when `change_scoped` is true. Both members are derived
484 /// from one function, so the boolean and the array cannot disagree.
485 ///
486 /// On `dead-code`, `production` and `include-entry-exports` appear only when
487 /// the run and the file differ on that channel, and `issue-type-filter`
488 /// appears only when the file holds a category that the run does not report.
489 ///
490 /// Read it to decide whether the narrowing is removable: a run narrowed
491 /// only by `diff`, `changed-since`, `changed-files`, `scope`, `file` or
492 /// `issue-type-filter` can be repeated unscoped to judge the baseline,
493 /// while `production`, `workspace` and `changed-workspaces` are the
494 /// caller's own choice about what to analyze and an unscoped repeat would
495 /// contradict it.
496 ///
497 /// The name set is open and the names a command can emit differ per
498 /// command; see [`ScopeReason`].
499 #[serde(default, skip_serializing_if = "BaselineScopeReasons::is_empty")]
500 #[cfg_attr(
501 feature = "schema",
502 schemars(with = "std::collections::BTreeSet<ScopeReason>")
503 )]
504 pub scope_reasons: BaselineScopeReasons,
505}
506
507#[cfg(test)]
508mod tests {
509 use super::{BaselineScopeReasons, BaselineStaleness, BaselineStalenessAdvisory, ScopeReason};
510
511 fn staleness(scope_reasons: BaselineScopeReasons) -> BaselineStaleness {
512 BaselineStaleness {
513 baseline_entries: 8,
514 matched_entries: 0,
515 stale_entries: 8,
516 current_findings: 0,
517 remaining_findings: None,
518 change_scoped: !scope_reasons.is_empty(),
519 stale: false,
520 warning: BaselineStalenessAdvisory::None,
521 gate_trips: false,
522 moved_entries: 0,
523 unrecognised_format: false,
524 saved_by: None,
525 format: None,
526 scope_reasons,
527 }
528 }
529
530 #[test]
531 fn reasons_serialize_as_a_kebab_case_array() {
532 let value = serde_json::to_value(staleness(
533 BaselineScopeReasons::empty()
534 .with(ScopeReason::Production)
535 .with(ScopeReason::ChangedSince),
536 ))
537 .expect("staleness serializes");
538
539 assert_eq!(
540 value.get("scope_reasons"),
541 Some(&serde_json::json!(["changed-since", "production"]))
542 );
543 }
544
545 #[test]
546 fn reasons_serialize_in_declaration_order_whatever_the_insertion_order() {
547 let forwards = BaselineScopeReasons::empty()
548 .with(ScopeReason::Diff)
549 .with(ScopeReason::IssueTypeFilter)
550 .with(ScopeReason::Production);
551 let backwards = BaselineScopeReasons::empty()
552 .with(ScopeReason::Production)
553 .with(ScopeReason::IssueTypeFilter)
554 .with(ScopeReason::Diff);
555
556 let expected = serde_json::json!(["diff", "issue-type-filter", "production"]);
557 assert_eq!(
558 serde_json::to_value(forwards).expect("reasons serialize"),
559 expected
560 );
561 assert_eq!(
562 serde_json::to_value(backwards).expect("reasons serialize"),
563 expected
564 );
565 }
566
567 /// `fallow report --from` reads a saved envelope back, so the staleness
568 /// object must read back to the bytes it was written as.
569 #[test]
570 fn a_saved_staleness_reads_back_to_the_same_bytes() {
571 for reasons in [
572 BaselineScopeReasons::empty(),
573 BaselineScopeReasons::empty()
574 .with(ScopeReason::Production)
575 .with(ScopeReason::Diff),
576 ] {
577 let mut written = staleness(reasons);
578 written.saved_by = Some("dead-code");
579 written.format = Some("legacy");
580 let value = serde_json::to_value(written).expect("staleness serializes");
581 let read: BaselineStaleness =
582 serde_json::from_value(value.clone()).expect("staleness deserializes");
583 assert_eq!(read.scope_reasons, reasons);
584 assert_eq!(
585 serde_json::to_value(read).expect("staleness serializes again"),
586 value
587 );
588 }
589 }
590
591 #[test]
592 fn an_unscoped_run_keeps_the_member_off_the_wire() {
593 let value = serde_json::to_value(staleness(BaselineScopeReasons::empty()))
594 .expect("staleness serializes");
595
596 assert!(
597 value.get("scope_reasons").is_none(),
598 "a whole-project run must stay byte-identical to a pre-change run"
599 );
600 assert_eq!(value.get("change_scoped"), Some(&serde_json::json!(false)));
601 }
602
603 #[test]
604 fn the_member_is_non_empty_exactly_when_the_run_was_narrowed() {
605 for reason in [
606 ScopeReason::Diff,
607 ScopeReason::ChangedSince,
608 ScopeReason::ChangedFiles,
609 ScopeReason::Workspace,
610 ScopeReason::ChangedWorkspaces,
611 ScopeReason::Scope,
612 ScopeReason::File,
613 ScopeReason::IssueTypeFilter,
614 ScopeReason::Production,
615 ] {
616 let reasons = BaselineScopeReasons::empty().with(reason);
617 assert!(reasons.contains(reason), "{reason:?} must round-trip");
618 assert!(!reasons.is_empty());
619 assert_eq!(reasons.join(), reason.as_str());
620 }
621 }
622
623 /// The same split the GitHub Action and the GitLab template encode in
624 /// `BASELINE_REMOVABLE_SCOPE_REASONS`. Kept as one list here so a new
625 /// channel has to answer the question rather than inherit an answer.
626 #[test]
627 fn removable_channels_are_the_ones_a_repeat_can_drop() {
628 let removable: Vec<&str> = ScopeReason::ALL
629 .into_iter()
630 .filter(|reason| reason.is_removable_by_rerun())
631 .map(ScopeReason::as_str)
632 .collect();
633
634 assert_eq!(
635 removable,
636 [
637 "diff",
638 "changed-since",
639 "package-baselines",
640 "changed-files",
641 "scope",
642 "file",
643 "issue-type-filter"
644 ]
645 );
646 }
647
648 #[test]
649 fn a_set_is_removable_only_when_every_channel_in_it_is() {
650 let removable = BaselineScopeReasons::empty()
651 .with(ScopeReason::ChangedSince)
652 .with(ScopeReason::Scope);
653 assert!(removable.all_removable_by_rerun());
654
655 assert!(
656 !removable
657 .with(ScopeReason::Production)
658 .all_removable_by_rerun(),
659 "a repeat that drops the base ref still runs in production mode"
660 );
661 }
662
663 #[test]
664 fn insert_if_is_the_only_gate_on_membership() {
665 let reasons = BaselineScopeReasons::empty()
666 .insert_if(false, ScopeReason::Diff)
667 .insert_if(true, ScopeReason::Scope);
668
669 assert!(!reasons.contains(ScopeReason::Diff));
670 assert!(reasons.contains(ScopeReason::Scope));
671 }
672
673 #[test]
674 fn every_reason_has_a_distinct_bit_and_a_distinct_name() {
675 let mut combined = BaselineScopeReasons::empty();
676 for reason in ScopeReason::ALL {
677 combined = combined.with(reason);
678 }
679 assert_eq!(combined.iter().count(), ScopeReason::ALL.len());
680
681 let names = ScopeReason::ALL.map(ScopeReason::as_str);
682 let mut sorted = names.to_vec();
683 sorted.sort_unstable();
684 sorted.dedup();
685 assert_eq!(sorted.len(), names.len());
686 }
687
688 #[test]
689 fn the_kebab_name_matches_what_serde_emits() {
690 for reason in ScopeReason::ALL {
691 assert_eq!(
692 serde_json::to_value(reason).expect("reason serializes"),
693 serde_json::json!(reason.as_str()),
694 );
695 }
696 }
697}