hopr_platform/
file.rs

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