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    event_txs: Vec<smol::channel::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        let events = paths
252            .into_iter()
253            .map(|path| fsevent::Event {
254                event_id: 0,
255                flags: fsevent::StreamFlags::empty(),
256                path: path.into(),
257            })
258            .collect::<Vec<_>>();
259
260        self.event_txs.retain(|tx| {
261            let _ = tx.try_send(events.clone());
262            !tx.is_closed()
263        });
264    }
265}
266
267#[cfg(any(test, feature = "test-support"))]
268pub struct FakeFs {
269    // Use an unfair lock to ensure tests are deterministic.
270    state: futures::lock::Mutex<FakeFsState>,
271    executor: std::sync::Weak<gpui::executor::Background>,
272}
273
274#[cfg(any(test, feature = "test-support"))]
275impl FakeFs {
276    pub fn new(executor: std::sync::Arc<gpui::executor::Background>) -> std::sync::Arc<Self> {
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: std::sync::Arc::downgrade(&executor),
292            state: futures::lock::Mutex::new(FakeFsState {
293                entries,
294                next_inode: 1,
295                event_txs: Default::default(),
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    async fn simulate_random_delay(&self) {
380        self.executor
381            .upgrade()
382            .expect("excecutor has been dropped")
383            .simulate_random_delay()
384            .await;
385    }
386}
387
388#[cfg(any(test, feature = "test-support"))]
389#[async_trait::async_trait]
390impl Fs for FakeFs {
391    async fn create_dir(&self, path: &Path) -> Result<()> {
392        self.simulate_random_delay().await;
393        let state = &mut *self.state.lock().await;
394        let path = normalize_path(path);
395        let mut ancestor_path = PathBuf::new();
396        let mut created_dir_paths = Vec::new();
397        for component in path.components() {
398            ancestor_path.push(component);
399            let entry = state
400                .entries
401                .entry(ancestor_path.clone())
402                .or_insert_with(|| {
403                    let inode = state.next_inode;
404                    state.next_inode += 1;
405                    created_dir_paths.push(ancestor_path.clone());
406                    FakeFsEntry {
407                        metadata: Metadata {
408                            inode,
409                            mtime: SystemTime::now(),
410                            is_dir: true,
411                            is_symlink: false,
412                        },
413                        content: None,
414                    }
415                });
416            if !entry.metadata.is_dir {
417                return Err(anyhow!(
418                    "cannot create directory because {:?} is a file",
419                    ancestor_path
420                ));
421            }
422        }
423        state.emit_event(&created_dir_paths).await;
424
425        Ok(())
426    }
427
428    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
429        self.simulate_random_delay().await;
430        let mut state = self.state.lock().await;
431        let path = normalize_path(path);
432        state.validate_path(&path)?;
433        if let Some(entry) = state.entries.get_mut(&path) {
434            if entry.metadata.is_dir || entry.metadata.is_symlink {
435                return Err(anyhow!(
436                    "cannot create file because {:?} is a dir or a symlink",
437                    path
438                ));
439            }
440
441            if options.overwrite {
442                entry.metadata.mtime = SystemTime::now();
443                entry.content = Some(Default::default());
444            } else if !options.ignore_if_exists {
445                return Err(anyhow!(
446                    "cannot create file because {:?} already exists",
447                    &path
448                ));
449            }
450        } else {
451            let inode = state.next_inode;
452            state.next_inode += 1;
453            let entry = FakeFsEntry {
454                metadata: Metadata {
455                    inode,
456                    mtime: SystemTime::now(),
457                    is_dir: false,
458                    is_symlink: false,
459                },
460                content: Some(Default::default()),
461            };
462            state.entries.insert(path.to_path_buf(), entry);
463        }
464        state.emit_event(&[path]).await;
465
466        Ok(())
467    }
468
469    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
470        let source = normalize_path(source);
471        let target = normalize_path(target);
472
473        let mut state = self.state.lock().await;
474        state.validate_path(&source)?;
475        state.validate_path(&target)?;
476
477        if !options.overwrite && state.entries.contains_key(&target) {
478            if options.ignore_if_exists {
479                return Ok(());
480            } else {
481                return Err(anyhow!("{target:?} already exists"));
482            }
483        }
484
485        let mut removed = Vec::new();
486        state.entries.retain(|path, entry| {
487            if let Ok(relative_path) = path.strip_prefix(&source) {
488                removed.push((relative_path.to_path_buf(), entry.clone()));
489                false
490            } else {
491                true
492            }
493        });
494
495        for (relative_path, entry) in removed {
496            let new_path = target.join(relative_path);
497            state.entries.insert(new_path, entry);
498        }
499
500        state.emit_event(&[source, target]).await;
501        Ok(())
502    }
503
504    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
505        let path = normalize_path(path);
506        let mut state = self.state.lock().await;
507        state.validate_path(&path)?;
508        if let Some(entry) = state.entries.get(&path) {
509            if !entry.metadata.is_dir {
510                return Err(anyhow!("cannot remove {path:?} because it is not a dir"));
511            }
512
513            if !options.recursive {
514                let descendants = state
515                    .entries
516                    .keys()
517                    .filter(|path| path.starts_with(path))
518                    .count();
519                if descendants > 1 {
520                    return Err(anyhow!("{path:?} is not empty"));
521                }
522            }
523
524            state.entries.retain(|path, _| !path.starts_with(path));
525            state.emit_event(&[path]).await;
526        } else if !options.ignore_if_not_exists {
527            return Err(anyhow!("{path:?} does not exist"));
528        }
529
530        Ok(())
531    }
532
533    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
534        let path = normalize_path(path);
535        let mut state = self.state.lock().await;
536        state.validate_path(&path)?;
537        if let Some(entry) = state.entries.get(&path) {
538            if entry.metadata.is_dir {
539                return Err(anyhow!("cannot remove {path:?} because it is not a file"));
540            }
541
542            state.entries.remove(&path);
543            state.emit_event(&[path]).await;
544        } else if !options.ignore_if_not_exists {
545            return Err(anyhow!("{path:?} does not exist"));
546        }
547        Ok(())
548    }
549
550    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
551        let text = self.load(path).await?;
552        Ok(Box::new(io::Cursor::new(text)))
553    }
554
555    async fn load(&self, path: &Path) -> Result<String> {
556        let path = normalize_path(path);
557        self.simulate_random_delay().await;
558        let state = self.state.lock().await;
559        let text = state
560            .entries
561            .get(&path)
562            .and_then(|e| e.content.as_ref())
563            .ok_or_else(|| anyhow!("file {:?} does not exist", path))?;
564        Ok(text.clone())
565    }
566
567    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
568        self.simulate_random_delay().await;
569        let mut state = self.state.lock().await;
570        let path = normalize_path(path);
571        state.validate_path(&path)?;
572        if let Some(entry) = state.entries.get_mut(&path) {
573            if entry.metadata.is_dir {
574                Err(anyhow!("cannot overwrite a directory with a file"))
575            } else {
576                entry.content = Some(text.chunks().collect());
577                entry.metadata.mtime = SystemTime::now();
578                state.emit_event(&[path]).await;
579                Ok(())
580            }
581        } else {
582            let inode = state.next_inode;
583            state.next_inode += 1;
584            let entry = FakeFsEntry {
585                metadata: Metadata {
586                    inode,
587                    mtime: SystemTime::now(),
588                    is_dir: false,
589                    is_symlink: false,
590                },
591                content: Some(text.chunks().collect()),
592            };
593            state.entries.insert(path.to_path_buf(), entry);
594            state.emit_event(&[path]).await;
595            Ok(())
596        }
597    }
598
599    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
600        self.simulate_random_delay().await;
601        Ok(normalize_path(path))
602    }
603
604    async fn is_file(&self, path: &Path) -> bool {
605        let path = normalize_path(path);
606        self.simulate_random_delay().await;
607        let state = self.state.lock().await;
608        state
609            .entries
610            .get(&path)
611            .map_or(false, |entry| !entry.metadata.is_dir)
612    }
613
614    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
615        self.simulate_random_delay().await;
616        let state = self.state.lock().await;
617        let path = normalize_path(path);
618        Ok(state.entries.get(&path).map(|entry| entry.metadata.clone()))
619    }
620
621    async fn read_dir(
622        &self,
623        abs_path: &Path,
624    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
625        use futures::{future, stream};
626        self.simulate_random_delay().await;
627        let state = self.state.lock().await;
628        let abs_path = normalize_path(abs_path);
629        Ok(Box::pin(stream::iter(state.entries.clone()).filter_map(
630            move |(child_path, _)| {
631                future::ready(if child_path.parent() == Some(&abs_path) {
632                    Some(Ok(child_path))
633                } else {
634                    None
635                })
636            },
637        )))
638    }
639
640    async fn watch(
641        &self,
642        path: &Path,
643        _: Duration,
644    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
645        let mut state = self.state.lock().await;
646        self.simulate_random_delay().await;
647        let (tx, rx) = smol::channel::unbounded();
648        state.event_txs.push(tx);
649        let path = path.to_path_buf();
650        Box::pin(futures::StreamExt::filter(rx, move |events| {
651            let result = events.iter().any(|event| event.path.starts_with(&path));
652            async move { result }
653        }))
654    }
655
656    fn is_fake(&self) -> bool {
657        true
658    }
659
660    #[cfg(any(test, feature = "test-support"))]
661    fn as_fake(&self) -> &FakeFs {
662        self
663    }
664}
665
666pub fn normalize_path(path: &Path) -> PathBuf {
667    let mut components = path.components().peekable();
668    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
669        components.next();
670        PathBuf::from(c.as_os_str())
671    } else {
672        PathBuf::new()
673    };
674
675    for component in components {
676        match component {
677            Component::Prefix(..) => unreachable!(),
678            Component::RootDir => {
679                ret.push(component.as_os_str());
680            }
681            Component::CurDir => {}
682            Component::ParentDir => {
683                ret.pop();
684            }
685            Component::Normal(c) => {
686                ret.push(c);
687            }
688        }
689    }
690    ret
691}