fs.rs

  1use anyhow::{anyhow, Result};
  2use fsevent::EventStream;
  3use futures::{Stream, StreamExt};
  4use smol::io::{AsyncReadExt, AsyncWriteExt};
  5use std::{
  6    io,
  7    os::unix::fs::MetadataExt,
  8    path::{Path, PathBuf},
  9    pin::Pin,
 10    time::{Duration, SystemTime},
 11};
 12use text::Rope;
 13
 14#[async_trait::async_trait]
 15pub trait Fs: Send + Sync {
 16    async fn create_dir(&self, path: &Path) -> Result<()>;
 17    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
 18    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
 19    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 20    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 21    async fn load(&self, path: &Path) -> Result<String>;
 22    async fn save(&self, path: &Path, text: &Rope) -> Result<()>;
 23    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 24    async fn is_file(&self, path: &Path) -> bool;
 25    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 26    async fn read_dir(
 27        &self,
 28        path: &Path,
 29    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 30    async fn watch(
 31        &self,
 32        path: &Path,
 33        latency: Duration,
 34    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>;
 35    fn is_fake(&self) -> bool;
 36    #[cfg(any(test, feature = "test-support"))]
 37    fn as_fake(&self) -> &FakeFs;
 38}
 39
 40#[derive(Copy, Clone, Default)]
 41pub struct CreateOptions {
 42    pub overwrite: bool,
 43    pub ignore_if_exists: bool,
 44}
 45
 46#[derive(Copy, Clone, Default)]
 47pub struct RenameOptions {
 48    pub overwrite: bool,
 49    pub ignore_if_exists: bool,
 50}
 51
 52#[derive(Copy, Clone, Default)]
 53pub struct RemoveOptions {
 54    pub recursive: bool,
 55    pub ignore_if_not_exists: bool,
 56}
 57
 58#[derive(Clone, Debug)]
 59pub struct Metadata {
 60    pub inode: u64,
 61    pub mtime: SystemTime,
 62    pub is_symlink: bool,
 63    pub is_dir: bool,
 64}
 65
 66pub struct RealFs;
 67
 68#[async_trait::async_trait]
 69impl Fs for RealFs {
 70    async fn create_dir(&self, path: &Path) -> Result<()> {
 71        Ok(smol::fs::create_dir_all(path).await?)
 72    }
 73
 74    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 75        let mut open_options = smol::fs::OpenOptions::new();
 76        open_options.write(true).create(true);
 77        if options.overwrite {
 78            open_options.truncate(true);
 79        } else if !options.ignore_if_exists {
 80            open_options.create_new(true);
 81        }
 82        open_options.open(path).await?;
 83        Ok(())
 84    }
 85
 86    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 87        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 88            if options.ignore_if_exists {
 89                return Ok(());
 90            } else {
 91                return Err(anyhow!("{target:?} already exists"));
 92            }
 93        }
 94
 95        smol::fs::rename(source, target).await?;
 96        Ok(())
 97    }
 98
 99    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
