use crate::error::ContextError;
use crate::text::stable_hash;
use std::fs;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use troupekit_tools::text::html_to_text;
const MAX_FILES_DEFAULT: usize = 10_000;
const MAX_FILE_BYTES_DEFAULT: u64 = 8 * 1024 * 1024;
const MAX_DEPTH_DEFAULT: usize = 16;
const MAX_ENTRIES_DEFAULT: usize = 100_000;
const EXTENSIONS_DEFAULT: [&str; 5] = ["txt", "md", "markdown", "html", "htm"];
const HTML_EXTENSIONS: [&str; 2] = ["html", "htm"];
const MARKDOWN_EXTENSIONS: [&str; 2] = ["md", "markdown"];
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadSettings {
extensions: Vec<String>,
max_files: usize,
max_file_bytes: u64,
max_depth: usize,
max_entries: usize,
follow_symlinks: bool,
skip_hidden: bool,
}
impl Default for LoadSettings {
fn default() -> Self {
Self {
extensions: EXTENSIONS_DEFAULT.iter().map(|e| (*e).to_string()).collect(),
max_files: MAX_FILES_DEFAULT,
max_file_bytes: MAX_FILE_BYTES_DEFAULT,
max_depth: MAX_DEPTH_DEFAULT,
max_entries: MAX_ENTRIES_DEFAULT,
follow_symlinks: false,
skip_hidden: true,
}
}
}
impl LoadSettings {
pub fn with_extensions<I, S>(mut self, extensions: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.extensions = extensions.into_iter().map(|e| e.into().to_ascii_lowercase()).collect();
self
}
pub fn with_max_files(mut self, max_files: usize) -> Self {
self.max_files = max_files;
self
}
pub fn with_max_file_bytes(mut self, max_file_bytes: u64) -> Self {
self.max_file_bytes = max_file_bytes;
self
}
pub fn with_max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
pub fn with_max_entries(mut self, max_entries: usize) -> Self {
self.max_entries = max_entries;
self
}
pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
self.follow_symlinks = follow;
self
}
pub fn with_skip_hidden(mut self, skip: bool) -> Self {
self.skip_hidden = skip;
self
}
pub fn extensions(&self) -> &[String] {
&self.extensions
}
pub fn max_files(&self) -> usize {
self.max_files
}
pub fn max_file_bytes(&self) -> u64 {
self.max_file_bytes
}
pub fn max_depth(&self) -> usize {
self.max_depth
}
pub fn max_entries(&self) -> usize {
self.max_entries
}
pub fn follow_symlinks(&self) -> bool {
self.follow_symlinks
}
pub fn skip_hidden(&self) -> bool {
self.skip_hidden
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedFile {
pub source: String,
pub text: String,
pub content_hash: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Walked {
pub files: Vec<LoadedFile>,
pub unsupported: usize,
pub symlinks: usize,
}
pub fn walk(dir: &Path, settings: &LoadSettings) -> Result<Walked, ContextError> {
let root_meta = fs::metadata(dir).map_err(|e| ContextError::Invalid(format!("cannot read folder: {e}")))?;
if !root_meta.is_dir() {
return Err(ContextError::Invalid("not a folder".into()));
}
let mut walked = Walked { files: Vec::new(), unsupported: 0, symlinks: 0 };
let mut pending: Vec<(PathBuf, usize)> = vec![(dir.to_path_buf(), 0)];
let mut entries_seen: usize = 0;
while let Some((folder, depth)) = pending.pop() {
assert!(depth <= settings.max_depth, "folder queued past max_depth");
let entries = fs::read_dir(&folder).map_err(|e| invalid(dir, &folder, &e.to_string()))?;
for entry in entries {
let entry = entry.map_err(|e| invalid(dir, &folder, &e.to_string()))?;
let path = entry.path();
entries_seen += 1;
if entries_seen > settings.max_entries {
return Err(invalid(dir, &path, &format!("more than max_entries {} entries", settings.max_entries)));
}
if settings.skip_hidden && entry.file_name().to_string_lossy().starts_with('.') {
continue;
}
let file_type = entry.file_type().map_err(|e| invalid(dir, &path, &e.to_string()))?;
let (is_dir, is_file) = if file_type.is_symlink() {
if !settings.follow_symlinks {
walked.symlinks += 1;
continue;
}
let target = fs::metadata(&path).map_err(|e| invalid(dir, &path, &e.to_string()))?;
(target.is_dir(), target.is_file())
} else {
(file_type.is_dir(), file_type.is_file())
};
if is_dir {
if depth + 1 > settings.max_depth {
return Err(invalid(dir, &path, &format!("folder deeper than max_depth {}", settings.max_depth)));
}
pending.push((path, depth + 1));
continue;
}
let Some(ext) = extension(&path, settings).filter(|_| is_file) else {
walked.unsupported += 1;
continue;
};
if walked.files.len() == settings.max_files {
return Err(invalid(dir, &path, &format!("more than max_files {} files", settings.max_files)));
}
walked.files.push(load_file(dir, &path, &ext, settings)?);
}
}
walked.files.sort_by(|a, b| a.source.cmp(&b.source));
assert!(walked.files.len() <= settings.max_files, "loaded past max_files");
assert!(entries_seen <= settings.max_entries, "visited past max_entries");
assert!(walked.files.windows(2).all(|w| w[0].source < w[1].source), "sources not unique and sorted");
Ok(walked)
}
fn extension(path: &Path, settings: &LoadSettings) -> Option<String> {
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
let readable = EXTENSIONS_DEFAULT.contains(&ext.as_str());
(readable && settings.extensions.contains(&ext)).then_some(ext)
}
fn load_file(root: &Path, path: &Path, ext: &str, settings: &LoadSettings) -> Result<LoadedFile, ContextError> {
let source = source_of(root, path)?;
let fail = |why: String| ContextError::Invalid(format!("{source}: {why}"));
let checked = if settings.follow_symlinks { fs::metadata(path) } else { fs::symlink_metadata(path) }.map_err(|e| fail(e.to_string()))?;
if !checked.is_file() {
return Err(fail("not a regular file".into()));
}
let (file, opened) = open_regular(path, settings.follow_symlinks).map_err(fail)?;
if !same_file(&checked, &opened) {
return Err(fail("changed between check and open".into()));
}
let size = opened.len();
if size > settings.max_file_bytes {
return Err(fail(format!("{size} bytes, over max_file_bytes {}", settings.max_file_bytes)));
}
let mut bytes = Vec::new();
file.take(settings.max_file_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| fail(e.to_string()))?;
if bytes.len() as u64 > settings.max_file_bytes {
return Err(fail(format!("grew over max_file_bytes {} while read", settings.max_file_bytes)));
}
let raw = String::from_utf8(bytes).map_err(|_| fail("not valid UTF-8".into()))?;
let text = if HTML_EXTENSIONS.contains(&ext) {
html_to_text(&raw)
} else if MARKDOWN_EXTENSIONS.contains(&ext) {
strip_front_matter(&raw).to_string()
} else {
raw
};
let content_hash = format!("{:016x}", stable_hash(&[&text]));
assert_eq!(content_hash.len(), 16, "hash is 16 hex chars");
Ok(LoadedFile { source, text, content_hash })
}
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly"))]
const O_NONBLOCK: i32 = 0x0004;
#[cfg(all(
any(target_os = "linux", target_os = "android"),
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")
))]
const O_NONBLOCK: i32 = 0o4000;
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")),
not(all(
any(target_os = "linux", target_os = "android"),
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")
))
))]
const O_NONBLOCK: i32 = 0;
#[cfg(windows)]
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
fn open_regular(path: &Path, follow: bool) -> Result<(fs::File, fs::Metadata), String> {
let mut options = fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
#[cfg(windows)]
if !follow {
std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, FILE_FLAG_OPEN_REPARSE_POINT);
}
#[cfg(not(windows))]
let _ = follow;
let file = options.open(path).map_err(|e| e.to_string())?;
let opened = file.metadata().map_err(|e| e.to_string())?;
if !opened.is_file() {
return Err("not a regular file".into());
}
Ok((file, opened))
}
#[cfg(unix)]
fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
use std::os::unix::fs::MetadataExt;
checked.dev() == opened.dev() && checked.ino() == opened.ino()
}
#[cfg(not(unix))]
fn same_file(checked: &fs::Metadata, opened: &fs::Metadata) -> bool {
checked.len() == opened.len() && checked.modified().ok() == opened.modified().ok()
}
fn strip_front_matter(text: &str) -> &str {
let Some(rest) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) else {
return text;
};
let mut offset = 0;
for line in rest.split_inclusive('\n') {
offset += line.len();
if line.trim_end_matches(['\r', '\n']) == "---" {
return &rest[offset..];
}
}
text
}
fn source_of(root: &Path, path: &Path) -> Result<String, ContextError> {
let relative = path.strip_prefix(root).expect("walked path is under the root");
let mut parts = Vec::new();
for component in relative.components() {
let Component::Normal(name) = component else {
unreachable!("read_dir yields plain names only");
};
let name = name.to_str().ok_or_else(|| ContextError::Invalid(format!("{}: name is not UTF-8", relative.to_string_lossy())))?;
parts.push(name);
}
assert!(!parts.is_empty(), "a file has a name");
Ok(parts.join("/"))
}
fn invalid(root: &Path, path: &Path, why: &str) -> ContextError {
let shown = path.strip_prefix(root).map_or_else(|_| String::from("."), |p| p.to_string_lossy().into_owned());
let shown = if shown.is_empty() { String::from(".") } else { shown };
ContextError::Invalid(format!("{shown}: {why}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly",
all(
any(target_os = "linux", target_os = "android"),
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")
)
))]
#[test]
fn open_regular_refuses_a_fifo_without_blocking() {
let dir = tempfile::tempdir().unwrap();
let fifo = dir.path().join("swapped.txt");
assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(open_regular(&fifo, false).map(|_| ())).unwrap());
let result = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("open blocked on a FIFO");
assert!(matches!(result, Err(ref why) if why.contains("not a regular file")), "{result:?}");
}
#[test]
fn open_regular_reads_a_regular_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("plain.txt");
fs::write(&file, "text").unwrap();
let (_, opened) = open_regular(&file, false).unwrap();
assert_eq!(opened.len(), 4);
}
#[cfg(windows)]
#[test]
fn open_regular_refuses_a_symlink_unless_followed() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("target.txt");
fs::write(&target, "text").unwrap();
let link = dir.path().join("link.txt");
std::os::windows::fs::symlink_file(&target, &link).unwrap();
let result = open_regular(&link, false).map(|_| ());
assert!(matches!(result, Err(ref why) if why.contains("not a regular file")), "{result:?}");
let (_, opened) = open_regular(&link, true).unwrap();
assert_eq!(opened.len(), 4);
}
#[test]
fn front_matter_needs_a_closing_line() {
assert_eq!(strip_front_matter("---\ntitle: a\n---\nbody"), "body");
assert_eq!(strip_front_matter("---\r\ntitle: a\r\n---\r\nbody"), "body");
assert_eq!(strip_front_matter("---\nno close"), "---\nno close");
assert_eq!(strip_front_matter("body\n---\nx\n---\n"), "body\n---\nx\n---\n");
}
}