Skip to main content

oneiros_fs/
lib.rs

1pub struct FileOps;
2
3impl FileOps {
4    pub fn ensure_dir(&self, path: impl AsRef<std::path::Path>) -> Result<(), std::io::Error> {
5        std::fs::create_dir_all(path)
6    }
7
8    pub fn read(&self, path: impl AsRef<std::path::Path>) -> Result<Vec<u8>, std::io::Error> {
9        std::fs::read(path)
10    }
11
12    pub fn read_to_string(
13        &self,
14        path: impl AsRef<std::path::Path>,
15    ) -> Result<String, std::io::Error> {
16        std::fs::read_to_string(path)
17    }
18
19    pub fn write(
20        &self,
21        path: impl AsRef<std::path::Path>,
22        contents: impl AsRef<[u8]>,
23    ) -> Result<(), std::io::Error> {
24        std::fs::write(path, contents)
25    }
26
27    pub fn append(
28        &self,
29        path: impl AsRef<std::path::Path>,
30        contents: impl AsRef<[u8]>,
31    ) -> Result<(), std::io::Error> {
32        use std::io::Write;
33        let mut file = std::fs::OpenOptions::new()
34            .create(true)
35            .append(true)
36            .open(path)?;
37        file.write_all(contents.as_ref())
38    }
39
40    pub fn contains(
41        &self,
42        path: impl AsRef<std::path::Path>,
43        pattern: &str,
44    ) -> Result<bool, std::io::Error> {
45        match std::fs::read_to_string(path) {
46            Ok(contents) => Ok(contents.contains(pattern)),
47            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
48            Err(e) => Err(e),
49        }
50    }
51}