Skip to main content

troupekit_context/
load.rs

1//! Loads text, markdown and HTML files from a folder for ingest.
2//! The walk is bounded in file count, file size and depth, skips hidden
3//! entries and symlinks by default, and returns files sorted by source.
4
5use 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/// Bounds and filters of a folder walk. Every field has a safe default:
21/// the five text extensions, 10 000 files, 8 MiB per file, depth 16,
22/// 100 000 directory entries, symlinks not followed, hidden entries
23/// skipped. Built with `Default` and the `with_*` setters.
24#[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    /// Sets the file extensions to load, compared without case.
52    /// Only `txt`, `md`, `markdown`, `html` and `htm` can be read; any
53    /// other extension in the list is still skipped.
54    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    /// Sets the most supported files one walk loads.
64    /// A folder with more is an error, so a walk never stops halfway
65    /// in silence. Default 10 000.
66    pub fn with_max_files(mut self, max_files: usize) -> Self {
67        self.max_files = max_files;
68        self
69    }
70
71    /// Sets the largest file in bytes.
72    /// A larger file is an error that names the source, checked from
73    /// metadata before any read. Default 8 MiB.
74    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    /// Sets the deepest folder level below the root, which is level 0.
80    /// A folder deeper than this is an error that names it. Hidden
81    /// folders are never entered, so they never trip it. Default 16.
82    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
83        self.max_depth = max_depth;
84        self
85    }
86
87    /// Sets the most directory entries one walk visits, of any kind.
88    /// It bounds a walk through big folders of unsupported files; more
89    /// entries is an error. Default 100 000.
90    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
91        self.max_entries = max_entries;
92        self
93    }
94
95    /// Sets whether symlinks are followed.
96    /// Off by default, because a link can point outside the folder the
97    /// user chose. A link not followed is counted in `Walked.symlinks`.
98    pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
99        self.follow_symlinks = follow;
100        self
101    }
102
103    /// Sets whether entries whose name starts with a dot are skipped.
104    /// On by default, so `.git` and editor files stay out. A skipped
105    /// hidden entry is neither entered nor counted.
106    pub fn with_skip_hidden(mut self, skip: bool) -> Self {
107        self.skip_hidden = skip;
108        self
109    }
110
111    /// Returns the extensions loaded, lowercase.
112    /// Only the five readable text extensions can match a file.
113    /// Default `txt`, `md`, `markdown`, `html`, `htm`.
114    pub fn extensions(&self) -> &[String] {
115        &self.extensions
116    }
117
118    /// Returns the most supported files one walk loads.
119    /// One more is an error naming the cap.
120    /// Default 10 000.
121    pub fn max_files(&self) -> usize {
122        self.max_files
123    }
124
125    /// Returns the largest file in bytes.
126    /// A larger file is an error naming the source.
127    /// Default 8 MiB.
128    pub fn max_file_bytes(&self) -> u64 {
129        self.max_file_bytes
130    }
131
132    /// Returns the deepest folder level walked.
133    /// The root is level 0.
134    /// Default 16.
135    pub fn max_depth(&self) -> usize {
136        self.max_depth
137    }
138
139    /// Returns the most directory entries one walk visits.
140    /// Every entry counts, hidden or not.
141    /// Default 100 000.
142    pub fn max_entries(&self) -> usize {
143        self.max_entries
144    }
145
146    /// Returns whether symlinks are followed.
147    /// A followed link is loaded like the file it points to.
148    /// Default false.
149    pub fn follow_symlinks(&self) -> bool {
150        self.follow_symlinks
151    }
152
153    /// Returns whether hidden entries are skipped.
154    /// A hidden entry starts with a dot.
155    /// Default true.
156    pub fn skip_hidden(&self) -> bool {
157        self.skip_hidden
158    }
159}
160
161/// One loaded file. `source` is the path relative to the walked folder
162/// with `/` separators, so no absolute path reaches a prompt. `text` is
163/// plain text, and `content_hash` is its stable hash in 16 hex chars.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct LoadedFile {
166    pub source: String,
167    pub text: String,
168    pub content_hash: String,
169}
170
171/// The result of one walk: the loaded files sorted by `source`, the
172/// count of entries skipped as unsupported (extension, or not a regular
173/// file such as a FIFO) and the count of symlinks not followed.
174/// Hidden entries are neither entered nor counted.
175#[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
183/// Walks `dir` and loads every file the settings allow.
184/// Input: a folder and the walk bounds. Output: the files sorted by
185/// source and the skip counts, or `ContextError::Invalid` naming the
186/// cap and relative path, or the source on invalid UTF-8 or a read error.
187pub 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
243/// Returns the lowercase extension of `path` when the settings list it
244/// and the loader can read it. Input: a file path and the settings.
245/// Output: the extension, or `None` to skip the file.
246fn 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
252/// Reads one file under the byte cap and turns it into plain text.
253/// Input: the walk root, the file, its extension and the settings.
254/// Output: the loaded file, or `Invalid` naming the source.
255fn 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, settings.follow_symlinks).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/// `O_NONBLOCK` of the targets std builds for, since this crate has no
289/// `libc` edge: 4 on the BSD family, 0o4000 on Linux and Android. On any
290/// other target it is 0, and a FIFO swapped in after the check can block.
291#[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/// `O_NONBLOCK` on Linux and Android for every architecture except the
294/// MIPS, SPARC, Alpha and PA-RISC families, which number it differently.
295/// Opening a FIFO with it returns at once instead of waiting for a writer.
296#[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/// No known `O_NONBLOCK` value for this target, so open stays blocking.
302/// The opened handle is still checked to be a regular file before reading.
303/// Listed in the eng-log as a known gap.
304#[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
314/// `FILE_FLAG_OPEN_REPARSE_POINT`: opens a symlink itself, not its target.
315#[cfg(windows)]
316const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
317
318/// Opens `path` for reading without waiting on a FIFO, then checks that
319/// the opened handle is a regular file before anything reads from it. On
320/// Windows without `follow`, a symlink is opened itself and so refused.
321/// Input: the path and `follow`. Output: the file and its handle metadata,
322/// or the reason: "not a regular file" for a link, FIFO, device or socket.
323fn open_regular(path: &Path, follow: bool) -> Result<(fs::File, fs::Metadata), String> {
324    let mut options = fs::OpenOptions::new();
325    options.read(true);
326    #[cfg(unix)]
327    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
328    #[cfg(windows)]
329    if !follow {
330        std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, FILE_FLAG_OPEN_REPARSE_POINT);
331    }
332    #[cfg(not(windows))]
333    let _ = follow;
334    let file = options.open(path).map_err(|e| e.to_string())?;
335    let opened = file.metadata().map_err(|e| e.to_string())?;
336    if !opened.is_file() {
337        return Err("not a regular file".into());
338    }
339    Ok((file, opened))
340}
341
342/// Tells whether two metadata records name the same file: same device
343/// and inode on Unix, so a path swapped for a symlink after the check is
344/// refused. Input: the checked and the opened metadata. Output: the answer.
345#[cfg(unix)]
346fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
347    use std::os::unix::fs::MetadataExt;
348    checked.dev() == opened.dev() && checked.ino() == opened.ino()
349}
350
351/// Tells whether two metadata records name the same file. Without inode
352/// numbers it compares length and modification time, the best stable std
353/// offers; on Windows `open_regular` already refuses a swapped-in link.
354/// Input: the checked and the opened metadata. Output: the answer.
355#[cfg(not(unix))]
356fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
357    checked.len() == opened.len() && checked.modified().ok() == opened.modified().ok()
358}
359
360/// Drops markdown front matter: a first line `---` up to the next line
361/// that is `---`. Input: the file text. Output: the text after the
362/// closing line, or the whole text when no closed block opens it.
363fn strip_front_matter(text: &str) -> &str {
364    let Some(rest) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) else {
365        return text;
366    };
367    let mut offset = 0;
368    for line in rest.split_inclusive('\n') {
369        offset += line.len();
370        if line.trim_end_matches(['\r', '\n']) == "---" {
371            return &rest[offset..];
372        }
373    }
374    text
375}
376
377/// Path of `path` relative to `root`, joined with `/`.
378/// Input: the walk root and a path inside it. Output: the relative
379/// source, or `Invalid` for a name that is not UTF-8.
380fn source_of(root: &Path, path: &Path) -> Result<String, ContextError> {
381    let relative = path.strip_prefix(root).expect("walked path is under the root");
382    let mut parts = Vec::new();
383    for component in relative.components() {
384        let Component::Normal(name) = component else {
385            unreachable!("read_dir yields plain names only");
386        };
387        let name = name.to_str().ok_or_else(|| ContextError::Invalid(format!("{}: name is not UTF-8", relative.to_string_lossy())))?;
388        parts.push(name);
389    }
390    assert!(!parts.is_empty(), "a file has a name");
391    Ok(parts.join("/"))
392}
393
394/// Error for an entry the walk cannot read, naming its relative path.
395/// Input: the root, the entry and the reason.
396/// Output: `Invalid` with the path and the reason.
397fn invalid(root: &Path, path: &Path, why: &str) -> ContextError {
398    let shown = path.strip_prefix(root).map_or_else(|_| String::from("."), |p| p.to_string_lossy().into_owned());
399    let shown = if shown.is_empty() { String::from(".") } else { shown };
400    ContextError::Invalid(format!("{shown}: {why}"))
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[cfg(any(
408        target_os = "macos",
409        target_os = "ios",
410        target_os = "freebsd",
411        target_os = "openbsd",
412        target_os = "netbsd",
413        target_os = "dragonfly",
414        all(
415            any(target_os = "linux", target_os = "android"),
416            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")
417        )
418    ))]
419    #[test]
420    fn open_regular_refuses_a_fifo_without_blocking() {
421        let dir = tempfile::tempdir().unwrap();
422        let fifo = dir.path().join("swapped.txt");
423        assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
424        let (tx, rx) = std::sync::mpsc::channel();
425        std::thread::spawn(move || tx.send(open_regular(&fifo, false).map(|_| ())).unwrap());
426        let result = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("open blocked on a FIFO");
427        assert!(matches!(result, Err(ref why) if why.contains("not a regular file")), "{result:?}");
428    }
429
430    #[test]
431    fn open_regular_reads_a_regular_file() {
432        let dir = tempfile::tempdir().unwrap();
433        let file = dir.path().join("plain.txt");
434        fs::write(&file, "text").unwrap();
435        let (_, opened) = open_regular(&file, false).unwrap();
436        assert_eq!(opened.len(), 4);
437    }
438
439    #[cfg(windows)]
440    #[test]
441    fn open_regular_refuses_a_symlink_unless_followed() {
442        let dir = tempfile::tempdir().unwrap();
443        let target = dir.path().join("target.txt");
444        fs::write(&target, "text").unwrap();
445        let link = dir.path().join("link.txt");
446        std::os::windows::fs::symlink_file(&target, &link).unwrap();
447        let result = open_regular(&link, false).map(|_| ());
448        assert!(matches!(result, Err(ref why) if why.contains("not a regular file")), "{result:?}");
449        let (_, opened) = open_regular(&link, true).unwrap();
450        assert_eq!(opened.len(), 4);
451    }
452
453    #[test]
454    fn front_matter_needs_a_closing_line() {
455        assert_eq!(strip_front_matter("---\ntitle: a\n---\nbody"), "body");
456        assert_eq!(strip_front_matter("---\r\ntitle: a\r\n---\r\nbody"), "body");
457        assert_eq!(strip_front_matter("---\nno close"), "---\nno close");
458        assert_eq!(strip_front_matter("body\n---\nx\n---\n"), "body\n---\nx\n---\n");
459    }
460}