Skip to main content

alint_core/
rule.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use crate::error::Result;
5use crate::facts::FactValues;
6use crate::level::Level;
7use crate::registry::RuleRegistry;
8use crate::walker::FileIndex;
9
10/// A single linting violation produced by a rule.
11#[derive(Debug, Clone)]
12pub struct Violation {
13    pub path: Option<PathBuf>,
14    pub message: String,
15    pub line: Option<usize>,
16    pub column: Option<usize>,
17}
18
19impl Violation {
20    pub fn new(message: impl Into<String>) -> Self {
21        Self {
22            path: None,
23            message: message.into(),
24            line: None,
25            column: None,
26        }
27    }
28
29    #[must_use]
30    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
31        self.path = Some(path.into());
32        self
33    }
34
35    #[must_use]
36    pub fn with_location(mut self, line: usize, column: usize) -> Self {
37        self.line = Some(line);
38        self.column = Some(column);
39        self
40    }
41}
42
43/// The collected outcome of evaluating a single rule.
44#[derive(Debug, Clone)]
45pub struct RuleResult {
46    pub rule_id: String,
47    pub level: Level,
48    pub policy_url: Option<String>,
49    pub violations: Vec<Violation>,
50    /// Whether the rule declares a [`Fixer`] — surfaced here so
51    /// the human formatter can tag violations as `fixable`
52    /// without threading the rule registry into the renderer.
53    pub is_fixable: bool,
54}
55
56impl RuleResult {
57    pub fn passed(&self) -> bool {
58        self.violations.is_empty()
59    }
60}
61
62/// Execution context handed to each rule during evaluation.
63///
64/// - `registry` — available for rules that need to build and evaluate nested
65///   rules at runtime (e.g. `for_each_dir`). Tests that don't exercise
66///   nested evaluation can set this to `None`.
67/// - `facts` — resolved fact values, computed once per `Engine::run`.
68/// - `vars` — user-supplied string variables from the config's `vars:` section.
69#[derive(Debug)]
70pub struct Context<'a> {
71    pub root: &'a Path,
72    pub index: &'a FileIndex,
73    pub registry: Option<&'a RuleRegistry>,
74    pub facts: Option<&'a FactValues>,
75    pub vars: Option<&'a HashMap<String, String>>,
76}
77
78/// Trait every built-in and plugin rule implements.
79pub trait Rule: Send + Sync + std::fmt::Debug {
80    fn id(&self) -> &str;
81    fn level(&self) -> Level;
82    fn policy_url(&self) -> Option<&str> {
83        None
84    }
85    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>>;
86
87    /// Optional automatic-fix strategy. Rules whose violations can be
88    /// mechanically corrected (e.g. creating a missing file, removing a
89    /// forbidden one, renaming to the correct case) return a
90    /// [`Fixer`] here; the default implementation reports the rule as
91    /// unfixable.
92    fn fixer(&self) -> Option<&dyn Fixer> {
93        None
94    }
95}
96
97/// Runtime context for applying a fix.
98#[derive(Debug)]
99pub struct FixContext<'a> {
100    pub root: &'a Path,
101    /// When true, fixers must describe what they would do without
102    /// touching the filesystem.
103    pub dry_run: bool,
104    /// Max bytes a content-editing fix will read + rewrite.
105    /// `None` means no cap. Honored by the `read_for_fix` helper
106    /// (and any custom fixer that opts in).
107    pub fix_size_limit: Option<u64>,
108}
109
110/// The result of applying (or simulating) one fix against one violation.
111#[derive(Debug, Clone)]
112pub enum FixOutcome {
113    /// The fix was applied (or would be, under `dry_run`). The string
114    /// is a human-readable one-liner — e.g. `"created LICENSE"`,
115    /// `"would remove target/debug.log"`.
116    Applied(String),
117    /// The fixer intentionally did nothing; the string explains why
118    /// (e.g. `"already exists"`, `"no path on violation"`). This is
119    /// distinct from a hard error returned via `Result::Err`.
120    Skipped(String),
121}
122
123/// A mechanical corrector for a specific rule's violations.
124pub trait Fixer: Send + Sync + std::fmt::Debug {
125    /// Short human-readable summary of what this fixer does,
126    /// independent of any specific violation.
127    fn describe(&self) -> String;
128
129    /// Apply the fix against a single violation.
130    fn apply(&self, violation: &Violation, ctx: &FixContext<'_>) -> Result<FixOutcome>;
131}
132
133/// Result of [`read_for_fix`] — either the bytes of the file,
134/// or a [`FixOutcome::Skipped`] the caller should return.
135///
136/// Content-editing fixers (`file_prepend`, `file_append`,
137/// `file_trim_trailing_whitespace`, …) funnel their initial read
138/// through this helper so the `fix_size_limit` guard is enforced
139/// uniformly: over-limit files are reported as `Skipped` with a
140/// clear reason, and a one-line warning is printed to stderr so
141/// scripted runs notice.
142#[derive(Debug)]
143pub enum ReadForFix {
144    Bytes(Vec<u8>),
145    Skipped(FixOutcome),
146}
147
148/// Check whether `abs` is within the `fix_size_limit` on `ctx`.
149/// Returns `Some(outcome)` when the file is over-limit (the
150/// caller returns this directly); returns `None` when the fix
151/// can proceed. Emits a one-line stderr warning on over-limit.
152///
153/// Use this in fixers that modify the file without reading the
154/// full body (e.g. streaming append). For read-modify-write
155/// flows, prefer [`read_for_fix`] which folds the check in.
156pub fn check_fix_size(
157    abs: &Path,
158    display_path: &std::path::Path,
159    ctx: &FixContext<'_>,
160) -> Result<Option<FixOutcome>> {
161    let Some(limit) = ctx.fix_size_limit else {
162        return Ok(None);
163    };
164    let metadata = std::fs::metadata(abs).map_err(|source| crate::error::Error::Io {
165        path: abs.to_path_buf(),
166        source,
167    })?;
168    if metadata.len() > limit {
169        let reason = format!(
170            "{} is {} bytes; exceeds fix_size_limit ({}). Raise \
171             `fix_size_limit` in .alint.yml (or set it to `null` to disable) \
172             to fix files this large.",
173            display_path.display(),
174            metadata.len(),
175            limit,
176        );
177        eprintln!("alint: warning: {reason}");
178        return Ok(Some(FixOutcome::Skipped(reason)));
179    }
180    Ok(None)
181}
182
183/// Read `abs` subject to the size limit on `ctx`. Over-limit
184/// files return `ReadForFix::Skipped(Outcome::Skipped(_))` and
185/// emit a one-line stderr warning; in-limit files return
186/// `ReadForFix::Bytes(...)`. Pass-through I/O errors propagate.
187pub fn read_for_fix(
188    abs: &Path,
189    display_path: &std::path::Path,
190    ctx: &FixContext<'_>,
191) -> Result<ReadForFix> {
192    if let Some(outcome) = check_fix_size(abs, display_path, ctx)? {
193        return Ok(ReadForFix::Skipped(outcome));
194    }
195    let bytes = std::fs::read(abs).map_err(|source| crate::error::Error::Io {
196        path: abs.to_path_buf(),
197        source,
198    })?;
199    Ok(ReadForFix::Bytes(bytes))
200}