hopr_platform/
file.rs

1pub mod native {
2    use std::{
3        fs,
4        path::{Path, PathBuf},
5    };
6
7    use crate::error::{PlatformError, Result};
8
9    pub fn read_to_string(file_path: &str) -> Result<String> {
10        fs::read_to_string(file_path).map_err(|e| {
11            PlatformError::GeneralError(format!("Failed to read the file '{}' with error: {}", file_path, e))
12        })
13    }
14
15    pub fn read_file(file_path: &str) -> Result<Box<[u8]>> {
16        match fs::read(file_path) {
17            Ok(buf) => Ok(Box::from(buf)),
18            Err(e) => Err(PlatformError::GeneralError(format!(
19                "Failed to read the file '{}' with error: {}",
20                file_path, e
21            ))),
22        }
23    }
24
25    pub fn join(components: &[&str]) -> Result<String> {
26        let mut path = PathBuf::new();
27
28        for component in components.iter() {
29            path.push(component);
30        }
31
32        match path.to_str().map(|p| p.to_owned()) {
33            Some(p) => Ok(p),
34            None => Err(PlatformError::GeneralError("Failed to stringify path".into())),
35        }
36    }
37
38    pub fn remove_dir_all(path: &std::path::Path) -> Result<()> {
39        fs::remove_dir_all(path).map_err(|e| PlatformError::GeneralError(e.to_string()))
40    }
41
42    pub fn write<R>(path: &str, contents: R) -> Result<()>
43    where
44        R: AsRef<[u8]>,
45    {
46        if let Some(parent_dir_path) = Path::new(path).parent() {
47            if !parent_dir_path.is_dir() {
48                fs::create_dir_all(parent_dir_path)
49                    .map_err(|e| PlatformError::GeneralError(format!("Failed to create dir '{}': {}", path, e)))?
50            }
51        }
52        fs::write(path, contents)
53            .map_err(|e| PlatformError::GeneralError(format!("Failed to write to file '{}': {}", path, e)))
54    }
55
56    pub fn metadata(path: &str) -> Result<()> {
57        match fs::metadata(path) {
58            Ok(_) => Ok(()), // currently not interested in details
59            Err(e) => Err(PlatformError::GeneralError(e.to_string())),
60        }
61    }
62}