refactor: stream input documents

This commit is contained in:
Dandaedre 2026-09-29 12:31:06 +02:00
parent b54c03744b
commit 648a4d50cb
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
12 changed files with 386 additions and 387 deletions

View File

@ -9,8 +9,8 @@ or assign an authorship probability.
The repository currently contains proof-of-concept code that:
- reads UTF-8 text from a file or recursively from a directory;
- reads text entries from ZIP-based files, including `.zip`, `.docx`, `.xlsx`,
- streams UTF-8 text from a file or recursively from a directory;
- streams text entries from ZIP-based files, including `.zip`, `.docx`, `.xlsx`,
and `.pptx`;
- rejects missing paths and invalid UTF-8 with a diagnostic error;
- detects a configured-in-code set of hyphen-like Unicode characters; and
@ -24,6 +24,8 @@ by the planned Clap-based detector binary during Milestone 1.
Reusable consumers should call the library facade: `load_config`,
`analyze_source`, `plan_replacements`, and `read_inputs`. Replacement planning is
pure and shares the exact resolved configuration used by analysis.
Input iteration yields a separate result per document, so a bad directory entry
does not discard successfully read siblings.
The implementation is being restructured into a reusable library plus detector,
formatter, and LSP binaries. See [tasks.md](tasks.md) for the ordered backlog and

101
src/input/archive.rs Normal file
View File

@ -0,0 +1,101 @@
//! Streaming ZIP-based archive input.
use std::{fs::File, io::Read, path::PathBuf};
use miette::{IntoDiagnostic, Result, WrapErr};
use zip::ZipArchive;
use crate::{SourceId, input::Document};
/// Iterator over text members in one ZIP archive.
pub(super) struct ArchiveDocuments {
/// Outer archive identity.
outer: PathBuf,
/// Open ZIP reader retained between iterator calls.
archive: ZipArchive<File>,
/// Index of the next member to inspect.
index: usize,
}
impl std::fmt::Debug for ArchiveDocuments {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ArchiveDocuments")
.field("outer", &self.outer)
.field("members", &self.archive.len())
.field("index", &self.index)
.finish()
}
}
impl ArchiveDocuments {
/// Open an archive for streaming member reads.
pub(super) fn open(outer: PathBuf) -> Result<Self> {
let file = File::open(&outer)
.into_diagnostic()
.wrap_err_with(|| format!("failed to open ZIP `{}`", outer.display()))?;
let archive = ZipArchive::new(file)
.into_diagnostic()
.wrap_err_with(|| format!("failed to parse ZIP `{}`", outer.display()))?;
Ok(Self {
outer,
archive,
index: 0,
})
}
}
impl Iterator for ArchiveDocuments {
type Item = Result<Document>;
fn next(&mut self) -> Option<Self::Item> {
while self.index < self.archive.len() {
let index = self.index;
self.index += 1;
let mut member = match self
.archive
.by_index(index)
.into_diagnostic()
.wrap_err_with(|| {
format!(
"failed to read member {index} from `{}`",
self.outer.display()
)
}) {
Ok(member) => member,
Err(error) => return Some(Err(error)),
};
if member.is_dir() {
continue;
}
let name = PathBuf::from(member.name());
let mut content = String::new();
if let Err(error) = member
.read_to_string(&mut content)
.into_diagnostic()
.wrap_err_with(|| {
format!(
"failed to read member `{}` from `{}` as UTF-8 text",
name.display(),
self.outer.display()
)
})
{
return Some(Err(error));
}
return Some(Ok(Document {
source: SourceId::ArchiveMember {
archive: self.outer.clone(),
member: name,
},
content,
}));
}
None
}
}

12
src/input/file.rs Normal file
View File

@ -0,0 +1,12 @@
//! Regular-file input support.
use std::{fs, path::Path};
use miette::{IntoDiagnostic, Result, WrapErr};
/// Read a regular file as strict UTF-8 text.
pub(super) fn read_text(path: &Path) -> Result<String> {
fs::read_to_string(path)
.into_diagnostic()
.wrap_err_with(|| format!("failed to read `{}` as UTF-8 text", path.display()))
}

