fallow_engine/project_config/
loader.rs1use std::path::{Path, PathBuf};
6
7use fallow_config::{ConfigLoadOptions, FallowConfig};
8
9use crate::EngineError;
10
11#[derive(Debug, Clone, Copy, Default)]
13pub struct ConfigFileOptions {
14 pub allow_remote_extends: bool,
16}
17
18#[derive(Debug)]
20pub struct ConfigFile {
21 pub config: FallowConfig,
23 pub path: Option<PathBuf>,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum ConfigLoadError {
31 Parse {
34 path: Option<PathBuf>,
37 message: String,
39 chain: String,
42 },
43}
44
45impl ConfigLoadError {
46 #[must_use]
48 pub fn message(&self) -> &str {
49 match self {
50 Self::Parse { message, .. } => message,
51 }
52 }
53
54 #[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
69pub 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
110fn 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 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 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}