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("executor 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 = normalize_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, dir_path: &Path, options: RemoveOptions) -> Result<()> {
505        let dir_path = normalize_path(dir_path);
506        let mut state = self.state.lock().await;
507        state.validate_path(&dir_path)?;
508        if let Some(entry) = state.entries.get(&dir_path) {
509            if !entry.metadata.is_dir {
510                return Err(anyhow!(
511                    "cannot remove {dir_path:?} because it is not a dir"
512                ));
513            }
514
515            if !options.recursive {
516                let descendants = state
517                    .entries
518                    .keys()
519                    .filter(|path| path.starts_with(path))
520                    .count();
521                if descendants > 1 {
522                    return Err(anyhow!("{dir_path:?} is not empty"));
523                }
524            }
525
526            state.entries.retain(|path, _| !path.starts_with(&dir_path));
527            state.emit_event(&[dir_path]).await;
528        } else if !options.ignore_if_not_exists {
529            return Err(anyhow!("{dir_path:?} does not exist"));
530        }
531
532        Ok(())
533    }
534
535    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
536        let path = normalize_path(path);
537        let mut state = self.state.lock().await;
538        state.validate_path(&path)?;
539        if let Some(entry) = state.entries.get(&path) {
540            if entry.metadata.is_dir {
541                return Err(anyhow!("cannot remove {path:?} because it is not a file"));
542            }
543
544            state.entries.remove(&path);
545            state.emit_event(&[path]).await;
546        } else if !options.ignore_if_not_exists {
547            return Err(anyhow!("{path:?} does not exist"));
548        }
549        Ok(())
550    }
551
552    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
553        let text = self.load(path).await?;
554        Ok(Box::new(io::Cursor::new(text)))
555    }
556
557    async fn load(&self, path: &Path) -> Result<String> {
558        let path = normalize_path(path);
559        self.simulate_random_delay().await;
560        let state = self.state.lock().await;
561        let text = state
562            .entries
563            .get(&path)
564            .and_then(|e| e.content.as_ref())
565            .ok_or_else(|| anyhow!("file {:?} does not exist", path))?;
566        Ok(text.clone())
567    }
568
569    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
570        self.simulate_random_delay().await;
571        let mut state = self.state.lock().await;
572        let path = normalize_path(path);
573        state.validate_path(&path)?;
574        if let Some(entry) = state.entries.get_mut(&path) {
575            if entry.metadata.is_dir {
576                Err(anyhow!("cannot overwrite a directory with a file"))
577            } else {
578                entry.content = Some(text.chunks().collect());
579                entry.metadata.mtime = SystemTime::now();
580                state.emit_event(&[path]).await;
581                Ok(())
582            }
583        } else {
584            let inode = state.next_inode;
585            state.next_inode += 1;
586            let entry = FakeFsEntry {
587                metadata: Metadata {
588                    inode,
589                    mtime: SystemTime::now(),
590                    is_dir: false,
591                    is_symlink: false,
592                },
593                content: Some(text.chunks().collect()),
594            };
595            state.entries.insert(path.to_path_buf(), entry);
596            state.emit_event(&[path]).await;
597            Ok(())
598        }
599    }
600
601    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
602        self.simulate_random_delay().await;
603        Ok(normalize_path(path))
604    }
605
606    async fn is_file(&self, path: &Path) -> bool {
607        let path = normalize_path(path);
608        self.simulate_random_delay().await;
609        let state = self.state.lock().await;
610        state
611            .entries
612            .get(&path)
613            .map_or(false, |entry| !entry.metadata.is_dir)
614    }
615
616    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
617        self.simulate_random_delay().await;
618        let state = self.state.lock().await;
619        let path = normalize_path(path);
620        Ok(state.entries.get(&path).map(|entry| entry.metadata.clone()))
621    }
622
623    async fn read_dir(
624        &self,
625        abs_path: &Path,
626    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
627        use futures::{future, stream};
628        self.simulate_random_delay().await;
629        let state = self.state.lock().await;
630        let abs_path = normalize_path(abs_path);
631        Ok(Box::pin(stream::iter(state.entries.clone()).filter_map(
632            move |(child_path, _)| {
633                future::ready(if child_path.parent() == Some(&abs_path) {
634                    Some(Ok(child_path))
635                } else {
636                    None
637                })
638            },
639        )))
640    }
641
642    async fn watch(
643        &self,
644        path: &Path,
645        _: Duration,
646    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
647        let mut state = self.state.lock().await;
648        self.simulate_random_delay().await;
649        let (tx, rx) = smol::channel::unbounded();
650        state.event_txs.push(tx);
651        let path = path.to_path_buf();
652        let executor = self.executor.clone();
653        Box::pin(futures::StreamExt::filter(rx, move |events| {
654            let result = events.iter().any(|event| event.path.starts_with(&path));
655            let executor = executor.clone();
656            async move {
657                if let Some(executor) = executor.clone().upgrade() {
658                    executor.simulate_random_delay().await;
659                }
660                result
661            }
662        }))
663    }
664
665    fn is_fake(&self) -> bool {
666        true
667    }
668
669    #[cfg(any(test, feature = "test-support"))]
670    fn as_fake(&self) -> &FakeFs {
671        self
672    }
673}
674
675pub fn normalize_path(path: &Path) -> PathBuf {
676    let mut components = path.components().peekable();
677    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
678        components.next();
679        PathBuf::from(c.as_os_str())
680    } else {
681        PathBuf::new()
682    };
683
684    for component in components {
685        match component {
686            Component::Prefix(..) => unreachable!(),
687            Component::RootDir => {
688                ret.push(component.as_os_str());
689            }
690            Component::CurDir => {}
691            Component::ParentDir => {
692                ret.pop();
693            }
694            Component::Normal(c) => {
695                ret.push(c);
696            }
697        }
698    }
699    ret
700}