fs.rs

   1pub mod fs_watcher;
   2
   3use parking_lot::Mutex;
   4use std::sync::atomic::{AtomicUsize, Ordering};
   5use std::time::Instant;
   6
   7use anyhow::{Context as _, Result, anyhow};
   8#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   9use ashpd::desktop::trash;
  10use futures::stream::iter;
  11use gpui::App;
  12use gpui::BackgroundExecutor;
  13use gpui::Global;
  14use gpui::ReadGlobal as _;
  15use gpui::SharedString;
  16use std::borrow::Cow;
  17use util::command::new_smol_command;
  18
  19#[cfg(unix)]
  20use std::os::fd::{AsFd, AsRawFd};
  21
  22#[cfg(unix)]
  23use std::os::unix::fs::{FileTypeExt, MetadataExt};
  24
  25#[cfg(any(target_os = "macos", target_os = "freebsd"))]
  26use std::mem::MaybeUninit;
  27
  28use async_tar::Archive;
  29use futures::{AsyncRead, Stream, StreamExt, future::BoxFuture};
  30use git::repository::{GitRepository, RealGitRepository};
  31use is_executable::IsExecutable;
  32use rope::Rope;
  33use serde::{Deserialize, Serialize};
  34use smol::io::AsyncWriteExt;
  35use std::{
  36    io::{self, Write},
  37    path::{Component, Path, PathBuf},
  38    pin::Pin,
  39    sync::Arc,
  40    time::{Duration, SystemTime, UNIX_EPOCH},
  41};
  42use tempfile::TempDir;
  43use text::LineEnding;
  44
  45#[cfg(feature = "test-support")]
  46mod fake_git_repo;
  47#[cfg(feature = "test-support")]
  48use collections::{BTreeMap, btree_map};
  49#[cfg(feature = "test-support")]
  50use fake_git_repo::FakeGitRepositoryState;
  51#[cfg(feature = "test-support")]
  52use git::{
  53    repository::{InitialGraphCommitData, RepoPath, repo_path},
  54    status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus},
  55};
  56
  57#[cfg(feature = "test-support")]
  58use smol::io::AsyncReadExt;
  59#[cfg(feature = "test-support")]
  60use std::ffi::OsStr;
  61
  62pub trait Watcher: Send + Sync {
  63    fn add(&self, path: &Path) -> Result<()>;
  64    fn remove(&self, path: &Path) -> Result<()>;
  65}
  66
  67#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  68pub enum PathEventKind {
  69    Removed,
  70    Created,
  71    Changed,
  72}
  73
  74#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  75pub struct PathEvent {
  76    pub path: PathBuf,
  77    pub kind: Option<PathEventKind>,
  78}
  79
  80impl From<PathEvent> for PathBuf {
  81    fn from(event: PathEvent) -> Self {
  82        event.path
  83    }
  84}
  85
  86#[async_trait::async_trait]
  87pub trait Fs: Send + Sync {
  88    async fn create_dir(&self, path: &Path) -> Result<()>;
  89    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  90    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  91    async fn create_file_with(
  92        &self,
  93        path: &Path,
  94        content: Pin<&mut (dyn AsyncRead + Send)>,
  95    ) -> Result<()>;
  96    async fn extract_tar_file(
  97        &self,
  98        path: &Path,
  99        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 100    ) -> Result<()>;
 101    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
 102    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
 103    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 104    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 105        self.remove_dir(path, options).await
 106    }
 107    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 108    async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 109        self.remove_file(path, options).await
 110    }
 111    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
 112    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>>;
 113    async fn load(&self, path: &Path) -> Result<String> {
 114        Ok(String::from_utf8(self.load_bytes(path).await?)?)
 115    }
 116    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
 117    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 118    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
 119    async fn write(&self, path: &Path, content: &[u8]) -> Result<()>;
 120    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 121    async fn is_file(&self, path: &Path) -> bool;
 122    async fn is_dir(&self, path: &Path) -> bool;
 123    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 124    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 125    async fn read_dir(
 126        &self,
 127        path: &Path,
 128    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 129
 130    async fn watch(
 131        &self,
 132        path: &Path,
 133        latency: Duration,
 134    ) -> (
 135        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 136        Arc<dyn Watcher>,
 137    );
 138
 139    fn open_repo(
 140        &self,
 141        abs_dot_git: &Path,
 142        system_git_binary_path: Option<&Path>,
 143    ) -> Option<Arc<dyn GitRepository>>;
 144    async fn git_init(&self, abs_work_directory: &Path, fallback_branch_name: String)
 145    -> Result<()>;
 146    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()>;
 147    fn is_fake(&self) -> bool;
 148    async fn is_case_sensitive(&self) -> Result<bool>;
 149    fn subscribe_to_jobs(&self) -> JobEventReceiver;
 150
 151    #[cfg(feature = "test-support")]
 152    fn as_fake(&self) -> Arc<FakeFs> {
 153        panic!("called as_fake on a real fs");
 154    }
 155}
 156
 157struct GlobalFs(Arc<dyn Fs>);
 158
 159impl Global for GlobalFs {}
 160
 161impl dyn Fs {
 162    /// Returns the global [`Fs`].
 163    pub fn global(cx: &App) -> Arc<Self> {
 164        GlobalFs::global(cx).0.clone()
 165    }
 166
 167    /// Sets the global [`Fs`].
 168    pub fn set_global(fs: Arc<Self>, cx: &mut App) {
 169        cx.set_global(GlobalFs(fs));
 170    }
 171}
 172
 173#[derive(Copy, Clone, Default)]
 174pub struct CreateOptions {
 175    pub overwrite: bool,
 176    pub ignore_if_exists: bool,
 177}
 178
 179#[derive(Copy, Clone, Default)]
 180pub struct CopyOptions {
 181    pub overwrite: bool,
 182    pub ignore_if_exists: bool,
 183}
 184
 185#[derive(Copy, Clone, Default)]
 186pub struct RenameOptions {
 187    pub overwrite: bool,
 188    pub ignore_if_exists: bool,
 189    /// Whether to create parent directories if they do not exist.
 190    pub create_parents: bool,
 191}
 192
 193#[derive(Copy, Clone, Default)]
 194pub struct RemoveOptions {
 195    pub recursive: bool,
 196    pub ignore_if_not_exists: bool,
 197}
 198
 199#[derive(Copy, Clone, Debug)]
 200pub struct Metadata {
 201    pub inode: u64,
 202    pub mtime: MTime,
 203    pub is_symlink: bool,
 204    pub is_dir: bool,
 205    pub len: u64,
 206    pub is_fifo: bool,
 207    pub is_executable: bool,
 208}
 209
 210/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
 211/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
 212/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
 213/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
 214///
 215/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
 216#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
 217#[serde(transparent)]
 218pub struct MTime(SystemTime);
 219
 220pub type JobId = usize;
 221
 222#[derive(Clone, Debug)]
 223pub struct JobInfo {
 224    pub start: Instant,
 225    pub message: SharedString,
 226    pub id: JobId,
 227}
 228
 229#[derive(Debug, Clone)]
 230pub enum JobEvent {
 231    Started { info: JobInfo },
 232    Completed { id: JobId },
 233}
 234
 235pub type JobEventSender = futures::channel::mpsc::UnboundedSender<JobEvent>;
 236pub type JobEventReceiver = futures::channel::mpsc::UnboundedReceiver<JobEvent>;
 237
 238struct JobTracker {
 239    id: JobId,
 240    subscribers: Arc<Mutex<Vec<JobEventSender>>>,
 241}
 242
 243impl JobTracker {
 244    fn new(info: JobInfo, subscribers: Arc<Mutex<Vec<JobEventSender>>>) -> Self {
 245        let id = info.id;
 246        {
 247            let mut subs = subscribers.lock();
 248            subs.retain(|sender| {
 249                sender
 250                    .unbounded_send(JobEvent::Started { info: info.clone() })
 251                    .is_ok()
 252            });
 253        }
 254        Self { id, subscribers }
 255    }
 256}
 257
 258impl Drop for JobTracker {
 259    fn drop(&mut self) {
 260        let mut subs = self.subscribers.lock();
 261        subs.retain(|sender| {
 262            sender
 263                .unbounded_send(JobEvent::Completed { id: self.id })
 264                .is_ok()
 265        });
 266    }
 267}
 268
 269impl MTime {
 270    /// Conversion intended for persistence and testing.
 271    pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
 272        MTime(UNIX_EPOCH + Duration::new(secs, nanos))
 273    }
 274
 275    /// Conversion intended for persistence.
 276    pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
 277        self.0
 278            .duration_since(UNIX_EPOCH)
 279            .ok()
 280            .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
 281    }
 282
 283    /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
 284    /// "_for_user" is to discourage misuse - this method should not be used when making decisions
 285    /// about file dirtiness.
 286    pub fn timestamp_for_user(self) -> SystemTime {
 287        self.0
 288    }
 289
 290    /// Temporary method to split out the behavior changes from introduction of this newtype.
 291    pub fn bad_is_greater_than(self, other: MTime) -> bool {
 292        self.0 > other.0
 293    }
 294}
 295
 296impl From<proto::Timestamp> for MTime {
 297    fn from(timestamp: proto::Timestamp) -> Self {
 298        MTime(timestamp.into())
 299    }
 300}
 301
 302impl From<MTime> for proto::Timestamp {
 303    fn from(mtime: MTime) -> Self {
 304        mtime.0.into()
 305    }
 306}
 307
 308pub struct RealFs {
 309    bundled_git_binary_path: Option<PathBuf>,
 310    executor: BackgroundExecutor,
 311    next_job_id: Arc<AtomicUsize>,
 312    job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,
 313}
 314
 315pub trait FileHandle: Send + Sync + std::fmt::Debug {
 316    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
 317}
 318
 319impl FileHandle for std::fs::File {
 320    #[cfg(target_os = "macos")]
 321    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 322        use std::{
 323            ffi::{CStr, OsStr},
 324            os::unix::ffi::OsStrExt,
 325        };
 326
 327        let fd = self.as_fd();
 328        let mut path_buf = MaybeUninit::<[u8; libc::PATH_MAX as usize]>::uninit();
 329
 330        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
 331        anyhow::ensure!(result != -1, "fcntl returned -1");
 332
 333        // SAFETY: `fcntl` will initialize the path buffer.
 334        let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr().cast()) };
 335        anyhow::ensure!(!c_str.is_empty(), "Could find a path for the file handle");
 336        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 337        Ok(path)
 338    }
 339
 340    #[cfg(target_os = "linux")]
 341    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 342        let fd = self.as_fd();
 343        let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
 344        let new_path = std::fs::read_link(fd_path)?;
 345        if new_path
 346            .file_name()
 347            .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
 348        {
 349            anyhow::bail!("file was deleted")
 350        };
 351
 352        Ok(new_path)
 353    }
 354
 355    #[cfg(target_os = "freebsd")]
 356    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 357        use std::{
 358            ffi::{CStr, OsStr},
 359            os::unix::ffi::OsStrExt,
 360        };
 361
 362        let fd = self.as_fd();
 363        let mut kif = MaybeUninit::<libc::kinfo_file>::uninit();
 364        kif.kf_structsize = libc::KINFO_FILE_SIZE;
 365
 366        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_KINFO, kif.as_mut_ptr()) };
 367        anyhow::ensure!(result != -1, "fcntl returned -1");
 368
 369        // SAFETY: `fcntl` will initialize the kif.
 370        let c_str = unsafe { CStr::from_ptr(kif.assume_init().kf_path.as_ptr()) };
 371        anyhow::ensure!(!c_str.is_empty(), "Could find a path for the file handle");
 372        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 373        Ok(path)
 374    }
 375
 376    #[cfg(target_os = "windows")]
 377    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 378        use std::ffi::OsString;
 379        use std::os::windows::ffi::OsStringExt;
 380        use std::os::windows::io::AsRawHandle;
 381
 382        use windows::Win32::Foundation::HANDLE;
 383        use windows::Win32::Storage::FileSystem::{
 384            FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW,
 385        };
 386
 387        let handle = HANDLE(self.as_raw_handle() as _);
 388
 389        // Query required buffer size (in wide chars)
 390        let required_len =
 391            unsafe { GetFinalPathNameByHandleW(handle, &mut [], FILE_NAME_NORMALIZED) };
 392        anyhow::ensure!(
 393            required_len != 0,
 394            "GetFinalPathNameByHandleW returned 0 length"
 395        );
 396
 397        // Allocate buffer and retrieve the path
 398        let mut buf: Vec<u16> = vec![0u16; required_len as usize + 1];
 399        let written = unsafe { GetFinalPathNameByHandleW(handle, &mut buf, FILE_NAME_NORMALIZED) };
 400        anyhow::ensure!(
 401            written != 0,
 402            "GetFinalPathNameByHandleW failed to write path"
 403        );
 404
 405        let os_str: OsString = OsString::from_wide(&buf[..written as usize]);
 406        anyhow::ensure!(!os_str.is_empty(), "Could find a path for the file handle");
 407        Ok(PathBuf::from(os_str))
 408    }
 409}
 410
 411pub struct RealWatcher {}
 412
 413impl RealFs {
 414    pub fn new(git_binary_path: Option<PathBuf>, executor: BackgroundExecutor) -> Self {
 415        Self {
 416            bundled_git_binary_path: git_binary_path,
 417            executor,
 418            next_job_id: Arc::new(AtomicUsize::new(0)),
 419            job_event_subscribers: Arc::new(Mutex::new(Vec::new())),
 420        }
 421    }
 422
 423    #[cfg(target_os = "windows")]
 424    fn canonicalize(path: &Path) -> Result<PathBuf> {
 425        let mut strip_prefix = None;
 426
 427        let mut new_path = PathBuf::new();
 428        for component in path.components() {
 429            match component {
 430                std::path::Component::Prefix(_) => {
 431                    let component = component.as_os_str();
 432                    let canonicalized = if component
 433                        .to_str()
 434                        .map(|e| e.ends_with("\\"))
 435                        .unwrap_or(false)
 436                    {
 437                        std::fs::canonicalize(component)
 438                    } else {
 439                        let mut component = component.to_os_string();
 440                        component.push("\\");
 441                        std::fs::canonicalize(component)
 442                    }?;
 443
 444                    let mut strip = PathBuf::new();
 445                    for component in canonicalized.components() {
 446                        match component {
 447                            Component::Prefix(prefix_component) => {
 448                                match prefix_component.kind() {
 449                                    std::path::Prefix::Verbatim(os_str) => {
 450                                        strip.push(os_str);
 451                                    }
 452                                    std::path::Prefix::VerbatimUNC(host, share) => {
 453                                        strip.push("\\\\");
 454                                        strip.push(host);
 455                                        strip.push(share);
 456                                    }
 457                                    std::path::Prefix::VerbatimDisk(disk) => {
 458                                        strip.push(format!("{}:", disk as char));
 459                                    }
 460                                    _ => strip.push(component),
 461                                };
 462                            }
 463                            _ => strip.push(component),
 464                        }
 465                    }
 466                    strip_prefix = Some(strip);
 467                    new_path.push(component);
 468                }
 469                std::path::Component::RootDir => {
 470                    new_path.push(component);
 471                }
 472                std::path::Component::CurDir => {
 473                    if strip_prefix.is_none() {
 474                        // unrooted path
 475                        new_path.push(component);
 476                    }
 477                }
 478                std::path::Component::ParentDir => {
 479                    if strip_prefix.is_some() {
 480                        // rooted path
 481                        new_path.pop();
 482                    } else {
 483                        new_path.push(component);
 484                    }
 485                }
 486                std::path::Component::Normal(_) => {
 487                    if let Ok(link) = std::fs::read_link(new_path.join(component)) {
 488                        let link = match &strip_prefix {
 489                            Some(e) => link.strip_prefix(e).unwrap_or(&link),
 490                            None => &link,
 491                        };
 492                        new_path.extend(link);
 493                    } else {
 494                        new_path.push(component);
 495                    }
 496                }
 497            }
 498        }
 499
 500        Ok(new_path)
 501    }
 502}
 503
 504#[async_trait::async_trait]
 505impl Fs for RealFs {
 506    async fn create_dir(&self, path: &Path) -> Result<()> {
 507        Ok(smol::fs::create_dir_all(path).await?)
 508    }
 509
 510    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 511        #[cfg(unix)]
 512        smol::fs::unix::symlink(target, path).await?;
 513
 514        #[cfg(windows)]
 515        if smol::fs::metadata(&target).await?.is_dir() {
 516            let status = new_smol_command("cmd")
 517                .args(["/C", "mklink", "/J"])
 518                .args([path, target.as_path()])
 519                .status()
 520                .await?;
 521
 522            if !status.success() {
 523                return Err(anyhow::anyhow!(
 524                    "Failed to create junction from {:?} to {:?}",
 525                    path,
 526                    target
 527                ));
 528            }
 529        } else {
 530            smol::fs::windows::symlink_file(target, path).await?
 531        }
 532
 533        Ok(())
 534    }
 535
 536    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 537        let mut open_options = smol::fs::OpenOptions::new();
 538        open_options.write(true).create(true);
 539        if options.overwrite {
 540            open_options.truncate(true);
 541        } else if !options.ignore_if_exists {
 542            open_options.create_new(true);
 543        }
 544        open_options
 545            .open(path)
 546            .await
 547            .with_context(|| format!("Failed to create file at {:?}", path))?;
 548        Ok(())
 549    }
 550
 551    async fn create_file_with(
 552        &self,
 553        path: &Path,
 554        content: Pin<&mut (dyn AsyncRead + Send)>,
 555    ) -> Result<()> {
 556        let mut file = smol::fs::File::create(&path)
 557            .await
 558            .with_context(|| format!("Failed to create file at {:?}", path))?;
 559        futures::io::copy(content, &mut file).await?;
 560        Ok(())
 561    }
 562
 563    async fn extract_tar_file(
 564        &self,
 565        path: &Path,
 566        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 567    ) -> Result<()> {
 568        content.unpack(path).await?;
 569        Ok(())
 570    }
 571
 572    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 573        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 574            if options.ignore_if_exists {
 575                return Ok(());
 576            } else {
 577                anyhow::bail!("{target:?} already exists");
 578            }
 579        }
 580
 581        smol::fs::copy(source, target).await?;
 582        Ok(())
 583    }
 584
 585    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 586        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 587            if options.ignore_if_exists {
 588                return Ok(());
 589            } else {
 590                anyhow::bail!("{target:?} already exists");
 591            }
 592        }
 593
 594        if options.create_parents {
 595            if let Some(parent) = target.parent() {
 596                self.create_dir(parent).await?;
 597            }
 598        }
 599
 600        smol::fs::rename(source, target).await?;
 601        Ok(())
 602    }
 603
 604    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 605        let result = if options.recursive {
 606            smol::fs::remove_dir_all(path).await
 607        } else {
 608            smol::fs::remove_dir(path).await
 609        };
 610        match result {
 611            Ok(()) => Ok(()),
 612            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 613                Ok(())
 614            }
 615            Err(err) => Err(err)?,
 616        }
 617    }
 618
 619    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 620        #[cfg(windows)]
 621        if let Ok(Some(metadata)) = self.metadata(path).await
 622            && metadata.is_symlink
 623            && metadata.is_dir
 624        {
 625            self.remove_dir(
 626                path,
 627                RemoveOptions {
 628                    recursive: false,
 629                    ignore_if_not_exists: true,
 630                },
 631            )
 632            .await?;
 633            return Ok(());
 634        }
 635
 636        match smol::fs::remove_file(path).await {
 637            Ok(()) => Ok(()),
 638            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 639                Ok(())
 640            }
 641            Err(err) => Err(err)?,
 642        }
 643    }
 644
 645    #[cfg(target_os = "macos")]
 646    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 647        use cocoa::{
 648            base::{id, nil},
 649            foundation::{NSAutoreleasePool, NSString},
 650        };
 651        use objc::{class, msg_send, sel, sel_impl};
 652
 653        unsafe {
 654            /// Allow NSString::alloc use here because it sets autorelease
 655            #[allow(clippy::disallowed_methods)]
 656            unsafe fn ns_string(string: &str) -> id {
 657                unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 658            }
 659
 660            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 661            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 662            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 663
 664            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 665        }
 666        Ok(())
 667    }
 668
 669    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 670    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 671        if let Ok(Some(metadata)) = self.metadata(path).await
 672            && metadata.is_symlink
 673        {
 674            // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
 675            return self.remove_file(path, RemoveOptions::default()).await;
 676        }
 677        let file = smol::fs::File::open(path).await?;
 678        match trash::trash_file(&file.as_fd()).await {
 679            Ok(_) => Ok(()),
 680            Err(err) => {
 681                log::error!("Failed to trash file: {}", err);
 682                // Trashing files can fail if you don't have a trashing dbus service configured.
 683                // In that case, delete the file directly instead.
 684                return self.remove_file(path, RemoveOptions::default()).await;
 685            }
 686        }
 687    }
 688
 689    #[cfg(target_os = "windows")]
 690    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 691        use util::paths::SanitizedPath;
 692        use windows::{
 693            Storage::{StorageDeleteOption, StorageFile},
 694            core::HSTRING,
 695        };
 696        // todo(windows)
 697        // When new version of `windows-rs` release, make this operation `async`
 698        let path = path.canonicalize()?;
 699        let path = SanitizedPath::new(&path);
 700        let path_string = path.to_string();
 701        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 702        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 703        Ok(())
 704    }
 705
 706    #[cfg(target_os = "macos")]
 707    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 708        self.trash_file(path, options).await
 709    }
 710
 711    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 712    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 713        self.trash_file(path, options).await
 714    }
 715
 716    #[cfg(target_os = "windows")]
 717    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 718        use util::paths::SanitizedPath;
 719        use windows::{
 720            Storage::{StorageDeleteOption, StorageFolder},
 721            core::HSTRING,
 722        };
 723
 724        // todo(windows)
 725        // When new version of `windows-rs` release, make this operation `async`
 726        let path = path.canonicalize()?;
 727        let path = SanitizedPath::new(&path);
 728        let path_string = path.to_string();
 729        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 730        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 731        Ok(())
 732    }
 733
 734    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
 735        Ok(Box::new(std::fs::File::open(path)?))
 736    }
 737
 738    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 739        let mut options = std::fs::OpenOptions::new();
 740        options.read(true);
 741        #[cfg(windows)]
 742        {
 743            use std::os::windows::fs::OpenOptionsExt;
 744            options.custom_flags(windows::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS.0);
 745        }
 746        Ok(Arc::new(options.open(path)?))
 747    }
 748
 749    async fn load(&self, path: &Path) -> Result<String> {
 750        let path = path.to_path_buf();
 751        self.executor
 752            .spawn(async move {
 753                std::fs::read_to_string(&path)
 754                    .with_context(|| format!("Failed to read file {}", path.display()))
 755            })
 756            .await
 757    }
 758
 759    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 760        let path = path.to_path_buf();
 761        let bytes = self
 762            .executor
 763            .spawn(async move { std::fs::read(path) })
 764            .await?;
 765        Ok(bytes)
 766    }
 767
 768    #[cfg(not(target_os = "windows"))]
 769    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 770        smol::unblock(move || {
 771            // Use the directory of the destination as temp dir to avoid
 772            // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 773            // See https://github.com/zed-industries/zed/pull/8437 for more details.
 774            let mut tmp_file =
 775                tempfile::NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 776            tmp_file.write_all(data.as_bytes())?;
 777            tmp_file.persist(path)?;
 778            anyhow::Ok(())
 779        })
 780        .await?;
 781
 782        Ok(())
 783    }
 784
 785    #[cfg(target_os = "windows")]
 786    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 787        smol::unblock(move || {
 788            // If temp dir is set to a different drive than the destination,
 789            // we receive error:
 790            //
 791            // failed to persist temporary file:
 792            // The system cannot move the file to a different disk drive. (os error 17)
 793            //
 794            // This is because `ReplaceFileW` does not support cross volume moves.
 795            // See the remark section: "The backup file, replaced file, and replacement file must all reside on the same volume."
 796            // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew#remarks
 797            //
 798            // So we use the directory of the destination as a temp dir to avoid it.
 799            // https://github.com/zed-industries/zed/issues/16571
 800            let temp_dir = TempDir::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 801            let temp_file = {
 802                let temp_file_path = temp_dir.path().join("temp_file");
 803                let mut file = std::fs::File::create_new(&temp_file_path)?;
 804                file.write_all(data.as_bytes())?;
 805                temp_file_path
 806            };
 807            atomic_replace(path.as_path(), temp_file.as_path())?;
 808            anyhow::Ok(())
 809        })
 810        .await?;
 811        Ok(())
 812    }
 813
 814    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 815        let buffer_size = text.summary().len.min(10 * 1024);
 816        if let Some(path) = path.parent() {
 817            self.create_dir(path)
 818                .await
 819                .with_context(|| format!("Failed to create directory at {:?}", path))?;
 820        }
 821        let file = smol::fs::File::create(path)
 822            .await
 823            .with_context(|| format!("Failed to create file at {:?}", path))?;
 824        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 825        for chunk in text::chunks_with_line_ending(text, line_ending) {
 826            writer.write_all(chunk.as_bytes()).await?;
 827        }
 828        writer.flush().await?;
 829        Ok(())
 830    }
 831
 832    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
 833        if let Some(path) = path.parent() {
 834            self.create_dir(path)
 835                .await
 836                .with_context(|| format!("Failed to create directory at {:?}", path))?;
 837        }
 838        let path = path.to_owned();
 839        let contents = content.to_owned();
 840        self.executor
 841            .spawn(async move {
 842                std::fs::write(path, contents)?;
 843                Ok(())
 844            })
 845            .await
 846    }
 847
 848    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 849        let path = path.to_owned();
 850        self.executor
 851            .spawn(async move {
 852                #[cfg(target_os = "windows")]
 853                let result = Self::canonicalize(&path);
 854
 855                #[cfg(not(target_os = "windows"))]
 856                let result = std::fs::canonicalize(&path);
 857
 858                result.with_context(|| format!("canonicalizing {path:?}"))
 859            })
 860            .await
 861    }
 862
 863    async fn is_file(&self, path: &Path) -> bool {
 864        let path = path.to_owned();
 865        self.executor
 866            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) })
 867            .await
 868    }
 869
 870    async fn is_dir(&self, path: &Path) -> bool {
 871        let path = path.to_owned();
 872        self.executor
 873            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_dir()) })
 874            .await
 875    }
 876
 877    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 878        let path_buf = path.to_owned();
 879        let symlink_metadata = match self
 880            .executor
 881            .spawn(async move { std::fs::symlink_metadata(&path_buf) })
 882            .await
 883        {
 884            Ok(metadata) => metadata,
 885            Err(err) => {
 886                return match err.kind() {
 887                    io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => Ok(None),
 888                    _ => Err(anyhow::Error::new(err)),
 889                };
 890            }
 891        };
 892
 893        let is_symlink = symlink_metadata.file_type().is_symlink();
 894        let metadata = if is_symlink {
 895            let path_buf = path.to_path_buf();
 896            // Read target metadata, if the target exists
 897            match self
 898                .executor
 899                .spawn(async move { std::fs::metadata(path_buf) })
 900                .await
 901            {
 902                Ok(target_metadata) => target_metadata,
 903                Err(err) => {
 904                    if err.kind() != io::ErrorKind::NotFound {
 905                        // TODO: Also FilesystemLoop when that's stable
 906                        log::warn!(
 907                            "Failed to read symlink target metadata for path {path:?}: {err}"
 908                        );
 909                    }
 910                    // For a broken or recursive symlink, return the symlink metadata. (Or
 911                    // as edge cases, a symlink into a directory we can't read, which is hard
 912                    // to distinguish from just being broken.)
 913                    symlink_metadata
 914                }
 915            }
 916        } else {
 917            symlink_metadata
 918        };
 919
 920        #[cfg(unix)]
 921        let inode = metadata.ino();
 922
 923        #[cfg(windows)]
 924        let inode = file_id(path).await?;
 925
 926        #[cfg(windows)]
 927        let is_fifo = false;
 928
 929        #[cfg(unix)]
 930        let is_fifo = metadata.file_type().is_fifo();
 931
 932        let path_buf = path.to_path_buf();
 933        let is_executable = self
 934            .executor
 935            .spawn(async move { path_buf.is_executable() })
 936            .await;
 937
 938        Ok(Some(Metadata {
 939            inode,
 940            mtime: MTime(metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH)),
 941            len: metadata.len(),
 942            is_symlink,
 943            is_dir: metadata.file_type().is_dir(),
 944            is_fifo,
 945            is_executable,
 946        }))
 947    }
 948
 949    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 950        let path = path.to_owned();
 951        let path = self
 952            .executor
 953            .spawn(async move { std::fs::read_link(&path) })
 954            .await?;
 955        Ok(path)
 956    }
 957
 958    async fn read_dir(
 959        &self,
 960        path: &Path,
 961    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 962        let path = path.to_owned();
 963        let result = iter(
 964            self.executor
 965                .spawn(async move { std::fs::read_dir(path) })
 966                .await?,
 967        )
 968        .map(|entry| match entry {
 969            Ok(entry) => Ok(entry.path()),
 970            Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
 971        });
 972        Ok(Box::pin(result))
 973    }
 974
 975    async fn watch(
 976        &self,
 977        path: &Path,
 978        latency: Duration,
 979    ) -> (
 980        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 981        Arc<dyn Watcher>,
 982    ) {
 983        use util::{ResultExt as _, paths::SanitizedPath};
 984        let executor = self.executor.clone();
 985
 986        let (tx, rx) = smol::channel::unbounded();
 987        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 988        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 989
 990        // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 991        if let Err(e) = watcher.add(path)
 992            && let Some(parent) = path.parent()
 993            && let Err(parent_e) = watcher.add(parent)
 994        {
 995            log::warn!(
 996                "Failed to watch {} and its parent directory {}:\n{e}\n{parent_e}",
 997                path.display(),
 998                parent.display()
 999            );
1000        }
1001
1002        // Check if path is a symlink and follow the target parent
1003        if let Some(mut target) = self.read_link(path).await.ok() {
1004            log::trace!("watch symlink {path:?} -> {target:?}");
1005            // Check if symlink target is relative path, if so make it absolute
1006            if target.is_relative()
1007                && let Some(parent) = path.parent()
1008            {
1009                target = parent.join(target);
1010                if let Ok(canonical) = self.canonicalize(&target).await {
1011                    target = SanitizedPath::new(&canonical).as_path().to_path_buf();
1012                }
1013            }
1014            watcher.add(&target).ok();
1015            if let Some(parent) = target.parent() {
1016                watcher.add(parent).log_err();
1017            }
1018        }
1019
1020        (
1021            Box::pin(rx.filter_map({
1022                let watcher = watcher.clone();
1023                let executor = executor.clone();
1024                move |_| {
1025                    let _ = watcher.clone();
1026                    let pending_paths = pending_paths.clone();
1027                    let executor = executor.clone();
1028                    async move {
1029                        executor.timer(latency).await;
1030                        let paths = std::mem::take(&mut *pending_paths.lock());
1031                        (!paths.is_empty()).then_some(paths)
1032                    }
1033                }
1034            })),
1035            watcher,
1036        )
1037    }
1038
1039    fn open_repo(
1040        &self,
1041        dotgit_path: &Path,
1042        system_git_binary_path: Option<&Path>,
1043    ) -> Option<Arc<dyn GitRepository>> {
1044        Some(Arc::new(RealGitRepository::new(
1045            dotgit_path,
1046            self.bundled_git_binary_path.clone(),
1047            system_git_binary_path.map(|path| path.to_path_buf()),
1048            self.executor.clone(),
1049        )?))
1050    }
1051
1052    async fn git_init(
1053        &self,
1054        abs_work_directory_path: &Path,
1055        fallback_branch_name: String,
1056    ) -> Result<()> {
1057        let config = new_smol_command("git")
1058            .current_dir(abs_work_directory_path)
1059            .args(&["config", "--global", "--get", "init.defaultBranch"])
1060            .output()
1061            .await?;
1062
1063        let branch_name;
1064
1065        if config.status.success() && !config.stdout.is_empty() {
1066            branch_name = String::from_utf8_lossy(&config.stdout);
1067        } else {
1068            branch_name = Cow::Borrowed(fallback_branch_name.as_str());
1069        }
1070
1071        new_smol_command("git")
1072            .current_dir(abs_work_directory_path)
1073            .args(&["init", "-b"])
1074            .arg(branch_name.trim())
1075            .output()
1076            .await?;
1077
1078        Ok(())
1079    }
1080
1081    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
1082        let job_id = self.next_job_id.fetch_add(1, Ordering::SeqCst);
1083        let job_info = JobInfo {
1084            id: job_id,
1085            start: Instant::now(),
1086            message: SharedString::from(format!("Cloning {}", repo_url)),
1087        };
1088
1089        let _job_tracker = JobTracker::new(job_info, self.job_event_subscribers.clone());
1090
1091        let output = new_smol_command("git")
1092            .current_dir(abs_work_directory)
1093            .args(&["clone", repo_url])
1094            .output()
1095            .await?;
1096
1097        if !output.status.success() {
1098            anyhow::bail!(
1099                "git clone failed: {}",
1100                String::from_utf8_lossy(&output.stderr)
1101            );
1102        }
1103
1104        Ok(())
1105    }
1106
1107    fn is_fake(&self) -> bool {
1108        false
1109    }
1110
1111    fn subscribe_to_jobs(&self) -> JobEventReceiver {
1112        let (sender, receiver) = futures::channel::mpsc::unbounded();
1113        self.job_event_subscribers.lock().push(sender);
1114        receiver
1115    }
1116
1117    /// Checks whether the file system is case sensitive by attempting to create two files
1118    /// that have the same name except for the casing.
1119    ///
1120    /// It creates both files in a temporary directory it removes at the end.
1121    async fn is_case_sensitive(&self) -> Result<bool> {
1122        let temp_dir = TempDir::new()?;
1123        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
1124        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
1125
1126        let create_opts = CreateOptions {
1127            overwrite: false,
1128            ignore_if_exists: false,
1129        };
1130
1131        // Create file1
1132        self.create_file(&test_file_1, create_opts).await?;
1133
1134        // Now check whether it's possible to create file2
1135        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
1136            Ok(_) => Ok(true),
1137            Err(e) => {
1138                if let Some(io_error) = e.downcast_ref::<io::Error>() {
1139                    if io_error.kind() == io::ErrorKind::AlreadyExists {
1140                        Ok(false)
1141                    } else {
1142                        Err(e)
1143                    }
1144                } else {
1145                    Err(e)
1146                }
1147            }
1148        };
1149
1150        temp_dir.close()?;
1151        case_sensitive
1152    }
1153}
1154
1155#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
1156impl Watcher for RealWatcher {
1157    fn add(&self, _: &Path) -> Result<()> {
1158        Ok(())
1159    }
1160
1161    fn remove(&self, _: &Path) -> Result<()> {
1162        Ok(())
1163    }
1164}
1165
1166#[cfg(feature = "test-support")]
1167pub struct FakeFs {
1168    this: std::sync::Weak<Self>,
1169    // Use an unfair lock to ensure tests are deterministic.
1170    state: Arc<Mutex<FakeFsState>>,
1171    executor: gpui::BackgroundExecutor,
1172}
1173
1174#[cfg(feature = "test-support")]
1175struct FakeFsState {
1176    root: FakeFsEntry,
1177    next_inode: u64,
1178    next_mtime: SystemTime,
1179    git_event_tx: smol::channel::Sender<PathBuf>,
1180    event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
1181    events_paused: bool,
1182    buffered_events: Vec<PathEvent>,
1183    metadata_call_count: usize,
1184    read_dir_call_count: usize,
1185    path_write_counts: std::collections::HashMap<PathBuf, usize>,
1186    moves: std::collections::HashMap<u64, PathBuf>,
1187    job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,
1188}
1189
1190#[cfg(feature = "test-support")]
1191#[derive(Clone, Debug)]
1192enum FakeFsEntry {
1193    File {
1194        inode: u64,
1195        mtime: MTime,
1196        len: u64,
1197        content: Vec<u8>,
1198        // The path to the repository state directory, if this is a gitfile.
1199        git_dir_path: Option<PathBuf>,
1200    },
1201    Dir {
1202        inode: u64,
1203        mtime: MTime,
1204        len: u64,
1205        entries: BTreeMap<String, FakeFsEntry>,
1206        git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
1207    },
1208    Symlink {
1209        target: PathBuf,
1210    },
1211}
1212
1213#[cfg(feature = "test-support")]
1214impl PartialEq for FakeFsEntry {
1215    fn eq(&self, other: &Self) -> bool {
1216        match (self, other) {
1217            (
1218                Self::File {
1219                    inode: l_inode,
1220                    mtime: l_mtime,
1221                    len: l_len,
1222                    content: l_content,
1223                    git_dir_path: l_git_dir_path,
1224                },
1225                Self::File {
1226                    inode: r_inode,
1227                    mtime: r_mtime,
1228                    len: r_len,
1229                    content: r_content,
1230                    git_dir_path: r_git_dir_path,
1231                },
1232            ) => {
1233                l_inode == r_inode
1234                    && l_mtime == r_mtime
1235                    && l_len == r_len
1236                    && l_content == r_content
1237                    && l_git_dir_path == r_git_dir_path
1238            }
1239            (
1240                Self::Dir {
1241                    inode: l_inode,
1242                    mtime: l_mtime,
1243                    len: l_len,
1244                    entries: l_entries,
1245                    git_repo_state: l_git_repo_state,
1246                },
1247                Self::Dir {
1248                    inode: r_inode,
1249                    mtime: r_mtime,
1250                    len: r_len,
1251                    entries: r_entries,
1252                    git_repo_state: r_git_repo_state,
1253                },
1254            ) => {
1255                let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1256                    (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1257                    (None, None) => true,
1258                    _ => false,
1259                };
1260                l_inode == r_inode
1261                    && l_mtime == r_mtime
1262                    && l_len == r_len
1263                    && l_entries == r_entries
1264                    && same_repo_state
1265            }
1266            (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1267                l_target == r_target
1268            }
1269            _ => false,
1270        }
1271    }
1272}
1273
1274#[cfg(feature = "test-support")]
1275impl FakeFsState {
1276    fn get_and_increment_mtime(&mut self) -> MTime {
1277        let mtime = self.next_mtime;
1278        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1279        MTime(mtime)
1280    }
1281
1282    fn get_and_increment_inode(&mut self) -> u64 {
1283        let inode = self.next_inode;
1284        self.next_inode += 1;
1285        inode
1286    }
1287
1288    fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1289        let mut canonical_path = PathBuf::new();
1290        let mut path = target.to_path_buf();
1291        let mut entry_stack = Vec::new();
1292        'outer: loop {
1293            let mut path_components = path.components().peekable();
1294            let mut prefix = None;
1295            while let Some(component) = path_components.next() {
1296                match component {
1297                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1298                    Component::RootDir => {
1299                        entry_stack.clear();
1300                        entry_stack.push(&self.root);
1301                        canonical_path.clear();
1302                        match prefix {
1303                            Some(prefix_component) => {
1304                                canonical_path = PathBuf::from(prefix_component.as_os_str());
1305                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1306                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1307                            }
1308                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1309                        }
1310                    }
1311                    Component::CurDir => {}
1312                    Component::ParentDir => {
1313                        entry_stack.pop()?;
1314                        canonical_path.pop();
1315                    }
1316                    Component::Normal(name) => {
1317                        let current_entry = *entry_stack.last()?;
1318                        if let FakeFsEntry::Dir { entries, .. } = current_entry {
1319                            let entry = entries.get(name.to_str().unwrap())?;
1320                            if (path_components.peek().is_some() || follow_symlink)
1321                                && let FakeFsEntry::Symlink { target, .. } = entry
1322                            {
1323                                let mut target = target.clone();
1324                                target.extend(path_components);
1325                                path = target;
1326                                continue 'outer;
1327                            }
1328                            entry_stack.push(entry);
1329                            canonical_path = canonical_path.join(name);
1330                        } else {
1331                            return None;
1332                        }
1333                    }
1334                }
1335            }
1336            break;
1337        }
1338
1339        if entry_stack.is_empty() {
1340            None
1341        } else {
1342            Some(canonical_path)
1343        }
1344    }
1345
1346    fn try_entry(
1347        &mut self,
1348        target: &Path,
1349        follow_symlink: bool,
1350    ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1351        let canonical_path = self.canonicalize(target, follow_symlink)?;
1352
1353        let mut components = canonical_path
1354            .components()
1355            .skip_while(|component| matches!(component, Component::Prefix(_)));
1356        let Some(Component::RootDir) = components.next() else {
1357            panic!(
1358                "the path {:?} was not canonicalized properly {:?}",
1359                target, canonical_path
1360            )
1361        };
1362
1363        let mut entry = &mut self.root;
1364        for component in components {
1365            match component {
1366                Component::Normal(name) => {
1367                    if let FakeFsEntry::Dir { entries, .. } = entry {
1368                        entry = entries.get_mut(name.to_str().unwrap())?;
1369                    } else {
1370                        return None;
1371                    }
1372                }
1373                _ => {
1374                    panic!(
1375                        "the path {:?} was not canonicalized properly {:?}",
1376                        target, canonical_path
1377                    )
1378                }
1379            }
1380        }
1381
1382        Some((entry, canonical_path))
1383    }
1384
1385    fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1386        Ok(self
1387            .try_entry(target, true)
1388            .ok_or_else(|| {
1389                anyhow!(io::Error::new(
1390                    io::ErrorKind::NotFound,
1391                    format!("not found: {target:?}")
1392                ))
1393            })?
1394            .0)
1395    }
1396
1397    fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1398    where
1399        Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1400    {
1401        let path = normalize_path(path);
1402        let filename = path.file_name().context("cannot overwrite the root")?;
1403        let parent_path = path.parent().unwrap();
1404
1405        let parent = self.entry(parent_path)?;
1406        let new_entry = parent
1407            .dir_entries(parent_path)?
1408            .entry(filename.to_str().unwrap().into());
1409        callback(new_entry)
1410    }
1411
1412    fn emit_event<I, T>(&mut self, paths: I)
1413    where
1414        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1415        T: Into<PathBuf>,
1416    {
1417        self.buffered_events
1418            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1419                path: path.into(),
1420                kind,
1421            }));
1422
1423        if !self.events_paused {
1424            self.flush_events(self.buffered_events.len());
1425        }
1426    }
1427
1428    fn flush_events(&mut self, mut count: usize) {
1429        count = count.min(self.buffered_events.len());
1430        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1431        self.event_txs.retain(|(_, tx)| {
1432            let _ = tx.try_send(events.clone());
1433            !tx.is_closed()
1434        });
1435    }
1436}
1437
1438#[cfg(feature = "test-support")]
1439pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1440    std::sync::LazyLock::new(|| OsStr::new(".git"));
1441
1442#[cfg(feature = "test-support")]
1443impl FakeFs {
1444    /// We need to use something large enough for Windows and Unix to consider this a new file.
1445    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1446    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1447
1448    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1449        let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1450
1451        let this = Arc::new_cyclic(|this| Self {
1452            this: this.clone(),
1453            executor: executor.clone(),
1454            state: Arc::new(Mutex::new(FakeFsState {
1455                root: FakeFsEntry::Dir {
1456                    inode: 0,
1457                    mtime: MTime(UNIX_EPOCH),
1458                    len: 0,
1459                    entries: Default::default(),
1460                    git_repo_state: None,
1461                },
1462                git_event_tx: tx,
1463                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1464                next_inode: 1,
1465                event_txs: Default::default(),
1466                buffered_events: Vec::new(),
1467                events_paused: false,
1468                read_dir_call_count: 0,
1469                metadata_call_count: 0,
1470                path_write_counts: Default::default(),
1471                moves: Default::default(),
1472                job_event_subscribers: Arc::new(Mutex::new(Vec::new())),
1473            })),
1474        });
1475
1476        executor.spawn({
1477            let this = this.clone();
1478            async move {
1479                while let Ok(git_event) = rx.recv().await {
1480                    if let Some(mut state) = this.state.try_lock() {
1481                        state.emit_event([(git_event, Some(PathEventKind::Changed))]);
1482                    } else {
1483                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1484                    }
1485                }
1486            }
1487        }).detach();
1488
1489        this
1490    }
1491
1492    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1493        let mut state = self.state.lock();
1494        state.next_mtime = next_mtime;
1495    }
1496
1497    pub fn get_and_increment_mtime(&self) -> MTime {
1498        let mut state = self.state.lock();
1499        state.get_and_increment_mtime()
1500    }
1501
1502    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1503        let mut state = self.state.lock();
1504        let path = path.as_ref();
1505        let new_mtime = state.get_and_increment_mtime();
1506        let new_inode = state.get_and_increment_inode();
1507        state
1508            .write_path(path, move |entry| {
1509                match entry {
1510                    btree_map::Entry::Vacant(e) => {
1511                        e.insert(FakeFsEntry::File {
1512                            inode: new_inode,
1513                            mtime: new_mtime,
1514                            content: Vec::new(),
1515                            len: 0,
1516                            git_dir_path: None,
1517                        });
1518                    }
1519                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1520                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1521                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1522                        FakeFsEntry::Symlink { .. } => {}
1523                    },
1524                }
1525                Ok(())
1526            })
1527            .unwrap();
1528        state.emit_event([(path.to_path_buf(), Some(PathEventKind::Changed))]);
1529    }
1530
1531    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1532        self.write_file_internal(path, content, true).unwrap()
1533    }
1534
1535    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1536        let mut state = self.state.lock();
1537        let path = path.as_ref();
1538        let file = FakeFsEntry::Symlink { target };
1539        state
1540            .write_path(path.as_ref(), move |e| match e {
1541                btree_map::Entry::Vacant(e) => {
1542                    e.insert(file);
1543                    Ok(())
1544                }
1545                btree_map::Entry::Occupied(mut e) => {
1546                    *e.get_mut() = file;
1547                    Ok(())
1548                }
1549            })
1550            .unwrap();
1551        state.emit_event([(path, Some(PathEventKind::Created))]);
1552    }
1553
1554    fn write_file_internal(
1555        &self,
1556        path: impl AsRef<Path>,
1557        new_content: Vec<u8>,
1558        recreate_inode: bool,
1559    ) -> Result<()> {
1560        fn inner(
1561            this: &FakeFs,
1562            path: &Path,
1563            new_content: Vec<u8>,
1564            recreate_inode: bool,
1565        ) -> Result<()> {
1566            let mut state = this.state.lock();
1567            let path_buf = path.to_path_buf();
1568            *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1569            let new_inode = state.get_and_increment_inode();
1570            let new_mtime = state.get_and_increment_mtime();
1571            let new_len = new_content.len() as u64;
1572            let mut kind = None;
1573            state.write_path(path, |entry| {
1574                match entry {
1575                    btree_map::Entry::Vacant(e) => {
1576                        kind = Some(PathEventKind::Created);
1577                        e.insert(FakeFsEntry::File {
1578                            inode: new_inode,
1579                            mtime: new_mtime,
1580                            len: new_len,
1581                            content: new_content,
1582                            git_dir_path: None,
1583                        });
1584                    }
1585                    btree_map::Entry::Occupied(mut e) => {
1586                        kind = Some(PathEventKind::Changed);
1587                        if let FakeFsEntry::File {
1588                            inode,
1589                            mtime,
1590                            len,
1591                            content,
1592                            ..
1593                        } = e.get_mut()
1594                        {
1595                            *mtime = new_mtime;
1596                            *content = new_content;
1597                            *len = new_len;
1598                            if recreate_inode {
1599                                *inode = new_inode;
1600                            }
1601                        } else {
1602                            anyhow::bail!("not a file")
1603                        }
1604                    }
1605                }
1606                Ok(())
1607            })?;
1608            state.emit_event([(path, kind)]);
1609            Ok(())
1610        }
1611        inner(self, path.as_ref(), new_content, recreate_inode)
1612    }
1613
1614    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1615        let path = path.as_ref();
1616        let path = normalize_path(path);
1617        let mut state = self.state.lock();
1618        let entry = state.entry(&path)?;
1619        entry.file_content(&path).cloned()
1620    }
1621
1622    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1623        let path = path.as_ref();
1624        let path = normalize_path(path);
1625        self.simulate_random_delay().await;
1626        let mut state = self.state.lock();
1627        let entry = state.entry(&path)?;
1628        entry.file_content(&path).cloned()
1629    }
1630
1631    pub fn pause_events(&self) {
1632        self.state.lock().events_paused = true;
1633    }
1634
1635    pub fn unpause_events_and_flush(&self) {
1636        self.state.lock().events_paused = false;
1637        self.flush_events(usize::MAX);
1638    }
1639
1640    pub fn buffered_event_count(&self) -> usize {
1641        self.state.lock().buffered_events.len()
1642    }
1643
1644    pub fn flush_events(&self, count: usize) {
1645        self.state.lock().flush_events(count);
1646    }
1647
1648    pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1649        self.state.lock().entry(target).cloned()
1650    }
1651
1652    pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1653        let mut state = self.state.lock();
1654        state.write_path(target, |entry| {
1655            match entry {
1656                btree_map::Entry::Vacant(vacant_entry) => {
1657                    vacant_entry.insert(new_entry);
1658                }
1659                btree_map::Entry::Occupied(mut occupied_entry) => {
1660                    occupied_entry.insert(new_entry);
1661                }
1662            }
1663            Ok(())
1664        })
1665    }
1666
1667    #[must_use]
1668    pub fn insert_tree<'a>(
1669        &'a self,
1670        path: impl 'a + AsRef<Path> + Send,
1671        tree: serde_json::Value,
1672    ) -> futures::future::BoxFuture<'a, ()> {
1673        use futures::FutureExt as _;
1674        use serde_json::Value::*;
1675
1676        fn inner<'a>(
1677            this: &'a FakeFs,
1678            path: Arc<Path>,
1679            tree: serde_json::Value,
1680        ) -> futures::future::BoxFuture<'a, ()> {
1681            async move {
1682                match tree {
1683                    Object(map) => {
1684                        this.create_dir(&path).await.unwrap();
1685                        for (name, contents) in map {
1686                            let mut path = PathBuf::from(path.as_ref());
1687                            path.push(name);
1688                            this.insert_tree(&path, contents).await;
1689                        }
1690                    }
1691                    Null => {
1692                        this.create_dir(&path).await.unwrap();
1693                    }
1694                    String(contents) => {
1695                        this.insert_file(&path, contents.into_bytes()).await;
1696                    }
1697                    _ => {
1698                        panic!("JSON object must contain only objects, strings, or null");
1699                    }
1700                }
1701            }
1702            .boxed()
1703        }
1704        inner(self, Arc::from(path.as_ref()), tree)
1705    }
1706
1707    pub fn insert_tree_from_real_fs<'a>(
1708        &'a self,
1709        path: impl 'a + AsRef<Path> + Send,
1710        src_path: impl 'a + AsRef<Path> + Send,
1711    ) -> futures::future::BoxFuture<'a, ()> {
1712        use futures::FutureExt as _;
1713
1714        async move {
1715            let path = path.as_ref();
1716            if std::fs::metadata(&src_path).unwrap().is_file() {
1717                let contents = std::fs::read(src_path).unwrap();
1718                self.insert_file(path, contents).await;
1719            } else {
1720                self.create_dir(path).await.unwrap();
1721                for entry in std::fs::read_dir(&src_path).unwrap() {
1722                    let entry = entry.unwrap();
1723                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1724                        .await;
1725                }
1726            }
1727        }
1728        .boxed()
1729    }
1730
1731    pub fn with_git_state_and_paths<T, F>(
1732        &self,
1733        dot_git: &Path,
1734        emit_git_event: bool,
1735        f: F,
1736    ) -> Result<T>
1737    where
1738        F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1739    {
1740        let mut state = self.state.lock();
1741        let git_event_tx = state.git_event_tx.clone();
1742        let entry = state.entry(dot_git).context("open .git")?;
1743
1744        if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1745            let repo_state = git_repo_state.get_or_insert_with(|| {
1746                log::debug!("insert git state for {dot_git:?}");
1747                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1748            });
1749            let mut repo_state = repo_state.lock();
1750
1751            let result = f(&mut repo_state, dot_git, dot_git);
1752
1753            drop(repo_state);
1754            if emit_git_event {
1755                state.emit_event([(dot_git, Some(PathEventKind::Changed))]);
1756            }
1757
1758            Ok(result)
1759        } else if let FakeFsEntry::File {
1760            content,
1761            git_dir_path,
1762            ..
1763        } = &mut *entry
1764        {
1765            let path = match git_dir_path {
1766                Some(path) => path,
1767                None => {
1768                    let path = std::str::from_utf8(content)
1769                        .ok()
1770                        .and_then(|content| content.strip_prefix("gitdir:"))
1771                        .context("not a valid gitfile")?
1772                        .trim();
1773                    git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1774                }
1775            }
1776            .clone();
1777            let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1778                anyhow::bail!("pointed-to git dir {path:?} not found")
1779            };
1780            let FakeFsEntry::Dir {
1781                git_repo_state,
1782                entries,
1783                ..
1784            } = git_dir_entry
1785            else {
1786                anyhow::bail!("gitfile points to a non-directory")
1787            };
1788            let common_dir = if let Some(child) = entries.get("commondir") {
1789                Path::new(
1790                    std::str::from_utf8(child.file_content("commondir".as_ref())?)
1791                        .context("commondir content")?,
1792                )
1793                .to_owned()
1794            } else {
1795                canonical_path.clone()
1796            };
1797            let repo_state = git_repo_state.get_or_insert_with(|| {
1798                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1799            });
1800            let mut repo_state = repo_state.lock();
1801
1802            let result = f(&mut repo_state, &canonical_path, &common_dir);
1803
1804            if emit_git_event {
1805                drop(repo_state);
1806                state.emit_event([(canonical_path, Some(PathEventKind::Changed))]);
1807            }
1808
1809            Ok(result)
1810        } else {
1811            anyhow::bail!("not a valid git repository");
1812        }
1813    }
1814
1815    pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1816    where
1817        F: FnOnce(&mut FakeGitRepositoryState) -> T,
1818    {
1819        self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1820    }
1821
1822    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1823        self.with_git_state(dot_git, true, |state| {
1824            let branch = branch.map(Into::into);
1825            state.branches.extend(branch.clone());
1826            state.current_branch_name = branch
1827        })
1828        .unwrap();
1829    }
1830
1831    pub fn set_remote_for_repo(
1832        &self,
1833        dot_git: &Path,
1834        name: impl Into<String>,
1835        url: impl Into<String>,
1836    ) {
1837        self.with_git_state(dot_git, true, |state| {
1838            state.remotes.insert(name.into(), url.into());
1839        })
1840        .unwrap();
1841    }
1842
1843    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1844        self.with_git_state(dot_git, true, |state| {
1845            if let Some(first) = branches.first()
1846                && state.current_branch_name.is_none()
1847            {
1848                state.current_branch_name = Some(first.to_string())
1849            }
1850            state
1851                .branches
1852                .extend(branches.iter().map(ToString::to_string));
1853        })
1854        .unwrap();
1855    }
1856
1857    pub fn set_unmerged_paths_for_repo(
1858        &self,
1859        dot_git: &Path,
1860        unmerged_state: &[(RepoPath, UnmergedStatus)],
1861    ) {
1862        self.with_git_state(dot_git, true, |state| {
1863            state.unmerged_paths.clear();
1864            state.unmerged_paths.extend(
1865                unmerged_state
1866                    .iter()
1867                    .map(|(path, content)| (path.clone(), *content)),
1868            );
1869        })
1870        .unwrap();
1871    }
1872
1873    pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(&str, String)]) {
1874        self.with_git_state(dot_git, true, |state| {
1875            state.index_contents.clear();
1876            state.index_contents.extend(
1877                index_state
1878                    .iter()
1879                    .map(|(path, content)| (repo_path(path), content.clone())),
1880            );
1881        })
1882        .unwrap();
1883    }
1884
1885    pub fn set_head_for_repo(
1886        &self,
1887        dot_git: &Path,
1888        head_state: &[(&str, String)],
1889        sha: impl Into<String>,
1890    ) {
1891        self.with_git_state(dot_git, true, |state| {
1892            state.head_contents.clear();
1893            state.head_contents.extend(
1894                head_state
1895                    .iter()
1896                    .map(|(path, content)| (repo_path(path), content.clone())),
1897            );
1898            state.refs.insert("HEAD".into(), sha.into());
1899        })
1900        .unwrap();
1901    }
1902
1903    pub fn set_head_and_index_for_repo(&self, dot_git: &Path, contents_by_path: &[(&str, String)]) {
1904        self.with_git_state(dot_git, true, |state| {
1905            state.head_contents.clear();
1906            state.head_contents.extend(
1907                contents_by_path
1908                    .iter()
1909                    .map(|(path, contents)| (repo_path(path), contents.clone())),
1910            );
1911            state.index_contents = state.head_contents.clone();
1912        })
1913        .unwrap();
1914    }
1915
1916    pub fn set_merge_base_content_for_repo(
1917        &self,
1918        dot_git: &Path,
1919        contents_by_path: &[(&str, String)],
1920    ) {
1921        self.with_git_state(dot_git, true, |state| {
1922            use git::Oid;
1923
1924            state.merge_base_contents.clear();
1925            let oids = (1..)
1926                .map(|n| n.to_string())
1927                .map(|n| Oid::from_bytes(n.repeat(20).as_bytes()).unwrap());
1928            for ((path, content), oid) in contents_by_path.iter().zip(oids) {
1929                state.merge_base_contents.insert(repo_path(path), oid);
1930                state.oids.insert(oid, content.clone());
1931            }
1932        })
1933        .unwrap();
1934    }
1935
1936    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1937        self.with_git_state(dot_git, true, |state| {
1938            state.blames.clear();
1939            state.blames.extend(blames);
1940        })
1941        .unwrap();
1942    }
1943
1944    pub fn set_graph_commits(&self, dot_git: &Path, commits: Vec<Arc<InitialGraphCommitData>>) {
1945        self.with_git_state(dot_git, true, |state| {
1946            state.graph_commits = commits;
1947        })
1948        .unwrap();
1949    }
1950
1951    /// Put the given git repository into a state with the given status,
1952    /// by mutating the head, index, and unmerged state.
1953    pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&str, FileStatus)]) {
1954        let workdir_path = dot_git.parent().unwrap();
1955        let workdir_contents = self.files_with_contents(workdir_path);
1956        self.with_git_state(dot_git, true, |state| {
1957            state.index_contents.clear();
1958            state.head_contents.clear();
1959            state.unmerged_paths.clear();
1960            for (path, content) in workdir_contents {
1961                use util::{paths::PathStyle, rel_path::RelPath};
1962
1963                let repo_path = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap();
1964                let repo_path = RepoPath::from_rel_path(&repo_path);
1965                let status = statuses
1966                    .iter()
1967                    .find_map(|(p, status)| (*p == repo_path.as_unix_str()).then_some(status));
1968                let mut content = String::from_utf8_lossy(&content).to_string();
1969
1970                let mut index_content = None;
1971                let mut head_content = None;
1972                match status {
1973                    None => {
1974                        index_content = Some(content.clone());
1975                        head_content = Some(content);
1976                    }
1977                    Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1978                    Some(FileStatus::Unmerged(unmerged_status)) => {
1979                        state
1980                            .unmerged_paths
1981                            .insert(repo_path.clone(), *unmerged_status);
1982                        content.push_str(" (unmerged)");
1983                        index_content = Some(content.clone());
1984                        head_content = Some(content);
1985                    }
1986                    Some(FileStatus::Tracked(TrackedStatus {
1987                        index_status,
1988                        worktree_status,
1989                    })) => {
1990                        match worktree_status {
1991                            StatusCode::Modified => {
1992                                let mut content = content.clone();
1993                                content.push_str(" (modified in working copy)");
1994                                index_content = Some(content);
1995                            }
1996                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1997                                index_content = Some(content.clone());
1998                            }
1999                            StatusCode::Added => {}
2000                            StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
2001                                panic!("cannot create these statuses for an existing file");
2002                            }
2003                        };
2004                        match index_status {
2005                            StatusCode::Modified => {
2006                                let mut content = index_content.clone().expect(
2007                                    "file cannot be both modified in index and created in working copy",
2008                                );
2009                                content.push_str(" (modified in index)");
2010                                head_content = Some(content);
2011                            }
2012                            StatusCode::TypeChanged | StatusCode::Unmodified => {
2013                                head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
2014                            }
2015                            StatusCode::Added => {}
2016                            StatusCode::Deleted  => {
2017                                head_content = Some("".into());
2018                            }
2019                            StatusCode::Renamed | StatusCode::Copied => {
2020                                panic!("cannot create these statuses for an existing file");
2021                            }
2022                        };
2023                    }
2024                };
2025
2026                if let Some(content) = index_content {
2027                    state.index_contents.insert(repo_path.clone(), content);
2028                }
2029                if let Some(content) = head_content {
2030                    state.head_contents.insert(repo_path.clone(), content);
2031                }
2032            }
2033        }).unwrap();
2034    }
2035
2036    pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
2037        self.with_git_state(dot_git, true, |state| {
2038            state.simulated_index_write_error_message = message;
2039        })
2040        .unwrap();
2041    }
2042
2043    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
2044        let mut result = Vec::new();
2045        let mut queue = collections::VecDeque::new();
2046        let state = &*self.state.lock();
2047        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2048        while let Some((path, entry)) = queue.pop_front() {
2049            if let FakeFsEntry::Dir { entries, .. } = entry {
2050                for (name, entry) in entries {
2051                    queue.push_back((path.join(name), entry));
2052                }
2053            }
2054            if include_dot_git
2055                || !path
2056                    .components()
2057                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
2058            {
2059                result.push(path);
2060            }
2061        }
2062        result
2063    }
2064
2065    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
2066        let mut result = Vec::new();
2067        let mut queue = collections::VecDeque::new();
2068        let state = &*self.state.lock();
2069        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2070        while let Some((path, entry)) = queue.pop_front() {
2071            if let FakeFsEntry::Dir { entries, .. } = entry {
2072                for (name, entry) in entries {
2073                    queue.push_back((path.join(name), entry));
2074                }
2075                if include_dot_git
2076                    || !path
2077                        .components()
2078                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
2079                {
2080                    result.push(path);
2081                }
2082            }
2083        }
2084        result
2085    }
2086
2087    pub fn files(&self) -> Vec<PathBuf> {
2088        let mut result = Vec::new();
2089        let mut queue = collections::VecDeque::new();
2090        let state = &*self.state.lock();
2091        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2092        while let Some((path, entry)) = queue.pop_front() {
2093            match entry {
2094                FakeFsEntry::File { .. } => result.push(path),
2095                FakeFsEntry::Dir { entries, .. } => {
2096                    for (name, entry) in entries {
2097                        queue.push_back((path.join(name), entry));
2098                    }
2099                }
2100                FakeFsEntry::Symlink { .. } => {}
2101            }
2102        }
2103        result
2104    }
2105
2106    pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
2107        let mut result = Vec::new();
2108        let mut queue = collections::VecDeque::new();
2109        let state = &*self.state.lock();
2110        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2111        while let Some((path, entry)) = queue.pop_front() {
2112            match entry {
2113                FakeFsEntry::File { content, .. } => {
2114                    if path.starts_with(prefix) {
2115                        result.push((path, content.clone()));
2116                    }
2117                }
2118                FakeFsEntry::Dir { entries, .. } => {
2119                    for (name, entry) in entries {
2120                        queue.push_back((path.join(name), entry));
2121                    }
2122                }
2123                FakeFsEntry::Symlink { .. } => {}
2124            }
2125        }
2126        result
2127    }
2128
2129    /// How many `read_dir` calls have been issued.
2130    pub fn read_dir_call_count(&self) -> usize {
2131        self.state.lock().read_dir_call_count
2132    }
2133
2134    pub fn watched_paths(&self) -> Vec<PathBuf> {
2135        let state = self.state.lock();
2136        state
2137            .event_txs
2138            .iter()
2139            .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
2140            .collect()
2141    }
2142
2143    /// How many `metadata` calls have been issued.
2144    pub fn metadata_call_count(&self) -> usize {
2145        self.state.lock().metadata_call_count
2146    }
2147
2148    /// How many write operations have been issued for a specific path.
2149    pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
2150        let path = path.as_ref().to_path_buf();
2151        self.state
2152            .lock()
2153            .path_write_counts
2154            .get(&path)
2155            .copied()
2156            .unwrap_or(0)
2157    }
2158
2159    pub fn emit_fs_event(&self, path: impl Into<PathBuf>, event: Option<PathEventKind>) {
2160        self.state.lock().emit_event(std::iter::once((path, event)));
2161    }
2162
2163    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
2164        self.executor.simulate_random_delay()
2165    }
2166}
2167
2168#[cfg(feature = "test-support")]
2169impl FakeFsEntry {
2170    fn is_file(&self) -> bool {
2171        matches!(self, Self::File { .. })
2172    }
2173
2174    fn is_symlink(&self) -> bool {
2175        matches!(self, Self::Symlink { .. })
2176    }
2177
2178    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
2179        if let Self::File { content, .. } = self {
2180            Ok(content)
2181        } else {
2182            anyhow::bail!("not a file: {path:?}");
2183        }
2184    }
2185
2186    fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
2187        if let Self::Dir { entries, .. } = self {
2188            Ok(entries)
2189        } else {
2190            anyhow::bail!("not a directory: {path:?}");
2191        }
2192    }
2193}
2194
2195#[cfg(feature = "test-support")]
2196struct FakeWatcher {
2197    tx: smol::channel::Sender<Vec<PathEvent>>,
2198    original_path: PathBuf,
2199    fs_state: Arc<Mutex<FakeFsState>>,
2200    prefixes: Mutex<Vec<PathBuf>>,
2201}
2202
2203#[cfg(feature = "test-support")]
2204impl Watcher for FakeWatcher {
2205    fn add(&self, path: &Path) -> Result<()> {
2206        if path.starts_with(&self.original_path) {
2207            return Ok(());
2208        }
2209        self.fs_state
2210            .try_lock()
2211            .unwrap()
2212            .event_txs
2213            .push((path.to_owned(), self.tx.clone()));
2214        self.prefixes.lock().push(path.to_owned());
2215        Ok(())
2216    }
2217
2218    fn remove(&self, _: &Path) -> Result<()> {
2219        Ok(())
2220    }
2221}
2222
2223#[cfg(feature = "test-support")]
2224#[derive(Debug)]
2225struct FakeHandle {
2226    inode: u64,
2227}
2228
2229#[cfg(feature = "test-support")]
2230impl FileHandle for FakeHandle {
2231    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
2232        let fs = fs.as_fake();
2233        let mut state = fs.state.lock();
2234        let Some(target) = state.moves.get(&self.inode).cloned() else {
2235            anyhow::bail!("fake fd not moved")
2236        };
2237
2238        if state.try_entry(&target, false).is_some() {
2239            return Ok(target);
2240        }
2241        anyhow::bail!("fake fd target not found")
2242    }
2243}
2244
2245#[cfg(feature = "test-support")]
2246#[async_trait::async_trait]
2247impl Fs for FakeFs {
2248    async fn create_dir(&self, path: &Path) -> Result<()> {
2249        self.simulate_random_delay().await;
2250
2251        let mut created_dirs = Vec::new();
2252        let mut cur_path = PathBuf::new();
2253        for component in path.components() {
2254            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
2255            cur_path.push(component);
2256            if should_skip {
2257                continue;
2258            }
2259            let mut state = self.state.lock();
2260
2261            let inode = state.get_and_increment_inode();
2262            let mtime = state.get_and_increment_mtime();
2263            state.write_path(&cur_path, |entry| {
2264                entry.or_insert_with(|| {
2265                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
2266                    FakeFsEntry::Dir {
2267                        inode,
2268                        mtime,
2269                        len: 0,
2270                        entries: Default::default(),
2271                        git_repo_state: None,
2272                    }
2273                });
2274                Ok(())
2275            })?
2276        }
2277
2278        self.state.lock().emit_event(created_dirs);
2279        Ok(())
2280    }
2281
2282    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2283        self.simulate_random_delay().await;
2284        let mut state = self.state.lock();
2285        let inode = state.get_and_increment_inode();
2286        let mtime = state.get_and_increment_mtime();
2287        let file = FakeFsEntry::File {
2288            inode,
2289            mtime,
2290            len: 0,
2291            content: Vec::new(),
2292            git_dir_path: None,
2293        };
2294        let mut kind = Some(PathEventKind::Created);
2295        state.write_path(path, |entry| {
2296            match entry {
2297                btree_map::Entry::Occupied(mut e) => {
2298                    if options.overwrite {
2299                        kind = Some(PathEventKind::Changed);
2300                        *e.get_mut() = file;
2301                    } else if !options.ignore_if_exists {
2302                        anyhow::bail!("path already exists: {path:?}");
2303                    }
2304                }
2305                btree_map::Entry::Vacant(e) => {
2306                    e.insert(file);
2307                }
2308            }
2309            Ok(())
2310        })?;
2311        state.emit_event([(path, kind)]);
2312        Ok(())
2313    }
2314
2315    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2316        let mut state = self.state.lock();
2317        let file = FakeFsEntry::Symlink { target };
2318        state
2319            .write_path(path.as_ref(), move |e| match e {
2320                btree_map::Entry::Vacant(e) => {
2321                    e.insert(file);
2322                    Ok(())
2323                }
2324                btree_map::Entry::Occupied(mut e) => {
2325                    *e.get_mut() = file;
2326                    Ok(())
2327                }
2328            })
2329            .unwrap();
2330        state.emit_event([(path, Some(PathEventKind::Created))]);
2331
2332        Ok(())
2333    }
2334
2335    async fn create_file_with(
2336        &self,
2337        path: &Path,
2338        mut content: Pin<&mut (dyn AsyncRead + Send)>,
2339    ) -> Result<()> {
2340        let mut bytes = Vec::new();
2341        content.read_to_end(&mut bytes).await?;
2342        self.write_file_internal(path, bytes, true)?;
2343        Ok(())
2344    }
2345
2346    async fn extract_tar_file(
2347        &self,
2348        path: &Path,
2349        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2350    ) -> Result<()> {
2351        let mut entries = content.entries()?;
2352        while let Some(entry) = entries.next().await {
2353            let mut entry = entry?;
2354            if entry.header().entry_type().is_file() {
2355                let path = path.join(entry.path()?.as_ref());
2356                let mut bytes = Vec::new();
2357                entry.read_to_end(&mut bytes).await?;
2358                self.create_dir(path.parent().unwrap()).await?;
2359                self.write_file_internal(&path, bytes, true)?;
2360            }
2361        }
2362        Ok(())
2363    }
2364
2365    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2366        self.simulate_random_delay().await;
2367
2368        let old_path = normalize_path(old_path);
2369        let new_path = normalize_path(new_path);
2370
2371        if options.create_parents {
2372            if let Some(parent) = new_path.parent() {
2373                self.create_dir(parent).await?;
2374            }
2375        }
2376
2377        let mut state = self.state.lock();
2378        let moved_entry = state.write_path(&old_path, |e| {
2379            if let btree_map::Entry::Occupied(e) = e {
2380                Ok(e.get().clone())
2381            } else {
2382                anyhow::bail!("path does not exist: {old_path:?}")
2383            }
2384        })?;
2385
2386        let inode = match moved_entry {
2387            FakeFsEntry::File { inode, .. } => inode,
2388            FakeFsEntry::Dir { inode, .. } => inode,
2389            _ => 0,
2390        };
2391
2392        state.moves.insert(inode, new_path.clone());
2393
2394        state.write_path(&new_path, |e| {
2395            match e {
2396                btree_map::Entry::Occupied(mut e) => {
2397                    if options.overwrite {
2398                        *e.get_mut() = moved_entry;
2399                    } else if !options.ignore_if_exists {
2400                        anyhow::bail!("path already exists: {new_path:?}");
2401                    }
2402                }
2403                btree_map::Entry::Vacant(e) => {
2404                    e.insert(moved_entry);
2405                }
2406            }
2407            Ok(())
2408        })?;
2409
2410        state
2411            .write_path(&old_path, |e| {
2412                if let btree_map::Entry::Occupied(e) = e {
2413                    Ok(e.remove())
2414                } else {
2415                    unreachable!()
2416                }
2417            })
2418            .unwrap();
2419
2420        state.emit_event([
2421            (old_path, Some(PathEventKind::Removed)),
2422            (new_path, Some(PathEventKind::Created)),
2423        ]);
2424        Ok(())
2425    }
2426
2427    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2428        self.simulate_random_delay().await;
2429
2430        let source = normalize_path(source);
2431        let target = normalize_path(target);
2432        let mut state = self.state.lock();
2433        let mtime = state.get_and_increment_mtime();
2434        let inode = state.get_and_increment_inode();
2435        let source_entry = state.entry(&source)?;
2436        let content = source_entry.file_content(&source)?.clone();
2437        let mut kind = Some(PathEventKind::Created);
2438        state.write_path(&target, |e| match e {
2439            btree_map::Entry::Occupied(e) => {
2440                if options.overwrite {
2441                    kind = Some(PathEventKind::Changed);
2442                    Ok(Some(e.get().clone()))
2443                } else if !options.ignore_if_exists {
2444                    anyhow::bail!("{target:?} already exists");
2445                } else {
2446                    Ok(None)
2447                }
2448            }
2449            btree_map::Entry::Vacant(e) => Ok(Some(
2450                e.insert(FakeFsEntry::File {
2451                    inode,
2452                    mtime,
2453                    len: content.len() as u64,
2454                    content,
2455                    git_dir_path: None,
2456                })
2457                .clone(),
2458            )),
2459        })?;
2460        state.emit_event([(target, kind)]);
2461        Ok(())
2462    }
2463
2464    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2465        self.simulate_random_delay().await;
2466
2467        let path = normalize_path(path);
2468        let parent_path = path.parent().context("cannot remove the root")?;
2469        let base_name = path.file_name().context("cannot remove the root")?;
2470
2471        let mut state = self.state.lock();
2472        let parent_entry = state.entry(parent_path)?;
2473        let entry = parent_entry
2474            .dir_entries(parent_path)?
2475            .entry(base_name.to_str().unwrap().into());
2476
2477        match entry {
2478            btree_map::Entry::Vacant(_) => {
2479                if !options.ignore_if_not_exists {
2480                    anyhow::bail!("{path:?} does not exist");
2481                }
2482            }
2483            btree_map::Entry::Occupied(mut entry) => {
2484                {
2485                    let children = entry.get_mut().dir_entries(&path)?;
2486                    if !options.recursive && !children.is_empty() {
2487                        anyhow::bail!("{path:?} is not empty");
2488                    }
2489                }
2490                entry.remove();
2491            }
2492        }
2493        state.emit_event([(path, Some(PathEventKind::Removed))]);
2494        Ok(())
2495    }
2496
2497    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2498        self.simulate_random_delay().await;
2499
2500        let path = normalize_path(path);
2501        let parent_path = path.parent().context("cannot remove the root")?;
2502        let base_name = path.file_name().unwrap();
2503        let mut state = self.state.lock();
2504        let parent_entry = state.entry(parent_path)?;
2505        let entry = parent_entry
2506            .dir_entries(parent_path)?
2507            .entry(base_name.to_str().unwrap().into());
2508        match entry {
2509            btree_map::Entry::Vacant(_) => {
2510                if !options.ignore_if_not_exists {
2511                    anyhow::bail!("{path:?} does not exist");
2512                }
2513            }
2514            btree_map::Entry::Occupied(mut entry) => {
2515                entry.get_mut().file_content(&path)?;
2516                entry.remove();
2517            }
2518        }
2519        state.emit_event([(path, Some(PathEventKind::Removed))]);
2520        Ok(())
2521    }
2522
2523    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2524        let bytes = self.load_internal(path).await?;
2525        Ok(Box::new(io::Cursor::new(bytes)))
2526    }
2527
2528    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2529        self.simulate_random_delay().await;
2530        let mut state = self.state.lock();
2531        let inode = match state.entry(path)? {
2532            FakeFsEntry::File { inode, .. } => *inode,
2533            FakeFsEntry::Dir { inode, .. } => *inode,
2534            _ => unreachable!(),
2535        };
2536        Ok(Arc::new(FakeHandle { inode }))
2537    }
2538
2539    async fn load(&self, path: &Path) -> Result<String> {
2540        let content = self.load_internal(path).await?;
2541        Ok(String::from_utf8(content)?)
2542    }
2543
2544    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2545        self.load_internal(path).await
2546    }
2547
2548    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2549        self.simulate_random_delay().await;
2550        let path = normalize_path(path.as_path());
2551        if let Some(path) = path.parent() {
2552            self.create_dir(path).await?;
2553        }
2554        self.write_file_internal(path, data.into_bytes(), true)?;
2555        Ok(())
2556    }
2557
2558    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2559        self.simulate_random_delay().await;
2560        let path = normalize_path(path);
2561        let content = text::chunks_with_line_ending(text, line_ending).collect::<String>();
2562        if let Some(path) = path.parent() {
2563            self.create_dir(path).await?;
2564        }
2565        self.write_file_internal(path, content.into_bytes(), false)?;
2566        Ok(())
2567    }
2568
2569    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2570        self.simulate_random_delay().await;
2571        let path = normalize_path(path);
2572        if let Some(path) = path.parent() {
2573            self.create_dir(path).await?;
2574        }
2575        self.write_file_internal(path, content.to_vec(), false)?;
2576        Ok(())
2577    }
2578
2579    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2580        let path = normalize_path(path);
2581        self.simulate_random_delay().await;
2582        let state = self.state.lock();
2583        let canonical_path = state
2584            .canonicalize(&path, true)
2585            .with_context(|| format!("path does not exist: {path:?}"))?;
2586        Ok(canonical_path)
2587    }
2588
2589    async fn is_file(&self, path: &Path) -> bool {
2590        let path = normalize_path(path);
2591        self.simulate_random_delay().await;
2592        let mut state = self.state.lock();
2593        if let Some((entry, _)) = state.try_entry(&path, true) {
2594            entry.is_file()
2595        } else {
2596            false
2597        }
2598    }
2599
2600    async fn is_dir(&self, path: &Path) -> bool {
2601        self.metadata(path)
2602            .await
2603            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2604    }
2605
2606    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2607        self.simulate_random_delay().await;
2608        let path = normalize_path(path);
2609        let mut state = self.state.lock();
2610        state.metadata_call_count += 1;
2611        if let Some((mut entry, _)) = state.try_entry(&path, false) {
2612            let is_symlink = entry.is_symlink();
2613            if is_symlink {
2614                if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2615                    entry = e;
2616                } else {
2617                    return Ok(None);
2618                }
2619            }
2620
2621            Ok(Some(match &*entry {
2622                FakeFsEntry::File {
2623                    inode, mtime, len, ..
2624                } => Metadata {
2625                    inode: *inode,
2626                    mtime: *mtime,
2627                    len: *len,
2628                    is_dir: false,
2629                    is_symlink,
2630                    is_fifo: false,
2631                    is_executable: false,
2632                },
2633                FakeFsEntry::Dir {
2634                    inode, mtime, len, ..
2635                } => Metadata {
2636                    inode: *inode,
2637                    mtime: *mtime,
2638                    len: *len,
2639                    is_dir: true,
2640                    is_symlink,
2641                    is_fifo: false,
2642                    is_executable: false,
2643                },
2644                FakeFsEntry::Symlink { .. } => unreachable!(),
2645            }))
2646        } else {
2647            Ok(None)
2648        }
2649    }
2650
2651    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2652        self.simulate_random_delay().await;
2653        let path = normalize_path(path);
2654        let mut state = self.state.lock();
2655        let (entry, _) = state
2656            .try_entry(&path, false)
2657            .with_context(|| format!("path does not exist: {path:?}"))?;
2658        if let FakeFsEntry::Symlink { target } = entry {
2659            Ok(target.clone())
2660        } else {
2661            anyhow::bail!("not a symlink: {path:?}")
2662        }
2663    }
2664
2665    async fn read_dir(
2666        &self,
2667        path: &Path,
2668    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2669        self.simulate_random_delay().await;
2670        let path = normalize_path(path);
2671        let mut state = self.state.lock();
2672        state.read_dir_call_count += 1;
2673        let entry = state.entry(&path)?;
2674        let children = entry.dir_entries(&path)?;
2675        let paths = children
2676            .keys()
2677            .map(|file_name| Ok(path.join(file_name)))
2678            .collect::<Vec<_>>();
2679        Ok(Box::pin(futures::stream::iter(paths)))
2680    }
2681
2682    async fn watch(
2683        &self,
2684        path: &Path,
2685        _: Duration,
2686    ) -> (
2687        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2688        Arc<dyn Watcher>,
2689    ) {
2690        self.simulate_random_delay().await;
2691        let (tx, rx) = smol::channel::unbounded();
2692        let path = path.to_path_buf();
2693        self.state.lock().event_txs.push((path.clone(), tx.clone()));
2694        let executor = self.executor.clone();
2695        let watcher = Arc::new(FakeWatcher {
2696            tx,
2697            original_path: path.to_owned(),
2698            fs_state: self.state.clone(),
2699            prefixes: Mutex::new(vec![path]),
2700        });
2701        (
2702            Box::pin(futures::StreamExt::filter(rx, {
2703                let watcher = watcher.clone();
2704                move |events| {
2705                    let result = events.iter().any(|evt_path| {
2706                        watcher
2707                            .prefixes
2708                            .lock()
2709                            .iter()
2710                            .any(|prefix| evt_path.path.starts_with(prefix))
2711                    });
2712                    let executor = executor.clone();
2713                    async move {
2714                        executor.simulate_random_delay().await;
2715                        result
2716                    }
2717                }
2718            })),
2719            watcher,
2720        )
2721    }
2722
2723    fn open_repo(
2724        &self,
2725        abs_dot_git: &Path,
2726        _system_git_binary: Option<&Path>,
2727    ) -> Option<Arc<dyn GitRepository>> {
2728        use util::ResultExt as _;
2729
2730        self.with_git_state_and_paths(
2731            abs_dot_git,
2732            false,
2733            |_, repository_dir_path, common_dir_path| {
2734                Arc::new(fake_git_repo::FakeGitRepository {
2735                    fs: self.this.upgrade().unwrap(),
2736                    executor: self.executor.clone(),
2737                    dot_git_path: abs_dot_git.to_path_buf(),
2738                    repository_dir_path: repository_dir_path.to_owned(),
2739                    common_dir_path: common_dir_path.to_owned(),
2740                    checkpoints: Arc::default(),
2741                }) as _
2742            },
2743        )
2744        .log_err()
2745    }
2746
2747    async fn git_init(
2748        &self,
2749        abs_work_directory_path: &Path,
2750        _fallback_branch_name: String,
2751    ) -> Result<()> {
2752        self.create_dir(&abs_work_directory_path.join(".git")).await
2753    }
2754
2755    async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2756        anyhow::bail!("Git clone is not supported in fake Fs")
2757    }
2758
2759    fn is_fake(&self) -> bool {
2760        true
2761    }
2762
2763    async fn is_case_sensitive(&self) -> Result<bool> {
2764        Ok(true)
2765    }
2766
2767    fn subscribe_to_jobs(&self) -> JobEventReceiver {
2768        let (sender, receiver) = futures::channel::mpsc::unbounded();
2769        self.state.lock().job_event_subscribers.lock().push(sender);
2770        receiver
2771    }
2772
2773    #[cfg(feature = "test-support")]
2774    fn as_fake(&self) -> Arc<FakeFs> {
2775        self.this.upgrade().unwrap()
2776    }
2777}
2778
2779pub fn normalize_path(path: &Path) -> PathBuf {
2780    let mut components = path.components().peekable();
2781    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2782        components.next();
2783        PathBuf::from(c.as_os_str())
2784    } else {
2785        PathBuf::new()
2786    };
2787
2788    for component in components {
2789        match component {
2790            Component::Prefix(..) => unreachable!(),
2791            Component::RootDir => {
2792                ret.push(component.as_os_str());
2793            }
2794            Component::CurDir => {}
2795            Component::ParentDir => {
2796                ret.pop();
2797            }
2798            Component::Normal(c) => {
2799                ret.push(c);
2800            }
2801        }
2802    }
2803    ret
2804}
2805
2806pub async fn copy_recursive<'a>(
2807    fs: &'a dyn Fs,
2808    source: &'a Path,
2809    target: &'a Path,
2810    options: CopyOptions,
2811) -> Result<()> {
2812    for (item, is_dir) in read_dir_items(fs, source).await? {
2813        let Ok(item_relative_path) = item.strip_prefix(source) else {
2814            continue;
2815        };
2816        let target_item = if item_relative_path == Path::new("") {
2817            target.to_path_buf()
2818        } else {
2819            target.join(item_relative_path)
2820        };
2821        if is_dir {
2822            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2823                if options.ignore_if_exists {
2824                    continue;
2825                } else {
2826                    anyhow::bail!("{target_item:?} already exists");
2827                }
2828            }
2829            let _ = fs
2830                .remove_dir(
2831                    &target_item,
2832                    RemoveOptions {
2833                        recursive: true,
2834                        ignore_if_not_exists: true,
2835                    },
2836                )
2837                .await;
2838            fs.create_dir(&target_item).await?;
2839        } else {
2840            fs.copy_file(&item, &target_item, options).await?;
2841        }
2842    }
2843    Ok(())
2844}
2845
2846/// Recursively reads all of the paths in the given directory.
2847///
2848/// Returns a vector of tuples of (path, is_dir).
2849pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2850    let mut items = Vec::new();
2851    read_recursive(fs, source, &mut items).await?;
2852    Ok(items)
2853}
2854
2855fn read_recursive<'a>(
2856    fs: &'a dyn Fs,
2857    source: &'a Path,
2858    output: &'a mut Vec<(PathBuf, bool)>,
2859) -> BoxFuture<'a, Result<()>> {
2860    use futures::future::FutureExt;
2861
2862    async move {
2863        let metadata = fs
2864            .metadata(source)
2865            .await?
2866            .with_context(|| format!("path does not exist: {source:?}"))?;
2867
2868        if metadata.is_dir {
2869            output.push((source.to_path_buf(), true));
2870            let mut children = fs.read_dir(source).await?;
2871            while let Some(child_path) = children.next().await {
2872                if let Ok(child_path) = child_path {
2873                    read_recursive(fs, &child_path, output).await?;
2874                }
2875            }
2876        } else {
2877            output.push((source.to_path_buf(), false));
2878        }
2879        Ok(())
2880    }
2881    .boxed()
2882}
2883
2884// todo(windows)
2885// can we get file id not open the file twice?
2886// https://github.com/rust-lang/rust/issues/63010
2887#[cfg(target_os = "windows")]
2888async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2889    use std::os::windows::io::AsRawHandle;
2890
2891    use smol::fs::windows::OpenOptionsExt;
2892    use windows::Win32::{
2893        Foundation::HANDLE,
2894        Storage::FileSystem::{
2895            BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2896        },
2897    };
2898
2899    let file = smol::fs::OpenOptions::new()
2900        .read(true)
2901        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2902        .open(path)
2903        .await?;
2904
2905    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2906    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2907    // This function supports Windows XP+
2908    smol::unblock(move || {
2909        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2910
2911        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2912    })
2913    .await
2914}
2915
2916#[cfg(target_os = "windows")]
2917fn atomic_replace<P: AsRef<Path>>(
2918    replaced_file: P,
2919    replacement_file: P,
2920) -> windows::core::Result<()> {
2921    use windows::{
2922        Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2923        core::HSTRING,
2924    };
2925
2926    // If the file does not exist, create it.
2927    let _ = std::fs::File::create_new(replaced_file.as_ref());
2928
2929    unsafe {
2930        ReplaceFileW(
2931            &HSTRING::from(replaced_file.as_ref().to_string_lossy().into_owned()),
2932            &HSTRING::from(replacement_file.as_ref().to_string_lossy().into_owned()),
2933            None,
2934            REPLACE_FILE_FLAGS::default(),
2935            None,
2936            None,
2937        )
2938    }
2939}