alpm_lint_config/
lint_config.rs

1use std::{fs::File, io::Read, path::Path};
2
3use fluent_i18n::t;
4use serde::{Deserialize, Serialize};
5
6use crate::{Error, LintGroup, LintRuleConfiguration};
7
8/// Configuration options for linting.
9///
10/// The options allow to
11///
12/// - configure the general lint rule behavior,
13/// - explicitly enable or disable individual lint rules,
14/// - and enable non-default lint groups.
15#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
16pub struct LintConfiguration {
17    /// All options that can be used to configure various lint rules.
18    pub options: LintRuleConfiguration,
19    /// All non-default groups that are additionally enabled.
20    pub groups: Vec<LintGroup>,
21    /// A list of lint rules that are explicitly disabled.
22    pub disabled_rules: Vec<String>,
23    /// A list of lint rules that are explicitly enabled.
24    pub enabled_rules: Vec<String>,
25}
26
27impl LintConfiguration {
28    /// Loads a [`LintConfiguration`] from a TOML configuration file.
29    ///
30    /// Reads the file at the specified path and parses it as TOML to create a configuration
31    /// instance.
32    ///
33    /// # Examples
34    ///
35    /// ```
36    /// # use std::io::Write;
37    /// # use tempfile::tempdir;
38    /// # use testresult::TestResult;
39    /// use alpm_lint_config::LintConfiguration;
40    ///
41    /// # fn main() -> TestResult {
42    /// # let temp_dir = tempdir()?;
43    /// # let config_path = temp_dir.path().join("lint_config.toml");
44    /// # let mut config_file = std::fs::File::create(&config_path)?;
45    /// # let toml_content = toml::to_string(&LintConfiguration::default())?;
46    /// # write!(config_file, "{}", toml_content)?;
47    /// #
48    /// // Load configuration from a TOML file containing the default configuration.
49    /// let config = LintConfiguration::from_path(&config_path)?;
50    ///
51    /// // The configuration is now available for use
52    /// assert_eq!(config, LintConfiguration::default());
53    /// # Ok(())
54    /// # }
55    /// ```
56    ///
57    /// # Errors
58    ///
59    /// Returns an error if:
60    ///
61    /// - the file at `path` cannot be opened for reading,
62    /// - the file contents cannot be read,
63    /// - or the file contents cannot be parsed as valid TOML.
64    pub fn from_path(path: &Path) -> Result<Self, Error> {
65        let mut file = File::open(path).map_err(|source| Error::IoPath {
66            path: path.to_path_buf(),
67            context: t!("error-io-open-config"),
68            source,
69        })?;
70
71        let mut buf = String::new();
72        file.read_to_string(&mut buf)
73            .map_err(|source| Error::IoPath {
74                path: path.to_path_buf(),
75                context: t!("error-io-read-config"),
76                source,
77            })?;
78
79        Ok(toml::from_str(&buf)?)
80    }
81}