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