fallow_engine/project_config/
loader.rs1use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use fallow_config::{ConfigLoadOptions, EnvSnapshot, FallowConfig};
9
10use crate::EngineError;
11
12#[derive(Debug, Clone, Copy)]
17#[non_exhaustive]
18pub struct ConfigFileOptions {
19 pub allow_remote_extends: bool,
21 pub extends_timeout: Duration,
23}
24
25impl ConfigFileOptions {
26 #[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#[derive(Debug)]
49pub struct ConfigFile {
50 pub config: FallowConfig,
52 pub path: Option<PathBuf>,
54 pub chain: ConfigChainSnapshot,
56}
57
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
62pub struct ConfigChainSnapshot {
63 files: Vec<(PathBuf, Option<Vec<u8>>)>,
65 changed_during_load: bool,
67}
68
69impl ConfigChainSnapshot {
70 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 fn around_load(before: &Self, after: Self) -> Self {
90 Self {
91 changed_during_load: *before != after,
92 ..after
93 }
94 }
95
96 #[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#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum ConfigLoadError {
112 Parse {
115 path: Option<PathBuf>,
118 message: String,
120 chain: String,
123 },
124}
125
126impl ConfigLoadError {
127 #[must_use]
129 pub fn message(&self) -> &str {
130 match self {
131 Self::Parse { message, .. } => message,
132 }
133 }
134
135 #[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#[must_use]
154pub fn find_config_file(root: &Path) -> Option<PathBuf> {
155 FallowConfig::find_config_path(root)
156}
157
158pub 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
211fn 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#[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 #[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 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 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}