100        let result = if options.recursive {
101            smol::fs::remove_dir_all(path).await
102        } else {
103            smol::fs::remove_dir(path).await
104        };
105        match result {
106            Ok(()) => Ok(()),
107            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
108                Ok(())
109            }
110            Err(err) => Err(err)?,
111        }
112    }
113
114    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
115        match smol::fs::remove_file(path).await {
116            Ok(()) => Ok(()),
117            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
118                Ok(())
119            }
120            Err(err) => Err(err)?,
121        }
122    }
123
124    async fn load(&self, path: &Path) -> Result<String> {
125        let mut file = smol::fs::File::open(path).await?;
126        let mut text = String::new();
127        file.read_to_string(&mut text).await?;
128        Ok(text)
129    }
130
131    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
132        let buffer_size = text.summary().bytes.min(10 * 1024);
133        let file = smol::fs::File::create(path).await?;
134        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
135        for chunk in text.chunks() {
136            writer.write_all(chunk.as_bytes()).await?;
137        }
138        writer.flush().await?;
139        Ok(())
140    }
141
142    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
143        Ok(smol::fs::canonicalize(path).await?)
144    }
145
146    async fn is_file(&self, path: &Path) -> bool {
147        smol::fs::metadata(path)
148            .await
149            .map_or(false, |metadata| metadata.is_file())
150    }
151
152    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
153        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
154            Ok(metadata) => metadata,
155            Err(err) => {
156                return match (err.kind(), err.raw_os_error()) {
157                    (io::ErrorKind::NotFound, _) => Ok(None),
158                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
159                    _ => Err(anyhow::Error::new(err)),
160                }
161            }
162        };
163
164        let is_symlink = symlink_metadata.file_type().is_symlink();
165        let metadata = if is_symlink {
166            smol::fs::metadata(path).await?
167        } else {
168            symlink_metadata
169        };
170        Ok(Some(Metadata {
171            inode: metadata.ino(),
172            mtime: metadata.modified().unwrap(),
173            is_symlink,
174            is_dir: metadata.file_type().is_dir(),
175        }))
176    }
177
178    async fn read_dir(
179        &self,
180        path: &Path,
181    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
182        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
183            Ok(entry) => Ok(entry.path()),
184            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
185        });
186        Ok(Box::pin(result))
187    }
188
189    async fn watch(
190        &self,
191        path: &Path,
192        latency: Duration,
193    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
194        let (tx, rx) = smol::channel::unbounded();
195        let (stream, handle) = EventStream::new(&[path], latency);
196        std::mem::forget(handle);
197        std::thread::spawn(move || {
198            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
199        });
200        Box::pin(rx)
201    }
202
203    fn is_fake(&self) -> bool {
204        false
205    }
206
207    #[cfg(any(test, feature = "test-support"))]
208    fn as_fake(&self) -> &FakeFs {
209        panic!("called `RealFs::as_fake`")
210    }
211}
212
213#[cfg(any(test, feature = "test-support"))]
214#[derive(Clone, Debug)]
215struct FakeFsEntry {
216    metadata: Metadata,
217    content: Option<String>,
218}
219
220#[cfg(any(test, feature = "test-support"))]
221struct FakeFsState {
222    entries: std::collections::BTreeMap<PathBuf, FakeFsEntry>,
223    next_inode: u64,
224    events_tx: postage::broadcast::Sender<Vec<fsevent::Event>>,
225}
226
227#[cfg(any(test, feature = "test-support"))]
228impl FakeFsState {
229    fn validate_path(&self, path: &Path) -> Result<()> {
230        if path.is_absolute()
231            && path
232                .parent()
233                .and_then(|path| self.entries.get(path))
234                .map_or(false, |e| e.metadata.is_dir)
235        {
236            Ok(())
237        } else {
238            Err(anyhow!("invalid path {:?}", path))
239        }
240    }
241
242    async fn emit_event<I, T>(&mut self, paths: I)
243    where
244        I: IntoIterator<Item = T>,
245        T: Into<PathBuf>,
246    {
247        use postage::prelude::Sink as _;
248
249        let events = paths
250            .into_iter()
251            .map(|path| fsevent::Event {
252                event_id: 0,
253                flags: fsevent::StreamFlags::empty(),
254                path: path.into(),
255            })
256            .collect();
257
258        let _ = self.events_tx.send(events).await;
259    }
260}
261
262#[cfg(any(test, feature = "test-support"))]
263pub struct FakeFs {
264    // Use an unfair lock to ensure tests are deterministic.
265    state: futures::lock::Mutex<FakeFsState>,
266    executor: std::sync::Arc<gpui::executor::Background>,
267}
268
269#[cfg(any(test, feature = "test-support"))]
270impl FakeFs {
271    pub fn new(executor: std::sync::Arc<gpui::executor::Background>) -> Self {
272        let (events_tx, _) = postage::broadcast::channel(2048);
273        let mut entries = std::collections::BTreeMap::new();
274        entries.insert(
275            Path::new("/").to_path_buf(),
276            FakeFsEntry {
277                metadata: Metadata {
278                    inode: 0,
279                    mtime: SystemTime::now(),
280                    is_dir: true,
281                    is_symlink: false,
282                },
283                content: None,
284            },
285        );
286        Self {
287            executor,
288            state: futures::lock::Mutex::new(FakeFsState {
289                entries,
290                next_inode: 1,
291                events_tx,
292            }),
293        }
294    }
295
296    pub async fn insert_dir(&self, path: impl AsRef<Path>) -> Result<()> {
297        let mut state = self.state.lock().await;
298        let path = path.as_ref();
299        state.validate_path(path)?;
300
301        let inode = state.next_inode;
302        state.next_inode += 1;
303        state.entries.insert(
304            path.to_path_buf(),
305            FakeFsEntry {
306                metadata: Metadata {
307                    inode,
308                    mtime: SystemTime::now(),
309                    is_dir: true,
310                    is_symlink: false,
311                },
312                content: None,
313            },
314        );
315        state.emit_event(&[path]).await;
316        Ok(())
317    }
318
319    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
320        let mut state = self.state.lock().await;
321        let path = path.as_ref();
322        state.validate_path(path)?;
323
324        let inode = state.next_inode;
325        state.next_inode += 1;
326        state.entries.insert(
327            path.to_path_buf(),
328            FakeFsEntry {
329                metadata: Metadata {
330                    inode,
331                    mtime: SystemTime::now(),
332                    is_dir: false,
333                    is_symlink: false,
334                },
335                content: Some(content),
336            },
337        );
338        state.emit_event(&[path]).await;
339        Ok(())
340    }
341
342    #[must_use]
343    pub fn insert_tree<'a>(
344        &'a self,
345        path: impl 'a + AsRef<Path> + Send,
346        tree: serde_json::Value,
347    ) -> futures::future::BoxFuture<'a, ()> {
348        use futures::FutureExt as _;
349        use serde_json::Value::*;
350
351        async move {
352            let path = path.as_ref();
353
354            match tree {
355                Object(map) => {
356                    self.insert_dir(path).await.unwrap();
357                    for (name, contents) in map {
358                        let mut path = PathBuf::from(path);
359                        path.push(name);
360                        self.insert_tree(&path, contents).await;
361                    }
362                }
363                Null => {
364                    self.insert_dir(&path).await.unwrap();
365                }
366                String(contents) => {
367                    self.insert_file(&path, contents).await.unwrap();
368                }
369                _ => {
370                    panic!("JSON object must contain only objects, strings, or null");
371                }
372            }
373        }
374        .boxed()
375    }
376}
377
378#[cfg(any(test, feature = "test-support"))]
379#[async_trait::async_trait]
380impl Fs for FakeFs {
381    async fn create_dir(&self, path: &Path) -> Result<()> {
382        self.executor.simulate_random_delay().await;
383        let state = &mut *self.state.lock().await;
384        let mut ancestor_path = PathBuf::new();
385        let mut created_dir_paths = Vec::new();
386        for component in path.components() {
387            ancestor_path.push(component);
388            let entry = state
389                .entries
390                .entry(ancestor_path.clone())
391                .or_insert_with(|| {
392                    let inode = state.next_inode;
393                    state.next_inode += 1;
394                    created_dir_paths.push(ancestor_path.clone());
395                    FakeFsEntry {
396                        metadata: Metadata {
397                            inode,
398                            mtime: SystemTime::now(),
399                            is_dir: true,
400                            is_symlink: false,
401                        },
402                        content: None,
403                    }
404                });
405            if !entry.metadata.is_dir {
406                return Err(anyhow!(
407                    "cannot create directory because {:?} is a file",
408                    ancestor_path
409                ));
410            }
411        }
412        state.emit_event(&created_dir_paths).await;
413
414        Ok(())
415    }
416
417    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
418        self.executor.simulate_random_delay().await;
419        let mut state = self.state.lock().await;
420        state.validate_path(path)?;
421        if let Some(entry) = state.entries.get_mut(path) {
422            if entry.metadata.is_dir || entry.metadata.is_symlink {
423                return Err(anyhow!(
424                    "cannot create file because {:?} is a dir or a symlink",
425                    path
426                ));
427            }
428
429            if options.overwrite {
430                entry.metadata.mtime = SystemTime::now();
431                entry.content = Some(Default::default());
432            } else if !options.ignore_if_exists {
433                return Err(anyhow!(
434                    "cannot create file because {:?} already exists",
435                    path
436                ));
437            }
438        } else {
439            let inode = state.next_inode;
440            state.next_inode += 1;
441            let entry = FakeFsEntry {
442                metadata: Metadata {
443                    inode,
444                    mtime: SystemTime::now(),
445                    is_dir: false,
446                    is_symlink: false,
447                },
448                content: Some(Default::default()),
449            };
450            state.entries.insert(path.to_path_buf(), entry);
451        }
452        state.emit_event(&[path]).await;
453
454        Ok(())
455    }
456
457    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
458        let mut state = self.state.lock().await;
459        state.validate_path(source)?;
460        state.validate_path(target)?;
461
462        if !options.overwrite && state.entries.contains_key(target) {
463            if options.ignore_if_exists {
464                return Ok(());
465            } else {
466                return Err(anyhow!("{target:?} already exists"));
467            }
468        }
469
470        let mut removed = Vec::new();
471        state.entries.retain(|path, entry| {
472            if let Ok(relative_path) = path.strip_prefix(source) {
473                removed.push((relative_path.to_path_buf(), entry.clone()));
474                false
475            } else {
476                true
477            }
478        });
479
480        for (relative_path, entry) in removed {
481            let new_path = target.join(relative_path);
482            state.entries.insert(new_path, entry);
483        }
484
485        state.emit_event(&[source, target]).await;
486        Ok(())
487    }
488
489    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
490        let mut state = self.state.lock().await;
491        state.validate_path(path)?;
492        if let Some(entry) = state.entries.get(path) {
493            if !entry.metadata.is_dir {
494                return Err(anyhow!("cannot remove {path:?} because it is not a dir"));
495            }
496
497            if !options.recursive {
498                let descendants = state
499                    .entries
500                    .keys()
501                    .filter(|path| path.starts_with(path))
502                    .count();
503                if descendants > 1 {
504                    return Err(anyhow!("{path:?} is not empty"));
505                }
506            }
507
508            state.entries.retain(|path, _| !path.starts_with(path));
509            state.emit_event(&[path]).await;
510        } else if !options.ignore_if_not_exists {
511            return Err(anyhow!("{path:?} does not exist"));
512        }
513
514        Ok(())
515    }
516
517    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
518        let mut state = self.state.lock().await;
519        state.validate_path(path)?;
520        if let Some(entry) = state.entries.get(path) {
521            if entry.metadata.is_dir {
522                return Err(anyhow!("cannot remove {path:?} because it is not a file"));
523            }
524
525            state.entries.remove(path);
526            state.emit_event(&[path]).await;
527        } else if !options.ignore_if_not_exists {
528            return Err(anyhow!("{path:?} does not exist"));
529        }
530        Ok(())
531    }
532
533    async fn load(&self, path: &Path) -> Result<String> {
534        self.executor.simulate_random_delay().await;
535        let state = self.state.lock().await;
536        let text = state
537            .entries
538            .get(path)
539            .and_then(|e| e.content.as_ref())
540            .ok_or_else(|| anyhow!("file {:?} does not exist", path))?;
541        Ok(text.clone())
542    }
543
544    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
545        self.executor.simulate_random_delay().await;
546        let mut state = self.state.lock().await;
547        state.validate_path(path)?;
548        if let Some(entry) = state.entries.get_mut(path) {
549            if entry.metadata.is_dir {
550                Err(anyhow!("cannot overwrite a directory with a file"))
551            } else {
552                entry.content = Some(text.chunks().collect());
553                entry.metadata.mtime = SystemTime::now();
554                state.emit_event(&[path]).await;
555                Ok(())
556            }
557        } else {
558            let inode = state.next_inode;
559            state.next_inode += 1;
560            let entry = FakeFsEntry {
561                metadata: Metadata {
562                    inode,
563                    mtime: SystemTime::now(),
564                    is_dir: false,
565                    is_symlink: false,
566                },
567                content: Some(text.chunks().collect()),
568            };
569            state.entries.insert(path.to_path_buf(), entry);
570            state.emit_event(&[path]).await;
571            Ok(())
572        }
573    }
574
575    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
576        self.executor.simulate_random_delay().await;
577        Ok(path.to_path_buf())
578    }
579
580    async fn is_file(&self, path: &Path) -> bool {
581        self.executor.simulate_random_delay().await;
582        let state = self.state.lock().await;
583        state
584            .entries
585            .get(path)
586            .map_or(false, |entry| !entry.metadata.is_dir)
587    }
588
589    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
590        self.executor.simulate_random_delay().await;
591        let state = self.state.lock().await;
592        Ok(state.entries.get(path).map(|entry| entry.metadata.clone()))
593    }
594
595    async fn read_dir(
596        &self,
597        abs_path: &Path,
598    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
599        use futures::{future, stream};
600        self.executor.simulate_random_delay().await;
601        let state = self.state.lock().await;
602        let abs_path = abs_path.to_path_buf();
603        Ok(Box::pin(stream::iter(state.entries.clone()).filter_map(
604            move |(child_path, _)| {
605                future::ready(if child_path.parent() == Some(&abs_path) {
606                    Some(Ok(child_path))
607                } else {
608                    None
609                })
610            },
611        )))
612    }
613
614    async fn watch(
615        &self,
616        path: &Path,
617        _: Duration,
618    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
619        let state = self.state.lock().await;
620        self.executor.simulate_random_delay().await;
621        let rx = state.events_tx.subscribe();
622        let path = path.to_path_buf();
623        Box::pin(futures::StreamExt::filter(rx, move |events| {
624            let result = events.iter().any(|event| event.path.starts_with(&path));
625            async move { result }
626        }))
627    }
628
629    fn is_fake(&self) -> bool {
630        true
631    }
632
633    #[cfg(any(test, feature = "test-support"))]
634    fn as_fake(&self) -> &FakeFs {
635        self
636    }
637}