nu_lint/
config.rs

1use std::{
2    collections::{HashMap, HashSet},
3    fs,
4    path::{Path, PathBuf},
5};
6
7use serde::{Deserialize, Serialize};
8
9use crate::{
10    LintError,
11    rule::Rule,
12    rules::{self, groups::ALL_GROUPS},
13};
14
15#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq, PartialOrd, Ord)]
16#[serde(rename_all = "lowercase")]
17pub enum LintLevel {
18    Hint,
19    #[default]
20    Warning,
21    Error,
22}
23
24#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
25#[serde(rename_all = "lowercase")]
26pub enum PipelinePlacement {
27    #[default]
28    Start,
29    End,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
33#[serde(default)]
34pub struct Config {
35    pub groups: HashMap<String, LintLevel>,
36    pub rules: HashMap<String, LintLevel>,
37    pub ignored: HashSet<String>,
38    pub additional: HashSet<String>,
39    pub sequential: bool,
40    pub pipeline_placement: PipelinePlacement,
41    pub max_pipeline_length: usize,
42    pub skip_external_parse_errors: bool,
43}
44
45impl Default for Config {
46    fn default() -> Self {
47        Self {
48            groups: HashMap::new(),
49            rules: HashMap::new(),
50            ignored: HashSet::from([rules::always_annotate_ext_hat::RULE.id().into()]),
51            additional: HashSet::new(),
52            sequential: false,
53            pipeline_placement: PipelinePlacement::default(),
54            max_pipeline_length: 80,
55            skip_external_parse_errors: true,
56        }
57    }
58}
59
60impl Config {
61    /// Load configuration from a TOML string.
62    ///
63    /// # Errors
64    ///
65    /// Errors when TOML string is not a valid TOML string.
66    pub(crate) fn load_from_str(toml_str: &str) -> Result<Self, LintError> {
67        toml::from_str(toml_str).map_err(|source| LintError::Config { source })
68    }
69    /// Load configuration from a TOML file.
70    ///
71    /// # Errors
72    ///
73    /// Returns an error if the file cannot be read or if the TOML content is
74    /// invalid.
75    pub(crate) fn load_from_file(path: &Path) -> Result<Self, LintError> {
76        let content = fs::read_to_string(path).map_err(|source| LintError::Io {
77            path: path.to_path_buf(),
78            source,
79        })?;
80        Self::load_from_str(&content)
81    }
82
83    /// Get the effective lint level for a specific rule
84    #[must_use]
85    pub fn get_lint_level(&self, rule: &dyn Rule) -> Option<LintLevel> {
86        let rule_id = rule.id();
87
88        if self.ignored.contains(rule_id) {
89            return None;
90        }
91
92        if let Some(level) = self.rules.get(rule_id) {
93            log::debug!(
94                "Rule '{rule_id}' has individual level '{level:?}' in config, overriding set \
95                 levels"
96            );
97            return Some(*level);
98        }
99
100        for (set_name, level) in &self.groups {
101            let Some(lint_set) = ALL_GROUPS.iter().find(|set| set.name == set_name.as_str()) else {
102                continue;
103            };
104
105            if !lint_set.rules.iter().any(|r| r.id() == rule_id) {
106                continue;
107            }
108
109            log::debug!("Rule '{rule_id}' found in set '{set_name}' with level {level:?}");
110            return Some(*level);
111        }
112
113        Some(rule.level())
114    }
115}
116
117/// Search for .nu-lint.toml starting from the given directory and walking up to
118/// parent directories
119#[must_use]
120pub fn find_config_file_from(start_dir: &Path) -> Option<PathBuf> {
121    let mut current_dir = start_dir.to_path_buf();
122
123    loop {
124        let config_path = current_dir.join(".nu-lint.toml");
125        if config_path.exists() && config_path.is_file() {
126            return Some(config_path);
127        }
128
129        if !current_dir.pop() {
130            break;
131        }
132    }
133
134    None
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use crate::rules::USED_RULES;
141
142    #[test]
143    fn test_load_config_simple_str() {
144        let toml_str = r#"
145        [rules]
146        snake_case_variables = "error"
147    "#;
148
149        let config = Config::load_from_str(toml_str).unwrap();
150        assert_eq!(
151            config.rules.get("snake_case_variables"),
152            Some(&LintLevel::Error)
153        );
154    }
155
156    #[test]
157    fn test_load_config_simple_str_set() {
158        let toml_str = r#"
159        ignored = [ "snake_case_variables" ]
160        [groups]
161        naming = "error"
162    "#;
163
164        let config = Config::load_from_str(toml_str).unwrap();
165        let found_set_level = config.groups.iter().find(|(k, _)| **k == "naming");
166        assert!(matches!(found_set_level, Some((_, LintLevel::Error))));
167        let ignored_rule = USED_RULES
168            .iter()
169            .find(|r| r.id() == "snake_case_variables")
170            .unwrap();
171        assert_eq!(config.get_lint_level(*ignored_rule), None);
172    }
173}