97
src/input/mod.rs Normal file
View File

@ -0,0 +1,97 @@
//! Streaming input acquisition for files, directories, and ZIP containers.
#[cfg(test)]
mod tests;
mod archive;
mod file;
mod walk;
use std::{path::Path, vec};
use miette::{Result, miette};
use crate::SourceId;
use self::{archive::ArchiveDocuments, walk::WalkDocuments};
/// One strict UTF-8 source document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document {
/// Stable identity of the file or archive member.
pub source: SourceId,
/// Complete UTF-8 content of this document.
pub content: String,
}
/// Streaming documents produced from one requested path.
#[derive(Debug)]
pub struct Documents {
/// Input-specific iterator implementation.
inner: DocumentsInner,
}
/// Private iterator variants hidden behind the stable public wrapper.
#[derive(Debug)]
enum DocumentsInner {
/// One regular-file result.
File(vec::IntoIter<Result<Document>>),
/// Recursive directory results.
Directory(WalkDocuments),
/// ZIP member results.
Archive(ArchiveDocuments),
}
impl Iterator for Documents {
type Item = Result<Document>;
fn next(&mut self) -> Option<Self::Item> {
match &mut self.inner {
DocumentsInner::File(document) => document.next(),
DocumentsInner::Directory(documents) => documents.next(),
DocumentsInner::Archive(documents) => documents.next(),
}
}
}
/// Open a file, directory, or recognized ZIP-based container for streaming.
pub fn read(path: &Path) -> Result<Documents> {
if path.is_file() {
if has_zip_extension(path) {
return ArchiveDocuments::open(path.to_path_buf()).map(|archive| Documents {
inner: DocumentsInner::Archive(archive),
});
}
let result = file::read_text(path).map(|content| Document {
source: SourceId::File(path.to_path_buf()),
content,
});
return Ok(Documents {
inner: DocumentsInner::File(vec![result].into_iter()),
});
}
if path.is_dir() {
return Ok(Documents {
inner: DocumentsInner::Directory(WalkDocuments::new(path)),
});
}
Err(miette!(
"path `{}` is neither a file nor a directory",
path.display()
))
}
/// Whether a path has an extension treated as a ZIP container.
fn has_zip_extension(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"zip" | "docx" | "xlsx" | "pptx"
)
})
}

100
src/input/tests.rs Normal file
View File

@ -0,0 +1,100 @@
use std::{
fs::{self, File},
io::Write,
path::Path,
};
use tempfile::tempdir;
use zip::write::FileOptions;
use super::*;
fn write_file(path: &Path, content: &str) {
let mut file = File::create(path).expect("create fixture");
file.write_all(content.as_bytes()).expect("write fixture");
}
fn create_zip(path: &Path) -> std::io::Result<()> {
let file = File::create(path)?;
let mut zip = zip::ZipWriter::new(file);
let options: FileOptions<()> = FileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
zip.start_file("foo.txt", options)?;
zip.write_all(b"hello foo")?;
zip.start_file("bar.txt", options)?;
zip.write_all(b"hello bar")?;
zip.finish()?;
Ok(())
}
#[test]
fn reads_one_file() {
let directory = tempdir().expect("temp dir");
let path = directory.path().join("test.txt");
write_file(&path, "line1\nline2");
let documents = read(&path)
.expect("open input")
.collect::<Result<Vec<_>>>()
.expect("read input");
assert_eq!(documents.len(), 1);
assert_eq!(documents[0].source, SourceId::File(path));
assert_eq!(documents[0].content, "line1\nline2");
}
#[test]
fn yields_a_directory_error_without_discarding_other_files() {
let directory = tempdir().expect("temp dir");
write_file(&directory.path().join("a.txt"), "a");
fs::write(directory.path().join("b.txt"), [0xff]).expect("write invalid fixture");
write_file(&directory.path().join("c.txt"), "c");
let results = read(directory.path())
.expect("open directory")
.collect::<Vec<_>>();
assert_eq!(results.len(), 3);
assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 2);
assert_eq!(results.iter().filter(|result| result.is_err()).count(), 1);
}
#[test]
fn streams_archive_members_with_outer_identity() {
let directory = tempdir().expect("temp dir");
let path = directory.path().join("archive.zip");
create_zip(&path).expect("create zip");
let documents = read(&path)
.expect("open archive")
.collect::<Result<Vec<_>>>()
.expect("read archive");
assert_eq!(documents.len(), 2);
assert!(documents.iter().all(|document| matches!(
&document.source,
SourceId::ArchiveMember { archive, .. } if archive == &path
)));
}
#[test]
fn invalid_utf8_is_a_per_document_error() {
let directory = tempdir().expect("temp dir");
let path = directory.path().join("invalid.txt");
fs::write(&path, [0xff, 0xfe]).expect("write fixture");
let mut documents = read(&path).expect("open input");
assert!(documents.next().expect("one result").is_err());
assert!(documents.next().is_none());
}
#[test]
fn missing_path_is_rejected() {
let directory = tempdir().expect("temp dir");
let path = directory.path().join("missing.txt");
let error = read(&path).expect_err("missing input should fail");
assert!(error.to_string().contains("neither a file nor a directory"));
}

