Skip to main content

alint_core/
config.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3
4use serde::Deserialize;
5
6use crate::facts::FactSpec;
7use crate::level::Level;
8
9/// Parsed form of a `.alint.yml` file.
10#[derive(Debug, Clone, Deserialize, Default)]
11#[serde(deny_unknown_fields)]
12pub struct Config {
13    pub version: u32,
14    /// Other config files this one inherits from. Entries resolved
15    /// left-to-right; later entries override earlier ones; the
16    /// current file's own definitions override everything it extends.
17    ///
18    /// Each entry is either a bare string (local path, `https://`
19    /// URL with SRI, or `alint://bundled/...`) or a mapping with
20    /// `url:` and optional `only:` / `except:` filters.
21    #[serde(default)]
22    pub extends: Vec<ExtendsEntry>,
23    #[serde(default)]
24    pub ignore: Vec<String>,
25    #[serde(default = "default_respect_gitignore")]
26    pub respect_gitignore: bool,
27    /// Free-form string variables referenced from rule messages and
28    /// `when` expressions as `{{vars.<name>}}` and `vars.<name>`.
29    #[serde(default)]
30    pub vars: HashMap<String, String>,
31    /// Repository properties evaluated once per run and referenced from
32    /// `when` clauses as `facts.<id>`.
33    #[serde(default)]
34    pub facts: Vec<FactSpec>,
35    #[serde(default)]
36    pub rules: Vec<RuleSpec>,
37    /// Maximum file size, in bytes, that content-editing fixes
38    /// will read and rewrite. Files over this limit are reported
39    /// as `Skipped` in the fix report and a one-line warning is
40    /// printed to stderr. Defaults to 1 MiB; set explicitly to
41    /// `null` to disable the cap entirely.
42    ///
43    /// Path-only fixes (`file_create`, `file_remove`,
44    /// `file_rename`) ignore the cap — they don't read content.
45    #[serde(default = "default_fix_size_limit")]
46    pub fix_size_limit: Option<u64>,
47    /// Opt in to discovery of `.alint.yml` / `.alint.yaml` files
48    /// in subdirectories. When `true`, the loader walks the
49    /// repository tree (from the root config's directory,
50    /// respecting `.gitignore` and `ignore:`) and finds any
51    /// nested config files; each nested rule's path-like fields
52    /// (`paths`, `select`, `primary`) are prefixed with the
53    /// directory that nested config lives in, so the rule
54    /// auto-scopes to that subtree. Default `false`.
55    ///
56    /// Only the user's top-level config may set this — nested
57    /// configs themselves cannot spawn further nested discovery.
58    #[serde(default)]
59    pub nested_configs: bool,
60}
61
62// Returning `Option<u64>` (rather than bare `u64`) keeps the
63// YAML-facing type consistent with `Config.fix_size_limit`:
64// users set `null` in YAML to mean "no limit". The Option is
65// load-bearing at the field level, so clippy's warning on the
66// default fn is noise here.
67#[allow(clippy::unnecessary_wraps)]
68fn default_fix_size_limit() -> Option<u64> {
69    Some(1 << 20)
70}
71
72fn default_respect_gitignore() -> bool {
73    true
74}
75
76impl Config {
77    pub const CURRENT_VERSION: u32 = 1;
78}
79
80/// A single `extends:` entry. Accepts either a bare string (the
81/// classic form — a local path, `https://` URL with SRI, or
82/// `alint://bundled/<name>@<rev>`) or a mapping that adds
83/// `only:` / `except:` filters on the inherited rule set.
84///
85/// ```yaml
86/// extends:
87///   - alint://bundled/oss-baseline@v1             # classic form
88///   - url: alint://bundled/rust@v1                # filtered form
89///     except: [rust-no-target-dir]                # drop by id
90///   - url: ./team-defaults.yml
91///     only: [team-copyright-header]               # keep by id
92/// ```
93///
94/// Filters resolve against the *fully-resolved* rule set of the
95/// entry (i.e. anything it transitively extends). `only:` and
96/// `except:` are mutually exclusive on a single entry; listing an
97/// unknown rule id is a config error so typos surface at load
98/// time.
99#[derive(Debug, Clone, Deserialize)]
100#[serde(untagged)]
101pub enum ExtendsEntry {
102    Url(String),
103    Filtered {
104        url: String,
105        #[serde(default)]
106        only: Option<Vec<String>>,
107        #[serde(default)]
108        except: Option<Vec<String>>,
109    },
110}
111
112impl ExtendsEntry {
113    /// The URL / path of the extended config. Uniform across both
114    /// enum variants.
115    pub fn url(&self) -> &str {
116        match self {
117            Self::Url(s) | Self::Filtered { url: s, .. } => s,
118        }
119    }
120
121    /// Rule ids to keep (drop everything else). `None` when no
122    /// `only:` filter is specified.
123    pub fn only(&self) -> Option<&[String]> {
124        match self {
125            Self::Filtered { only: Some(v), .. } => Some(v),
126            _ => None,
127        }
128    }
129
130    /// Rule ids to drop. `None` when no `except:` filter is
131    /// specified.
132    pub fn except(&self) -> Option<&[String]> {
133        match self {
134            Self::Filtered {
135                except: Some(v), ..
136            } => Some(v),
137            _ => None,
138        }
139    }
140}
141
142/// YAML shape for a rule's `paths:` field — a single glob, an array (with
143/// optional `!pattern` negations), or an explicit `{include, exclude}` pair.
144/// For the include/exclude form, each field accepts either a single string
145/// or a list of strings.
146#[derive(Debug, Clone, Deserialize)]
147#[serde(untagged)]
148pub enum PathsSpec {
149    Single(String),
150    Many(Vec<String>),
151    IncludeExclude {
152        #[serde(default, deserialize_with = "string_or_vec")]
153        include: Vec<String>,
154        #[serde(default, deserialize_with = "string_or_vec")]
155        exclude: Vec<String>,
156    },
157}
158
159fn string_or_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
160where
161    D: serde::Deserializer<'de>,
162{
163    #[derive(Deserialize)]
164    #[serde(untagged)]
165    enum OneOrMany {
166        One(String),
167        Many(Vec<String>),
168    }
169    match OneOrMany::deserialize(deserializer)? {
170        OneOrMany::One(s) => Ok(vec![s]),
171        OneOrMany::Many(v) => Ok(v),
172    }
173}
174
175/// YAML-level description of a rule before it is instantiated into a `Box<dyn Rule>`
176/// by a [`RuleBuilder`](crate::registry::RuleBuilder).
177#[derive(Debug, Clone, Deserialize)]
178pub struct RuleSpec {
179    pub id: String,
180    pub kind: String,
181    pub level: Level,
182    #[serde(default)]
183    pub paths: Option<PathsSpec>,
184    #[serde(default)]
185    pub message: Option<String>,
186    #[serde(default)]
187    pub policy_url: Option<String>,
188    #[serde(default)]
189    pub when: Option<String>,
190    /// Optional mechanical-fix strategy. Rules whose builders understand
191    /// the chosen op attach a [`Fixer`](crate::Fixer) to the built rule;
192    /// rules whose kind is incompatible with the op return a config error
193    /// at build time.
194    #[serde(default)]
195    pub fix: Option<FixSpec>,
196    /// Restrict the rule to files / directories tracked in git's index.
197    /// When `true`, the rule's `paths`-matched entries are intersected
198    /// with the set of git-tracked files; entries that exist in the
199    /// walked tree but aren't in `git ls-files` output are skipped.
200    /// Only meaningful for rule kinds that opt in (currently the
201    /// existence family — `file_exists`, `file_absent`, `dir_exists`,
202    /// `dir_absent`); rule kinds that don't support it surface a clean
203    /// config error when this is `true` so silent mis-configuration
204    /// doesn't slip through.
205    ///
206    /// Default `false`. Has no effect outside a git repo.
207    #[serde(default)]
208    pub git_tracked_only: bool,
209    /// Per-file ancestor-manifest gate. When set, the rule
210    /// only fires on files that have at least one ancestor
211    /// directory (including the file's own directory)
212    /// containing a file matching the configured
213    /// `has_ancestor` name(s). Composes AND with `paths:`
214    /// and `git_tracked_only:`.
215    ///
216    /// Only meaningful for per-file rules; cross-file rule
217    /// builders MUST reject this field at build time
218    /// (see the design doc for the cross-file alternative
219    /// via `for_each_dir + when_iter:`).
220    ///
221    /// Default `None` (no scope filter; existing rules
222    /// preserve their pre-v0.9.6 behaviour).
223    #[serde(default)]
224    pub scope_filter: Option<crate::ScopeFilterSpec>,
225    /// The entire YAML mapping, retained so each rule builder can deserialize
226    /// its kind-specific fields without every option being represented here.
227    #[serde(flatten)]
228    pub extra: serde_yaml_ng::Mapping,
229}
230
231/// The `fix:` block on a rule. Exactly one op key must be present —
232/// alint errors at load time when the op and rule kind are incompatible.
233#[derive(Debug, Clone, Deserialize)]
234#[serde(untagged)]
235pub enum FixSpec {
236    FileCreate {
237        file_create: FileCreateFixSpec,
238    },
239    FileRemove {
240        file_remove: FileRemoveFixSpec,
241    },
242    FilePrepend {
243        file_prepend: FilePrependFixSpec,
244    },
245    FileAppend {
246        file_append: FileAppendFixSpec,
247    },
248    FileRename {
249        file_rename: FileRenameFixSpec,
250    },
251    FileTrimTrailingWhitespace {
252        file_trim_trailing_whitespace: FileTrimTrailingWhitespaceFixSpec,
253    },
254    FileAppendFinalNewline {
255        file_append_final_newline: FileAppendFinalNewlineFixSpec,
256    },
257    FileNormalizeLineEndings {
258        file_normalize_line_endings: FileNormalizeLineEndingsFixSpec,
259    },
260    FileStripBidi {
261        file_strip_bidi: FileStripBidiFixSpec,
262    },
263    FileStripZeroWidth {
264        file_strip_zero_width: FileStripZeroWidthFixSpec,
265    },
266    FileStripBom {
267        file_strip_bom: FileStripBomFixSpec,
268    },
269    FileCollapseBlankLines {
270        file_collapse_blank_lines: FileCollapseBlankLinesFixSpec,
271    },
272}
273
274impl FixSpec {
275    /// The op name as it appears in YAML — used in config-error messages.
276    pub fn op_name(&self) -> &'static str {
277        match self {
278            Self::FileCreate { .. } => "file_create",
279            Self::FileRemove { .. } => "file_remove",
280            Self::FilePrepend { .. } => "file_prepend",
281            Self::FileAppend { .. } => "file_append",
282            Self::FileRename { .. } => "file_rename",
283            Self::FileTrimTrailingWhitespace { .. } => "file_trim_trailing_whitespace",
284            Self::FileAppendFinalNewline { .. } => "file_append_final_newline",
285            Self::FileNormalizeLineEndings { .. } => "file_normalize_line_endings",
286            Self::FileStripBidi { .. } => "file_strip_bidi",
287            Self::FileStripZeroWidth { .. } => "file_strip_zero_width",
288            Self::FileStripBom { .. } => "file_strip_bom",
289            Self::FileCollapseBlankLines { .. } => "file_collapse_blank_lines",
290        }
291    }
292}
293
294#[derive(Debug, Clone, Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct FileCreateFixSpec {
297    /// Inline content to write. Mutually exclusive with
298    /// `content_from`; exactly one of the two must be set. For
299    /// an empty file, pass `content: ""` explicitly.
300    #[serde(default)]
301    pub content: Option<String>,
302    /// Path to a file (relative to the lint root) whose bytes
303    /// will be the content. Mutually exclusive with `content`.
304    /// Read at fix-apply time; missing source produces a
305    /// `Skipped` outcome rather than a panic. Useful for
306    /// LICENSE / NOTICE / CONTRIBUTING boilerplate that's too
307    /// long to inline in YAML.
308    #[serde(default)]
309    pub content_from: Option<PathBuf>,
310    /// Path to create, relative to the repo root. When omitted, the
311    /// rule builder substitutes the first literal entry from the rule's
312    /// `paths:` list.
313    #[serde(default)]
314    pub path: Option<PathBuf>,
315    /// Whether to create intermediate directories. Defaults to true.
316    #[serde(default = "default_create_parents")]
317    pub create_parents: bool,
318}
319
320fn default_create_parents() -> bool {
321    true
322}
323
324#[derive(Debug, Clone, Deserialize, Default)]
325#[serde(deny_unknown_fields)]
326pub struct FileRemoveFixSpec {}
327
328#[derive(Debug, Clone, Deserialize)]
329#[serde(deny_unknown_fields)]
330pub struct FilePrependFixSpec {
331    /// Inline bytes to insert at the beginning of each
332    /// violating file. Mutually exclusive with `content_from`.
333    /// A trailing newline is the caller's responsibility.
334    #[serde(default)]
335    pub content: Option<String>,
336    /// Path to a file (relative to the lint root) whose bytes
337    /// will be prepended. Mutually exclusive with `content`.
338    #[serde(default)]
339    pub content_from: Option<PathBuf>,
340}
341
342#[derive(Debug, Clone, Deserialize)]
343#[serde(deny_unknown_fields)]
344pub struct FileAppendFixSpec {
345    /// Inline bytes to append to each violating file. Mutually
346    /// exclusive with `content_from`. A leading newline is the
347    /// caller's responsibility.
348    #[serde(default)]
349    pub content: Option<String>,
350    /// Path to a file (relative to the lint root) whose bytes
351    /// will be appended. Mutually exclusive with `content`.
352    #[serde(default)]
353    pub content_from: Option<PathBuf>,
354}
355
356/// Resolution of an `(content, content_from)` pair to a single
357/// content source. Used by the three fixers that take either.
358/// Errors when neither or both are set.
359pub fn resolve_content_source(
360    rule_id: &str,
361    op_name: &str,
362    inline: &Option<String>,
363    from: &Option<PathBuf>,
364) -> crate::error::Result<ContentSourceSpec> {
365    match (inline, from) {
366        (Some(_), Some(_)) => Err(crate::error::Error::rule_config(
367            rule_id,
368            format!("fix.{op_name}: `content` and `content_from` are mutually exclusive"),
369        )),
370        (None, None) => Err(crate::error::Error::rule_config(
371            rule_id,
372            format!("fix.{op_name}: one of `content` or `content_from` is required"),
373        )),
374        (Some(s), None) => Ok(ContentSourceSpec::Inline(s.clone())),
375        (None, Some(p)) => Ok(ContentSourceSpec::File(p.clone())),
376    }
377}
378
379/// Pre-validated content source — exactly one of inline or
380/// from-file. Resolved at config-parse time so fixers don't
381/// need to reproduce the XOR check at apply time.
382#[derive(Debug, Clone)]
383pub enum ContentSourceSpec {
384    /// Inline string body.
385    Inline(String),
386    /// Path relative to the lint root; bytes are read at fix-
387    /// apply time.
388    File(PathBuf),
389}
390
391impl From<String> for ContentSourceSpec {
392    fn from(s: String) -> Self {
393        Self::Inline(s)
394    }
395}
396
397impl From<&str> for ContentSourceSpec {
398    fn from(s: &str) -> Self {
399        Self::Inline(s.to_string())
400    }
401}
402
403/// Empty marker: `file_rename` takes no parameters. The target name
404/// is derived from the parent rule (e.g. `filename_case` converts the
405/// stem to its configured case; the extension is preserved).
406#[derive(Debug, Clone, Deserialize, Default)]
407#[serde(deny_unknown_fields)]
408pub struct FileRenameFixSpec {}
409
410/// Empty marker. Behavior: read file (subject to `fix_size_limit`),
411/// strip trailing space/tab on every line, write back.
412#[derive(Debug, Clone, Deserialize, Default)]
413#[serde(deny_unknown_fields)]
414pub struct FileTrimTrailingWhitespaceFixSpec {}
415
416/// Empty marker. Behavior: if the file has content and does not
417/// end with `\n`, append one.
418#[derive(Debug, Clone, Deserialize, Default)]
419#[serde(deny_unknown_fields)]
420pub struct FileAppendFinalNewlineFixSpec {}
421
422/// Empty marker. Behavior: rewrite the file with every line ending
423/// replaced by the parent rule's configured target (`lf` or `crlf`).
424#[derive(Debug, Clone, Deserialize, Default)]
425#[serde(deny_unknown_fields)]
426pub struct FileNormalizeLineEndingsFixSpec {}
427
428/// Empty marker. Behavior: remove every Unicode bidi control
429/// character (U+202A–202E, U+2066–2069) from the file's content.
430#[derive(Debug, Clone, Deserialize, Default)]
431#[serde(deny_unknown_fields)]
432pub struct FileStripBidiFixSpec {}
433
434/// Empty marker. Behavior: remove every zero-width character
435/// (U+200B / U+200C / U+200D / U+FEFF) from the file's content,
436/// *except* a leading BOM (U+FEFF at position 0) — that's the
437/// responsibility of the `no_bom` rule.
438#[derive(Debug, Clone, Deserialize, Default)]
439#[serde(deny_unknown_fields)]
440pub struct FileStripZeroWidthFixSpec {}
441
442/// Empty marker. Behavior: remove a leading UTF-8/UTF-16/UTF-32
443/// BOM byte sequence if present; otherwise a no-op.
444#[derive(Debug, Clone, Deserialize, Default)]
445#[serde(deny_unknown_fields)]
446pub struct FileStripBomFixSpec {}
447
448/// Empty marker. Behavior: collapse runs of blank lines longer than
449/// the parent rule's `max` down to exactly `max` blank lines.
450#[derive(Debug, Clone, Deserialize, Default)]
451#[serde(deny_unknown_fields)]
452pub struct FileCollapseBlankLinesFixSpec {}
453
454impl RuleSpec {
455    /// Deserialize the full spec (common + kind-specific fields) into a typed
456    /// options struct. Common fields are reconstructed into the mapping so
457    /// the target struct can `#[derive(Deserialize)]` against the whole shape
458    /// when convenient.
459    pub fn deserialize_options<T>(&self) -> crate::error::Result<T>
460    where
461        T: serde::de::DeserializeOwned,
462    {
463        Ok(serde_yaml_ng::from_value(serde_yaml_ng::Value::Mapping(
464            self.extra.clone(),
465        ))?)
466    }
467
468    /// Parse and validate this spec's optional `scope_filter:`
469    /// field into a built [`ScopeFilter`](crate::ScopeFilter).
470    /// Returns `Ok(None)` when the spec has no `scope_filter`
471    /// set (the common case).
472    ///
473    /// Per-file rule builders call this and store the result
474    /// on the built rule; the rule's
475    /// [`Rule::scope_filter`](crate::Rule::scope_filter) method
476    /// returns it back to the engine, which gates per-file
477    /// dispatch on `ScopeFilter::matches` (`engine.rs`
478    /// `run_per_file`). Cross-file rules MUST NOT call this —
479    /// they call
480    /// [`reject_scope_filter_on_cross_file`](crate::reject_scope_filter_on_cross_file)
481    /// instead so a misconfigured `scope_filter:` on a cross-
482    /// file rule surfaces as a clear build-time error rather
483    /// than a silently-ignored field.
484    pub fn parse_scope_filter(&self) -> crate::error::Result<Option<crate::ScopeFilter>> {
485        match &self.scope_filter {
486            Some(spec) => Ok(Some(crate::ScopeFilter::from_spec(&self.id, spec.clone())?)),
487            None => Ok(None),
488        }
489    }
490}
491
492/// Rule specification for nested rules (e.g. the `require:` block of
493/// `for_each_dir`). Unlike [`RuleSpec`], `id` and `level` are synthesized
494/// from the parent rule — users just supply the `kind` plus kind-specific
495/// options, optionally with a `message` / `policy_url` / `when`.
496#[derive(Debug, Clone, Deserialize)]
497pub struct NestedRuleSpec {
498    pub kind: String,
499    #[serde(default)]
500    pub paths: Option<PathsSpec>,
501    #[serde(default)]
502    pub message: Option<String>,
503    #[serde(default)]
504    pub policy_url: Option<String>,
505    #[serde(default)]
506    pub when: Option<String>,
507    /// Per-file scope filter — see [`RuleSpec::scope_filter`]
508    /// for semantics. Inherited unchanged when
509    /// [`NestedRuleSpec::instantiate`] synthesises a full
510    /// `RuleSpec` per-iteration.
511    #[serde(default)]
512    pub scope_filter: Option<crate::ScopeFilterSpec>,
513    #[serde(flatten)]
514    pub extra: serde_yaml_ng::Mapping,
515}
516
517impl NestedRuleSpec {
518    /// Synthesize a full [`RuleSpec`] for a single iteration, applying
519    /// path-template substitution (using the iterated entry's tokens) to
520    /// every string field. The resulting spec has `id =
521    /// "{parent_id}.require[{idx}]"` and inherits `level` from the parent.
522    pub fn instantiate(
523        &self,
524        parent_id: &str,
525        idx: usize,
526        level: Level,
527        tokens: &crate::template::PathTokens,
528    ) -> RuleSpec {
529        RuleSpec {
530            id: format!("{parent_id}.require[{idx}]"),
531            kind: self.kind.clone(),
532            level,
533            paths: self
534                .paths
535                .as_ref()
536                .map(|p| crate::template::render_paths_spec(p, tokens)),
537            message: self
538                .message
539                .as_deref()
540                .map(|m| crate::template::render_path(m, tokens)),
541            policy_url: self.policy_url.clone(),
542            when: self.when.clone(),
543            fix: None,
544            // Nested rules don't currently expose
545            // `git_tracked_only` from their parent's spec — the
546            // option is meaningful on top-level rules only for
547            // now. If/when `for_each_dir`'s nested rules need it,
548            // plumb it through here.
549            git_tracked_only: false,
550            scope_filter: self.scope_filter.clone(),
551            extra: crate::template::render_mapping(self.extra.clone(), tokens),
552        }
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559    use crate::template::PathTokens;
560    use std::path::Path;
561
562    #[test]
563    fn config_default_respects_gitignore_and_caps_fix_size() {
564        // Round-trip the documented defaults through serde to
565        // catch silent default drift.
566        let cfg: Config = serde_yaml_ng::from_str("version: 1\n").expect("minimal config");
567        assert_eq!(cfg.version, 1);
568        assert!(cfg.respect_gitignore);
569        assert_eq!(cfg.fix_size_limit, Some(1 << 20));
570        assert!(!cfg.nested_configs);
571        assert!(cfg.extends.is_empty());
572        assert!(cfg.rules.is_empty());
573    }
574
575    #[test]
576    fn config_rejects_unknown_top_level_field() {
577        let err = serde_yaml_ng::from_str::<Config>("version: 1\nignored_typo: true\n");
578        assert!(err.is_err(), "deny_unknown_fields should reject typos");
579    }
580
581    #[test]
582    fn config_explicit_null_disables_fix_size_limit() {
583        let cfg: Config = serde_yaml_ng::from_str("version: 1\nfix_size_limit: null\n").unwrap();
584        assert_eq!(cfg.fix_size_limit, None);
585    }
586
587    #[test]
588    fn extends_entry_url_form_has_no_filters() {
589        let e = ExtendsEntry::Url("alint://bundled/oss-baseline@v1".into());
590        assert_eq!(e.url(), "alint://bundled/oss-baseline@v1");
591        assert!(e.only().is_none());
592        assert!(e.except().is_none());
593    }
594
595    #[test]
596    fn extends_entry_filtered_form_exposes_only_and_except() {
597        let e = ExtendsEntry::Filtered {
598            url: "alint://bundled/rust@v1".into(),
599            only: Some(vec!["rust-edition".into()]),
600            except: None,
601        };
602        assert_eq!(e.url(), "alint://bundled/rust@v1");
603        assert_eq!(e.only(), Some(&["rust-edition".to_string()][..]));
604        assert!(e.except().is_none());
605    }
606
607    #[test]
608    fn extends_entry_filtered_form_supports_except_only() {
609        let e = ExtendsEntry::Filtered {
610            url: "./team.yml".into(),
611            only: None,
612            except: Some(vec!["legacy-rule".into()]),
613        };
614        assert_eq!(e.except(), Some(&["legacy-rule".to_string()][..]));
615        assert!(e.only().is_none());
616    }
617
618    #[test]
619    fn paths_spec_accepts_three_shapes() {
620        let single: PathsSpec = serde_yaml_ng::from_str("\"src/**\"").unwrap();
621        assert!(matches!(single, PathsSpec::Single(s) if s == "src/**"));
622
623        let many: PathsSpec = serde_yaml_ng::from_str("[\"src/**\", \"!src/vendor/**\"]").unwrap();
624        assert!(matches!(many, PathsSpec::Many(v) if v.len() == 2));
625
626        let inc_exc: PathsSpec =
627            serde_yaml_ng::from_str("include: src/**\nexclude: src/vendor/**\n").unwrap();
628        match inc_exc {
629            PathsSpec::IncludeExclude { include, exclude } => {
630                assert_eq!(include, vec!["src/**"]);
631                assert_eq!(exclude, vec!["src/vendor/**"]);
632            }
633            _ => panic!("expected include/exclude shape"),
634        }
635    }
636
637    #[test]
638    fn paths_spec_include_accepts_string_or_vec() {
639        let from_string: PathsSpec =
640            serde_yaml_ng::from_str("include: a\nexclude:\n  - b\n  - c\n").unwrap();
641        let PathsSpec::IncludeExclude { include, exclude } = from_string else {
642            panic!("expected include/exclude shape");
643        };
644        assert_eq!(include, vec!["a"]);
645        assert_eq!(exclude, vec!["b", "c"]);
646    }
647
648    #[test]
649    fn rule_spec_deserialize_options_picks_up_kind_specific_fields() {
650        #[derive(Deserialize, Debug)]
651        struct PatternOnly {
652            pattern: String,
653        }
654        let spec: RuleSpec = serde_yaml_ng::from_str(
655            "id: r\nkind: file_content_matches\nlevel: error\npaths: src/**\npattern: TODO\n",
656        )
657        .unwrap();
658        let opts: PatternOnly = spec.deserialize_options().unwrap();
659        assert_eq!(opts.pattern, "TODO");
660    }
661
662    #[test]
663    fn fix_spec_op_name_covers_every_variant() {
664        // Round-trip every documented op name through YAML; any
665        // future fix variant added without a corresponding
666        // op_name arm will fall through serde and trip this test.
667        let cases = [
668            ("file_create:\n  content: x\n", "file_create"),
669            ("file_remove: {}", "file_remove"),
670            ("file_prepend:\n  content: x\n", "file_prepend"),
671            ("file_append:\n  content: x\n", "file_append"),
672            ("file_rename: {}", "file_rename"),
673            (
674                "file_trim_trailing_whitespace: {}",
675                "file_trim_trailing_whitespace",
676            ),
677            ("file_append_final_newline: {}", "file_append_final_newline"),
678            (
679                "file_normalize_line_endings: {}",
680                "file_normalize_line_endings",
681            ),
682            ("file_strip_bidi: {}", "file_strip_bidi"),
683            ("file_strip_zero_width: {}", "file_strip_zero_width"),
684            ("file_strip_bom: {}", "file_strip_bom"),
685            ("file_collapse_blank_lines: {}", "file_collapse_blank_lines"),
686        ];
687        for (yaml, expected) in cases {
688            let spec: FixSpec =
689                serde_yaml_ng::from_str(yaml).unwrap_or_else(|e| panic!("{yaml}: {e}"));
690            assert_eq!(spec.op_name(), expected);
691        }
692    }
693
694    #[test]
695    fn resolve_content_source_inline_only() {
696        let s = Some("hello".to_string());
697        let resolved = resolve_content_source("r", "file_create", &s, &None).unwrap();
698        assert!(matches!(resolved, ContentSourceSpec::Inline(b) if b == "hello"));
699    }
700
701    #[test]
702    fn resolve_content_source_file_only() {
703        let p = Some(Path::new("LICENSE").into());
704        let resolved = resolve_content_source("r", "file_create", &None, &p).unwrap();
705        assert!(matches!(resolved, ContentSourceSpec::File(p) if p == Path::new("LICENSE")));
706    }
707
708    #[test]
709    fn resolve_content_source_rejects_both_set() {
710        let err = resolve_content_source(
711            "r",
712            "file_prepend",
713            &Some("x".into()),
714            &Some(Path::new("y").into()),
715        )
716        .unwrap_err();
717        assert!(err.to_string().contains("mutually exclusive"));
718    }
719
720    #[test]
721    fn resolve_content_source_rejects_neither_set() {
722        let err = resolve_content_source("r", "file_append", &None, &None).unwrap_err();
723        assert!(err.to_string().contains("required"));
724    }
725
726    #[test]
727    fn content_source_spec_from_string_variants() {
728        let from_owned: ContentSourceSpec = String::from("hi").into();
729        assert!(matches!(from_owned, ContentSourceSpec::Inline(s) if s == "hi"));
730        let from_str: ContentSourceSpec = "hi".into();
731        assert!(matches!(from_str, ContentSourceSpec::Inline(s) if s == "hi"));
732    }
733
734    #[test]
735    fn nested_rule_spec_instantiate_synthesizes_id_and_inherits_level() {
736        let nested: NestedRuleSpec = serde_yaml_ng::from_str(
737            "kind: file_exists\npaths: \"{path}/README.md\"\nmessage: missing in {path}\n",
738        )
739        .unwrap();
740        let tokens = PathTokens::from_path(Path::new("packages/foo"));
741        let spec = nested.instantiate("every-pkg-has-readme", 0, Level::Error, &tokens);
742
743        assert_eq!(spec.id, "every-pkg-has-readme.require[0]");
744        assert_eq!(spec.kind, "file_exists");
745        assert_eq!(spec.level, Level::Error);
746        // Path template should have been rendered for both
747        // `paths:` and `message:` from the iterated tokens.
748        match spec.paths {
749            Some(PathsSpec::Single(p)) => assert_eq!(p, "packages/foo/README.md"),
750            other => panic!("unexpected paths shape: {other:?}"),
751        }
752        assert_eq!(spec.message.as_deref(), Some("missing in packages/foo"));
753        // Nested rules don't propagate git_tracked_only — the
754        // option is meaningful on top-level rules only.
755        assert!(!spec.git_tracked_only);
756    }
757}