tabnas_multisource/
preload.rs1use std::collections::BTreeMap;
10
11use crate::vfs::{OsFs, SourceFs};
12
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct PreloadOptions {
16 pub folders: Vec<String>,
18 pub ext: Vec<String>,
21 pub recursive: bool,
23}
24
25impl PreloadOptions {
26 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 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 pub fn with_recursive(mut self, recursive: bool) -> Self {
51 self.recursive = recursive;
52 self
53 }
54
55 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
75pub fn preload_files(options: &PreloadOptions) -> BTreeMap<String, String> {
89 preload_files_with(options, &OsFs)
90}
91
92pub 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
112const 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}