alint_core/rule.rs
1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::path::Path;
4use std::sync::Arc;
5
6use crate::error::Result;
7use crate::facts::FactValues;
8use crate::level::Level;
9use crate::registry::RuleRegistry;
10use crate::walker::FileIndex;
11
12/// A single linting violation produced by a rule.
13///
14/// `path` holds an [`Arc<Path>`]; rules clone the [`Arc`] from
15/// [`FileEntry::path`](crate::walker::FileEntry::path) (a cheap
16/// atomic refcount bump) rather than copying the path bytes. At
17/// 100k violations this saves 100k path-byte allocations.
18///
19/// `message` is a [`Cow<'static, str>`]; per-match templated
20/// messages live as `Cow::Owned(String)` (no change in cost),
21/// while fixed messages can live as `Cow::Borrowed("…")` if a
22/// rule chooses to construct them that way. Public API on the
23/// struct is unchanged at the byte level — `Display` and serde
24/// `Serialize` impls go through the inner `&str` / `&Path`.
25#[derive(Debug, Clone)]
26pub struct Violation {
27 pub path: Option<Arc<Path>>,
28 pub message: Cow<'static, str>,
29 pub line: Option<usize>,
30 pub column: Option<usize>,
31}
32
33impl Violation {
34 pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
35 Self {
36 path: None,
37 message: message.into(),
38 line: None,
39 column: None,
40 }
41 }
42
43 /// Attach a path to the violation. Accepts anything convertible
44 /// into `Arc<Path>` — the canonical caller is
45 /// `.with_path(entry.path.clone())` where `entry.path` is the
46 /// `Arc<Path>` already owned by the [`FileIndex`]; this clones
47 /// the [`Arc`] (atomic refcount bump) rather than the bytes.
48 /// `PathBuf`, `&Path`, and `Box<Path>` are also accepted via
49 /// std's `From` impls; for an ad-hoc `&str` use
50 /// `Path::new("a.rs")` to convert first.
51 #[must_use]
52 pub fn with_path(mut self, path: impl Into<Arc<Path>>) -> Self {
53 self.path = Some(path.into());
54 self
55 }
56
57 #[must_use]
58 pub fn with_location(mut self, line: usize, column: usize) -> Self {
59 self.line = Some(line);
60 self.column = Some(column);
61 self
62 }
63}
64
65/// The collected outcome of evaluating a single rule.
66///
67/// `rule_id` holds an [`Arc<str>`]: the engine builds it once
68/// per rule run and shares it across every violation that rule
69/// produces, saving N-1 allocations per rule. `policy_url`
70/// follows the same shape via [`Arc<str>`] — set once per rule,
71/// shared across violations.
72#[derive(Debug, Clone)]
73pub struct RuleResult {
74 pub rule_id: Arc<str>,
75 pub level: Level,
76 pub policy_url: Option<Arc<str>>,
77 pub violations: Vec<Violation>,
78 /// Whether the rule declares a [`Fixer`] — surfaced here so
79 /// the human formatter can tag violations as `fixable`
80 /// without threading the rule registry into the renderer.
81 pub is_fixable: bool,
82}
83
84impl RuleResult {
85 pub fn passed(&self) -> bool {
86 self.violations.is_empty()
87 }
88}
89
90/// Execution context handed to each rule during evaluation.
91///
92/// - `registry` — available for rules that need to build and evaluate nested
93/// rules at runtime (e.g. `for_each_dir`). Tests that don't exercise
94/// nested evaluation can set this to `None`.
95/// - `facts` — resolved fact values, computed once per `Engine::run`.
96/// - `vars` — user-supplied string variables from the config's `vars:` section.
97/// - `git_tracked` — set of repo paths reported by `git ls-files`,
98/// computed once per run when at least one rule has
99/// `git_tracked_only: true`. `None` outside a git repo or when
100/// no rule asked for it. Rules that opt in consult it via
101/// [`Context::is_git_tracked`].
102/// - `git_blame` — per-file `git blame` cache, computed lazily
103/// when at least one rule reports `wants_git_blame()`. `None`
104/// when no rule asked for it. Rules consult it via
105/// [`crate::git::BlameCache::get`]; both "outside a git repo"
106/// and "blame failed for this file" surface as a `None`
107/// lookup, which the rule treats as "silent no-op."
108#[derive(Debug)]
109pub struct Context<'a> {
110 pub root: &'a Path,
111 pub index: &'a FileIndex,
112 pub registry: Option<&'a RuleRegistry>,
113 pub facts: Option<&'a FactValues>,
114 pub vars: Option<&'a HashMap<String, String>>,
115 pub git_tracked: Option<&'a std::collections::HashSet<std::path::PathBuf>>,
116 pub git_blame: Option<&'a crate::git::BlameCache>,
117}
118
119impl Context<'_> {
120 /// True if `rel_path` is in git's index. Returns `false` when
121 /// no tracked-set was computed (no git repo, or no rule asked
122 /// for it). Rules that opt into `git_tracked_only` therefore
123 /// silently skip every entry outside a git repo, which is the
124 /// right behaviour for the canonical "don't let X be
125 /// committed" use case.
126 pub fn is_git_tracked(&self, rel_path: &Path) -> bool {
127 match self.git_tracked {
128 Some(set) => set.contains(rel_path),
129 None => false,
130 }
131 }
132
133 /// True if the directory at `rel_path` contains at least one
134 /// git-tracked file. Used by `dir_*` rules opting into
135 /// `git_tracked_only`. Same `None`-means-untracked semantics
136 /// as [`Context::is_git_tracked`].
137 pub fn dir_has_tracked_files(&self, rel_path: &Path) -> bool {
138 match self.git_tracked {
139 Some(set) => crate::git::dir_has_tracked_files(rel_path, set),
140 None => false,
141 }
142 }
143}
144
145/// How a rule narrows its iteration to git-tracked entries.
146/// Returned by [`Rule::git_tracked_mode`]; the engine reads
147/// this at construction time to pick the right pre-filtered
148/// `FileIndex` (file-only or dir-aware) for each opted-in
149/// rule.
150///
151/// The mode is per-rule (a config might opt in some rules and
152/// not others). The engine builds at most two filtered indexes
153/// per run regardless of how many rules opt in, so the cost
154/// amortises across the whole rule set.
155///
156/// See `docs/design/v0.9/git-tracked-filtered-index.md` for
157/// the v0.9.11 structural fix this enum is the entry point of.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum GitTrackedMode {
160 /// Rule does not consult the git-tracked set. Engine
161 /// routes the rule's evaluation against the unfiltered
162 /// `FileIndex`. The default; do not override unless the
163 /// rule opts into `git_tracked_only:`.
164 Off,
165 /// Rule iterates files (`ctx.index.files()`) and the
166 /// engine narrows that to entries where
167 /// `git_tracked.contains(path)` before the rule sees them.
168 /// File-mode existence rules (`file_exists`, `file_absent`)
169 /// pick this mode when the spec's `git_tracked_only: true`.
170 FileOnly,
171 /// Rule iterates dirs (`ctx.index.dirs()`) and the engine
172 /// narrows that to dirs where
173 /// `dir_has_tracked_files(path, &git_tracked)`. Dir-mode
174 /// existence rules (`dir_exists`, `dir_absent`) pick this
175 /// mode when the spec's `git_tracked_only: true`. The
176 /// filtered index also includes the tracked files
177 /// themselves so a `dir_*` rule's nested per-file checks
178 /// (e.g. `paths:` glob) still match.
179 DirAware,
180}
181
182/// Trait every built-in and plugin rule implements.
183pub trait Rule: Send + Sync + std::fmt::Debug {
184 fn id(&self) -> &str;
185 fn level(&self) -> Level;
186 fn policy_url(&self) -> Option<&str> {
187 None
188 }
189 /// Whether (and how) this rule narrows its iteration to
190 /// git-tracked entries. Default [`GitTrackedMode::Off`].
191 /// Rule kinds that support `git_tracked_only:` override to
192 /// return [`GitTrackedMode::FileOnly`] (file-mode rules:
193 /// check `set.contains(path)`) or [`GitTrackedMode::DirAware`]
194 /// (dir-mode rules: check `dir_has_tracked_files(path, set)`)
195 /// when the user opts in.
196 ///
197 /// The engine collects the tracked-paths set (via
198 /// `git ls-files`) once per run when ANY rule returns a
199 /// non-`Off` mode, then builds a pre-filtered `FileIndex`
200 /// for each mode and routes opted-in rules to the right
201 /// `Context`. Rules iterate `ctx.index.files()` /
202 /// `ctx.index.dirs()` exactly as before — the index is
203 /// already narrowed, so no per-rule `if self.git_tracked_only
204 /// && !ctx.is_git_tracked(...)` runtime check is needed.
205 /// Closes the same recurrence-risk shape as v0.9.10's
206 /// `Scope`-owns-`scope_filter` fix:
207 /// `docs/design/v0.9/git-tracked-filtered-index.md`.
208 fn git_tracked_mode(&self) -> GitTrackedMode {
209 GitTrackedMode::Off
210 }
211
212 /// Deprecated alias for `git_tracked_mode() != GitTrackedMode::Off`.
213 /// Kept for one minor version so out-of-tree rule plugins
214 /// that override this method continue to opt in to the
215 /// engine's git-tracked-paths setup. Will be removed in
216 /// v0.9.12; override [`Rule::git_tracked_mode`] instead.
217 #[deprecated(
218 since = "0.9.11",
219 note = "override `git_tracked_mode` instead; this method is delegated and will be removed in v0.9.12"
220 )]
221 fn wants_git_tracked(&self) -> bool {
222 self.git_tracked_mode() != GitTrackedMode::Off
223 }
224
225 /// Whether this rule needs `git blame` output on
226 /// [`Context`]. Default `false`; the `git_blame_age` rule
227 /// kind overrides to return `true`. The engine builds the
228 /// shared [`crate::git::BlameCache`] once per run when any
229 /// rule opts in, so multiple blame-aware rules over
230 /// overlapping `paths:` re-use the parsed result.
231 fn wants_git_blame(&self) -> bool {
232 false
233 }
234
235 /// In `--changed` mode, return `true` to evaluate this rule
236 /// against the **full** [`FileIndex`] rather than the
237 /// changed-only filtered subset. Default `false` (per-file
238 /// semantics — the rule sees only changed files in scope).
239 ///
240 /// Cross-file rules (`pair`, `for_each_dir`,
241 /// `every_matching_has`, `unique_by`, `dir_contains`,
242 /// `dir_only_contains`) override to `true` because their
243 /// inputs span the whole tree by definition — a verdict on
244 /// the changed file depends on what's still in the rest of
245 /// the tree. Existence rules (`file_exists`, `file_absent`,
246 /// `dir_exists`, `dir_absent`) likewise consult the whole
247 /// tree to answer "is X present?" correctly.
248 fn requires_full_index(&self) -> bool {
249 false
250 }
251
252 /// In `--changed` mode, return the [`Scope`](crate::Scope)
253 /// this rule is scoped to (typically the rule's `paths:`
254 /// field). The engine intersects the scope with the
255 /// changed-set; rules whose scope doesn't intersect are
256 /// skipped, which is the optimisation `--changed` exists
257 /// for.
258 ///
259 /// Default `None` ("no scope information") means the rule is
260 /// always evaluated. Cross-file rules deliberately leave this
261 /// as `None` (they always evaluate per the roadmap contract).
262 /// Per-file rules with a single `Scope` field should override
263 /// to return `Some(&self.scope)`.
264 fn path_scope(&self) -> Option<&crate::scope::Scope> {
265 None
266 }
267
268 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>>;
269
270 /// Optional automatic-fix strategy. Rules whose violations can be
271 /// mechanically corrected (e.g. creating a missing file, removing a
272 /// forbidden one, renaming to the correct case) return a
273 /// [`Fixer`] here; the default implementation reports the rule as
274 /// unfixable.
275 fn fixer(&self) -> Option<&dyn Fixer> {
276 None
277 }
278
279 /// Opt into the file-major dispatch path. Per-file rules that
280 /// can evaluate one file at a time given a pre-loaded byte
281 /// slice override this to return `Some(self)`; cross-file
282 /// rules and any rule with `requires_full_index() == true`
283 /// leave it as `None` and keep evaluating under the rule-
284 /// major loop.
285 ///
286 /// When the engine has multiple per-file rules sharing one
287 /// scope, the file-major loop reads each matched file once
288 /// and dispatches to every applicable per-file rule against
289 /// the same byte buffer — coalescing N reads of one file
290 /// into 1.
291 fn as_per_file(&self) -> Option<&dyn PerFileRule> {
292 None
293 }
294}
295
296/// File-major dispatch entry-point for a per-file rule.
297///
298/// Rules that can evaluate one file at a time given a pre-loaded
299/// byte slice implement this trait alongside [`Rule`] and opt
300/// into the file-major path via [`Rule::as_per_file`]. The
301/// engine reads each file once per evaluation pass and calls
302/// `evaluate_file` on every per-file rule whose
303/// [`path_scope`](PerFileRule::path_scope) matches that file —
304/// avoiding the per-rule `std::fs::read` the rule-major loop
305/// would otherwise duplicate.
306///
307/// Implementations MUST NOT call `std::fs::read` themselves; the
308/// `bytes` argument is the engine's already-read content. The
309/// rule's existing [`Rule::evaluate`] implementation (which does
310/// read the file) stays in place as the rule-major fallback —
311/// it's still the path used by `alint fix` (sequential
312/// filesystem mutation rules out coalesced reads there) and by
313/// fallback test harnesses.
314pub trait PerFileRule: Send + Sync + std::fmt::Debug {
315 /// The rule's scope. The engine checks
316 /// `path_scope().matches(path)` before calling
317 /// `evaluate_file`; a rule that returns
318 /// [`Scope::match_all`](crate::scope::Scope::match_all) is
319 /// in scope for every file.
320 fn path_scope(&self) -> &crate::scope::Scope;
321
322 /// Evaluate one file given the engine's already-read byte
323 /// content. The `path` is the relative path from the lint
324 /// root; the rule should `with_path(path.into())` (or clone
325 /// the matched [`FileEntry::path`](crate::walker::FileEntry::path)
326 /// if it has one in hand) on emitted violations.
327 fn evaluate_file(&self, ctx: &Context<'_>, path: &Path, bytes: &[u8])
328 -> Result<Vec<Violation>>;
329
330 /// Optional lower bound on the bytes the rule needs to
331 /// evaluate. Default `None` means "I need the whole file."
332 /// Used as a hint; the engine in v0.9.3 reads the whole
333 /// file regardless and hands it to every applicable rule —
334 /// the hint is reserved for a future engine-side bounded-
335 /// read optimisation.
336 fn max_bytes_needed(&self) -> Option<usize> {
337 None
338 }
339}
340
341/// Runtime context for applying a fix.
342#[derive(Debug)]
343pub struct FixContext<'a> {
344 pub root: &'a Path,
345 /// When true, fixers must describe what they would do without
346 /// touching the filesystem.
347 pub dry_run: bool,
348 /// Max bytes a content-editing fix will read + rewrite.
349 /// `None` means no cap. Honored by the `read_for_fix` helper
350 /// (and any custom fixer that opts in).
351 pub fix_size_limit: Option<u64>,
352}
353
354/// The result of applying (or simulating) one fix against one violation.
355#[derive(Debug, Clone)]
356pub enum FixOutcome {
357 /// The fix was applied (or would be, under `dry_run`). The string
358 /// is a human-readable one-liner — e.g. `"created LICENSE"`,
359 /// `"would remove target/debug.log"`.
360 Applied(String),
361 /// The fixer intentionally did nothing; the string explains why
362 /// (e.g. `"already exists"`, `"no path on violation"`). This is
363 /// distinct from a hard error returned via `Result::Err`.
364 Skipped(String),
365}
366
367/// A mechanical corrector for a specific rule's violations.
368pub trait Fixer: Send + Sync + std::fmt::Debug {
369 /// Short human-readable summary of what this fixer does,
370 /// independent of any specific violation.
371 fn describe(&self) -> String;
372
373 /// Apply the fix against a single violation.
374 fn apply(&self, violation: &Violation, ctx: &FixContext<'_>) -> Result<FixOutcome>;
375}
376
377/// Result of [`read_for_fix`] — either the bytes of the file,
378/// or a [`FixOutcome::Skipped`] the caller should return.
379///
380/// Content-editing fixers (`file_prepend`, `file_append`,
381/// `file_trim_trailing_whitespace`, …) funnel their initial read
382/// through this helper so the `fix_size_limit` guard is enforced
383/// uniformly: over-limit files are reported as `Skipped` with a
384/// clear reason, and a one-line warning is printed to stderr so
385/// scripted runs notice.
386#[derive(Debug)]
387pub enum ReadForFix {
388 Bytes(Vec<u8>),
389 Skipped(FixOutcome),
390}
391
392/// Check whether `abs` is within the `fix_size_limit` on `ctx`.
393/// Returns `Some(outcome)` when the file is over-limit (the
394/// caller returns this directly); returns `None` when the fix
395/// can proceed. Emits a one-line stderr warning on over-limit.
396///
397/// Use this in fixers that modify the file without reading the
398/// full body (e.g. streaming append). For read-modify-write
399/// flows, prefer [`read_for_fix`] which folds the check in.
400pub fn check_fix_size(
401 abs: &Path,
402 display_path: &std::path::Path,
403 ctx: &FixContext<'_>,
404) -> Result<Option<FixOutcome>> {
405 let Some(limit) = ctx.fix_size_limit else {
406 return Ok(None);
407 };
408 let metadata = std::fs::metadata(abs).map_err(|source| crate::error::Error::Io {
409 path: abs.to_path_buf(),
410 source,
411 })?;
412 if metadata.len() > limit {
413 let reason = format!(
414 "{} is {} bytes; exceeds fix_size_limit ({}). Raise \
415 `fix_size_limit` in .alint.yml (or set it to `null` to disable) \
416 to fix files this large.",
417 display_path.display(),
418 metadata.len(),
419 limit,
420 );
421 eprintln!("alint: warning: {reason}");
422 return Ok(Some(FixOutcome::Skipped(reason)));
423 }
424 Ok(None)
425}
426
427/// Read `abs` subject to the size limit on `ctx`. Over-limit
428/// files return `ReadForFix::Skipped(Outcome::Skipped(_))` and
429/// emit a one-line stderr warning; in-limit files return
430/// `ReadForFix::Bytes(...)`. Pass-through I/O errors propagate.
431pub fn read_for_fix(
432 abs: &Path,
433 display_path: &std::path::Path,
434 ctx: &FixContext<'_>,
435) -> Result<ReadForFix> {
436 if let Some(outcome) = check_fix_size(abs, display_path, ctx)? {
437 return Ok(ReadForFix::Skipped(outcome));
438 }
439 let bytes = std::fs::read(abs).map_err(|source| crate::error::Error::Io {
440 path: abs.to_path_buf(),
441 source,
442 })?;
443 Ok(ReadForFix::Bytes(bytes))
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 fn empty_index() -> FileIndex {
451 FileIndex::default()
452 }
453
454 #[test]
455 fn violation_builder_sets_fields_via_chain() {
456 let v = Violation::new("trailing whitespace")
457 .with_path(Path::new("src/main.rs"))
458 .with_location(12, 4);
459 assert_eq!(v.message, "trailing whitespace");
460 assert_eq!(v.path.as_deref(), Some(Path::new("src/main.rs")));
461 assert_eq!(v.line, Some(12));
462 assert_eq!(v.column, Some(4));
463 }
464
465 #[test]
466 fn violation_new_starts_with_no_path_or_location() {
467 let v = Violation::new("global note");
468 assert!(v.path.is_none());
469 assert!(v.line.is_none());
470 assert!(v.column.is_none());
471 }
472
473 #[test]
474 fn rule_result_passed_iff_violations_empty() {
475 let mut r = RuleResult {
476 rule_id: "x".into(),
477 level: Level::Error,
478 policy_url: None,
479 violations: Vec::new(),
480 is_fixable: false,
481 };
482 assert!(r.passed());
483 r.violations.push(Violation::new("oops"));
484 assert!(!r.passed());
485 }
486
487 #[test]
488 fn context_is_git_tracked_returns_false_outside_repo() {
489 let idx = empty_index();
490 let ctx = Context {
491 root: Path::new("/tmp"),
492 index: &idx,
493 registry: None,
494 facts: None,
495 vars: None,
496 git_tracked: None, // outside-a-repo / no rule opted in
497 git_blame: None,
498 };
499 assert!(!ctx.is_git_tracked(Path::new("anything.rs")));
500 assert!(!ctx.dir_has_tracked_files(Path::new("src")));
501 }
502
503 #[test]
504 fn context_is_git_tracked_consults_set_when_present() {
505 let mut tracked: std::collections::HashSet<std::path::PathBuf> =
506 std::collections::HashSet::new();
507 tracked.insert(std::path::PathBuf::from("src/main.rs"));
508 let idx = empty_index();
509 let ctx = Context {
510 root: Path::new("/tmp"),
511 index: &idx,
512 registry: None,
513 facts: None,
514 vars: None,
515 git_tracked: Some(&tracked),
516 git_blame: None,
517 };
518 assert!(ctx.is_git_tracked(Path::new("src/main.rs")));
519 assert!(!ctx.is_git_tracked(Path::new("README.md")));
520 }
521
522 /// Stand-in `Rule` impl that returns the trait defaults.
523 /// Lets us assert the documented defaults without dragging
524 /// in a real registered rule.
525 #[derive(Debug)]
526 struct DefaultRule;
527
528 impl Rule for DefaultRule {
529 fn id(&self) -> &'static str {
530 "default"
531 }
532 fn level(&self) -> Level {
533 Level::Warning
534 }
535 fn evaluate(&self, _ctx: &Context<'_>) -> Result<Vec<Violation>> {
536 Ok(Vec::new())
537 }
538 }
539
540 #[test]
541 fn rule_trait_defaults_are_safe_no_ops() {
542 let r = DefaultRule;
543 assert_eq!(r.policy_url(), None);
544 assert_eq!(r.git_tracked_mode(), GitTrackedMode::Off);
545 assert!(!r.wants_git_blame());
546 assert!(!r.requires_full_index());
547 assert!(r.path_scope().is_none());
548 assert!(r.fixer().is_none());
549 }
550
551 #[test]
552 fn check_fix_size_returns_none_when_limit_disabled() {
553 let dir = tempfile::tempdir().unwrap();
554 let f = dir.path().join("a.txt");
555 std::fs::write(&f, b"hello").unwrap();
556 let ctx = FixContext {
557 root: dir.path(),
558 dry_run: false,
559 fix_size_limit: None,
560 };
561 let outcome = check_fix_size(&f, Path::new("a.txt"), &ctx).unwrap();
562 assert!(outcome.is_none());
563 }
564
565 #[test]
566 fn check_fix_size_skips_over_limit_files() {
567 let dir = tempfile::tempdir().unwrap();
568 let f = dir.path().join("big.txt");
569 std::fs::write(&f, vec![b'x'; 1024]).unwrap();
570 let ctx = FixContext {
571 root: dir.path(),
572 dry_run: false,
573 fix_size_limit: Some(64),
574 };
575 let outcome = check_fix_size(&f, Path::new("big.txt"), &ctx).unwrap();
576 match outcome {
577 Some(FixOutcome::Skipped(reason)) => {
578 assert!(reason.contains("exceeds fix_size_limit"));
579 assert!(reason.contains("big.txt"));
580 }
581 other => panic!("expected Skipped, got {other:?}"),
582 }
583 }
584
585 #[test]
586 fn read_for_fix_returns_bytes_when_in_limit() {
587 let dir = tempfile::tempdir().unwrap();
588 let f = dir.path().join("a.txt");
589 std::fs::write(&f, b"hello").unwrap();
590 let ctx = FixContext {
591 root: dir.path(),
592 dry_run: false,
593 fix_size_limit: Some(1 << 20),
594 };
595 match read_for_fix(&f, Path::new("a.txt"), &ctx).unwrap() {
596 ReadForFix::Bytes(b) => assert_eq!(b, b"hello"),
597 ReadForFix::Skipped(_) => panic!("expected Bytes, got Skipped"),
598 }
599 }
600
601 #[test]
602 fn read_for_fix_returns_skipped_when_over_limit() {
603 let dir = tempfile::tempdir().unwrap();
604 let f = dir.path().join("big.txt");
605 std::fs::write(&f, vec![b'x'; 1024]).unwrap();
606 let ctx = FixContext {
607 root: dir.path(),
608 dry_run: false,
609 fix_size_limit: Some(64),
610 };
611 match read_for_fix(&f, Path::new("big.txt"), &ctx).unwrap() {
612 ReadForFix::Skipped(FixOutcome::Skipped(_)) => {}
613 ReadForFix::Skipped(FixOutcome::Applied(_)) => {
614 panic!("expected Skipped, got Skipped(Applied)")
615 }
616 ReadForFix::Bytes(_) => panic!("expected Skipped, got Bytes"),
617 }
618 }
619
620 #[test]
621 fn fix_outcome_variants_are_constructible() {
622 // Sanity: documented variant shapes haven't drifted.
623 let _applied = FixOutcome::Applied("created LICENSE".into());
624 let _skipped = FixOutcome::Skipped("already exists".into());
625 }
626}