Skip to main content

fallow_engine/project_config/
loader.rs

1//! The one loader of the fallow config file. Each engine entry point and the
2//! programmatic API read the config file through [`load_config_file`], so the
3//! trust policy and the error detail are the same on each surface.
4
5use std::path::{Path, PathBuf};
6
7use fallow_config::{ConfigLoadOptions, FallowConfig};
8
9use crate::EngineError;
10
11/// The options of [`load_config_file`].
12#[derive(Debug, Clone, Copy, Default)]
13pub struct ConfigFileOptions {
14    /// Permit `https://` entries in the `extends` chain of the config.
15    pub allow_remote_extends: bool,
16}
17
18/// The config file of a project, before resolution.
19#[derive(Debug)]
20pub struct ConfigFile {
21    /// The parsed config. This is the default config when no file exists.
22    pub config: FallowConfig,
23    /// The path of the loaded file. `None` when no file exists.
24    pub path: Option<PathBuf>,
25    /// The bytes of the loaded file and of its local `extends` chain.
26    pub chain: ConfigChainSnapshot,
27}
28
29/// The bytes of a config file and of each local file of its `extends`
30/// chain. The loader reads them before and after it parses the file, so a
31/// long-lived caller can see that the parsed config is out of date.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct ConfigChainSnapshot {
34    /// Each file with its bytes, or `None` when the file did not read.
35    files: Vec<(PathBuf, Option<Vec<u8>>)>,
36    /// A file of the chain changed while the loader parsed it.
37    changed_during_load: bool,
38}
39
40impl ConfigChainSnapshot {
41    /// Read the file at `path` and each local file that it extends. No path
42    /// gives an empty snapshot.
43    fn read(path: Option<&Path>) -> Self {
44        let files = path
45            .into_iter()
46            .flat_map(FallowConfig::local_source_files)
47            .map(|file| {
48                let bytes = std::fs::read(&file).ok();
49                (file, bytes)
50            })
51            .collect();
52        Self {
53            files,
54            changed_during_load: false,
55        }
56    }
57
58    /// The snapshot `after` the parse, marked as changed when it differs
59    /// from the snapshot `before` the parse.
60    fn around_load(before: &Self, after: Self) -> Self {
61        Self {
62            changed_during_load: *before != after,
63            ..after
64        }
65    }
66
67    /// Whether a file of the chain changed while the loader parsed it, or
68    /// has other bytes now.
69    #[must_use]
70    pub fn changed(&self) -> bool {
71        self.changed_during_load
72            || self
73                .files
74                .iter()
75                .any(|(path, bytes)| std::fs::read(path).ok() != *bytes)
76    }
77}
78
79/// The error of [`load_config_file`].
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum ConfigLoadError {
83    /// The config file cannot be read or parsed, or its `extends` chain is
84    /// refused.
85    Parse {
86        /// The explicit config path. `None` for a discovered file, whose path
87        /// is in `message`.
88        path: Option<PathBuf>,
89        /// The top error.
90        message: String,
91        /// The top error and its causes. For a discovered file, this is the
92        /// same text as `message`.
93        chain: String,
94    },
95}
96
97impl ConfigLoadError {
98    /// The top error, without its causes.
99    #[must_use]
100    pub fn message(&self) -> &str {
101        match self {
102            Self::Parse { message, .. } => message,
103        }
104    }
105
106    /// The full error text: the error and its causes.
107    #[must_use]
108    pub fn chain(&self) -> &str {
109        match self {
110            Self::Parse { chain, .. } => chain,
111        }
112    }
113}
114
115impl From<ConfigLoadError> for EngineError {
116    fn from(err: ConfigLoadError) -> Self {
117        Self::new(format!("invalid config: {}", err.chain()))
118    }
119}
120
121/// The config file that discovery finds from `root` up to the repository
122/// root, without a load. A caller that only checks whether a project has a
123/// config file, or that writes to the config file, calls this function.
124#[must_use]
125pub fn find_config_file(root: &Path) -> Option<PathBuf> {
126    FallowConfig::find_config_path(root)
127}
128
129/// Load the config file of a project: the file at `config_path`, else the
130/// first config file that discovery finds from `root` up to the repository
131/// root. A project without a config file gets the default config.
132///
133/// # Errors
134///
135/// Returns [`ConfigLoadError::Parse`] when the file cannot be read or parsed,
136/// or when `options` refuses an entry of its `extends` chain.
137pub fn load_config_file(
138    root: &Path,
139    config_path: Option<&Path>,
140    options: ConfigFileOptions,
141) -> Result<ConfigFile, ConfigLoadError> {
142    #[cfg(any(test, feature = "testing"))]
143    load_count::record(root);
144    let load_options = ConfigLoadOptions {
145        allow_remote_extends: options.allow_remote_extends,
146    };
147    if let Some(path) = config_path {
148        let before = ConfigChainSnapshot::read(Some(path));
149        return FallowConfig::load_with_options(path, load_options)
150            .map(|config| ConfigFile {
151                config,
152                path: Some(path.to_path_buf()),
153                chain: ConfigChainSnapshot::around_load(
154                    &before,
155                    ConfigChainSnapshot::read(Some(path)),
156                ),
157            })
158            .map_err(|err| explicit_load_error(path, &err));
159    }
160    let before = ConfigChainSnapshot::read(find_config_file(root).as_deref());
161    match FallowConfig::find_and_load_with_options(root, load_options) {
162        Ok(Some((config, path))) => Ok(ConfigFile {
163            config,
164            chain: ConfigChainSnapshot::around_load(
165                &before,
166                ConfigChainSnapshot::read(Some(&path)),
167            ),
168            path: Some(path),
169        }),
170        Ok(None) => Ok(ConfigFile {
171            config: FallowConfig::default(),
172            path: None,
173            chain: ConfigChainSnapshot::around_load(&before, ConfigChainSnapshot::default()),
174        }),
175        Err(message) => Err(ConfigLoadError::Parse {
176            path: None,
177            chain: message.clone(),
178            message,
179        }),
180    }
181}
182
183/// The error of an explicit config path. The alternate format of a config
184/// error report adds each cause to the top error.
185fn explicit_load_error(path: &Path, err: &impl std::fmt::Display) -> ConfigLoadError {
186    ConfigLoadError::Parse {
187        path: Some(path.to_path_buf()),
188        message: err.to_string(),
189        chain: format!("{err:#}"),
190    }
191}
192
193/// A count of the calls of [`load_config_file`] for each project root, for
194/// tests that check how often one call reads the config file.
195#[cfg(any(test, feature = "testing"))]
196pub mod load_count {
197    use std::path::{Path, PathBuf};
198    use std::sync::{Mutex, PoisonError};
199
200    use rustc_hash::FxHashMap;
201
202    static LOADS: Mutex<Option<FxHashMap<PathBuf, usize>>> = Mutex::new(None);
203
204    pub(super) fn record(root: &Path) {
205        let mut loads = LOADS.lock().unwrap_or_else(PoisonError::into_inner);
206        *loads
207            .get_or_insert_with(FxHashMap::default)
208            .entry(root.to_path_buf())
209            .or_default() += 1;
210    }
211
212    /// The number of config loads for `root` since the process started. Each
213    /// test uses its own temporary root, so tests that run in parallel do not
214    /// change the count of another test.
215    #[must_use]
216    pub fn config_loads(root: &Path) -> usize {
217        LOADS
218            .lock()
219            .unwrap_or_else(PoisonError::into_inner)
220            .as_ref()
221            .and_then(|loads| loads.get(root).copied())
222            .unwrap_or(0)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn each_load_counts_for_its_root() {
232        let dir = tempfile::tempdir().expect("tempdir");
233        std::fs::create_dir(dir.path().join(".git")).expect("git marker");
234        assert_eq!(load_count::config_loads(dir.path()), 0);
235        for _ in 0..2 {
236            load_config_file(dir.path(), None, ConfigFileOptions::default()).expect("loads");
237        }
238        assert_eq!(load_count::config_loads(dir.path()), 2);
239    }
240
241    /// No server listens on port 1, so the fetch fails at once and offline.
242    const UNREACHABLE_REMOTE_EXTENDS: &str = r#"{ "extends": "https://127.0.0.1:1/fallow.json" }"#;
243
244    fn project(config: &str) -> (tempfile::TempDir, PathBuf) {
245        let dir = tempfile::tempdir().expect("tempdir");
246        let root = dir.path().to_path_buf();
247        std::fs::create_dir(root.join(".git")).expect("git marker");
248        std::fs::write(root.join(".fallowrc.json"), config).expect("config");
249        (dir, root)
250    }
251
252    #[test]
253    fn explicit_error_keeps_the_path_and_the_cause_chain() {
254        let (_dir, root) = project(r#"{ "production": "yes" }"#);
255        let path = root.join(".fallowrc.json");
256        let cause = FallowConfig::load(&path).expect_err("wrong type");
257        let err = load_config_file(&root, Some(&path), ConfigFileOptions::default())
258            .expect_err("wrong type");
259        assert_eq!(
260            err,
261            ConfigLoadError::Parse {
262                path: Some(path),
263                message: cause.to_string(),
264                chain: format!("{cause:#}"),
265            }
266        );
267    }
268
269    /// An error with one cause. Its alternate format adds the cause, as the
270    /// default handler of a `miette::Report` does.
271    struct WrappedError;
272
273    impl std::fmt::Display for WrappedError {
274        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275            f.write_str("Failed to read config file")?;
276            if f.alternate() {
277                f.write_str(": no such file")?;
278            }
279            Ok(())
280        }
281    }
282
283    #[test]
284    fn explicit_error_chain_adds_each_cause() {
285        let err = explicit_load_error(Path::new("fallow.json"), &WrappedError);
286        assert_eq!(
287            err,
288            ConfigLoadError::Parse {
289                path: Some(PathBuf::from("fallow.json")),
290                message: "Failed to read config file".to_owned(),
291                chain: "Failed to read config file: no such file".to_owned(),
292            }
293        );
294    }
295
296    #[test]
297    fn remote_extends_is_fetched_with_the_opt_in() {
298        let (_dir, root) = project(UNREACHABLE_REMOTE_EXTENDS);
299        let options = ConfigFileOptions {
300            allow_remote_extends: true,
301        };
302        for config_path in [None, Some(root.join(".fallowrc.json"))] {
303            let err =
304                load_config_file(&root, config_path.as_deref(), options).expect_err("fetch fails");
305            assert!(
306                err.chain().contains("Failed to fetch remote config"),
307                "{err:?}"
308            );
309        }
310    }
311
312    #[test]
313    fn discovered_error_has_no_path_and_one_text() {
314        let (_dir, root) = project(r#"{ "rules": "#);
315        let cause = FallowConfig::find_and_load(&root).expect_err("syntax error");
316        let err =
317            load_config_file(&root, None, ConfigFileOptions::default()).expect_err("syntax error");
318        assert_eq!(
319            err,
320            ConfigLoadError::Parse {
321                path: None,
322                message: cause.clone(),
323                chain: cause,
324            }
325        );
326    }
327
328    #[test]
329    fn the_chain_snapshot_sees_an_edit_of_each_local_file() {
330        let (_dir, root) = project(r#"{ "extends": "./base.json" }"#);
331        let base = root.join("base.json");
332        std::fs::write(&base, r#"{ "entry": ["a.ts"] }"#).expect("base");
333        let config = root.join(".fallowrc.json");
334        for config_path in [None, Some(config.as_path())] {
335            let file =
336                load_config_file(&root, config_path, ConfigFileOptions::default()).expect("loads");
337            assert!(!file.chain.changed());
338            std::fs::write(&base, r#"{ "entry": ["b.ts"] }"#).expect("same-size edit");
339            assert!(file.chain.changed());
340            std::fs::write(&base, r#"{ "entry": ["a.ts"] }"#).expect("restore");
341        }
342    }
343
344    #[test]
345    fn a_chain_that_differs_around_the_parse_counts_as_changed() {
346        let (_dir, root) = project("{}");
347        let config = root.join(".fallowrc.json");
348        let before = ConfigChainSnapshot::read(Some(&config));
349        std::fs::write(&config, r#"{ "entry": [] }"#).expect("edit during the parse");
350        let after = ConfigChainSnapshot::read(Some(&config));
351        assert!(ConfigChainSnapshot::around_load(&before, after.clone()).changed());
352        assert!(!ConfigChainSnapshot::around_load(&after.clone(), after).changed());
353        assert!(
354            ConfigChainSnapshot::around_load(&before, ConfigChainSnapshot::default()).changed(),
355            "a discovered file that is gone at the parse counts as changed"
356        );
357    }
358
359    #[test]
360    fn remote_extends_is_refused_by_default() {
361        let (_dir, root) = project(r#"{ "extends": "https://example.com/fallow.json" }"#);
362        let err = load_config_file(&root, None, ConfigFileOptions::default()).expect_err("refused");
363        assert!(err.chain().contains("Remote config extends"), "{err:?}");
364    }
365
366    #[test]
367    fn a_project_without_a_file_gets_the_default_config() {
368        let dir = tempfile::tempdir().expect("tempdir");
369        std::fs::create_dir(dir.path().join(".git")).expect("git marker");
370        let file = load_config_file(dir.path(), None, ConfigFileOptions::default())
371            .expect("defaults load");
372        assert_eq!(file.path, None);
373        assert_eq!(
374            file.config.production,
375            fallow_config::ProductionConfig::default()
376        );
377    }
378}