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}
26
27/// The error of [`load_config_file`].
28#[derive(Debug, Clone, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum ConfigLoadError {
31    /// The config file cannot be read or parsed, or its `extends` chain is
32    /// refused.
33    Parse {
34        /// The explicit config path. `None` for a discovered file, whose path
35        /// is in `message`.
36        path: Option<PathBuf>,
37        /// The top error.
38        message: String,
39        /// The top error and its causes. For a discovered file, this is the
40        /// same text as `message`.
41        chain: String,
42    },
43}
44
45impl ConfigLoadError {
46    /// The top error, without its causes.
47    #[must_use]
48    pub fn message(&self) -> &str {
49        match self {
50            Self::Parse { message, .. } => message,
51        }
52    }
53
54    /// The full error text: the error and its causes.
55    #[must_use]
56    pub fn chain(&self) -> &str {
57        match self {
58            Self::Parse { chain, .. } => chain,
59        }
60    }
61}
62
63impl From<ConfigLoadError> for EngineError {
64    fn from(err: ConfigLoadError) -> Self {
65        Self::new(format!("invalid config: {}", err.chain()))
66    }
67}
68
69/// Load the config file of a project: the file at `config_path`, else the
70/// first config file that discovery finds from `root` up to the repository
71/// root. A project without a config file gets the default config.
72///
73/// # Errors
74///
75/// Returns [`ConfigLoadError::Parse`] when the file cannot be read or parsed,
76/// or when `options` refuses an entry of its `extends` chain.
77pub fn load_config_file(
78    root: &Path,
79    config_path: Option<&Path>,
80    options: ConfigFileOptions,
81) -> Result<ConfigFile, ConfigLoadError> {
82    let load_options = ConfigLoadOptions {
83        allow_remote_extends: options.allow_remote_extends,
84    };
85    if let Some(path) = config_path {
86        return FallowConfig::load_with_options(path, load_options)
87            .map(|config| ConfigFile {
88                config,
89                path: Some(path.to_path_buf()),
90            })
91            .map_err(|err| explicit_load_error(path, &err));
92    }
93    match FallowConfig::find_and_load_with_options(root, load_options) {
94        Ok(Some((config, path))) => Ok(ConfigFile {
95            config,
96            path: Some(path),
97        }),
98        Ok(None) => Ok(ConfigFile {
99            config: FallowConfig::default(),
100            path: None,
101        }),
102        Err(message) => Err(ConfigLoadError::Parse {
103            path: None,
104            chain: message.clone(),
105            message,
106        }),
107    }
108}
109
110/// The error of an explicit config path. The alternate format of a config
111/// error report adds each cause to the top error.
112fn explicit_load_error(path: &Path, err: &impl std::fmt::Display) -> ConfigLoadError {
113    ConfigLoadError::Parse {
114        path: Some(path.to_path_buf()),
115        message: err.to_string(),
116        chain: format!("{err:#}"),
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    /// No server listens on port 1, so the fetch fails at once and offline.
125    const UNREACHABLE_REMOTE_EXTENDS: &str = r#"{ "extends": "https://127.0.0.1:1/fallow.json" }"#;
126
127    fn project(config: &str) -> (tempfile::TempDir, PathBuf) {
128        let dir = tempfile::tempdir().expect("tempdir");
129        let root = dir.path().to_path_buf();
130        std::fs::create_dir(root.join(".git")).expect("git marker");
131        std::fs::write(root.join(".fallowrc.json"), config).expect("config");
132        (dir, root)
133    }
134
135    #[test]
136    fn explicit_error_keeps_the_path_and_the_cause_chain() {
137        let (_dir, root) = project(r#"{ "production": "yes" }"#);
138        let path = root.join(".fallowrc.json");
139        let cause = FallowConfig::load(&path).expect_err("wrong type");
140        let err = load_config_file(&root, Some(&path), ConfigFileOptions::default())
141            .expect_err("wrong type");
142        assert_eq!(
143            err,
144            ConfigLoadError::Parse {
145                path: Some(path),
146                message: cause.to_string(),
147                chain: format!("{cause:#}"),
148            }
149        );
150    }
151
152    /// An error with one cause. Its alternate format adds the cause, as the
153    /// default handler of a `miette::Report` does.
154    struct WrappedError;
155
156    impl std::fmt::Display for WrappedError {
157        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158            f.write_str("Failed to read config file")?;
159            if f.alternate() {
160                f.write_str(": no such file")?;
161            }
162            Ok(())
163        }
164    }
165
166    #[test]
167    fn explicit_error_chain_adds_each_cause() {
168        let err = explicit_load_error(Path::new("fallow.json"), &WrappedError);
169        assert_eq!(
170            err,
171            ConfigLoadError::Parse {
172                path: Some(PathBuf::from("fallow.json")),
173                message: "Failed to read config file".to_owned(),
174                chain: "Failed to read config file: no such file".to_owned(),
175            }
176        );
177    }
178
179    #[test]
180    fn remote_extends_is_fetched_with_the_opt_in() {
181        let (_dir, root) = project(UNREACHABLE_REMOTE_EXTENDS);
182        let options = ConfigFileOptions {
183            allow_remote_extends: true,
184        };
185        for config_path in [None, Some(root.join(".fallowrc.json"))] {
186            let err =
187                load_config_file(&root, config_path.as_deref(), options).expect_err("fetch fails");
188            assert!(
189                err.chain().contains("Failed to fetch remote config"),
190                "{err:?}"
191            );
192        }
193    }
194
195    #[test]
196    fn discovered_error_has_no_path_and_one_text() {
197        let (_dir, root) = project(r#"{ "rules": "#);
198        let cause = FallowConfig::find_and_load(&root).expect_err("syntax error");
199        let err =
200            load_config_file(&root, None, ConfigFileOptions::default()).expect_err("syntax error");
201        assert_eq!(
202            err,
203            ConfigLoadError::Parse {
204                path: None,
205                message: cause.clone(),
206                chain: cause,
207            }
208        );
209    }
210
211    #[test]
212    fn remote_extends_is_refused_by_default() {
213        let (_dir, root) = project(r#"{ "extends": "https://example.com/fallow.json" }"#);
214        let err = load_config_file(&root, None, ConfigFileOptions::default()).expect_err("refused");
215        assert!(err.chain().contains("Remote config extends"), "{err:?}");
216    }
217
218    #[test]
219    fn a_project_without_a_file_gets_the_default_config() {
220        let dir = tempfile::tempdir().expect("tempdir");
221        std::fs::create_dir(dir.path().join(".git")).expect("git marker");
222        let file = load_config_file(dir.path(), None, ConfigFileOptions::default())
223            .expect("defaults load");
224        assert_eq!(file.path, None);
225        assert_eq!(
226            file.config.production,
227            fallow_config::ProductionConfig::default()
228        );
229    }
230}