Skip to main content

tabnas_multisource/
preload.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Reading folders into memory before a parse starts.
4//!
5//! A preload turns per-reference filesystem reads into map lookups, and
6//! is also how a caller vets what a parse may reach: scan once, inspect
7//! the map, and give the resolver nothing else.
8
9use std::collections::BTreeMap;
10
11use crate::vfs::{OsFs, SourceFs};
12
13/// Which folders to scan, and for what.
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct PreloadOptions {
16    /// Folders to scan.
17    pub folders: Vec<String>,
18    /// Extensions to load. Empty selects `.jsonic` and `.json`. A
19    /// missing leading dot is added.
20    pub ext: Vec<String>,
21    /// Descend into subfolders.
22    pub recursive: bool,
23}
24
25impl PreloadOptions {
26    /// A scan of `folders`, non-recursive, with the default extensions.
27    pub fn new<I, S>(folders: I) -> Self
28    where
29        I: IntoIterator<Item = S>,
30        S: Into<String>,
31    {
32        PreloadOptions {
33            folders: folders.into_iter().map(Into::into).collect(),
34            ext: Vec::new(),
35            recursive: false,
36        }
37    }
38
39    /// Load only files with these extensions.
40    pub fn with_ext<I, S>(mut self, ext: I) -> Self
41    where
42        I: IntoIterator<Item = S>,
43        S: Into<String>,
44    {
45        self.ext = ext.into_iter().map(Into::into).collect();
46        self
47    }
48
49    /// Descend into subfolders.
50    pub fn with_recursive(mut self, recursive: bool) -> Self {
51        self.recursive = recursive;
52        self
53    }
54
55    /// The extension list with a leading dot on every entry, and the
56    /// default when none was given.
57    fn extensions(&self) -> Vec<String> {
58        let raw: Vec<String> = if self.ext.is_empty() {
59            vec![".jsonic".to_string(), ".json".to_string()]
60        } else {
61            self.ext.clone()
62        };
63        raw.into_iter()
64            .map(|ext| {
65                if ext.starts_with('.') {
66                    ext
67                } else {
68                    format!(".{ext}")
69                }
70            })
71            .collect()
72    }
73}
74
75/// Scan the folders in `options` on the real filesystem, returning full
76/// path to content for every file matching one of the extensions.
77///
78/// Folders that do not exist, and files that cannot be read, are
79/// skipped. The result feeds [`crate::FileResolver::with_preload`].
80///
81/// ```
82/// use tabnas_multisource::{preload_files_with, MapFs, PreloadOptions};
83///
84/// let disk = MapFs::from([("conf/a.jsonic", "a:1"), ("conf/note.txt", "skip")]);
85/// let loaded = preload_files_with(&PreloadOptions::new(["conf"]), &disk);
86/// assert_eq!(loaded.keys().collect::<Vec<_>>(), vec!["conf/a.jsonic"]);
87/// ```
88pub fn preload_files(options: &PreloadOptions) -> BTreeMap<String, String> {
89    preload_files_with(options, &OsFs)
90}
91
92/// Scan the folders in `options` on `filesystem`.
93pub fn preload_files_with(
94    options: &PreloadOptions,
95    filesystem: &dyn SourceFs,
96) -> BTreeMap<String, String> {
97    let extensions = options.extensions();
98    let mut filemap = BTreeMap::new();
99    for folder in &options.folders {
100        scan(
101            filesystem,
102            &filesystem.canon(folder),
103            &extensions,
104            options.recursive,
105            &mut filemap,
106            0,
107        );
108    }
109    filemap
110}
111
112/// How deep a recursive scan descends. A folder tree deep enough to
113/// exhaust the stack is not a tree anyone means to preload, and the
114/// walk is recursive.
115const MAX_SCAN_DEPTH: usize = 64;
116
117fn scan(
118    filesystem: &dyn SourceFs,
119    folder: &str,
120    extensions: &[String],
121    recursive: bool,
122    filemap: &mut BTreeMap<String, String>,
123    depth: usize,
124) {
125    if depth > MAX_SCAN_DEPTH {
126        return;
127    }
128    let Some(entries) = filesystem.read_dir(folder) else {
129        return;
130    };
131    for entry in entries {
132        let full = filesystem.join(&[folder, &entry.name]);
133        if entry.is_dir {
134            if recursive {
135                scan(filesystem, &full, extensions, recursive, filemap, depth + 1);
136            }
137            continue;
138        }
139        if extensions
140            .iter()
141            .any(|ext| entry.name.ends_with(ext.as_str()))
142        {
143            if let Some(src) = filesystem.read_file(&full) {
144                filemap.insert(full, src);
145            }
146        }
147    }
148}