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 = read_chain_file(&file);
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)| read_chain_file(path) != *bytes)
105    }
106}
107
108/// The bytes of a file of the `extends` chain: a regular file within the
109/// size limit of the config read, else `None`.
110fn read_chain_file(path: &Path) -> Option<Vec<u8>> {
111    fallow_types::read_guard::read_bytes_bounded(
112        path,
113        fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
114    )
115    .ok()
116}
117
118/// The error of [`load_config_file`].
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum ConfigLoadError {
122    /// The config file cannot be read or parsed, or its `extends` chain is
123    /// refused.
124    Parse {
125        /// The explicit config path. `None` for a discovered file, whose path
126        /// is in `message`.
127        path: Option<PathBuf>,
128        /// The top error.
129        message: String,
130        /// The top error and its causes. For a discovered file, this is the
131        /// same text as `message`.
132        chain: String,
133    },
134}
135
136impl ConfigLoadError {
137    /// The top error, without its causes.
138    #[must_use]
139    pub fn message(&self) -> &str {
140        match self {
141            Self::Parse { message, .. } => message,
142        }
143    }
144
145    /// The full error text: the error and its causes.
146    #[must_use]
147    pub fn chain(&self) -> &str {
148        match self {
149            Self::Parse { chain, .. } => chain,
150        }
151    }
152}
153
154impl From<ConfigLoadError> for EngineError {
155    fn from(err: ConfigLoadError) -> Self {
156        Self::new(format!("invalid config: {}", err.chain()))
157    }
158}
159
160/// The config file that discovery finds from `root` up to the repository
161/// root, without a load. A caller that only checks whether a project has a
162/// config file, or that writes to the config file, calls this function.
163#[must_use]
164pub fn find_config_file(root: &Path) -> Option<PathBuf> {
165    register_tracked_link_probe();
166    FallowConfig::find_config_path(root)
167}
168
169/// Give config discovery the git probe for a config file link out of the
170/// project: discovery allows such a link when git does not track it. A
171/// host calls it at startup, so that each config discovery, also one
172/// outside the project load, gets the same answer.
173pub fn register_tracked_link_probe() {
174    fallow_config::set_tracked_link_probe(git_tracks_entry);
175}
176
177/// Whether git tracks the entry at `path`. See
178/// [`fallow_config::TrackedLinkProbe`].
179fn git_tracks_entry(path: &Path) -> Option<bool> {
180    let output = crate::git_env::git_command(path.parent()?)
181        .args(["--literal-pathspecs", "ls-files", "-z", "--"])
182        .arg(path.file_name()?)
183        .stderr(std::process::Stdio::null())
184        .output()
185        .ok()?;
186    output.status.success().then_some(!output.stdout.is_empty())
187}
188
189/// Load the config file of a project: the file at `config_path`, else the
190/// first config file that discovery finds from `root` up to the repository
191/// root. A project without a config file gets the default config.
192///
193/// # Errors
194///
195/// Returns [`ConfigLoadError::Parse`] when the file cannot be read or parsed,
196/// or when `options` refuses an entry of its `extends` chain.
197pub fn load_config_file(
198    root: &Path,
199    config_path: Option<&Path>,
200    options: ConfigFileOptions,
201) -> Result<ConfigFile, ConfigLoadError> {
202    #[cfg(any(test, feature = "testing"))]
203    load_count::record(root);
204    register_tracked_link_probe();
205    let load_options = ConfigLoadOptions::new(options.allow_remote_extends)
206        .with_extends_timeout(options.extends_timeout);
207    let file = load_config_file_unchecked(root, config_path, load_options)?;
208    file.config.record_outside_values(root);
209    if let Err(errors) = file.config.check_file_path_keys_inside(root) {
210        let message = format!("invalid config:\n  - {}", errors.join("\n  - "));
211        return Err(ConfigLoadError::Parse {
212            path: file.path,
213            chain: message.clone(),
214            message,
215        });
216    }
217    Ok(file)
218}
219
220fn load_config_file_unchecked(
221    root: &Path,
222    config_path: Option<&Path>,
223    load_options: ConfigLoadOptions,
224) -> Result<ConfigFile, ConfigLoadError> {
225    if let Some(path) = config_path {
226        let before = ConfigChainSnapshot::read(Some(path));
227        return FallowConfig::load_with_options(path, load_options)
228            .map(|config| ConfigFile {
229                config,
230                path: Some(path.to_path_buf()),
231                chain: ConfigChainSnapshot::around_load(
232                    &before,
233                    ConfigChainSnapshot::read(Some(path)),
234                ),
235            })
236            .map_err(|err| explicit_load_error(path, &err));
237    }
238    let before = ConfigChainSnapshot::read(find_config_file(root).as_deref());
239    match FallowConfig::find_and_load_with_options(root, load_options) {
240        Ok(Some((config, path))) => Ok(ConfigFile {
241            config,
242            chain: ConfigChainSnapshot::around_load(
243                &before,
244                ConfigChainSnapshot::read(Some(&path)),
245            ),
246            path: Some(path),
247        }),
248        Ok(None) => Ok(ConfigFile {
249            config: FallowConfig::default(),
250            path: None,
251            chain: ConfigChainSnapshot::around_load(&before, ConfigChainSnapshot::default()),
252        }),
253        Err(message) => Err(ConfigLoadError::Parse {
254            path: None,
255            chain: message.clone(),
256            message,
257        }),
258    }
259}
260
261/// The error of an explicit config path. The alternate format of a config
262/// error report adds each cause to the top error.
263fn explicit_load_error(path: &Path, err: &impl std::fmt::Display) -> ConfigLoadError {
264    ConfigLoadError::Parse {
265        path: Some(path.to_path_buf()),
266        message: err.to_string(),
267        chain: format!("{err:#}"),
268    }
269}
270
271/// A count of the calls of [`load_config_file`] for each project root, for
272/// tests that check how often one call reads the config file.
273#[cfg(any(test, feature = "testing"))]
274pub mod load_count {
275    use std::path::{Path, PathBuf};
276    use std::sync::{Mutex, PoisonError};
277
278    use rustc_hash::FxHashMap;
279
280    static LOADS: Mutex<Option<FxHashMap<PathBuf, usize>>> = Mutex::new(None);
281
282    pub(super) fn record(root: &Path) {
283        let mut loads = LOADS.lock().unwrap_or_else(PoisonError::into_inner);
284        *loads
285            .get_or_insert_with(FxHashMap::default)
286            .entry(root.to_path_buf())
287            .or_default() += 1;
288    }
289
290    /// The number of config loads for `root` since the process started. Each
291    /// test uses its own temporary root, so tests that run in parallel do not
292    /// change the count of another test.
293    #[must_use]
294    pub fn config_loads(root: &Path) -> usize {
295        LOADS
296            .lock()
297            .unwrap_or_else(PoisonError::into_inner)
298            .as_ref()
299            .and_then(|loads| loads.get(root).copied())
300            .unwrap_or(0)
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn each_load_counts_for_its_root() {
310        let dir = tempfile::tempdir().expect("tempdir");
311        std::fs::create_dir(dir.path().join(".git")).expect("git marker");
312        assert_eq!(load_count::config_loads(dir.path()), 0);
313        for _ in 0..2 {
314            load_config_file(dir.path(), None, ConfigFileOptions::default()).expect("loads");
315        }
316        assert_eq!(load_count::config_loads(dir.path()), 2);
317    }
318
319    #[cfg(unix)]
320    #[test]
321    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
322    fn an_untracked_config_link_out_of_the_checkout_loads() {
323        let dir = tempfile::tempdir().expect("tempdir");
324        let outer = dunce::canonicalize(dir.path()).expect("canonical");
325        let root = outer.join("project");
326        std::fs::create_dir(&root).expect("project");
327        let git = |args: &[&str]| {
328            let status = crate::git_fixture::fixture_git_command(&root)
329                .args(args)
330                .stdout(std::process::Stdio::null())
331                .stderr(std::process::Stdio::null())
332                .status()
333                .expect("run git");
334            assert!(status.success(), "git {args:?}");
335        };
336        git(&["init", "-q"]);
337        std::fs::write(outer.join("dotfiles.json"), r#"{ "entry": ["src/a.ts"] }"#)
338            .expect("config");
339        std::os::unix::fs::symlink(outer.join("dotfiles.json"), root.join(".fallowrc.json"))
340            .expect("link");
341
342        let file = load_config_file(&root, None, ConfigFileOptions::default()).expect("loads");
343        assert_eq!(file.config.entry, vec!["src/a.ts".to_owned()]);
344        assert!(find_config_file(&root).is_some());
345
346        git(&["add", ".fallowrc.json"]);
347        assert!(load_config_file(&root, None, ConfigFileOptions::default()).is_err());
348        assert!(find_config_file(&root).is_none());
349    }
350
351    /// No server listens on port 1, so the fetch fails at once and offline.
352    const UNREACHABLE_REMOTE_EXTENDS: &str = r#"{ "extends": "https://127.0.0.1:1/fallow.json" }"#;
353
354    fn project(config: &str) -> (tempfile::TempDir, PathBuf) {
355        let dir = tempfile::tempdir().expect("tempdir");
356        let root = dir.path().to_path_buf();
357        std::fs::create_dir(root.join(".git")).expect("git marker");
358        std::fs::write(root.join(".fallowrc.json"), config).expect("config");
359        (dir, root)
360    }
361
362    #[cfg(unix)]
363    #[test]
364    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
365    fn config_path_keys_through_a_link_out_of_the_root_are_refused() {
366        let outside = tempfile::tempdir().expect("tempdir");
367        for config in [
368            r#"{ "codeowners": "linked/CODEOWNERS" }"#,
369            r#"{ "health": { "coverage": "linked/coverage-final.json" } }"#,
370            r#"{ "audit": { "dupesBaseline": "linked/dupes.json" } }"#,
371        ] {
372            let (_dir, root) = project(config);
373            std::os::unix::fs::symlink(outside.path(), root.join("linked")).expect("link");
374            let err =
375                load_config_file(&root, None, ConfigFileOptions::default()).expect_err(config);
376            assert!(err.chain().contains("outside"), "{config}: {}", err.chain());
377        }
378        let (_dir, root) = project(r#"{ "codeowners": "missing/CODEOWNERS" }"#);
379        load_config_file(&root, None, ConfigFileOptions::default()).expect("a missing file loads");
380    }
381
382    #[test]
383    fn explicit_error_keeps_the_path_and_the_cause_chain() {
384        let (_dir, root) = project(r#"{ "production": "yes" }"#);
385        let path = root.join(".fallowrc.json");
386        let cause = FallowConfig::load(&path).expect_err("wrong type");
387        let err = load_config_file(&root, Some(&path), ConfigFileOptions::default())
388            .expect_err("wrong type");
389        assert_eq!(
390            err,
391            ConfigLoadError::Parse {
392                path: Some(path),
393                message: cause.to_string(),
394                chain: format!("{cause:#}"),
395            }
396        );
397    }
398
399    /// An error with one cause. Its alternate format adds the cause, as the
400    /// default handler of a `miette::Report` does.
401    struct WrappedError;
402
403    impl std::fmt::Display for WrappedError {
404        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405            f.write_str("Failed to read config file")?;
406            if f.alternate() {
407                f.write_str(": no such file")?;
408            }
409            Ok(())
410        }
411    }
412
413    #[test]
414    fn explicit_error_chain_adds_each_cause() {
415        let err = explicit_load_error(Path::new("fallow.json"), &WrappedError);
416        assert_eq!(
417            err,
418            ConfigLoadError::Parse {
419                path: Some(PathBuf::from("fallow.json")),
420                message: "Failed to read config file".to_owned(),
421                chain: "Failed to read config file: no such file".to_owned(),
422            }
423        );
424    }
425
426    #[test]
427    fn file_options_take_the_extends_timeout_of_the_snapshot() {
428        let env = EnvSnapshot::from_pairs(&[("FALLOW_EXTENDS_TIMEOUT_SECS", "9")], None);
429        assert_eq!(
430            ConfigFileOptions::new(true, &env).extends_timeout,
431            Duration::from_secs(9)
432        );
433        assert_eq!(
434            ConfigFileOptions::default().extends_timeout,
435            Duration::from_secs(5)
436        );
437    }
438
439    #[test]
440    fn remote_extends_is_fetched_with_the_opt_in() {
441        let (_dir, root) = project(UNREACHABLE_REMOTE_EXTENDS);
442        let options = ConfigFileOptions::new(true, &EnvSnapshot::none());
443        for config_path in [None, Some(root.join(".fallowrc.json"))] {
444            let err =
445                load_config_file(&root, config_path.as_deref(), options).expect_err("fetch fails");
446            assert!(
447                err.chain().contains("Failed to fetch remote config"),
448                "{err:?}"
449            );
450        }
451    }
452
453    #[test]
454    fn discovered_error_has_no_path_and_one_text() {
455        let (_dir, root) = project(r#"{ "rules": "#);
456        let cause = FallowConfig::find_and_load(&root).expect_err("syntax error");
457        let err =
458            load_config_file(&root, None, ConfigFileOptions::default()).expect_err("syntax error");
459        assert_eq!(
460            err,
461            ConfigLoadError::Parse {
462                path: None,
463                message: cause.clone(),
464                chain: cause,
465            }
466        );
467    }
468
469    #[test]
470    fn the_chain_snapshot_sees_an_edit_of_each_local_file() {
471        let (_dir, root) = project(r#"{ "extends": "./base.json" }"#);
472        let base = root.join("base.json");
473        std::fs::write(&base, r#"{ "entry": ["a.ts"] }"#).expect("base");
474        let config = root.join(".fallowrc.json");
475        for config_path in [None, Some(config.as_path())] {
476            let file =
477                load_config_file(&root, config_path, ConfigFileOptions::default()).expect("loads");
478            assert!(!file.chain.changed());
479            std::fs::write(&base, r#"{ "entry": ["b.ts"] }"#).expect("same-size edit");
480            assert!(file.chain.changed());
481            std::fs::write(&base, r#"{ "entry": ["a.ts"] }"#).expect("restore");
482        }
483    }
484
485    #[test]
486    fn a_chain_that_differs_around_the_parse_counts_as_changed() {
487        let (_dir, root) = project("{}");
488        let config = root.join(".fallowrc.json");
489        let before = ConfigChainSnapshot::read(Some(&config));
490        std::fs::write(&config, r#"{ "entry": [] }"#).expect("edit during the parse");
491        let after = ConfigChainSnapshot::read(Some(&config));
492        assert!(ConfigChainSnapshot::around_load(&before, after.clone()).changed());
493        assert!(!ConfigChainSnapshot::around_load(&after.clone(), after).changed());
494        assert!(
495            ConfigChainSnapshot::around_load(&before, ConfigChainSnapshot::default()).changed(),
496            "a discovered file that is gone at the parse counts as changed"
497        );
498    }
499
500    #[test]
501    fn remote_extends_is_refused_by_default() {
502        let (_dir, root) = project(r#"{ "extends": "https://example.com/fallow.json" }"#);
503        let err = load_config_file(&root, None, ConfigFileOptions::default()).expect_err("refused");
504        assert!(err.chain().contains("Remote config extends"), "{err:?}");
505    }
506
507    #[test]
508    fn a_project_without_a_file_gets_the_default_config() {
509        let dir = tempfile::tempdir().expect("tempdir");
510        std::fs::create_dir(dir.path().join(".git")).expect("git marker");
511        let file = load_config_file(dir.path(), None, ConfigFileOptions::default())
512            .expect("defaults load");
513        assert_eq!(file.path, None);
514        assert_eq!(
515            file.config.production,
516            fallow_config::ProductionConfig::default()
517        );
518    }
519
520    /// Run `load_config_file` for `root` on a thread: `Some(true)` when the
521    /// load fails within a few seconds, `None` when it does not return.
522    #[cfg(unix)]
523    fn load_fails_in_time(root: &Path) -> Option<bool> {
524        let (sender, receiver) = std::sync::mpsc::channel();
525        let root = root.to_path_buf();
526        std::thread::spawn(move || {
527            let _ = sender.send(load_config_file(&root, None, ConfigFileOptions::default()));
528        });
529        receiver
530            .recv_timeout(std::time::Duration::from_secs(20))
531            .ok()
532            .map(|result| result.is_err())
533    }
534
535    /// A project with a `.git` entry whose config extends `entry`.
536    #[cfg(unix)]
537    fn project_extending(entry: &str) -> (tempfile::TempDir, PathBuf) {
538        let dir = tempfile::tempdir().expect("tempdir");
539        let root = dunce::canonicalize(dir.path()).expect("canonical");
540        std::fs::create_dir(root.join(".git")).expect("git marker");
541        std::fs::write(
542            root.join(".fallowrc.json"),
543            format!(r#"{{ "extends": "{entry}" }}"#),
544        )
545        .expect("config");
546        (dir, root)
547    }
548
549    #[cfg(unix)]
550    #[test]
551    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
552    fn a_pipe_in_the_extends_chain_is_refused_without_a_wait() {
553        let (_dir, root) = project_extending("./pipe.json");
554        let status = std::process::Command::new("mkfifo")
555            .arg(root.join("pipe.json"))
556            .status()
557            .expect("run mkfifo");
558        assert!(status.success(), "mkfifo must create the test pipe");
559
560        assert_eq!(load_fails_in_time(&root), Some(true));
561        let files = FallowConfig::local_source_files(&root.join(".fallowrc.json"));
562        assert!(
563            !files.iter().any(|file| file.ends_with("pipe.json")),
564            "{files:?}"
565        );
566    }
567
568    #[cfg(unix)]
569    #[test]
570    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
571    fn a_device_in_the_extends_chain_is_refused() {
572        for device in ["null", "zero"] {
573            let probe = tempfile::tempdir().expect("tempdir");
574            let depth = dunce::canonicalize(probe.path())
575                .expect("canonical")
576                .components()
577                .count();
578            // The project is another temp dir with the same parent, so it has
579            // `depth` components with the file system root. Its `depth - 1`
580            // parents lead to the file system root, and one more `..`
581            // stays there.
582            let up = "../".repeat(depth);
583            let (_dir, root) = project_extending(&format!("{up}dev/{device}"));
584
585            let files = FallowConfig::local_source_files(&root.join(".fallowrc.json"));
586            assert!(
587                !files.iter().any(|file| file.starts_with("/dev")),
588                "{device}: {files:?}"
589            );
590            assert_eq!(load_fails_in_time(&root), Some(true), "{device}");
591        }
592    }
593}