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