1use std::io;
2use std::path::{Path, PathBuf};
3use std::string::String;
4
5use thiserror::Error;
6
7#[derive(Clone, Debug, Eq, Hash, PartialEq)]
9pub struct File {
10 path: PathBuf,
11 text: String,
12}
13
14impl File {
15 pub fn from_path(path: PathBuf, root: Option<&Path>) -> Result<Self, FileFromPathError> {
17 use std::fs;
18 let content = match root {
19 Some(root) => fs::read_to_string(root.join(&path)),
20 None => fs::read_to_string(&path),
21 };
22 match content {
23 Ok(text) => Ok(Self { path, text }),
24 Err(err) => Err(FileFromPathError::IoError { err, path }),
25 }
26 }
27
28 pub fn from_path_and_text(path: PathBuf, text: String) -> Self {
30 Self { path, text }
31 }
32
33 pub fn text(&self) -> &str {
35 &self.text
36 }
37
38 pub fn path(&self) -> &Path {
40 &self.path
41 }
42}
43
44#[derive(Debug, Error)]
46pub enum FileFromPathError {
47 #[error("Failed to read file at `{path}`: {err}")]
49 IoError {
50 path: PathBuf,
52 #[source]
54 err: io::Error,
55 },
56}