readme_sync/
file.rs

1use std::io;
2use std::path::{Path, PathBuf};
3use std::string::String;
4
5use thiserror::Error;
6
7/// File path and its contents.
8#[derive(Clone, Debug, Eq, Hash, PartialEq)]
9pub struct File {
10    path: PathBuf,
11    text: String,
12}
13
14impl File {
15    /// Reads file from the specified path.
16    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    /// Creates file from the specified path and text.
29    pub fn from_path_and_text(path: PathBuf, text: String) -> Self {
30        Self { path, text }
31    }
32
33    /// Returns file text.
34    pub fn text(&self) -> &str {
35        &self.text
36    }
37
38    /// Returns file path.
39    pub fn path(&self) -> &Path {
40        &self.path
41    }
42}
43
44/// An error which can occur when reading a file from the specified path.
45#[derive(Debug, Error)]
46pub enum FileFromPathError {
47    /// File reading failed.
48    #[error("Failed to read file at `{path}`: {err}")]
49    IoError {
50        /// File path.
51        path: PathBuf,
52        /// Rust `io::Error`.
53        #[source]
54        err: io::Error,
55    },
56}