54
src/input/walk.rs Normal file
View File

@ -0,0 +1,54 @@
//! Streaming directory traversal.
use std::path::Path;
use miette::{IntoDiagnostic, Result, WrapErr};
use walkdir::{IntoIter, WalkDir};
use crate::{SourceId, input::Document};
/// Iterator over readable regular files below a directory.
#[derive(Debug)]
pub(super) struct WalkDocuments {
/// Underlying streaming directory iterator.
entries: IntoIter,
}
impl WalkDocuments {
/// Begin a recursive walk without following symbolic links.
pub(super) fn new(root: &Path) -> Self {
Self {
entries: WalkDir::new(root).follow_links(false).into_iter(),
}
}
}
impl Iterator for WalkDocuments {
type Item = Result<Document>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let entry = match self.entries.next()? {
Ok(entry) => entry,
Err(error) => return Some(Err(error).into_diagnostic()),
};
if !entry.file_type().is_file() {
continue;
}
let path = entry.into_path();
let content = match std::fs::read_to_string(&path)
.into_diagnostic()
.wrap_err_with(|| format!("failed to read `{}` as UTF-8 text", path.display()))
{
Ok(content) => content,
Err(error) => return Some(Err(error)),
};
return Some(Ok(Document {
source: SourceId::File(path),
content,
}));
}
}
}

View File

@ -7,13 +7,13 @@ use std::path::Path;
mod config;
mod detector;
mod input;
mod model;
mod reader;
mod replacement;
pub use config::{Config, ReplacementRule};
pub use input::{Document, Documents};
pub use model::{Analysis, Category, Confidence, Finding, RuleId, SourceId, TextEdit};
pub use reader::{FileContent, FileDescriptorIterator};
/// Load the configuration embedded in this build.
///
@ -34,8 +34,8 @@ pub fn plan_replacements(config: &Config, source: &str) -> Vec<TextEdit> {
}
/// Read documents from a file, directory, or supported ZIP-based container.
pub fn read_inputs(path: &Path) -> miette::Result<FileDescriptorIterator> {
reader::universal_read(path)
pub fn read_inputs(path: &Path) -> miette::Result<Documents> {
input::read(path)
}
#[cfg(test)]

View File

@ -19,7 +19,7 @@ fn main() -> Result<()> {
let analysis = analyze_source(&config, &document.content);
println!(
"{}: confidence {}, {} finding(s)",
document.path.display(),
document.source,
analysis.confidence.score(),
analysis.findings.len()
);

View File

@ -71,6 +71,18 @@ pub enum SourceId {
},
}
impl fmt::Display for SourceId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stdin => formatter.write_str("<stdin>"),
Self::File(path) => path.display().fmt(formatter),
Self::ArchiveMember { archive, member } => {
write!(formatter, "{}::{}", archive.display(), member.display())
}
}
}
}
/// A non-overlapping replacement against an analyzed source snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {

