1use crate::error::ContextError;
6use crate::text::stable_hash;
7use std::fs;
8use std::io::Read;
9use std::path::{Component, Path, PathBuf};
10use troupekit_tools::text::html_to_text;
11
12const MAX_FILES_DEFAULT: usize = 10_000;
13const MAX_FILE_BYTES_DEFAULT: u64 = 8 * 1024 * 1024;
14const MAX_DEPTH_DEFAULT: usize = 16;
15const MAX_ENTRIES_DEFAULT: usize = 100_000;
16const EXTENSIONS_DEFAULT: [&str; 5] = ["txt", "md", "markdown", "html", "htm"];
17const HTML_EXTENSIONS: [&str; 2] = ["html", "htm"];
18const MARKDOWN_EXTENSIONS: [&str; 2] = ["md", "markdown"];
19
20#[non_exhaustive]
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct LoadSettings {
27 extensions: Vec<String>,
28 max_files: usize,
29 max_file_bytes: u64,
30 max_depth: usize,
31 max_entries: usize,
32 follow_symlinks: bool,
33 skip_hidden: bool,
34}
35
36impl Default for LoadSettings {
37 fn default() -> Self {
38 Self {
39 extensions: EXTENSIONS_DEFAULT.iter().map(|e| (*e).to_string()).collect(),
40 max_files: MAX_FILES_DEFAULT,
41 max_file_bytes: MAX_FILE_BYTES_DEFAULT,
42 max_depth: MAX_DEPTH_DEFAULT,
43 max_entries: MAX_ENTRIES_DEFAULT,
44 follow_symlinks: false,
45 skip_hidden: true,
46 }
47 }
48}
49
50impl LoadSettings {
51 pub fn with_extensions<I, S>(mut self, extensions: I) -> Self
55 where
56 I: IntoIterator<Item = S>,
57 S: Into<String>,
58 {
59 self.extensions = extensions.into_iter().map(|e| e.into().to_ascii_lowercase()).collect();
60 self
61 }
62
63 pub fn with_max_files(mut self, max_files: usize) -> Self {
67 self.max_files = max_files;
68 self
69 }
70
71 pub fn with_max_file_bytes(mut self, max_file_bytes: u64) -> Self {
75 self.max_file_bytes = max_file_bytes;
76 self
77 }
78
79 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
83 self.max_depth = max_depth;
84 self
85 }
86
87 pub fn with_max_entries(mut self, max_entries: usize) -> Self {
91 self.max_entries = max_entries;
92 self
93 }
94
95 pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
99 self.follow_symlinks = follow;
100 self
101 }
102
103 pub fn with_skip_hidden(mut self, skip: bool) -> Self {
107 self.skip_hidden = skip;
108 self
109 }
110
111 pub fn extensions(&self) -> &[String] {
115 &self.extensions
116 }
117
118 pub fn max_files(&self) -> usize {
122 self.max_files
123 }
124
125 pub fn max_file_bytes(&self) -> u64 {
129 self.max_file_bytes
130 }
131
132 pub fn max_depth(&self) -> usize {
136 self.max_depth
137 }
138
139 pub fn max_entries(&self) -> usize {
143 self.max_entries
144 }
145
146 pub fn follow_symlinks(&self) -> bool {
150 self.follow_symlinks
151 }
152
153 pub fn skip_hidden(&self) -> bool {
157 self.skip_hidden
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct LoadedFile {
166 pub source: String,
167 pub text: String,
168 pub content_hash: String,
169}
170
171#[non_exhaustive]
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Walked {
178 pub files: Vec<LoadedFile>,
179 pub unsupported: usize,
180 pub symlinks: usize,
181}
182
183pub fn walk(dir: &Path, settings: &LoadSettings) -> Result<Walked, ContextError> {
188 let root_meta = fs::metadata(dir).map_err(|e| ContextError::Invalid(format!("cannot read folder: {e}")))?;
189 if !root_meta.is_dir() {
190 return Err(ContextError::Invalid("not a folder".into()));
191 }
192 let mut walked = Walked { files: Vec::new(), unsupported: 0, symlinks: 0 };
193 let mut pending: Vec<(PathBuf, usize)> = vec![(dir.to_path_buf(), 0)];
194 let mut entries_seen: usize = 0;
195 while let Some((folder, depth)) = pending.pop() {
196 assert!(depth <= settings.max_depth, "folder queued past max_depth");
197 let entries = fs::read_dir(&folder).map_err(|e| invalid(dir, &folder, &e.to_string()))?;
198 for entry in entries {
199 let entry = entry.map_err(|e| invalid(dir, &folder, &e.to_string()))?;
200 let path = entry.path();
201 entries_seen += 1;
202 if entries_seen > settings.max_entries {
203 return Err(invalid(dir, &path, &format!("more than max_entries {} entries", settings.max_entries)));
204 }
205 if settings.skip_hidden && entry.file_name().to_string_lossy().starts_with('.') {
206 continue;
207 }
208 let file_type = entry.file_type().map_err(|e| invalid(dir, &path, &e.to_string()))?;
209 let (is_dir, is_file) = if file_type.is_symlink() {
210 if !settings.follow_symlinks {
211 walked.symlinks += 1;
212 continue;
213 }
214 let target = fs::metadata(&path).map_err(|e| invalid(dir, &path, &e.to_string()))?;
215 (target.is_dir(), target.is_file())
216 } else {
217 (file_type.is_dir(), file_type.is_file())
218 };
219 if is_dir {
220 if depth + 1 > settings.max_depth {
221 return Err(invalid(dir, &path, &format!("folder deeper than max_depth {}", settings.max_depth)));
222 }
223 pending.push((path, depth + 1));
224 continue;
225 }
226 let Some(ext) = extension(&path, settings).filter(|_| is_file) else {
227 walked.unsupported += 1;
228 continue;
229 };
230 if walked.files.len() == settings.max_files {
231 return Err(invalid(dir, &path, &format!("more than max_files {} files", settings.max_files)));
232 }
233 walked.files.push(load_file(dir, &path, &ext, settings)?);
234 }
235 }
236 walked.files.sort_by(|a, b| a.source.cmp(&b.source));
237 assert!(walked.files.len() <= settings.max_files, "loaded past max_files");
238 assert!(entries_seen <= settings.max_entries, "visited past max_entries");
239 assert!(walked.files.windows(2).all(|w| w[0].source < w[1].source), "sources not unique and sorted");
240 Ok(walked)
241}
242
243fn extension(path: &Path, settings: &LoadSettings) -> Option<String> {
247 let ext = path.extension()?.to_str()?.to_ascii_lowercase();
248 let readable = EXTENSIONS_DEFAULT.contains(&ext.as_str());
249 (readable && settings.extensions.contains(&ext)).then_some(ext)
250}
251
252fn load_file(root: &Path, path: &Path, ext: &str, settings: &LoadSettings) -> Result<LoadedFile, ContextError> {
256 let source = source_of(root, path)?;
257 let fail = |why: String| ContextError::Invalid(format!("{source}: {why}"));
258 let checked = if settings.follow_symlinks { fs::metadata(path) } else { fs::symlink_metadata(path) }.map_err(|e| fail(e.to_string()))?;
259 if !checked.is_file() {
260 return Err(fail("not a regular file".into()));
261 }
262 let (file, opened) = open_regular(path).map_err(fail)?;
263 if !same_file(&checked, &opened) {
264 return Err(fail("changed between check and open".into()));
265 }
266 let size = opened.len();
267 if size > settings.max_file_bytes {
268 return Err(fail(format!("{size} bytes, over max_file_bytes {}", settings.max_file_bytes)));
269 }
270 let mut bytes = Vec::new();
271 file.take(settings.max_file_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| fail(e.to_string()))?;
272 if bytes.len() as u64 > settings.max_file_bytes {
273 return Err(fail(format!("grew over max_file_bytes {} while read", settings.max_file_bytes)));
274 }
275 let raw = String::from_utf8(bytes).map_err(|_| fail("not valid UTF-8".into()))?;
276 let text = if HTML_EXTENSIONS.contains(&ext) {
277 html_to_text(&raw)
278 } else if MARKDOWN_EXTENSIONS.contains(&ext) {
279 strip_front_matter(&raw).to_string()
280 } else {
281 raw
282 };
283 let content_hash = format!("{:016x}", stable_hash(&[&text]));
284 assert_eq!(content_hash.len(), 16, "hash is 16 hex chars");
285 Ok(LoadedFile { source, text, content_hash })
286}
287
288#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))]
292const O_NONBLOCK: i32 = 0x0004;
293#[cfg(all(
297 any(target_os = "linux", target_os = "android"),
298 any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64", target_arch = "riscv64", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "s390x", target_arch = "loongarch64")
299))]
300const O_NONBLOCK: i32 = 0o4000;
301#[cfg(all(
305 unix,
306 not(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")),
307 not(all(
308 any(target_os = "linux", target_os = "android"),
309 any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64", target_arch = "riscv64", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "s390x", target_arch = "loongarch64")
310 ))
311))]
312const O_NONBLOCK: i32 = 0;
313
314fn open_regular(path: &Path) -> Result<(fs::File, fs::Metadata), String> {
319 let mut options = fs::OpenOptions::new();
320 options.read(true);
321 #[cfg(unix)]
322 std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
323 let file = options.open(path).map_err(|e| e.to_string())?;
324 let opened = file.metadata().map_err(|e| e.to_string())?;
325 if !opened.is_file() {
326 return Err("not a regular file".into());
327 }
328 Ok((file, opened))
329}
330
331#[cfg(unix)]
335fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
336 use std::os::unix::fs::MetadataExt;
337 checked.dev() == opened.dev() && checked.ino() == opened.ino()
338}
339
340#[cfg(not(unix))]
344fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
345 checked.len() == opened.len() && checked.modified().ok() == opened.modified().ok()
346}
347
348fn strip_front_matter(text: &str) -> &str {
352 let Some(rest) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) else {
353 return text;
354 };
355 let mut offset = 0;
356 for line in rest.split_inclusive('\n') {
357 offset += line.len();
358 if line.trim_end_matches(['\r', '\n']) == "---" {
359 return &rest[offset..];
360 }
361 }
362 text
363}
364
365fn source_of(root: &Path, path: &Path) -> Result<String, ContextError> {
369 let relative = path.strip_prefix(root).expect("walked path is under the root");
370 let mut parts = Vec::new();
371 for component in relative.components() {
372 let Component::Normal(name) = component else {
373 unreachable!("read_dir yields plain names only");
374 };
375 let name = name.to_str().ok_or_else(|| ContextError::Invalid(format!("{}: name is not UTF-8", relative.to_string_lossy())))?;
376 parts.push(name);
377 }
378 assert!(!parts.is_empty(), "a file has a name");
379 Ok(parts.join("/"))
380}
381
382fn invalid(root: &Path, path: &Path, why: &str) -> ContextError {
386 let shown = path.strip_prefix(root).map_or_else(|_| String::from("."), |p| p.to_string_lossy().into_owned());
387 let shown = if shown.is_empty() { String::from(".") } else { shown };
388 ContextError::Invalid(format!("{shown}: {why}"))
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[cfg(unix)]
396 #[test]
397 fn open_regular_refuses_a_fifo_without_blocking() {
398 let dir = tempfile::tempdir().unwrap();
399 let fifo = dir.path().join("swapped.txt");
400 assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
401 let (tx, rx) = std::sync::mpsc::channel();
402 std::thread::spawn(move || tx.send(open_regular(&fifo).map(|_| ())).unwrap());
403 let result = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("open blocked on a FIFO");
404 assert!(matches!(result, Err(ref why) if why.contains("not a regular file")), "{result:?}");
405 let file = dir.path().join("plain.txt");
406 fs::write(&file, "text").unwrap();
407 let (_, opened) = open_regular(&file).unwrap();
408 assert_eq!(opened.len(), 4);
409 }
410
411 #[test]
412 fn front_matter_needs_a_closing_line() {
413 assert_eq!(strip_front_matter("---\ntitle: a\n---\nbody"), "body");
414 assert_eq!(strip_front_matter("---\r\ntitle: a\r\n---\r\nbody"), "body");
415 assert_eq!(strip_front_matter("---\nno close"), "---\nno close");
416 assert_eq!(strip_front_matter("body\n---\nx\n---\n"), "body\n---\nx\n---\n");
417 }
418}