ec4rs/
section.rs

1use crate::glob::Glob;
2use crate::{rawvalue::RawValue, Properties};
3
4use std::path::Path;
5
6// Glob internals aren't stable enough to safely implement PartialEq here.
7
8/// One section of an EditorConfig file.
9#[derive(Clone)]
10pub struct Section {
11    pattern: Glob,
12    props: crate::Properties,
13}
14
15impl Section {
16    /// Constrcts a new [`Section`] that applies to files matching the specified pattern.
17    pub fn new(pattern: &str) -> Section {
18        Section {
19            pattern: Glob::new(pattern),
20            props: crate::Properties::new(),
21        }
22    }
23    /// Returns a shared reference to the internal [`Properties`] map.
24    pub fn props(&self) -> &Properties {
25        &self.props
26    }
27    /// Returns a mutable reference to the internal [`Properties`] map.
28    pub fn props_mut(&mut self) -> &mut Properties {
29        &mut self.props
30    }
31    /// Extracts the [`Properties`] map from `self`.
32    pub fn into_props(self) -> Properties {
33        self.props
34    }
35    /// Adds a property with the specified key, lowercasing the key.
36    pub fn insert(&mut self, key: impl AsRef<str>, val: impl Into<RawValue>) {
37        self.props
38            .insert_raw_for_key(key.as_ref().to_lowercase(), val);
39    }
40    /// Returns true if and only if this section applies to a file at the specified path.
41    pub fn applies_to(&self, path: impl AsRef<Path>) -> bool {
42        self.pattern.matches(path.as_ref())
43    }
44}
45
46impl crate::PropertiesSource for &Section {
47    /// Adds this section's properties to a [`Properties`].
48    ///
49    /// This implementation is infallible.
50    fn apply_to(
51        self,
52        props: &mut Properties,
53        path: impl AsRef<std::path::Path>,
54    ) -> Result<(), crate::Error> {
55        let path_ref = path.as_ref();
56        if self.applies_to(path_ref) {
57            let _ = self.props.apply_to(props, path_ref);
58        }
59        Ok(())
60    }
61}