View File

@ -1,254 +0,0 @@
//! # Multimode reader
//!
//! This module implements a *very* small proof‑of‑concept file reader that can handle
//! individual files, directories and simple ZIP‑based archives (e.g. DOCX, XLSX,
//! …). The public API is intentionally minimal – just enough to
//! demonstrate how you can read a file line‑by‑line or perform a
//! search‑&‑replace operation.
//!
//! The key types are:
//! * `FileDescriptorIterator` – an iterator that yields a `FileContent` for every
//! readable file found under a given path.
//! * `FileContent` – a tiny wrapper that keeps the file’s path and its
//! entire textual content.
//!
//! The helper functions below give a quick way to read a single file, walk a
//! directory or unpack a ZIP archive. All functions return `miette::Result` so
//! that any error can be displayed in a user‑friendly way.
#[cfg(test)]
mod tests;
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
};
use miette::{Result, miette};
use walkdir::WalkDir;
use zip::ZipArchive;
/// Information about a single file.
///
/// * `path` – the absolute (or relative) path to the file.
/// * `content` – the file’s content as a UTF‑8 string.
///
/// The struct is intentionally lightweight; for the POC we only store the
/// contents as a `String`. In a real‑world library you might want to keep a
/// reader instead of the whole string.
#[derive(Debug, Clone)]
pub struct FileContent {
/// Path of the source file or archive entry.
pub path: PathBuf,
/// Complete UTF-8 text read from the source.
pub content: String,
}
/// Iterator over files found under a path.
///
/// The iterator will return one `FileContent` per file. It is intentionally
/// simple – it holds all file descriptors in a vector and yields them one by
/// one. This makes it easy to use in a `for` loop while still keeping the
/// implementation short.
#[derive(Debug)]
pub struct FileDescriptorIterator {
/// Documents that have already been loaded by the proof-of-concept reader.
files: Vec<FileContent>,
/// Index of the next document to yield.
index: usize,
}
impl FileDescriptorIterator {
/// Create a new iterator from a vector of `FileContent`s.
pub fn new(files: Vec<FileContent>) -> Self {
Self { files, index: 0 }
}
/// Return the number of files that will be yielded.
pub fn len(&self) -> usize {
self.files.len()
}
/// Return `true` if the iterator has no more items.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Iterator for FileDescriptorIterator {
type Item = Result<FileContent>;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.files.len() {
return None;
}
let res = self.files[self.index].clone();
self.index += 1;
Some(Ok(res))
}
}
/// Universal reader.
///
/// * `file_path` – a path that can point to a file, a directory or a ZIP
/// archive.
/// * Returns a `FileDescriptorIterator` that yields the files contained in the
/// input. If the input is a plain file, the iterator will contain a single
/// element.
///
/// The function recognises ZIP files by their extension (`.zip`, `.docx`,
/// `.xlsx`, …). If the file is not a recognised ZIP format it is treated as
/// a plain file.
///
/// Errors are wrapped with `miette` so that they can be printed nicely to the
/// console.
pub fn universal_read(file_path: &Path) -> Result<FileDescriptorIterator> {
if file_path.is_file() {
// If the file looks like a zip we handle it specially
if is_zip(file_path) {
let zip_files = read_zip(file_path)?;
return Ok(FileDescriptorIterator::new(zip_files));
}
// Plain file – just read it
let content = read_file(file_path)?;
return Ok(FileDescriptorIterator::new(vec![FileContent {
path: file_path.to_path_buf(),
content,
}]));
}
if file_path.is_dir() {
let dir_files = read_folder(file_path)?;
return Ok(FileDescriptorIterator::new(dir_files));
}
Err(miette!(
"The path `{}` is neither a file, a directory nor a recognised zip archive",
file_path.display()
))
}
/// Read a single file into a `String`.
///
/// The file is opened and its content is read as UTF‑8. If the file contains
/// non‑UTF‑8 data an error is returned.
pub fn read_file(file_path: &Path) -> Result<String> {
let mut file = File::open(file_path)
.map_err(|e| miette!("Failed to open `{}`: {}", file_path.display(), e))?;
let mut content = String::new();
file.read_to_string(&mut content)
.map_err(|e| miette!("Failed to read `{}`: {}", file_path.display(), e))?;
Ok(content)
}
/// Recursively walk a directory and read all regular files.
///
/// The function returns a `Vec<FileContent>` where each element contains the
/// path and the full textual content of a file. Hidden files and directories
/// are *not* filtered out – they are processed like any other entry.
pub fn read_folder(dir_path: &Path) -> Result<Vec<FileContent>> {
let mut files = Vec::new();
for entry in WalkDir::new(dir_path)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
{
let path = entry.path().to_path_buf();
let content = read_file(&path)?;
files.push(FileContent { path, content });
}
Ok(files)
}
/// Return `true` if the file has an extension that we treat as a ZIP archive.
/// For simplicity we just check the first part of the extension (e.g. “zip”
/// for “docx”).
fn is_zip(path: &Path) -> bool {
path.extension()
.and_then(|s| s.to_str())
.map(|ext| {
let ext_lower = ext.to_ascii_lowercase();
ext_lower == "zip" || ext_lower == "docx" || ext_lower == "xlsx" || ext_lower == "pptx"
})
.unwrap_or(false)
}
/// Read all entries from a ZIP archive.
///
/// The function extracts each entry’s name and content. If an entry is a
/// directory it is ignored – only regular files are returned.
///
/// The ZIP file must contain text files. For non‑text files you would need
/// a more sophisticated approach (e.g. decoding binary data or using a
/// specific codec).
pub fn read_zip(zip_path: &Path) -> Result<Vec<FileContent>> {
let file = File::open(zip_path)
.map_err(|e| miette!("Failed to open ZIP `{}`: {}", zip_path.display(), e))?;
let mut archive = ZipArchive::new(file)
.map_err(|e| miette!("Failed to read ZIP `{}`: {}", zip_path.display(), e))?;
let mut files = Vec::new();
for i in 0..archive.len() {
let mut entry = archive.by_index(i).map_err(|e| {
miette!(
"Failed to read entry {} in `{}`: {}",
i,
zip_path.display(),
e
)
})?;
// Skip directories
if entry.is_dir() {
continue;
}
let mut content = String::new();
entry.read_to_string(&mut content).map_err(|e| {
miette!(
"Failed to read entry `{}` in `{}`: {}",
entry.name(),
zip_path.display(),
e
)
})?;
files.push(FileContent {
path: PathBuf::from(entry.name()),
content,
});
}
Ok(files)
}
/// Search‑and‑replace in a single file.
///
/// The function reads the file, replaces all occurrences of `target` with
/// `replacement` and writes the modified text back to the original file.
/// If the file cannot be read or written an error is returned.
///
/// # Examples
///
/// ```ignore
/// let path = Path::new("example.txt");
/// replace_in_file(path, "foo", "bar")?;
/// ```
#[cfg(test)]
pub fn replace_in_file(path: &Path, target: &str, replacement: &str) -> Result<()> {
use std::io::Write;
let content = read_file(path)?;
let new_content = content.replace(target, replacement);
let mut file = File::create(path)
.map_err(|e| miette!("Failed to open `{}` for writing: {}", path.display(), e))?;
file.write_all(new_content.as_bytes())
.map_err(|e| miette!("Failed to write `{}`: {}", path.display(), e))?;
Ok(())
}

