grits_core/
fs.rs

1use anyhow::Result;
2use std::io::{BufRead, Write};
3use std::path::Path;
4
5pub trait FileSystem {
6    fn read_to_string(&self, path: &Path) -> Result<String>;
7    fn write(&self, path: &Path, contents: &[u8]) -> Result<()>;
8    fn create_dir_all(&self, path: &Path) -> Result<()>;
9    fn rename(&self, from: &Path, to: &Path) -> Result<()>;
10    fn exists(&self, path: &Path) -> bool;
11    fn open_read(&self, path: &Path) -> Result<Box<dyn BufRead>>;
12    fn open_write(&self, path: &Path) -> Result<Box<dyn Write>>;
13}
14
15#[cfg(not(target_arch = "wasm32"))]
16pub struct StdFileSystem;
17
18#[cfg(not(target_arch = "wasm32"))]
19impl FileSystem for StdFileSystem {
20    fn read_to_string(&self, path: &Path) -> Result<String> {
21        Ok(std::fs::read_to_string(path)?)
22    }
23
24    fn write(&self, path: &Path, contents: &[u8]) -> Result<()> {
25        std::fs::write(path, contents)?;
26        Ok(())
27    }
28
29    fn create_dir_all(&self, path: &Path) -> Result<()> {
30        std::fs::create_dir_all(path)?;
31        Ok(())
32    }
33
34    fn rename(&self, from: &Path, to: &Path) -> Result<()> {
35        std::fs::rename(from, to)?;
36        Ok(())
37    }
38
39    fn exists(&self, path: &Path) -> bool {
40        path.exists()
41    }
42
43    fn open_read(&self, path: &Path) -> Result<Box<dyn BufRead>> {
44        use std::io::BufReader;
45        let file = std::fs::File::open(path)?;
46        Ok(Box::new(BufReader::new(file)))
47    }
48
49    fn open_write(&self, path: &Path) -> Result<Box<dyn Write>> {
50        let file = std::fs::File::create(path)?;
51        Ok(Box::new(file))
52    }
53}