files.rs
//! File helpers: reading a testmark document from disk.
//!
//! Free functions, not methods: `Document` itself has no notion of where its
//! text came from, and keeping I/O out of the document model keeps that model
//! pure. (The write-side helper, `write_back`, lives in the `check` module:
//! writing is only ever the return leg of a check-with-regen cycle.)
use std::fmt;
use std::path::{Path, PathBuf};
use crate::document::{Document, ParseError};
/// Read and parse a testmark file.
pub fn read_file(path: &Path) -> Result<Document, ReadFileError> {
let text = std::fs::read_to_string(path).map_err(|source| ReadFileError::Io {
path: path.to_path_buf(),
source,
})?;
Document::parse(&text).map_err(|source| ReadFileError::Parse {
path: path.to_path_buf(),
source,
})
}
/// Problems from [`read_file`].
#[derive(Debug)]
pub enum ReadFileError {
Io {
path: PathBuf,
source: std::io::Error,
},
Parse {
path: PathBuf,
source: ParseError,
},
}
impl fmt::Display for ReadFileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReadFileError::Io {
path,
source,
} => write!(f, "reading {}: {source}", path.display()),
ReadFileError::Parse {
path,
source,
} => write!(f, "{}: {source}", path.display()),
}
}
}
impl std::error::Error for ReadFileError {}
crates/testmark/src/files.rs · 1.3 KiB · 20c0b098ea