use std::collections::BTreeMap;
use crate::vfs::{OsFs, SourceFs};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PreloadOptions {
pub folders: Vec<String>,
pub ext: Vec<String>,
pub recursive: bool,
}
impl PreloadOptions {
pub fn new<I, S>(folders: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
PreloadOptions {
folders: folders.into_iter().map(Into::into).collect(),
ext: Vec::new(),
recursive: false,
}
}
pub fn with_ext<I, S>(mut self, ext: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.ext = ext.into_iter().map(Into::into).collect();
self
}
pub fn with_recursive(mut self, recursive: bool) -> Self {
self.recursive = recursive;
self
}
fn extensions(&self) -> Vec<String> {
let raw: Vec<String> = if self.ext.is_empty() {
vec![".jsonic".to_string(), ".json".to_string()]
} else {
self.ext.clone()
};
raw.into_iter()
.map(|ext| {
if ext.starts_with('.') {
ext
} else {
format!(".{ext}")
}
})
.collect()
}
}
pub fn preload_files(options: &PreloadOptions) -> BTreeMap<String, String> {
preload_files_with(options, &OsFs)
}
pub fn preload_files_with(
options: &PreloadOptions,
filesystem: &dyn SourceFs,
) -> BTreeMap<String, String> {
let extensions = options.extensions();
let mut filemap = BTreeMap::new();
for folder in &options.folders {
scan(
filesystem,
&filesystem.canon(folder),
&extensions,
options.recursive,
&mut filemap,
0,
);
}
filemap
}
const MAX_SCAN_DEPTH: usize = 64;
fn scan(
filesystem: &dyn SourceFs,
folder: &str,
extensions: &[String],
recursive: bool,
filemap: &mut BTreeMap<String, String>,
depth: usize,
) {
if depth > MAX_SCAN_DEPTH {
return;
}
let Some(entries) = filesystem.read_dir(folder) else {
return;
};
for entry in entries {
let full = filesystem.join(&[folder, &entry.name]);
if entry.is_dir {
if recursive {
scan(filesystem, &full, extensions, recursive, filemap, depth + 1);
}
continue;
}
if extensions
.iter()
.any(|ext| entry.name.ends_with(ext.as_str()))
{
if let Some(src) = filesystem.read_file(&full) {
filemap.insert(full, src);
}
}
}
}