View File

@ -1,125 +0,0 @@
use super::*;
use std::fs::{self, File};
use std::io::Write;
use tempfile::tempdir;
use zip::write::FileOptions;
/// Helper to write a file with the given content
fn write_file(path: &Path, content: &str) {
let mut f = File::create(path).expect("unable to create test file");
f.write_all(content.as_bytes())
.expect("unable to write test file");
}
/// Create a small ZIP file containing two text entries.
fn create_zip(path: &Path) -> std::io::Result<()> {
let file = File::create(path)?;
let mut zip = zip::ZipWriter::new(file);
let options: FileOptions<()> = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
zip.start_file("foo.txt", options)?;
zip.write_all(b"hello foo")?;
zip.start_file("bar.txt", options)?;
zip.write_all(b"hello bar")?;
zip.finish()?;
Ok(())
}
#[test]
fn test_read_single_file() {
let dir = tempdir().expect("temp dir");
let file_path = dir.path().join("test.txt");
write_file(&file_path, "line1\nline2");
let it = universal_read(&file_path).expect("universal_read");
let mut collected = Vec::new();
for r in it {
collected.push(r.expect("file read"));
}
assert_eq!(collected.len(), 1);
assert_eq!(collected[0].path, file_path);
assert_eq!(collected[0].content, "line1\nline2");
}
#[test]
fn test_read_file_rejects_invalid_utf8() {
let dir = tempdir().expect("temp dir");
let file_path = dir.path().join("invalid.txt");
fs::write(&file_path, [0xff, 0xfe, 0xfd]).expect("write invalid UTF-8 fixture");
let error = read_file(&file_path).expect_err("invalid UTF-8 should fail");
assert!(
error.to_string().contains("Failed to read"),
"unexpected error: {error}"
);
assert!(
error
.to_string()
.contains("stream did not contain valid UTF-8"),
"unexpected error: {error}"
);
}
#[test]
fn test_universal_read_rejects_missing_path() {
let dir = tempdir().expect("temp dir");
let missing_path = dir.path().join("missing.txt");
let error = universal_read(&missing_path).expect_err("missing path should fail");
assert_eq!(
error.to_string(),
format!(
"The path `{}` is neither a file, a directory nor a recognised zip archive",
missing_path.display()
)
);
}
#[test]
fn test_read_folder() {
let dir = tempdir().expect("temp dir");
let sub = dir.path().join("sub");
fs::create_dir(&sub).expect("mkdir");
write_file(&dir.path().join("a.txt"), "a");
write_file(&sub.join("b.txt"), "b");
let it = universal_read(dir.path()).expect("universal_read");
let mut paths: Vec<PathBuf> = it.map(|r| r.expect("file read").path).collect();
paths.sort();
assert_eq!(paths, vec![dir.path().join("a.txt"), sub.join("b.txt")]);
}
#[test]
fn test_read_zip() {
let dir = tempdir().expect("temp dir");
let zip_path = dir.path().join("archive.zip");
create_zip(&zip_path).expect("create zip");
let it = universal_read(&zip_path).expect("universal_read");
let mut entries: Vec<String> = it.map(|r| r.expect("file read").content).collect();
entries.sort();
assert_eq!(
entries,
vec!["hello bar".to_string(), "hello foo".to_string()]
);
}
#[test]
fn test_replace_in_file() {
let dir = tempdir().expect("temp dir");
let file_path = dir.path().join("sample.txt");
write_file(&file_path, "foo bar foo");
replace_in_file(&file_path, "foo", "baz").expect("replace");
let content = read_file(&file_path).expect("read");
assert_eq!(content, "baz bar baz");
}

View File

@ -49,7 +49,7 @@ are written down, and a clean baseline passes all quality gates.
source, planning replacements, and reading inputs.
- [x] Replace demo functions and ad hoc errors in `main.rs` with typed domain
values (`SourceId`, `Finding`, `Analysis`, `Confidence`, `TextEdit`).
- [ ] Split `reader.rs` into `input/file.rs`, `input/walk.rs`, and
- [x] Split `reader.rs` into `input/file.rs`, `input/walk.rs`, and
`input/archive.rs`; yield one `Result<Document, InputError>` at a time rather
than loading a directory into a `Vec`.
- [ ] Preserve outer and inner archive identities. Prevent path traversal and