1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#[cfg(feature = "thiserror")]
use std::io;
use std::path::{Path, PathBuf};
use std::string::String;
#[cfg(feature = "thiserror")]
use thiserror::Error;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct File {
path: PathBuf,
text: String,
}
impl File {
#[cfg(feature = "thiserror")]
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 { text, path }
}
pub fn text(&self) -> &str {
&self.text
}
pub fn path(&self) -> &Path {
&self.path
}
}
#[cfg(feature = "thiserror")]
#[derive(Debug, Error)]
pub enum FileFromPathError {
#[error("Failed to read file at `{path}`: {err}")]
IoError {
path: PathBuf,
#[source]
err: io::Error,
},
}