Skip to main content

sokf_core/config/
excludes_d.rs

1//! This module reads the drop-in folder `/.sokf/excludes.d/`, whose files, at
2//! any depth, each list further globs beside `repository.exclude` (CONF-3).
3//! A tool that keeps files in the repository, such as the copies of a pack,
4//! adds the paths that sokf skips in a file of its own there, and never edits
5//! `/.sokf/config.toml`.
6
7use std::fs;
8
9use serde::Deserialize;
10
11use crate::{Error, RepoPath, RepoRoot, Result};
12
13/// `EXCLUDES_DIR` is the drop-in folder of the added excludes, relative to
14/// the repository root.
15pub const EXCLUDES_DIR: &str = ".sokf/excludes.d";
16
17/// `ExcludesFile` is one file of `/.sokf/excludes.d/`: only a list of globs.
18#[derive(Debug, Clone, Default, Deserialize)]
19#[serde(deny_unknown_fields)]
20struct ExcludesFile {
21    #[serde(default)]
22    exclude: Vec<String>,
23}
24
25/// An `AddedExclude` is one glob that a file of `/.sokf/excludes.d/` lists,
26/// with the file.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct AddedExclude {
29    /// The file that lists the glob.
30    pub file: RepoPath,
31    /// The `/`-rooted glob.
32    pub glob: String,
33}
34
35/// `read_added` reads every `*.toml` file of `/.sokf/excludes.d/`, at any
36/// depth, in the byte order of their paths, and returns the globs that they
37/// list, in the order of each file. It refuses a file that doesn't parse,
38/// that has a key other than `exclude`, or that lists a glob that isn't
39/// `/`-rooted or doesn't parse, with an error that names the file. An absent
40/// folder adds no glob.
41// sokf-implements: CONF-3_AC-9
42// sokf-implements: CONF-3_AC-10
43pub(crate) fn read_added(root: &RepoRoot) -> Result<Vec<AddedExclude>> {
44    let mut found = Vec::new();
45    for file in excludes_files(root)? {
46        let text =
47            fs::read_to_string(file.to_fs(root)).map_err(|e| Error::io(file.to_fs(root), e))?;
48        let parsed: ExcludesFile = toml::from_str(&text)
49            .map_err(|e| Error::config(file.clone(), e.message().to_string()))?;
50        for glob in parsed.exclude {
51            // sokf-implements: CONF-3_AC-11
52            if let Some(m) = super::file::glob_fault("exclude", &glob) {
53                return Err(Error::config(file, m));
54            }
55            found.push(AddedExclude {
56                file: file.clone(),
57                glob,
58            });
59        }
60    }
61    Ok(found)
62}
63
64/// `excludes_files` returns the files of `/.sokf/excludes.d/` that list
65/// globs: each `*.toml` at any depth that is a file, through a symbolic link
66/// too, in the byte order of their paths. An absent folder holds none.
67fn excludes_files(root: &RepoRoot) -> Result<Vec<RepoPath>> {
68    super::d_folder::d_files(root, EXCLUDES_DIR, "toml", false)
69}
70
71/// `excludes_files_lenient` returns the files of `/.sokf/excludes.d/` as
72/// `excludes_files` does, and skips each directory that can't be read, so
73/// that the files of every other directory still count.
74pub fn excludes_files_lenient(root: &RepoRoot) -> Vec<RepoPath> {
75    super::d_folder::d_files(root, EXCLUDES_DIR, "toml", true).unwrap_or_default()
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    // sokf-tests: CONF-3_AC-9
83    // sokf-tests: CONF-3_AC-10
84    // sokf-tests: CONF-3_AC-11
85    #[test]
86    fn reads_each_file_in_path_order_and_refuses_a_bad_one() {
87        let dir = crate::test_support::fresh_dir("excludes-d");
88        let root = RepoRoot::new(dir.clone());
89        assert_eq!(read_added(&root).unwrap(), vec![]);
90        crate::test_support::write(
91            &dir,
92            ".sokf/excludes.d/b.toml",
93            "exclude = [\"/b1\", \"/b2/**\"]\n",
94        );
95        crate::test_support::write(&dir, ".sokf/excludes.d/a.toml", "exclude = [\"/a/**\"]\n");
96        crate::test_support::write(
97            &dir,
98            ".sokf/excludes.d/a/deep.toml",
99            "exclude = [\"/deep/*.rs\"]\n",
100        );
101        crate::test_support::write(&dir, ".sokf/excludes.d/empty.toml", "");
102        crate::test_support::write(&dir, ".sokf/excludes.d/notes.txt", "exclude = 1\n");
103        let globs: Vec<(String, String)> = read_added(&root)
104            .unwrap()
105            .into_iter()
106            .map(|e| (e.file.to_string(), e.glob))
107            .collect();
108        assert_eq!(
109            globs,
110            vec![
111                ("/.sokf/excludes.d/a.toml".into(), "/a/**".into()),
112                ("/.sokf/excludes.d/a/deep.toml".into(), "/deep/*.rs".into()),
113                ("/.sokf/excludes.d/b.toml".into(), "/b1".into()),
114                ("/.sokf/excludes.d/b.toml".into(), "/b2/**".into()),
115            ]
116        );
117        for (bad, says) in [
118            ("exclude = [", "unclosed array"),
119            ("exclude = []\nroots = []\n", "unknown field `roots`"),
120            ("exclude = \"/x\"\n", "invalid type: string"),
121            (
122                "exclude = [\"x/**\"]\n",
123                "exclude glob `x/**` is not /-rooted",
124            ),
125            ("exclude = [\"/[\"]\n", "exclude glob `/[` does not parse"),
126        ] {
127            crate::test_support::write(&dir, ".sokf/excludes.d/c.toml", bad);
128            let e = read_added(&root).unwrap_err();
129            assert!(matches!(e, Error::Config { .. }), "{bad:?} -> {e}");
130            let e = e.to_string();
131            assert!(
132                e.starts_with("/.sokf/excludes.d/c.toml: "),
133                "{bad:?} -> {e}"
134            );
135            assert!(e.contains(says), "{bad:?} -> {e}");
136        }
137        fs::remove_dir_all(&dir).unwrap();
138    }
139}