alpm_lint_config/
lint_config.rs

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