use std::io;
use std::path::{Path, PathBuf};
use std::string::String;
use thiserror::Error;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File {
path: PathBuf,
text: String,
}
impl File {
pub fn from_path(path: PathBuf, root: Option<&Path>) -> Result<Self, FileFromPathError> {
use std::fs;
let content = match root {
Some(root) => fs::read_to_string(root.join(&path)),
None => fs::read_to_string(&path),
};
match content {
Ok(text) => Ok(Self { path, text }),
Err(err) => Err(FileFromPathError::IoError { err, path }),
}
}
pub fn from_path_and_text(path: PathBuf, text: String) -> Self {
Self { path, text }
}
pub fn text(&self) -> &str {
&self.text
}
pub fn path(&self) -> &Path {
&self.path
}
}
#[derive(Debug, Error)]
pub enum FileFromPathError {
#[error("Failed to read file at `{path}`: {err}")]
IoError {
path: PathBuf,
#[source]
err: io::Error,
},
}