Skip to main content

alint_rules/
filename_case.rs

1//! `filename_case` — every file in scope must have a basename whose stem
2//! matches a case convention.
3//!
4//! The check runs on the *stem* (filename with the final extension removed),
5//! matching ls-lint precedent. For files with compound extensions like
6//! `foo.spec.ts`, the stem is `foo.spec`, which will fail most case checks —
7//! use `filename_regex` for finer control in those situations.
8
9use alint_core::{Context, Error, FixSpec, Fixer, Level, Result, Rule, RuleSpec, Scope, Violation};
10use serde::Deserialize;
11
12use crate::case::CaseConvention;
13use crate::fixers::FileRenameFixer;
14
15#[derive(Debug, Deserialize)]
16struct Options {
17    case: CaseConvention,
18}
19
20#[derive(Debug)]
21pub struct FilenameCaseRule {
22    id: String,
23    level: Level,
24    policy_url: Option<String>,
25    message: Option<String>,
26    scope: Scope,
27    case: CaseConvention,
28    fixer: Option<FileRenameFixer>,
29}
30
31impl Rule for FilenameCaseRule {
32    fn id(&self) -> &str {
33        &self.id
34    }
35    fn level(&self) -> Level {
36        self.level
37    }
38    fn policy_url(&self) -> Option<&str> {
39        self.policy_url.as_deref()
40    }
41
42    fn fixer(&self) -> Option<&dyn Fixer> {
43        self.fixer.as_ref().map(|f| f as &dyn Fixer)
44    }
45
46    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
47        let mut violations = Vec::new();
48        for entry in ctx.index.files() {
49            if !self.scope.matches(&entry.path) {
50                continue;
51            }
52            let Some(stem) = entry.path.file_stem().and_then(|s| s.to_str()) else {
53                continue;
54            };
55            if !self.case.check(stem) {
56                let msg = self.message.clone().unwrap_or_else(|| {
57                    format!(
58                        "filename stem {:?} is not {}",
59                        stem,
60                        self.case.display_name()
61                    )
62                });
63                violations.push(Violation::new(msg).with_path(&entry.path));
64            }
65        }
66        Ok(violations)
67    }
68}
69
70pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
71    let Some(paths) = &spec.paths else {
72        return Err(Error::rule_config(
73            &spec.id,
74            "filename_case requires a `paths` field",
75        ));
76    };
77    let opts: Options = spec
78        .deserialize_options()
79        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
80    let fixer = match &spec.fix {
81        Some(FixSpec::FileRename { .. }) => Some(FileRenameFixer::new(opts.case)),
82        Some(other) => {
83            return Err(Error::rule_config(
84                &spec.id,
85                format!(
86                    "fix.{} is not compatible with filename_case",
87                    other.op_name()
88                ),
89            ));
90        }
91        None => None,
92    };
93    Ok(Box::new(FilenameCaseRule {
94        id: spec.id.clone(),
95        level: spec.level,
96        policy_url: spec.policy_url.clone(),
97        message: spec.message.clone(),
98        scope: Scope::from_paths_spec(paths)?,
99        case: opts.case,
100        fixer,
101    }))
102}