Skip to main content

indigo_core/
fs.rs

1//! Abstract filesystem interface.
2
3use crate::IndigoBuildHasher;
4use anyhow::{Context as _, anyhow};
5use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
6use std::{
7    collections::HashMap,
8    env, fs,
9    sync::{Arc, Mutex},
10};
11
12pub trait Fs {
13    fn read(&self, path: &Utf8Path) -> anyhow::Result<Vec<u8>>;
14
15    fn write(&self, path: &Utf8Path, bytes: &[u8]) -> anyhow::Result<()>;
16
17    fn exists(&self, path: &Utf8Path) -> anyhow::Result<bool>;
18}
19
20const _ASSERT_FS_IS_DYN_COMPATIBLE: Option<&dyn Fs> = None;
21
22impl<T: Fs + ?Sized> Fs for Arc<T> {
23    fn read(&self, path: &Utf8Path) -> anyhow::Result<Vec<u8>> {
24        T::read(self, path)
25    }
26    fn write(&self, path: &Utf8Path, bytes: &[u8]) -> anyhow::Result<()> {
27        T::write(self, path, bytes)
28    }
29    fn exists(&self, path: &Utf8Path) -> anyhow::Result<bool> {
30        T::exists(self, path)
31    }
32}
33
34/// Trivial filesystem implementation that panics if you do anything. This is the default filesystem
35/// implementation for `Server`.
36pub struct NoFs;
37
38impl Fs for NoFs {
39    fn read(&self, _path: &Utf8Path) -> anyhow::Result<Vec<u8>> {
40        panic!("No filesystem implementation configured");
41    }
42
43    fn write(&self, _path: &Utf8Path, _bytes: &[u8]) -> anyhow::Result<()> {
44        panic!("No filesystem implementation configured");
45    }
46
47    fn exists(&self, _path: &Utf8Path) -> anyhow::Result<bool> {
48        panic!("No filesystem implementation configured");
49    }
50}
51
52/// Real filesystem implementation that uses functions from `std::fs`.
53pub struct RealFs;
54
55impl Fs for RealFs {
56    fn read(&self, path: &Utf8Path) -> anyhow::Result<Vec<u8>> {
57        Ok(fs::read(path)?)
58    }
59
60    fn write(&self, path: &Utf8Path, bytes: &[u8]) -> anyhow::Result<()> {
61        Ok(fs::write(path, bytes)?)
62    }
63
64    fn exists(&self, path: &Utf8Path) -> anyhow::Result<bool> {
65        Ok(fs::exists(path)?)
66    }
67}
68
69/// In-memory filesystem implementation for testing. Currently only supports canonicalized paths
70/// (i.e. absolute, normalized, and no symlinks).
71#[derive(Default)]
72pub struct TestFs {
73    pub files: Arc<Mutex<HashMap<Utf8PathBuf, Vec<u8>, IndigoBuildHasher>>>,
74}
75
76impl Fs for TestFs {
77    fn read(&self, path: &Utf8Path) -> anyhow::Result<Vec<u8>> {
78        let files = self.files.lock().unwrap();
79        if let Some(bytes) = files.get(path) {
80            Ok(bytes.clone())
81        } else {
82            Err(anyhow!("File not found: `{path}`"))
83        }
84    }
85
86    fn write(&self, path: &Utf8Path, bytes: &[u8]) -> anyhow::Result<()> {
87        let mut files = self.files.lock().unwrap();
88        files.insert(path.to_path_buf(), bytes.to_vec());
89        Ok(())
90    }
91
92    fn exists(&self, path: &Utf8Path) -> anyhow::Result<bool> {
93        let files = self.files.lock().unwrap();
94        let exists = files.contains_key(path);
95        Ok(exists)
96    }
97}
98
99pub fn home_dir() -> anyhow::Result<Utf8PathBuf> {
100    let home = env::home_dir().context("Failed to get home directory")?;
101    let home = Utf8PathBuf::try_from(home)?;
102    anyhow::ensure!(
103        home.is_absolute(),
104        "Home directory is not absolute: `{home}`"
105    );
106    Ok(home)
107}
108
109pub fn pwd() -> anyhow::Result<Utf8PathBuf> {
110    // Try to use the shell's `$PWD` (doesn't resolve symlinks) if possible
111    let unix_cwd = Utf8PathBuf::try_from(env::current_dir()?)?;
112    let Ok(shell_pwd) = env::var("PWD").map(Utf8PathBuf::from) else {
113        // Missing or not UTF-8
114        return Ok(unix_cwd);
115    };
116    if !shell_pwd.is_absolute() {
117        // Not absolute
118        return Ok(unix_cwd);
119    }
120    if shell_pwd
121        .components()
122        .any(|c| c == Utf8Component::ParentDir)
123    {
124        // Not normalized
125        return Ok(unix_cwd);
126    }
127    if !fs::canonicalize(&shell_pwd).is_ok_and(|pwd| pwd == unix_cwd) {
128        // Stale
129        return Ok(unix_cwd);
130    }
131    Ok(shell_pwd)
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn test() -> anyhow::Result<()> {
140        let fs = TestFs::default();
141        fs.write("foo.rs".into(), b"fn foo() {}")?;
142        fs.write("bar.rs".into(), b"fn bar() {}")?;
143        assert!(fs.exists("foo.rs".into())?);
144        assert_eq!(&fs.read("foo.rs".into())?, b"fn foo() {}");
145        assert_eq!(&fs.read("bar.rs".into())?, b"fn bar() {}");
146        assert!(fs.read("baz.rs".into()).is_err());
147        assert!(!fs.exists("baz.rs".into())?);
148        fs.write("foo.rs".into(), b"fn foo() { panic!() }")?;
149        assert_eq!(&fs.read("foo.rs".into())?, b"fn foo() { panic!() }");
150        Ok(())
151    }
152}