fs.rs

   1pub mod repository;
   2
   3use anyhow::{anyhow, Result};
   4pub use fsevent::Event;
   5#[cfg(target_os = "macos")]
   6use fsevent::EventStream;
   7
   8#[cfg(not(target_os = "macos"))]
   9use fsevent::StreamFlags;
  10
  11#[cfg(not(target_os = "macos"))]
  12use notify::{Config, EventKind, Watcher};
  13
  14#[cfg(unix)]
  15use std::os::unix::fs::MetadataExt;
  16
  17use async_tar::Archive;
  18use futures::{future::BoxFuture, AsyncRead, Stream, StreamExt};
  19use git2::Repository as LibGitRepository;
  20use parking_lot::Mutex;
  21use repository::GitRepository;
  22use rope::Rope;
  23use smol::io::{AsyncReadExt, AsyncWriteExt};
  24use std::io::Write;
  25use std::sync::Arc;
  26use std::{
  27    io,
  28    path::{Component, Path, PathBuf},
  29    pin::Pin,
  30    time::{Duration, SystemTime},
  31};
  32use tempfile::{NamedTempFile, TempDir};
  33use text::LineEnding;
  34use util::{paths, ResultExt};
  35
  36#[cfg(any(test, feature = "test-support"))]
  37use collections::{btree_map, BTreeMap};
  38#[cfg(any(test, feature = "test-support"))]
  39use repository::{FakeGitRepositoryState, GitFileStatus};
  40#[cfg(any(test, feature = "test-support"))]
  41use std::ffi::OsStr;
  42
  43#[async_trait::async_trait]
  44pub trait Fs: Send + Sync {
  45    async fn create_dir(&self, path: &Path) -> Result<()>;
  46    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  47    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  48    async fn create_file_with(
  49        &self,
  50        path: &Path,
  51        content: Pin<&mut (dyn AsyncRead + Send)>,
  52    ) -> Result<()>;
  53    async fn extract_tar_file(
  54        &self,
  55        path: &Path,
  56        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
  57    ) -> Result<()>;
  58    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
  59    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
  60    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  61    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  62    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
  63    async fn load(&self, path: &Path) -> Result<String>;
  64    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
  65    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
  66    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
  67    async fn is_file(&self, path: &Path) -> bool;
  68    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
  69    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
  70    async fn read_dir(
  71        &self,
  72        path: &Path,
  73    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
  74
  75    async fn watch(
  76        &self,
  77        path: &Path,
  78        latency: Duration,
  79    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>>;
  80
  81    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>>;
  82    fn is_fake(&self) -> bool;
  83    async fn is_case_sensitive(&self) -> Result<bool>;
  84    #[cfg(any(test, feature = "test-support"))]
  85    fn as_fake(&self) -> &FakeFs;
  86}
  87
  88#[derive(Copy, Clone, Default)]
  89pub struct CreateOptions {
  90    pub overwrite: bool,
  91    pub ignore_if_exists: bool,
  92}
  93
  94#[derive(Copy, Clone, Default)]
  95pub struct CopyOptions {
  96    pub overwrite: bool,
  97    pub ignore_if_exists: bool,
  98}
  99
 100#[derive(Copy, Clone, Default)]
 101pub struct RenameOptions {
 102    pub overwrite: bool,
 103    pub ignore_if_exists: bool,
 104}
 105
 106#[derive(Copy, Clone, Default)]
 107pub struct RemoveOptions {
 108    pub recursive: bool,
 109    pub ignore_if_not_exists: bool,
 110}
 111
 112#[derive(Copy, Clone, Debug)]
 113pub struct Metadata {
 114    pub inode: u64,
 115    pub mtime: SystemTime,
 116    pub is_symlink: bool,
 117    pub is_dir: bool,
 118}
 119
 120pub struct RealFs;
 121
 122#[async_trait::async_trait]
 123impl Fs for RealFs {
 124    async fn create_dir(&self, path: &Path) -> Result<()> {
 125        Ok(smol::fs::create_dir_all(path).await?)
 126    }
 127
 128    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 129        #[cfg(target_family = "unix")]
 130        smol::fs::unix::symlink(target, path).await?;
 131
 132        #[cfg(target_family = "windows")]
 133        Err(anyhow!("not supported yet on windows"))?;
 134
 135        Ok(())
 136    }
 137
 138    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 139        let mut open_options = smol::fs::OpenOptions::new();
 140        open_options.write(true).create(true);
 141        if options.overwrite {
 142            open_options.truncate(true);
 143        } else if !options.ignore_if_exists {
 144            open_options.create_new(true);
 145        }
 146        open_options.open(path).await?;
 147        Ok(())
 148    }
 149
 150    async fn create_file_with(
 151        &self,
 152        path: &Path,
 153        content: Pin<&mut (dyn AsyncRead + Send)>,
 154    ) -> Result<()> {
 155        let mut file = smol::fs::File::create(&path).await?;
 156        futures::io::copy(content, &mut file).await?;
 157        Ok(())
 158    }
 159
 160    async fn extract_tar_file(
 161        &self,
 162        path: &Path,
 163        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 164    ) -> Result<()> {
 165        content.unpack(path).await?;
 166        Ok(())
 167    }
 168
 169    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 170        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 171            if options.ignore_if_exists {
 172                return Ok(());
 173            } else {
 174                return Err(anyhow!("{target:?} already exists"));
 175            }
 176        }
 177
 178        smol::fs::copy(source, target).await?;
 179        Ok(())
 180    }
 181
 182    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 183        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 184            if options.ignore_if_exists {
 185                return Ok(());
 186            } else {
 187                return Err(anyhow!("{target:?} already exists"));
 188            }
 189        }
 190
 191        smol::fs::rename(source, target).await?;
 192        Ok(())
 193    }
 194
 195    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 196        let result = if options.recursive {
 197            smol::fs::remove_dir_all(path).await
 198        } else {
 199            smol::fs::remove_dir(path).await
 200        };
 201        match result {
 202            Ok(()) => Ok(()),
 203            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 204                Ok(())
 205            }
 206            Err(err) => Err(err)?,
 207        }
 208    }
 209
 210    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 211        match smol::fs::remove_file(path).await {
 212            Ok(()) => Ok(()),
 213            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 214                Ok(())
 215            }
 216            Err(err) => Err(err)?,
 217        }
 218    }
 219
 220    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 221        Ok(Box::new(std::fs::File::open(path)?))
 222    }
 223
 224    async fn load(&self, path: &Path) -> Result<String> {
 225        let mut file = smol::fs::File::open(path).await?;
 226        // We use `read_exact` here instead of `read_to_string` as the latter is *very*
 227        // happy to reallocate often, which comes into play when we're loading large files.
 228        let mut storage = vec![0; file.metadata().await?.len() as usize];
 229        file.read_exact(&mut storage).await?;
 230        Ok(String::from_utf8(storage)?)
 231    }
 232
 233    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 234        smol::unblock(move || {
 235            let mut tmp_file = if cfg!(target_os = "linux") {
 236                // Use the directory of the destination as temp dir to avoid
 237                // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 238                // See https://github.com/zed-industries/zed/pull/8437 for more details.
 239                NamedTempFile::new_in(path.parent().unwrap_or(&paths::TEMP_DIR))
 240            } else {
 241                NamedTempFile::new()
 242            }?;
 243            tmp_file.write_all(data.as_bytes())?;
 244            tmp_file.persist(path)?;
 245            Ok::<(), anyhow::Error>(())
 246        })
 247        .await?;
 248
 249        Ok(())
 250    }
 251
 252    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 253        let buffer_size = text.summary().len.min(10 * 1024);
 254        if let Some(path) = path.parent() {
 255            self.create_dir(path).await?;
 256        }
 257        let file = smol::fs::File::create(path).await?;
 258        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 259        for chunk in chunks(text, line_ending) {
 260            writer.write_all(chunk.as_bytes()).await?;
 261        }
 262        writer.flush().await?;
 263        Ok(())
 264    }
 265
 266    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 267        Ok(smol::fs::canonicalize(path).await?)
 268    }
 269
 270    async fn is_file(&self, path: &Path) -> bool {
 271        smol::fs::metadata(path)
 272            .await
 273            .map_or(false, |metadata| metadata.is_file())
 274    }
 275
 276    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 277        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 278            Ok(metadata) => metadata,
 279            Err(err) => {
 280                return match (err.kind(), err.raw_os_error()) {
 281                    (io::ErrorKind::NotFound, _) => Ok(None),
 282                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 283                    _ => Err(anyhow::Error::new(err)),
 284                }
 285            }
 286        };
 287
 288        let is_symlink = symlink_metadata.file_type().is_symlink();
 289        let metadata = if is_symlink {
 290            smol::fs::metadata(path).await?
 291        } else {
 292            symlink_metadata
 293        };
 294
 295        #[cfg(unix)]
 296        let inode = metadata.ino();
 297
 298        #[cfg(windows)]
 299        let inode = file_id(path).await?;
 300
 301        Ok(Some(Metadata {
 302            inode,
 303            mtime: metadata.modified().unwrap(),
 304            is_symlink,
 305            is_dir: metadata.file_type().is_dir(),
 306        }))
 307    }
 308
 309    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 310        let path = smol::fs::read_link(path).await?;
 311        Ok(path)
 312    }
 313
 314    async fn read_dir(
 315        &self,
 316        path: &Path,
 317    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 318        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 319            Ok(entry) => Ok(entry.path()),
 320            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 321        });
 322        Ok(Box::pin(result))
 323    }
 324
 325    #[cfg(target_os = "macos")]
 326    async fn watch(
 327        &self,
 328        path: &Path,
 329        latency: Duration,
 330    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
 331        let (tx, rx) = smol::channel::unbounded();
 332        let (stream, handle) = EventStream::new(&[path], latency);
 333        std::thread::spawn(move || {
 334            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
 335        });
 336        Box::pin(rx.chain(futures::stream::once(async move {
 337            drop(handle);
 338            vec![]
 339        })))
 340    }
 341
 342    #[cfg(not(target_os = "macos"))]
 343    async fn watch(
 344        &self,
 345        path: &Path,
 346        latency: Duration,
 347    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
 348        let (tx, rx) = smol::channel::unbounded();
 349
 350        if !path.exists() {
 351            log::error!("watch path does not exist: {}", path.display());
 352            return Box::pin(rx);
 353        }
 354
 355        let mut watcher =
 356            notify::recommended_watcher(move |res: Result<notify::Event, _>| match res {
 357                Ok(event) => {
 358                    let flags = match event.kind {
 359                        // ITEM_REMOVED is currently the only flag we care about
 360                        EventKind::Remove(_) => StreamFlags::ITEM_REMOVED,
 361                        _ => StreamFlags::NONE,
 362                    };
 363                    let events = event
 364                        .paths
 365                        .into_iter()
 366                        .map(|path| Event {
 367                            event_id: 0,
 368                            flags,
 369                            path,
 370                        })
 371                        .collect::<Vec<_>>();
 372                    let _ = tx.try_send(events);
 373                }
 374                Err(err) => {
 375                    log::error!("watch error: {}", err);
 376                }
 377            })
 378            .unwrap();
 379
 380        watcher
 381            .configure(Config::default().with_poll_interval(latency))
 382            .unwrap();
 383
 384        watcher
 385            .watch(path, notify::RecursiveMode::Recursive)
 386            .unwrap();
 387
 388        Box::pin(rx)
 389    }
 390
 391    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
 392        LibGitRepository::open(dotgit_path)
 393            .log_err()
 394            .map::<Arc<Mutex<dyn GitRepository>>, _>(|libgit_repository| {
 395                Arc::new(Mutex::new(libgit_repository))
 396            })
 397    }
 398
 399    fn is_fake(&self) -> bool {
 400        false
 401    }
 402
 403    /// Checks whether the file system is case sensitive by attempting to create two files
 404    /// that have the same name except for the casing.
 405    ///
 406    /// It creates both files in a temporary directory it removes at the end.
 407    async fn is_case_sensitive(&self) -> Result<bool> {
 408        let temp_dir = TempDir::new()?;
 409        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 410        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 411
 412        let create_opts = CreateOptions {
 413            overwrite: false,
 414            ignore_if_exists: false,
 415        };
 416
 417        // Create file1
 418        self.create_file(&test_file_1, create_opts).await?;
 419
 420        // Now check whether it's possible to create file2
 421        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 422            Ok(_) => Ok(true),
 423            Err(e) => {
 424                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 425                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 426                        Ok(false)
 427                    } else {
 428                        Err(e)
 429                    }
 430                } else {
 431                    Err(e)
 432                }
 433            }
 434        };
 435
 436        temp_dir.close()?;
 437        case_sensitive
 438    }
 439
 440    #[cfg(any(test, feature = "test-support"))]
 441    fn as_fake(&self) -> &FakeFs {
 442        panic!("called `RealFs::as_fake`")
 443    }
 444}
 445
 446pub fn fs_events_paths(events: Vec<Event>) -> Vec<PathBuf> {
 447    events.into_iter().map(|event| event.path).collect()
 448}
 449
 450#[cfg(any(test, feature = "test-support"))]
 451pub struct FakeFs {
 452    // Use an unfair lock to ensure tests are deterministic.
 453    state: Mutex<FakeFsState>,
 454    executor: gpui::BackgroundExecutor,
 455}
 456
 457#[cfg(any(test, feature = "test-support"))]
 458struct FakeFsState {
 459    root: Arc<Mutex<FakeFsEntry>>,
 460    next_inode: u64,
 461    next_mtime: SystemTime,
 462    event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
 463    events_paused: bool,
 464    buffered_events: Vec<fsevent::Event>,
 465    metadata_call_count: usize,
 466    read_dir_call_count: usize,
 467}
 468
 469#[cfg(any(test, feature = "test-support"))]
 470#[derive(Debug)]
 471enum FakeFsEntry {
 472    File {
 473        inode: u64,
 474        mtime: SystemTime,
 475        content: Vec<u8>,
 476    },
 477    Dir {
 478        inode: u64,
 479        mtime: SystemTime,
 480        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 481        git_repo_state: Option<Arc<Mutex<repository::FakeGitRepositoryState>>>,
 482    },
 483    Symlink {
 484        target: PathBuf,
 485    },
 486}
 487
 488#[cfg(any(test, feature = "test-support"))]
 489impl FakeFsState {
 490    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 491        Ok(self
 492            .try_read_path(target, true)
 493            .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
 494            .0)
 495    }
 496
 497    fn try_read_path(
 498        &self,
 499        target: &Path,
 500        follow_symlink: bool,
 501    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 502        let mut path = target.to_path_buf();
 503        let mut canonical_path = PathBuf::new();
 504        let mut entry_stack = Vec::new();
 505        'outer: loop {
 506            let mut path_components = path.components().peekable();
 507            while let Some(component) = path_components.next() {
 508                match component {
 509                    Component::Prefix(_) => panic!("prefix paths aren't supported"),
 510                    Component::RootDir => {
 511                        entry_stack.clear();
 512                        entry_stack.push(self.root.clone());
 513                        canonical_path.clear();
 514                        canonical_path.push("/");
 515                    }
 516                    Component::CurDir => {}
 517                    Component::ParentDir => {
 518                        entry_stack.pop()?;
 519                        canonical_path.pop();
 520                    }
 521                    Component::Normal(name) => {
 522                        let current_entry = entry_stack.last().cloned()?;
 523                        let current_entry = current_entry.lock();
 524                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 525                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 526                            if path_components.peek().is_some() || follow_symlink {
 527                                let entry = entry.lock();
 528                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 529                                    let mut target = target.clone();
 530                                    target.extend(path_components);
 531                                    path = target;
 532                                    continue 'outer;
 533                                }
 534                            }
 535                            entry_stack.push(entry.clone());
 536                            canonical_path.push(name);
 537                        } else {
 538                            return None;
 539                        }
 540                    }
 541                }
 542            }
 543            break;
 544        }
 545        Some((entry_stack.pop()?, canonical_path))
 546    }
 547
 548    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 549    where
 550        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 551    {
 552        let path = normalize_path(path);
 553        let filename = path
 554            .file_name()
 555            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 556        let parent_path = path.parent().unwrap();
 557
 558        let parent = self.read_path(parent_path)?;
 559        let mut parent = parent.lock();
 560        let new_entry = parent
 561            .dir_entries(parent_path)?
 562            .entry(filename.to_str().unwrap().into());
 563        callback(new_entry)
 564    }
 565
 566    fn emit_event<I, T>(&mut self, paths: I)
 567    where
 568        I: IntoIterator<Item = T>,
 569        T: Into<PathBuf>,
 570    {
 571        self.buffered_events
 572            .extend(paths.into_iter().map(|path| fsevent::Event {
 573                event_id: 0,
 574                flags: fsevent::StreamFlags::empty(),
 575                path: path.into(),
 576            }));
 577
 578        if !self.events_paused {
 579            self.flush_events(self.buffered_events.len());
 580        }
 581    }
 582
 583    fn flush_events(&mut self, mut count: usize) {
 584        count = count.min(self.buffered_events.len());
 585        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 586        self.event_txs.retain(|tx| {
 587            let _ = tx.try_send(events.clone());
 588            !tx.is_closed()
 589        });
 590    }
 591}
 592
 593#[cfg(any(test, feature = "test-support"))]
 594lazy_static::lazy_static! {
 595    pub static ref FS_DOT_GIT: &'static OsStr = OsStr::new(".git");
 596}
 597
 598#[cfg(any(test, feature = "test-support"))]
 599impl FakeFs {
 600    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
 601        Arc::new(Self {
 602            executor,
 603            state: Mutex::new(FakeFsState {
 604                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 605                    inode: 0,
 606                    mtime: SystemTime::UNIX_EPOCH,
 607                    entries: Default::default(),
 608                    git_repo_state: None,
 609                })),
 610                next_mtime: SystemTime::UNIX_EPOCH,
 611                next_inode: 1,
 612                event_txs: Default::default(),
 613                buffered_events: Vec::new(),
 614                events_paused: false,
 615                read_dir_call_count: 0,
 616                metadata_call_count: 0,
 617            }),
 618        })
 619    }
 620
 621    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
 622        self.write_file_internal(path, content).unwrap()
 623    }
 624
 625    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 626        let mut state = self.state.lock();
 627        let path = path.as_ref();
 628        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 629        state
 630            .write_path(path.as_ref(), move |e| match e {
 631                btree_map::Entry::Vacant(e) => {
 632                    e.insert(file);
 633                    Ok(())
 634                }
 635                btree_map::Entry::Occupied(mut e) => {
 636                    *e.get_mut() = file;
 637                    Ok(())
 638                }
 639            })
 640            .unwrap();
 641        state.emit_event([path]);
 642    }
 643
 644    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
 645        let mut state = self.state.lock();
 646        let path = path.as_ref();
 647        let inode = state.next_inode;
 648        let mtime = state.next_mtime;
 649        state.next_inode += 1;
 650        state.next_mtime += Duration::from_nanos(1);
 651        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 652            inode,
 653            mtime,
 654            content,
 655        }));
 656        state.write_path(path, move |entry| {
 657            match entry {
 658                btree_map::Entry::Vacant(e) => {
 659                    e.insert(file);
 660                }
 661                btree_map::Entry::Occupied(mut e) => {
 662                    *e.get_mut() = file;
 663                }
 664            }
 665            Ok(())
 666        })?;
 667        state.emit_event([path]);
 668        Ok(())
 669    }
 670
 671    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
 672        let path = path.as_ref();
 673        let path = normalize_path(path);
 674        self.simulate_random_delay().await;
 675        let state = self.state.lock();
 676        let entry = state.read_path(&path)?;
 677        let entry = entry.lock();
 678        entry.file_content(&path).cloned()
 679    }
 680
 681    pub fn pause_events(&self) {
 682        self.state.lock().events_paused = true;
 683    }
 684
 685    pub fn buffered_event_count(&self) -> usize {
 686        self.state.lock().buffered_events.len()
 687    }
 688
 689    pub fn flush_events(&self, count: usize) {
 690        self.state.lock().flush_events(count);
 691    }
 692
 693    #[must_use]
 694    pub fn insert_tree<'a>(
 695        &'a self,
 696        path: impl 'a + AsRef<Path> + Send,
 697        tree: serde_json::Value,
 698    ) -> futures::future::BoxFuture<'a, ()> {
 699        use futures::FutureExt as _;
 700        use serde_json::Value::*;
 701
 702        async move {
 703            let path = path.as_ref();
 704
 705            match tree {
 706                Object(map) => {
 707                    self.create_dir(path).await.unwrap();
 708                    for (name, contents) in map {
 709                        let mut path = PathBuf::from(path);
 710                        path.push(name);
 711                        self.insert_tree(&path, contents).await;
 712                    }
 713                }
 714                Null => {
 715                    self.create_dir(path).await.unwrap();
 716                }
 717                String(contents) => {
 718                    self.insert_file(&path, contents.into_bytes()).await;
 719                }
 720                _ => {
 721                    panic!("JSON object must contain only objects, strings, or null");
 722                }
 723            }
 724        }
 725        .boxed()
 726    }
 727
 728    pub fn insert_tree_from_real_fs<'a>(
 729        &'a self,
 730        path: impl 'a + AsRef<Path> + Send,
 731        src_path: impl 'a + AsRef<Path> + Send,
 732    ) -> futures::future::BoxFuture<'a, ()> {
 733        use futures::FutureExt as _;
 734
 735        async move {
 736            let path = path.as_ref();
 737            if std::fs::metadata(&src_path).unwrap().is_file() {
 738                let contents = std::fs::read(src_path).unwrap();
 739                self.insert_file(path, contents).await;
 740            } else {
 741                self.create_dir(path).await.unwrap();
 742                for entry in std::fs::read_dir(&src_path).unwrap() {
 743                    let entry = entry.unwrap();
 744                    self.insert_tree_from_real_fs(&path.join(entry.file_name()), &entry.path())
 745                        .await;
 746                }
 747            }
 748        }
 749        .boxed()
 750    }
 751
 752    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
 753    where
 754        F: FnOnce(&mut FakeGitRepositoryState),
 755    {
 756        let mut state = self.state.lock();
 757        let entry = state.read_path(dot_git).unwrap();
 758        let mut entry = entry.lock();
 759
 760        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
 761            let repo_state = git_repo_state.get_or_insert_with(Default::default);
 762            let mut repo_state = repo_state.lock();
 763
 764            f(&mut repo_state);
 765
 766            if emit_git_event {
 767                state.emit_event([dot_git]);
 768            }
 769        } else {
 770            panic!("not a directory");
 771        }
 772    }
 773
 774    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
 775        self.with_git_state(dot_git, true, |state| {
 776            state.branch_name = branch.map(Into::into)
 777        })
 778    }
 779
 780    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
 781        self.with_git_state(dot_git, true, |state| {
 782            state.index_contents.clear();
 783            state.index_contents.extend(
 784                head_state
 785                    .iter()
 786                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
 787            );
 788        });
 789    }
 790
 791    pub fn set_status_for_repo_via_working_copy_change(
 792        &self,
 793        dot_git: &Path,
 794        statuses: &[(&Path, GitFileStatus)],
 795    ) {
 796        self.with_git_state(dot_git, false, |state| {
 797            state.worktree_statuses.clear();
 798            state.worktree_statuses.extend(
 799                statuses
 800                    .iter()
 801                    .map(|(path, content)| ((**path).into(), *content)),
 802            );
 803        });
 804        self.state.lock().emit_event(
 805            statuses
 806                .iter()
 807                .map(|(path, _)| dot_git.parent().unwrap().join(path)),
 808        );
 809    }
 810
 811    pub fn set_status_for_repo_via_git_operation(
 812        &self,
 813        dot_git: &Path,
 814        statuses: &[(&Path, GitFileStatus)],
 815    ) {
 816        self.with_git_state(dot_git, true, |state| {
 817            state.worktree_statuses.clear();
 818            state.worktree_statuses.extend(
 819                statuses
 820                    .iter()
 821                    .map(|(path, content)| ((**path).into(), *content)),
 822            );
 823        });
 824    }
 825
 826    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
 827        let mut result = Vec::new();
 828        let mut queue = collections::VecDeque::new();
 829        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 830        while let Some((path, entry)) = queue.pop_front() {
 831            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 832                for (name, entry) in entries {
 833                    queue.push_back((path.join(name), entry.clone()));
 834                }
 835            }
 836            if include_dot_git
 837                || !path
 838                    .components()
 839                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
 840            {
 841                result.push(path);
 842            }
 843        }
 844        result
 845    }
 846
 847    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
 848        let mut result = Vec::new();
 849        let mut queue = collections::VecDeque::new();
 850        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 851        while let Some((path, entry)) = queue.pop_front() {
 852            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 853                for (name, entry) in entries {
 854                    queue.push_back((path.join(name), entry.clone()));
 855                }
 856                if include_dot_git
 857                    || !path
 858                        .components()
 859                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
 860                {
 861                    result.push(path);
 862                }
 863            }
 864        }
 865        result
 866    }
 867
 868    pub fn files(&self) -> Vec<PathBuf> {
 869        let mut result = Vec::new();
 870        let mut queue = collections::VecDeque::new();
 871        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 872        while let Some((path, entry)) = queue.pop_front() {
 873            let e = entry.lock();
 874            match &*e {
 875                FakeFsEntry::File { .. } => result.push(path),
 876                FakeFsEntry::Dir { entries, .. } => {
 877                    for (name, entry) in entries {
 878                        queue.push_back((path.join(name), entry.clone()));
 879                    }
 880                }
 881                FakeFsEntry::Symlink { .. } => {}
 882            }
 883        }
 884        result
 885    }
 886
 887    /// How many `read_dir` calls have been issued.
 888    pub fn read_dir_call_count(&self) -> usize {
 889        self.state.lock().read_dir_call_count
 890    }
 891
 892    /// How many `metadata` calls have been issued.
 893    pub fn metadata_call_count(&self) -> usize {
 894        self.state.lock().metadata_call_count
 895    }
 896
 897    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
 898        self.executor.simulate_random_delay()
 899    }
 900}
 901
 902#[cfg(any(test, feature = "test-support"))]
 903impl FakeFsEntry {
 904    fn is_file(&self) -> bool {
 905        matches!(self, Self::File { .. })
 906    }
 907
 908    fn is_symlink(&self) -> bool {
 909        matches!(self, Self::Symlink { .. })
 910    }
 911
 912    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
 913        if let Self::File { content, .. } = self {
 914            Ok(content)
 915        } else {
 916            Err(anyhow!("not a file: {}", path.display()))
 917        }
 918    }
 919
 920    fn set_file_content(&mut self, path: &Path, new_content: Vec<u8>) -> Result<()> {
 921        if let Self::File { content, mtime, .. } = self {
 922            *mtime = SystemTime::now();
 923            *content = new_content;
 924            Ok(())
 925        } else {
 926            Err(anyhow!("not a file: {}", path.display()))
 927        }
 928    }
 929
 930    fn dir_entries(
 931        &mut self,
 932        path: &Path,
 933    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 934        if let Self::Dir { entries, .. } = self {
 935            Ok(entries)
 936        } else {
 937            Err(anyhow!("not a directory: {}", path.display()))
 938        }
 939    }
 940}
 941
 942#[cfg(any(test, feature = "test-support"))]
 943#[async_trait::async_trait]
 944impl Fs for FakeFs {
 945    async fn create_dir(&self, path: &Path) -> Result<()> {
 946        self.simulate_random_delay().await;
 947
 948        let mut created_dirs = Vec::new();
 949        let mut cur_path = PathBuf::new();
 950        for component in path.components() {
 951            let mut state = self.state.lock();
 952            cur_path.push(component);
 953            if cur_path == Path::new("/") {
 954                continue;
 955            }
 956
 957            let inode = state.next_inode;
 958            let mtime = state.next_mtime;
 959            state.next_mtime += Duration::from_nanos(1);
 960            state.next_inode += 1;
 961            state.write_path(&cur_path, |entry| {
 962                entry.or_insert_with(|| {
 963                    created_dirs.push(cur_path.clone());
 964                    Arc::new(Mutex::new(FakeFsEntry::Dir {
 965                        inode,
 966                        mtime,
 967                        entries: Default::default(),
 968                        git_repo_state: None,
 969                    }))
 970                });
 971                Ok(())
 972            })?
 973        }
 974
 975        self.state.lock().emit_event(&created_dirs);
 976        Ok(())
 977    }
 978
 979    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 980        self.simulate_random_delay().await;
 981        let mut state = self.state.lock();
 982        let inode = state.next_inode;
 983        let mtime = state.next_mtime;
 984        state.next_mtime += Duration::from_nanos(1);
 985        state.next_inode += 1;
 986        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 987            inode,
 988            mtime,
 989            content: Vec::new(),
 990        }));
 991        state.write_path(path, |entry| {
 992            match entry {
 993                btree_map::Entry::Occupied(mut e) => {
 994                    if options.overwrite {
 995                        *e.get_mut() = file;
 996                    } else if !options.ignore_if_exists {
 997                        return Err(anyhow!("path already exists: {}", path.display()));
 998                    }
 999                }
1000                btree_map::Entry::Vacant(e) => {
1001                    e.insert(file);
1002                }
1003            }
1004            Ok(())
1005        })?;
1006        state.emit_event([path]);
1007        Ok(())
1008    }
1009
1010    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1011        let mut state = self.state.lock();
1012        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1013        state
1014            .write_path(path.as_ref(), move |e| match e {
1015                btree_map::Entry::Vacant(e) => {
1016                    e.insert(file);
1017                    Ok(())
1018                }
1019                btree_map::Entry::Occupied(mut e) => {
1020                    *e.get_mut() = file;
1021                    Ok(())
1022                }
1023            })
1024            .unwrap();
1025        state.emit_event(&[path]);
1026        Ok(())
1027    }
1028
1029    async fn create_file_with(
1030        &self,
1031        path: &Path,
1032        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1033    ) -> Result<()> {
1034        let mut bytes = Vec::new();
1035        content.read_to_end(&mut bytes).await?;
1036        self.write_file_internal(path, bytes)?;
1037        Ok(())
1038    }
1039
1040    async fn extract_tar_file(
1041        &self,
1042        path: &Path,
1043        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1044    ) -> Result<()> {
1045        let mut entries = content.entries()?;
1046        while let Some(entry) = entries.next().await {
1047            let mut entry = entry?;
1048            if entry.header().entry_type().is_file() {
1049                let path = path.join(entry.path()?.as_ref());
1050                let mut bytes = Vec::new();
1051                entry.read_to_end(&mut bytes).await?;
1052                self.create_dir(path.parent().unwrap()).await?;
1053                self.write_file_internal(&path, bytes)?;
1054            }
1055        }
1056        Ok(())
1057    }
1058
1059    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1060        self.simulate_random_delay().await;
1061
1062        let old_path = normalize_path(old_path);
1063        let new_path = normalize_path(new_path);
1064
1065        let mut state = self.state.lock();
1066        let moved_entry = state.write_path(&old_path, |e| {
1067            if let btree_map::Entry::Occupied(e) = e {
1068                Ok(e.get().clone())
1069            } else {
1070                Err(anyhow!("path does not exist: {}", &old_path.display()))
1071            }
1072        })?;
1073
1074        state.write_path(&new_path, |e| {
1075            match e {
1076                btree_map::Entry::Occupied(mut e) => {
1077                    if options.overwrite {
1078                        *e.get_mut() = moved_entry;
1079                    } else if !options.ignore_if_exists {
1080                        return Err(anyhow!("path already exists: {}", new_path.display()));
1081                    }
1082                }
1083                btree_map::Entry::Vacant(e) => {
1084                    e.insert(moved_entry);
1085                }
1086            }
1087            Ok(())
1088        })?;
1089
1090        state
1091            .write_path(&old_path, |e| {
1092                if let btree_map::Entry::Occupied(e) = e {
1093                    Ok(e.remove())
1094                } else {
1095                    unreachable!()
1096                }
1097            })
1098            .unwrap();
1099
1100        state.emit_event(&[old_path, new_path]);
1101        Ok(())
1102    }
1103
1104    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1105        self.simulate_random_delay().await;
1106
1107        let source = normalize_path(source);
1108        let target = normalize_path(target);
1109        let mut state = self.state.lock();
1110        let mtime = state.next_mtime;
1111        let inode = util::post_inc(&mut state.next_inode);
1112        state.next_mtime += Duration::from_nanos(1);
1113        let source_entry = state.read_path(&source)?;
1114        let content = source_entry.lock().file_content(&source)?.clone();
1115        let entry = state.write_path(&target, |e| match e {
1116            btree_map::Entry::Occupied(e) => {
1117                if options.overwrite {
1118                    Ok(Some(e.get().clone()))
1119                } else if !options.ignore_if_exists {
1120                    return Err(anyhow!("{target:?} already exists"));
1121                } else {
1122                    Ok(None)
1123                }
1124            }
1125            btree_map::Entry::Vacant(e) => Ok(Some(
1126                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1127                    inode,
1128                    mtime,
1129                    content: Vec::new(),
1130                })))
1131                .clone(),
1132            )),
1133        })?;
1134        if let Some(entry) = entry {
1135            entry.lock().set_file_content(&target, content)?;
1136        }
1137        state.emit_event(&[target]);
1138        Ok(())
1139    }
1140
1141    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1142        self.simulate_random_delay().await;
1143
1144        let path = normalize_path(path);
1145        let parent_path = path
1146            .parent()
1147            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1148        let base_name = path.file_name().unwrap();
1149
1150        let mut state = self.state.lock();
1151        let parent_entry = state.read_path(parent_path)?;
1152        let mut parent_entry = parent_entry.lock();
1153        let entry = parent_entry
1154            .dir_entries(parent_path)?
1155            .entry(base_name.to_str().unwrap().into());
1156
1157        match entry {
1158            btree_map::Entry::Vacant(_) => {
1159                if !options.ignore_if_not_exists {
1160                    return Err(anyhow!("{path:?} does not exist"));
1161                }
1162            }
1163            btree_map::Entry::Occupied(e) => {
1164                {
1165                    let mut entry = e.get().lock();
1166                    let children = entry.dir_entries(&path)?;
1167                    if !options.recursive && !children.is_empty() {
1168                        return Err(anyhow!("{path:?} is not empty"));
1169                    }
1170                }
1171                e.remove();
1172            }
1173        }
1174        state.emit_event(&[path]);
1175        Ok(())
1176    }
1177
1178    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1179        self.simulate_random_delay().await;
1180
1181        let path = normalize_path(path);
1182        let parent_path = path
1183            .parent()
1184            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1185        let base_name = path.file_name().unwrap();
1186        let mut state = self.state.lock();
1187        let parent_entry = state.read_path(parent_path)?;
1188        let mut parent_entry = parent_entry.lock();
1189        let entry = parent_entry
1190            .dir_entries(parent_path)?
1191            .entry(base_name.to_str().unwrap().into());
1192        match entry {
1193            btree_map::Entry::Vacant(_) => {
1194                if !options.ignore_if_not_exists {
1195                    return Err(anyhow!("{path:?} does not exist"));
1196                }
1197            }
1198            btree_map::Entry::Occupied(e) => {
1199                e.get().lock().file_content(&path)?;
1200                e.remove();
1201            }
1202        }
1203        state.emit_event(&[path]);
1204        Ok(())
1205    }
1206
1207    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1208        let bytes = self.load_internal(path).await?;
1209        Ok(Box::new(io::Cursor::new(bytes)))
1210    }
1211
1212    async fn load(&self, path: &Path) -> Result<String> {
1213        let content = self.load_internal(path).await?;
1214        Ok(String::from_utf8(content.clone())?)
1215    }
1216
1217    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1218        self.simulate_random_delay().await;
1219        let path = normalize_path(path.as_path());
1220        self.write_file_internal(path, data.into_bytes())?;
1221        Ok(())
1222    }
1223
1224    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1225        self.simulate_random_delay().await;
1226        let path = normalize_path(path);
1227        let content = chunks(text, line_ending).collect::<String>();
1228        if let Some(path) = path.parent() {
1229            self.create_dir(path).await?;
1230        }
1231        self.write_file_internal(path, content.into_bytes())?;
1232        Ok(())
1233    }
1234
1235    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1236        let path = normalize_path(path);
1237        self.simulate_random_delay().await;
1238        let state = self.state.lock();
1239        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1240            Ok(canonical_path)
1241        } else {
1242            Err(anyhow!("path does not exist: {}", path.display()))
1243        }
1244    }
1245
1246    async fn is_file(&self, path: &Path) -> bool {
1247        let path = normalize_path(path);
1248        self.simulate_random_delay().await;
1249        let state = self.state.lock();
1250        if let Some((entry, _)) = state.try_read_path(&path, true) {
1251            entry.lock().is_file()
1252        } else {
1253            false
1254        }
1255    }
1256
1257    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1258        self.simulate_random_delay().await;
1259        let path = normalize_path(path);
1260        let mut state = self.state.lock();
1261        state.metadata_call_count += 1;
1262        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1263            let is_symlink = entry.lock().is_symlink();
1264            if is_symlink {
1265                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1266                    entry = e;
1267                } else {
1268                    return Ok(None);
1269                }
1270            }
1271
1272            let entry = entry.lock();
1273            Ok(Some(match &*entry {
1274                FakeFsEntry::File { inode, mtime, .. } => Metadata {
1275                    inode: *inode,
1276                    mtime: *mtime,
1277                    is_dir: false,
1278                    is_symlink,
1279                },
1280                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1281                    inode: *inode,
1282                    mtime: *mtime,
1283                    is_dir: true,
1284                    is_symlink,
1285                },
1286                FakeFsEntry::Symlink { .. } => unreachable!(),
1287            }))
1288        } else {
1289            Ok(None)
1290        }
1291    }
1292
1293    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1294        self.simulate_random_delay().await;
1295        let path = normalize_path(path);
1296        let state = self.state.lock();
1297        if let Some((entry, _)) = state.try_read_path(&path, false) {
1298            let entry = entry.lock();
1299            if let FakeFsEntry::Symlink { target } = &*entry {
1300                Ok(target.clone())
1301            } else {
1302                Err(anyhow!("not a symlink: {}", path.display()))
1303            }
1304        } else {
1305            Err(anyhow!("path does not exist: {}", path.display()))
1306        }
1307    }
1308
1309    async fn read_dir(
1310        &self,
1311        path: &Path,
1312    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1313        self.simulate_random_delay().await;
1314        let path = normalize_path(path);
1315        let mut state = self.state.lock();
1316        state.read_dir_call_count += 1;
1317        let entry = state.read_path(&path)?;
1318        let mut entry = entry.lock();
1319        let children = entry.dir_entries(&path)?;
1320        let paths = children
1321            .keys()
1322            .map(|file_name| Ok(path.join(file_name)))
1323            .collect::<Vec<_>>();
1324        Ok(Box::pin(futures::stream::iter(paths)))
1325    }
1326
1327    async fn watch(
1328        &self,
1329        path: &Path,
1330        _: Duration,
1331    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
1332        self.simulate_random_delay().await;
1333        let (tx, rx) = smol::channel::unbounded();
1334        self.state.lock().event_txs.push(tx);
1335        let path = path.to_path_buf();
1336        let executor = self.executor.clone();
1337        Box::pin(futures::StreamExt::filter(rx, move |events| {
1338            let result = events.iter().any(|event| event.path.starts_with(&path));
1339            let executor = executor.clone();
1340            async move {
1341                executor.simulate_random_delay().await;
1342                result
1343            }
1344        }))
1345    }
1346
1347    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
1348        let state = self.state.lock();
1349        let entry = state.read_path(abs_dot_git).unwrap();
1350        let mut entry = entry.lock();
1351        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1352            let state = git_repo_state
1353                .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
1354                .clone();
1355            Some(repository::FakeGitRepository::open(state))
1356        } else {
1357            None
1358        }
1359    }
1360
1361    fn is_fake(&self) -> bool {
1362        true
1363    }
1364
1365    async fn is_case_sensitive(&self) -> Result<bool> {
1366        Ok(true)
1367    }
1368
1369    #[cfg(any(test, feature = "test-support"))]
1370    fn as_fake(&self) -> &FakeFs {
1371        self
1372    }
1373}
1374
1375fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1376    rope.chunks().flat_map(move |chunk| {
1377        let mut newline = false;
1378        chunk.split('\n').flat_map(move |line| {
1379            let ending = if newline {
1380                Some(line_ending.as_str())
1381            } else {
1382                None
1383            };
1384            newline = true;
1385            ending.into_iter().chain([line])
1386        })
1387    })
1388}
1389
1390pub fn normalize_path(path: &Path) -> PathBuf {
1391    let mut components = path.components().peekable();
1392    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1393        components.next();
1394        PathBuf::from(c.as_os_str())
1395    } else {
1396        PathBuf::new()
1397    };
1398
1399    for component in components {
1400        match component {
1401            Component::Prefix(..) => unreachable!(),
1402            Component::RootDir => {
1403                ret.push(component.as_os_str());
1404            }
1405            Component::CurDir => {}
1406            Component::ParentDir => {
1407                ret.pop();
1408            }
1409            Component::Normal(c) => {
1410                ret.push(c);
1411            }
1412        }
1413    }
1414    ret
1415}
1416
1417pub fn copy_recursive<'a>(
1418    fs: &'a dyn Fs,
1419    source: &'a Path,
1420    target: &'a Path,
1421    options: CopyOptions,
1422) -> BoxFuture<'a, Result<()>> {
1423    use futures::future::FutureExt;
1424
1425    async move {
1426        let metadata = fs
1427            .metadata(source)
1428            .await?
1429            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1430        if metadata.is_dir {
1431            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1432                if options.ignore_if_exists {
1433                    return Ok(());
1434                } else {
1435                    return Err(anyhow!("{target:?} already exists"));
1436                }
1437            }
1438
1439            let _ = fs
1440                .remove_dir(
1441                    target,
1442                    RemoveOptions {
1443                        recursive: true,
1444                        ignore_if_not_exists: true,
1445                    },
1446                )
1447                .await;
1448            fs.create_dir(target).await?;
1449            let mut children = fs.read_dir(source).await?;
1450            while let Some(child_path) = children.next().await {
1451                if let Ok(child_path) = child_path {
1452                    if let Some(file_name) = child_path.file_name() {
1453                        let child_target_path = target.join(file_name);
1454                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1455                    }
1456                }
1457            }
1458
1459            Ok(())
1460        } else {
1461            fs.copy_file(source, target, options).await
1462        }
1463    }
1464    .boxed()
1465}
1466
1467// todo(windows)
1468// can we get file id not open the file twice?
1469// https://github.com/rust-lang/rust/issues/63010
1470#[cfg(target_os = "windows")]
1471async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
1472    use std::os::windows::io::AsRawHandle;
1473
1474    use smol::fs::windows::OpenOptionsExt;
1475    use windows_sys::Win32::{
1476        Foundation::HANDLE,
1477        Storage::FileSystem::{
1478            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
1479        },
1480    };
1481
1482    let file = smol::fs::OpenOptions::new()
1483        .read(true)
1484        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1485        .open(path)
1486        .await?;
1487
1488    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
1489    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
1490    // This function supports Windows XP+
1491    smol::unblock(move || {
1492        let ret = unsafe { GetFileInformationByHandle(file.as_raw_handle() as HANDLE, &mut info) };
1493        if ret == 0 {
1494            return Err(anyhow!(format!("{}", std::io::Error::last_os_error())));
1495        };
1496
1497        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
1498    })
1499    .await
1500}
1501
1502#[cfg(test)]
1503mod tests {
1504    use super::*;
1505    use gpui::BackgroundExecutor;
1506    use serde_json::json;
1507
1508    #[gpui::test]
1509    async fn test_fake_fs(executor: BackgroundExecutor) {
1510        let fs = FakeFs::new(executor.clone());
1511        fs.insert_tree(
1512            "/root",
1513            json!({
1514                "dir1": {
1515                    "a": "A",
1516                    "b": "B"
1517                },
1518                "dir2": {
1519                    "c": "C",
1520                    "dir3": {
1521                        "d": "D"
1522                    }
1523                }
1524            }),
1525        )
1526        .await;
1527
1528        assert_eq!(
1529            fs.files(),
1530            vec![
1531                PathBuf::from("/root/dir1/a"),
1532                PathBuf::from("/root/dir1/b"),
1533                PathBuf::from("/root/dir2/c"),
1534                PathBuf::from("/root/dir2/dir3/d"),
1535            ]
1536        );
1537
1538        fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
1539            .await
1540            .unwrap();
1541
1542        assert_eq!(
1543            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1544                .await
1545                .unwrap(),
1546            PathBuf::from("/root/dir2/dir3"),
1547        );
1548        assert_eq!(
1549            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1550                .await
1551                .unwrap(),
1552            PathBuf::from("/root/dir2/dir3/d"),
1553        );
1554        assert_eq!(
1555            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1556            "D",
1557        );
1558    }
1559}