Skip to main content

base/interface/exec/in_process/
filesystem.rs

1//! A filesystem that is a map.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, Mutex};
6
7use crate::interface::exec::{DirEntry, ExecError, FileSystem, Metadata};
8
9/// A tree of files held in memory.
10///
11/// Cloning shares the tree, so a provider set handed to a tool and the handle
12/// a test keeps are the same filesystem.
13#[derive(Clone, Default)]
14pub struct InMemoryFileSystem {
15    files: Arc<Mutex<BTreeMap<PathBuf, Vec<u8>>>>,
16    dirs: Arc<Mutex<BTreeMap<PathBuf, ()>>>,
17}
18
19impl InMemoryFileSystem {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Seed a file, creating its parents.
25    pub fn with_file(self, path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Self {
26        let p = crate::path::normalize_lexically(path.as_ref());
27        self.mark_parents(&p);
28        self.files
29            .lock()
30            .unwrap_or_else(std::sync::PoisonError::into_inner)
31            .insert(p, contents.as_ref().to_vec());
32        self
33    }
34
35    /// What is in there now, for a test to assert against.
36    pub fn snapshot(&self) -> BTreeMap<PathBuf, Vec<u8>> {
37        self.files
38            .lock()
39            .unwrap_or_else(std::sync::PoisonError::into_inner)
40            .clone()
41    }
42
43    fn mark_parents(&self, path: &Path) {
44        let mut dirs = self
45            .dirs
46            .lock()
47            .unwrap_or_else(std::sync::PoisonError::into_inner);
48        let mut cur = path.parent();
49        while let Some(d) = cur {
50            if d.as_os_str().is_empty() {
51                break;
52            }
53            dirs.insert(d.to_path_buf(), ());
54            cur = d.parent();
55        }
56    }
57
58    fn is_dir(&self, path: &Path) -> bool {
59        self.dirs
60            .lock()
61            .unwrap_or_else(std::sync::PoisonError::into_inner)
62            .contains_key(path)
63    }
64}
65
66fn missing(path: &Path) -> ExecError {
67    ExecError::failed(format!("{}: no such file", path.display()))
68}
69
70#[async_trait::async_trait]
71impl FileSystem for InMemoryFileSystem {
72    async fn read(&self, path: &Path) -> Result<Vec<u8>, ExecError> {
73        let p = crate::path::normalize_lexically(path);
74        self.files
75            .lock()
76            .unwrap_or_else(std::sync::PoisonError::into_inner)
77            .get(&p)
78            .cloned()
79            .ok_or_else(|| missing(path))
80    }
81
82    async fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), ExecError> {
83        let p = crate::path::normalize_lexically(path);
84        self.mark_parents(&p);
85        self.files
86            .lock()
87            .unwrap_or_else(std::sync::PoisonError::into_inner)
88            .insert(p, bytes.to_vec());
89        Ok(())
90    }
91
92    async fn create_dir_all(&self, path: &Path) -> Result<(), ExecError> {
93        let p = crate::path::normalize_lexically(path);
94        self.dirs
95            .lock()
96            .unwrap_or_else(std::sync::PoisonError::into_inner)
97            .insert(p.clone(), ());
98        self.mark_parents(&p);
99        Ok(())
100    }
101
102    async fn read_dir(&self, path: &Path) -> Result<Vec<DirEntry>, ExecError> {
103        let p = crate::path::normalize_lexically(path);
104        if !self.is_dir(&p)
105            && !self
106                .files
107                .lock()
108                .unwrap_or_else(std::sync::PoisonError::into_inner)
109                .keys()
110                .any(|k| k.starts_with(&p))
111        {
112            return Err(missing(path));
113        }
114        let mut out: Vec<DirEntry> = Vec::new();
115        for k in self
116            .files
117            .lock()
118            .unwrap_or_else(std::sync::PoisonError::into_inner)
119            .keys()
120        {
121            if k.parent() == Some(p.as_path()) {
122                out.push(DirEntry {
123                    path: k.clone(),
124                    is_dir: false,
125                });
126            }
127        }
128        for d in self
129            .dirs
130            .lock()
131            .unwrap_or_else(std::sync::PoisonError::into_inner)
132            .keys()
133        {
134            if d.parent() == Some(p.as_path()) {
135                out.push(DirEntry {
136                    path: d.clone(),
137                    is_dir: true,
138                });
139            }
140        }
141        out.sort_by(|a, b| a.path.cmp(&b.path));
142        Ok(out)
143    }
144
145    async fn remove_dir_all(&self, path: &Path) -> Result<(), ExecError> {
146        let p = crate::path::normalize_lexically(path);
147        self.files
148            .lock()
149            .unwrap_or_else(std::sync::PoisonError::into_inner)
150            .retain(|k, _| !k.starts_with(&p));
151        self.dirs
152            .lock()
153            .unwrap_or_else(std::sync::PoisonError::into_inner)
154            .retain(|k, _| !k.starts_with(&p));
155        Ok(())
156    }
157
158    async fn metadata(&self, path: &Path) -> Result<Metadata, ExecError> {
159        let p = crate::path::normalize_lexically(path);
160        if let Some(bytes) = self
161            .files
162            .lock()
163            .unwrap_or_else(std::sync::PoisonError::into_inner)
164            .get(&p)
165        {
166            return Ok(Metadata {
167                is_dir: false,
168                is_file: true,
169                is_symlink: false,
170                len: bytes.len() as u64,
171            });
172        }
173        if self.is_dir(&p) {
174            return Ok(Metadata {
175                is_dir: true,
176                is_file: false,
177                is_symlink: false,
178                len: 0,
179            });
180        }
181        Err(missing(path))
182    }
183
184    async fn remove_file(&self, path: &Path) -> Result<(), ExecError> {
185        let p = crate::path::normalize_lexically(path);
186        self.files
187            .lock()
188            .unwrap_or_else(std::sync::PoisonError::into_inner)
189            .remove(&p)
190            .map(|_| ())
191            .ok_or_else(|| missing(path))
192    }
193
194    async fn rename(&self, from: &Path, to: &Path) -> Result<(), ExecError> {
195        let (from_n, to_n) = (
196            crate::path::normalize_lexically(from),
197            crate::path::normalize_lexically(to),
198        );
199        let moved = |p: &PathBuf| match p.strip_prefix(&from_n) {
200            Ok(rest) if rest.as_os_str().is_empty() => Some(to_n.clone()),
201            Ok(rest) => Some(to_n.join(rest)),
202            Err(_) => None,
203        };
204        let mut files = self
205            .files
206            .lock()
207            .unwrap_or_else(std::sync::PoisonError::into_inner);
208        let mut dirs = self
209            .dirs
210            .lock()
211            .unwrap_or_else(std::sync::PoisonError::into_inner);
212        if !files.contains_key(&from_n) && !dirs.contains_key(&from_n) {
213            return Err(missing(from));
214        }
215        let files_moved: Vec<PathBuf> = files
216            .keys()
217            .filter(|k| moved(k).is_some())
218            .cloned()
219            .collect();
220        for old in files_moved {
221            if let (Some(new), Some(bytes)) = (moved(&old), files.remove(&old)) {
222                files.insert(new, bytes);
223            }
224        }
225        let dirs_moved: Vec<PathBuf> = dirs
226            .keys()
227            .filter(|k| moved(k).is_some())
228            .cloned()
229            .collect();
230        for old in dirs_moved {
231            dirs.remove(&old);
232            if let Some(new) = moved(&old) {
233                dirs.insert(new, ());
234            }
235        }
236        Ok(())
237    }
238
239    async fn canonicalize(&self, path: &Path) -> Result<PathBuf, ExecError> {
240        let p = crate::path::normalize_lexically(path);
241        if self
242            .files
243            .lock()
244            .unwrap_or_else(std::sync::PoisonError::into_inner)
245            .contains_key(&p)
246            || self.is_dir(&p)
247        {
248            Ok(p)
249        } else {
250            Err(missing(path))
251        }
252    }
253}