worktree.rs

   1mod ignore;
   2mod worktree_settings;
   3
   4use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   5use anyhow::{Context as _, Result, anyhow};
   6use chardetng::EncodingDetector;
   7use clock::ReplicaId;
   8use collections::{HashMap, HashSet, VecDeque};
   9use encoding_rs::Encoding;
  10use fs::{
  11    Fs, MTime, PathEvent, PathEventKind, RemoveOptions, Watcher, copy_recursive, read_dir_items,
  12};
  13use futures::{
  14    FutureExt as _, Stream, StreamExt,
  15    channel::{
  16        mpsc::{self, UnboundedSender},
  17        oneshot,
  18    },
  19    select_biased, stream,
  20    task::Poll,
  21};
  22use fuzzy::CharBag;
  23use git::{
  24    COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR, REPO_EXCLUDE,
  25    status::GitSummary,
  26};
  27use gpui::{
  28    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Priority,
  29    Task,
  30};
  31use ignore::IgnoreStack;
  32use language::DiskState;
  33
  34use parking_lot::Mutex;
  35use paths::{local_settings_folder_name, local_vscode_folder_name};
  36use postage::{
  37    barrier,
  38    prelude::{Sink as _, Stream as _},
  39    watch,
  40};
  41use rpc::{
  42    AnyProtoClient,
  43    proto::{self, split_worktree_update},
  44};
  45pub use settings::WorktreeId;
  46use settings::{Settings, SettingsLocation, SettingsStore};
  47use smallvec::{SmallVec, smallvec};
  48use smol::channel::{self, Sender};
  49use std::{
  50    any::Any,
  51    borrow::Borrow as _,
  52    cmp::Ordering,
  53    collections::hash_map,
  54    convert::TryFrom,
  55    ffi::OsStr,
  56    fmt,
  57    future::Future,
  58    mem::{self},
  59    ops::{Deref, DerefMut, Range},
  60    path::{Path, PathBuf},
  61    pin::Pin,
  62    sync::{
  63        Arc,
  64        atomic::{AtomicUsize, Ordering::SeqCst},
  65    },
  66    time::{Duration, Instant},
  67};
  68use sum_tree::{Bias, Dimensions, Edit, KeyedItem, SeekTarget, SumTree, Summary, TreeMap, TreeSet};
  69use text::{LineEnding, Rope};
  70use util::{
  71    ResultExt, debug_panic, maybe,
  72    paths::{PathMatcher, PathStyle, SanitizedPath, home_dir},
  73    rel_path::RelPath,
  74};
  75pub use worktree_settings::WorktreeSettings;
  76
  77use crate::ignore::IgnoreKind;
  78
  79pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  80
  81/// A set of local or remote files that are being opened as part of a project.
  82/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
  83/// Stores git repositories data and the diagnostics for the file(s).
  84///
  85/// Has an absolute path, and may be set to be visible in Zed UI or not.
  86/// May correspond to a directory or a single file.
  87/// Possible examples:
  88/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
  89/// * a directory opened in Zed — may be added as a visible entry to the current worktree
  90///
  91/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
  92pub enum Worktree {
  93    Local(LocalWorktree),
  94    Remote(RemoteWorktree),
  95}
  96
  97/// An entry, created in the worktree.
  98#[derive(Debug)]
  99pub enum CreatedEntry {
 100    /// Got created and indexed by the worktree, receiving a corresponding entry.
 101    Included(Entry),
 102    /// Got created, but not indexed due to falling under exclusion filters.
 103    Excluded { abs_path: PathBuf },
 104}
 105
 106#[derive(Debug)]
 107pub struct LoadedFile {
 108    pub file: Arc<File>,
 109    pub text: String,
 110    pub encoding: &'static Encoding,
 111    pub has_bom: bool,
 112}
 113
 114pub struct LoadedBinaryFile {
 115    pub file: Arc<File>,
 116    pub content: Vec<u8>,
 117}
 118
 119impl fmt::Debug for LoadedBinaryFile {
 120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 121        f.debug_struct("LoadedBinaryFile")
 122            .field("file", &self.file)
 123            .field("content_bytes", &self.content.len())
 124            .finish()
 125    }
 126}
 127
 128pub struct LocalWorktree {
 129    snapshot: LocalSnapshot,
 130    scan_requests_tx: channel::Sender<ScanRequest>,
 131    path_prefixes_to_scan_tx: channel::Sender<PathPrefixScanRequest>,
 132    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
 133    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 134    _background_scanner_tasks: Vec<Task<()>>,
 135    update_observer: Option<UpdateObservationState>,
 136    fs: Arc<dyn Fs>,
 137    fs_case_sensitive: bool,
 138    visible: bool,
 139    next_entry_id: Arc<AtomicUsize>,
 140    settings: WorktreeSettings,
 141    share_private_files: bool,
 142    scanning_enabled: bool,
 143}
 144
 145pub struct PathPrefixScanRequest {
 146    path: Arc<RelPath>,
 147    done: SmallVec<[barrier::Sender; 1]>,
 148}
 149
 150struct ScanRequest {
 151    relative_paths: Vec<Arc<RelPath>>,
 152    done: SmallVec<[barrier::Sender; 1]>,
 153}
 154
 155pub struct RemoteWorktree {
 156    snapshot: Snapshot,
 157    background_snapshot: Arc<Mutex<(Snapshot, Vec<proto::UpdateWorktree>)>>,
 158    project_id: u64,
 159    client: AnyProtoClient,
 160    file_scan_inclusions: PathMatcher,
 161    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
 162    update_observer: Option<mpsc::UnboundedSender<proto::UpdateWorktree>>,
 163    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 164    replica_id: ReplicaId,
 165    visible: bool,
 166    disconnected: bool,
 167}
 168
 169#[derive(Clone)]
 170pub struct Snapshot {
 171    id: WorktreeId,
 172    /// The absolute path of the worktree root.
 173    abs_path: Arc<SanitizedPath>,
 174    path_style: PathStyle,
 175    root_name: Arc<RelPath>,
 176    root_char_bag: CharBag,
 177    entries_by_path: SumTree<Entry>,
 178    entries_by_id: SumTree<PathEntry>,
 179    always_included_entries: Vec<Arc<RelPath>>,
 180
 181    /// A number that increases every time the worktree begins scanning
 182    /// a set of paths from the filesystem. This scanning could be caused
 183    /// by some operation performed on the worktree, such as reading or
 184    /// writing a file, or by an event reported by the filesystem.
 185    scan_id: usize,
 186
 187    /// The latest scan id that has completed, and whose preceding scans
 188    /// have all completed. The current `scan_id` could be more than one
 189    /// greater than the `completed_scan_id` if operations are performed
 190    /// on the worktree while it is processing a file-system event.
 191    completed_scan_id: usize,
 192}
 193
 194/// This path corresponds to the 'content path' of a repository in relation
 195/// to Zed's project root.
 196/// In the majority of the cases, this is the folder that contains the .git folder.
 197/// But if a sub-folder of a git repository is opened, this corresponds to the
 198/// project root and the .git folder is located in a parent directory.
 199#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
 200pub enum WorkDirectory {
 201    InProject {
 202        relative_path: Arc<RelPath>,
 203    },
 204    AboveProject {
 205        absolute_path: Arc<Path>,
 206        location_in_repo: Arc<Path>,
 207    },
 208}
 209
 210impl WorkDirectory {
 211    fn path_key(&self) -> PathKey {
 212        match self {
 213            WorkDirectory::InProject { relative_path } => PathKey(relative_path.clone()),
 214            WorkDirectory::AboveProject { .. } => PathKey(RelPath::empty().into()),
 215        }
 216    }
 217
 218    /// Returns true if the given path is a child of the work directory.
 219    ///
 220    /// Note that the path may not be a member of this repository, if there
 221    /// is a repository in a directory between these two paths
 222    /// external .git folder in a parent folder of the project root.
 223    #[track_caller]
 224    pub fn directory_contains(&self, path: &RelPath) -> bool {
 225        match self {
 226            WorkDirectory::InProject { relative_path } => path.starts_with(relative_path),
 227            WorkDirectory::AboveProject { .. } => true,
 228        }
 229    }
 230}
 231
 232impl Default for WorkDirectory {
 233    fn default() -> Self {
 234        Self::InProject {
 235            relative_path: Arc::from(RelPath::empty()),
 236        }
 237    }
 238}
 239
 240#[derive(Clone)]
 241pub struct LocalSnapshot {
 242    snapshot: Snapshot,
 243    global_gitignore: Option<Arc<Gitignore>>,
 244    /// Exclude files for all git repositories in the worktree, indexed by their absolute path.
 245    /// The boolean indicates whether the gitignore needs to be updated.
 246    repo_exclude_by_work_dir_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 247    /// All of the gitignore files in the worktree, indexed by their absolute path.
 248    /// The boolean indicates whether the gitignore needs to be updated.
 249    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 250    /// All of the git repositories in the worktree, indexed by the project entry
 251    /// id of their parent directory.
 252    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 253    /// The file handle of the worktree root
 254    /// (so we can find it after it's been moved)
 255    root_file_handle: Option<Arc<dyn fs::FileHandle>>,
 256}
 257
 258struct BackgroundScannerState {
 259    snapshot: LocalSnapshot,
 260    scanned_dirs: HashSet<ProjectEntryId>,
 261    path_prefixes_to_scan: HashSet<Arc<RelPath>>,
 262    paths_to_scan: HashSet<Arc<RelPath>>,
 263    /// The ids of all of the entries that were removed from the snapshot
 264    /// as part of the current update. These entry ids may be re-used
 265    /// if the same inode is discovered at a new path, or if the given
 266    /// path is re-created after being deleted.
 267    removed_entries: HashMap<u64, Entry>,
 268    changed_paths: Vec<Arc<RelPath>>,
 269    prev_snapshot: Snapshot,
 270    scanning_enabled: bool,
 271}
 272
 273#[derive(Clone, Debug, Eq, PartialEq)]
 274struct EventRoot {
 275    path: Arc<RelPath>,
 276    was_rescanned: bool,
 277}
 278
 279#[derive(Debug, Clone)]
 280struct LocalRepositoryEntry {
 281    work_directory_id: ProjectEntryId,
 282    work_directory: WorkDirectory,
 283    work_directory_abs_path: Arc<Path>,
 284    git_dir_scan_id: usize,
 285    /// Absolute path to the original .git entry that caused us to create this repository.
 286    ///
 287    /// This is normally a directory, but may be a "gitfile" that points to a directory elsewhere
 288    /// (whose path we then store in `repository_dir_abs_path`).
 289    dot_git_abs_path: Arc<Path>,
 290    /// Absolute path to the "commondir" for this repository.
 291    ///
 292    /// This is always a directory. For a normal repository, this is the same as
 293    /// `dot_git_abs_path`. For a linked worktree, this is the main repo's `.git`
 294    /// directory (resolved from the worktree's `commondir` file). For a submodule,
 295    /// this equals `repository_dir_abs_path` (submodules don't have a `commondir`
 296    /// file).
 297    common_dir_abs_path: Arc<Path>,
 298    /// Absolute path to the directory holding the repository's state.
 299    ///
 300    /// For a normal repository, this is a directory and coincides with `dot_git_abs_path` and
 301    /// `common_dir_abs_path`. For a submodule or worktree, this is some subdirectory of the
 302    /// commondir like `/project/.git/modules/foo`.
 303    repository_dir_abs_path: Arc<Path>,
 304}
 305
 306impl sum_tree::Item for LocalRepositoryEntry {
 307    type Summary = PathSummary<sum_tree::NoSummary>;
 308
 309    fn summary(&self, _: <Self::Summary as Summary>::Context<'_>) -> Self::Summary {
 310        PathSummary {
 311            max_path: self.work_directory.path_key().0,
 312            item_summary: sum_tree::NoSummary,
 313        }
 314    }
 315}
 316
 317impl KeyedItem for LocalRepositoryEntry {
 318    type Key = PathKey;
 319
 320    fn key(&self) -> Self::Key {
 321        self.work_directory.path_key()
 322    }
 323}
 324
 325impl Deref for LocalRepositoryEntry {
 326    type Target = WorkDirectory;
 327
 328    fn deref(&self) -> &Self::Target {
 329        &self.work_directory
 330    }
 331}
 332
 333impl Deref for LocalSnapshot {
 334    type Target = Snapshot;
 335
 336    fn deref(&self) -> &Self::Target {
 337        &self.snapshot
 338    }
 339}
 340
 341impl DerefMut for LocalSnapshot {
 342    fn deref_mut(&mut self) -> &mut Self::Target {
 343        &mut self.snapshot
 344    }
 345}
 346
 347enum ScanState {
 348    Started,
 349    Updated {
 350        snapshot: LocalSnapshot,
 351        changes: UpdatedEntriesSet,
 352        barrier: SmallVec<[barrier::Sender; 1]>,
 353        scanning: bool,
 354    },
 355    RootUpdated {
 356        new_path: Arc<SanitizedPath>,
 357    },
 358    RootDeleted,
 359}
 360
 361struct UpdateObservationState {
 362    snapshots_tx: mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet)>,
 363    resume_updates: watch::Sender<()>,
 364    _maintain_remote_snapshot: Task<Option<()>>,
 365}
 366
 367#[derive(Debug, Clone)]
 368pub enum Event {
 369    UpdatedEntries(UpdatedEntriesSet),
 370    UpdatedGitRepositories(UpdatedGitRepositoriesSet),
 371    DeletedEntry(ProjectEntryId),
 372    /// The worktree root itself has been deleted (for single-file worktrees)
 373    Deleted,
 374}
 375
 376impl EventEmitter<Event> for Worktree {}
 377
 378impl Worktree {
 379    pub async fn local(
 380        path: impl Into<Arc<Path>>,
 381        visible: bool,
 382        fs: Arc<dyn Fs>,
 383        next_entry_id: Arc<AtomicUsize>,
 384        scanning_enabled: bool,
 385        worktree_id: WorktreeId,
 386        cx: &mut AsyncApp,
 387    ) -> Result<Entity<Self>> {
 388        let abs_path = path.into();
 389        let metadata = fs
 390            .metadata(&abs_path)
 391            .await
 392            .context("failed to stat worktree path")?;
 393
 394        let fs_case_sensitive = fs.is_case_sensitive().await;
 395
 396        let root_file_handle = if metadata.as_ref().is_some() {
 397            fs.open_handle(&abs_path)
 398                .await
 399                .with_context(|| {
 400                    format!(
 401                        "failed to open local worktree root at {}",
 402                        abs_path.display()
 403                    )
 404                })
 405                .log_err()
 406        } else {
 407            None
 408        };
 409
 410        Ok(cx.new(move |cx: &mut Context<Worktree>| {
 411            let mut snapshot = LocalSnapshot {
 412                ignores_by_parent_abs_path: Default::default(),
 413                global_gitignore: Default::default(),
 414                repo_exclude_by_work_dir_abs_path: Default::default(),
 415                git_repositories: Default::default(),
 416                snapshot: Snapshot::new(
 417                    worktree_id,
 418                    abs_path
 419                        .file_name()
 420                        .and_then(|f| f.to_str())
 421                        .map_or(RelPath::empty().into(), |f| {
 422                            RelPath::unix(f).unwrap().into()
 423                        }),
 424                    abs_path.clone(),
 425                    PathStyle::local(),
 426                ),
 427                root_file_handle,
 428            };
 429
 430            let worktree_id = snapshot.id();
 431            let settings_location = Some(SettingsLocation {
 432                worktree_id,
 433                path: RelPath::empty(),
 434            });
 435
 436            let settings = WorktreeSettings::get(settings_location, cx).clone();
 437            cx.observe_global::<SettingsStore>(move |this, cx| {
 438                if let Self::Local(this) = this {
 439                    let settings = WorktreeSettings::get(settings_location, cx).clone();
 440                    if this.settings != settings {
 441                        this.settings = settings;
 442                        this.restart_background_scanners(cx);
 443                    }
 444                }
 445            })
 446            .detach();
 447
 448            let share_private_files = false;
 449            if let Some(metadata) = metadata {
 450                let mut entry = Entry::new(
 451                    RelPath::empty().into(),
 452                    &metadata,
 453                    ProjectEntryId::new(&next_entry_id),
 454                    snapshot.root_char_bag,
 455                    None,
 456                );
 457                if metadata.is_dir {
 458                    if !scanning_enabled {
 459                        entry.kind = EntryKind::UnloadedDir;
 460                    }
 461                } else {
 462                    if let Some(file_name) = abs_path.file_name()
 463                        && let Some(file_name) = file_name.to_str()
 464                        && let Ok(path) = RelPath::unix(file_name)
 465                    {
 466                        entry.is_private = !share_private_files && settings.is_path_private(path);
 467                        entry.is_hidden = settings.is_path_hidden(path);
 468                    }
 469                }
 470                cx.foreground_executor()
 471                    .block_on(snapshot.insert_entry(entry, fs.as_ref()));
 472            }
 473
 474            let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 475            let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 476            let mut worktree = LocalWorktree {
 477                share_private_files,
 478                next_entry_id,
 479                snapshot,
 480                is_scanning: watch::channel_with(true),
 481                snapshot_subscriptions: Default::default(),
 482                update_observer: None,
 483                scan_requests_tx,
 484                path_prefixes_to_scan_tx,
 485                _background_scanner_tasks: Vec::new(),
 486                fs,
 487                fs_case_sensitive,
 488                visible,
 489                settings,
 490                scanning_enabled,
 491            };
 492            worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
 493            Worktree::Local(worktree)
 494        }))
 495    }
 496
 497    pub fn remote(
 498        project_id: u64,
 499        replica_id: ReplicaId,
 500        worktree: proto::WorktreeMetadata,
 501        client: AnyProtoClient,
 502        path_style: PathStyle,
 503        cx: &mut App,
 504    ) -> Entity<Self> {
 505        cx.new(|cx: &mut Context<Self>| {
 506            let snapshot = Snapshot::new(
 507                WorktreeId::from_proto(worktree.id),
 508                RelPath::from_proto(&worktree.root_name)
 509                    .unwrap_or_else(|_| RelPath::empty().into()),
 510                Path::new(&worktree.abs_path).into(),
 511                path_style,
 512            );
 513
 514            let background_snapshot = Arc::new(Mutex::new((
 515                snapshot.clone(),
 516                Vec::<proto::UpdateWorktree>::new(),
 517            )));
 518            let (background_updates_tx, mut background_updates_rx) =
 519                mpsc::unbounded::<proto::UpdateWorktree>();
 520            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 521
 522            let worktree_id = snapshot.id();
 523            let settings_location = Some(SettingsLocation {
 524                worktree_id,
 525                path: RelPath::empty(),
 526            });
 527
 528            let settings = WorktreeSettings::get(settings_location, cx).clone();
 529            let worktree = RemoteWorktree {
 530                client,
 531                project_id,
 532                replica_id,
 533                snapshot,
 534                file_scan_inclusions: settings.parent_dir_scan_inclusions.clone(),
 535                background_snapshot: background_snapshot.clone(),
 536                updates_tx: Some(background_updates_tx),
 537                update_observer: None,
 538                snapshot_subscriptions: Default::default(),
 539                visible: worktree.visible,
 540                disconnected: false,
 541            };
 542
 543            // Apply updates to a separate snapshot in a background task, then
 544            // send them to a foreground task which updates the model.
 545            cx.background_spawn(async move {
 546                while let Some(update) = background_updates_rx.next().await {
 547                    {
 548                        let mut lock = background_snapshot.lock();
 549                        lock.0.apply_remote_update(
 550                            update.clone(),
 551                            &settings.parent_dir_scan_inclusions,
 552                        );
 553                        lock.1.push(update);
 554                    }
 555                    snapshot_updated_tx.send(()).await.ok();
 556                }
 557            })
 558            .detach();
 559
 560            // On the foreground task, update to the latest snapshot and notify
 561            // any update observer of all updates that led to that snapshot.
 562            cx.spawn(async move |this, cx| {
 563                while (snapshot_updated_rx.recv().await).is_some() {
 564                    this.update(cx, |this, cx| {
 565                        let mut entries_changed = false;
 566                        let this = this.as_remote_mut().unwrap();
 567                        {
 568                            let mut lock = this.background_snapshot.lock();
 569                            this.snapshot = lock.0.clone();
 570                            for update in lock.1.drain(..) {
 571                                entries_changed |= !update.updated_entries.is_empty()
 572                                    || !update.removed_entries.is_empty();
 573                                if let Some(tx) = &this.update_observer {
 574                                    tx.unbounded_send(update).ok();
 575                                }
 576                            }
 577                        };
 578
 579                        if entries_changed {
 580                            cx.emit(Event::UpdatedEntries(Arc::default()));
 581                        }
 582                        cx.notify();
 583                        while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 584                            if this.observed_snapshot(*scan_id) {
 585                                let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 586                                let _ = tx.send(());
 587                            } else {
 588                                break;
 589                            }
 590                        }
 591                    })?;
 592                }
 593                anyhow::Ok(())
 594            })
 595            .detach();
 596
 597            Worktree::Remote(worktree)
 598        })
 599    }
 600
 601    pub fn as_local(&self) -> Option<&LocalWorktree> {
 602        if let Worktree::Local(worktree) = self {
 603            Some(worktree)
 604        } else {
 605            None
 606        }
 607    }
 608
 609    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 610        if let Worktree::Remote(worktree) = self {
 611            Some(worktree)
 612        } else {
 613            None
 614        }
 615    }
 616
 617    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 618        if let Worktree::Local(worktree) = self {
 619            Some(worktree)
 620        } else {
 621            None
 622        }
 623    }
 624
 625    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 626        if let Worktree::Remote(worktree) = self {
 627            Some(worktree)
 628        } else {
 629            None
 630        }
 631    }
 632
 633    pub fn is_local(&self) -> bool {
 634        matches!(self, Worktree::Local(_))
 635    }
 636
 637    pub fn is_remote(&self) -> bool {
 638        !self.is_local()
 639    }
 640
 641    pub fn settings_location(&self, _: &Context<Self>) -> SettingsLocation<'static> {
 642        SettingsLocation {
 643            worktree_id: self.id(),
 644            path: RelPath::empty(),
 645        }
 646    }
 647
 648    pub fn snapshot(&self) -> Snapshot {
 649        match self {
 650            Worktree::Local(worktree) => worktree.snapshot.snapshot.clone(),
 651            Worktree::Remote(worktree) => worktree.snapshot.clone(),
 652        }
 653    }
 654
 655    pub fn scan_id(&self) -> usize {
 656        match self {
 657            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 658            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 659        }
 660    }
 661
 662    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 663        proto::WorktreeMetadata {
 664            id: self.id().to_proto(),
 665            root_name: self.root_name().to_proto(),
 666            visible: self.is_visible(),
 667            abs_path: self.abs_path().to_string_lossy().into_owned(),
 668        }
 669    }
 670
 671    pub fn completed_scan_id(&self) -> usize {
 672        match self {
 673            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 674            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 675        }
 676    }
 677
 678    pub fn is_visible(&self) -> bool {
 679        match self {
 680            Worktree::Local(worktree) => worktree.visible,
 681            Worktree::Remote(worktree) => worktree.visible,
 682        }
 683    }
 684
 685    pub fn replica_id(&self) -> ReplicaId {
 686        match self {
 687            Worktree::Local(_) => ReplicaId::LOCAL,
 688            Worktree::Remote(worktree) => worktree.replica_id,
 689        }
 690    }
 691
 692    pub fn abs_path(&self) -> Arc<Path> {
 693        match self {
 694            Worktree::Local(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
 695            Worktree::Remote(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
 696        }
 697    }
 698
 699    pub fn root_file(&self, cx: &Context<Self>) -> Option<Arc<File>> {
 700        let entry = self.root_entry()?;
 701        Some(File::for_entry(entry.clone(), cx.entity()))
 702    }
 703
 704    pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
 705    where
 706        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
 707        Fut: 'static + Send + Future<Output = bool>,
 708    {
 709        match self {
 710            Worktree::Local(this) => this.observe_updates(project_id, cx, callback),
 711            Worktree::Remote(this) => this.observe_updates(project_id, cx, callback),
 712        }
 713    }
 714
 715    pub fn stop_observing_updates(&mut self) {
 716        match self {
 717            Worktree::Local(this) => {
 718                this.update_observer.take();
 719            }
 720            Worktree::Remote(this) => {
 721                this.update_observer.take();
 722            }
 723        }
 724    }
 725
 726    pub fn wait_for_snapshot(
 727        &mut self,
 728        scan_id: usize,
 729    ) -> impl Future<Output = Result<()>> + use<> {
 730        match self {
 731            Worktree::Local(this) => this.wait_for_snapshot(scan_id).boxed(),
 732            Worktree::Remote(this) => this.wait_for_snapshot(scan_id).boxed(),
 733        }
 734    }
 735
 736    #[cfg(feature = "test-support")]
 737    pub fn has_update_observer(&self) -> bool {
 738        match self {
 739            Worktree::Local(this) => this.update_observer.is_some(),
 740            Worktree::Remote(this) => this.update_observer.is_some(),
 741        }
 742    }
 743
 744    pub fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
 745        match self {
 746            Worktree::Local(this) => this.load_file(path, cx),
 747            Worktree::Remote(_) => {
 748                Task::ready(Err(anyhow!("remote worktrees can't yet load files")))
 749            }
 750        }
 751    }
 752
 753    pub fn load_binary_file(
 754        &self,
 755        path: &RelPath,
 756        cx: &Context<Worktree>,
 757    ) -> Task<Result<LoadedBinaryFile>> {
 758        match self {
 759            Worktree::Local(this) => this.load_binary_file(path, cx),
 760            Worktree::Remote(_) => {
 761                Task::ready(Err(anyhow!("remote worktrees can't yet load binary files")))
 762            }
 763        }
 764    }
 765
 766    pub fn write_file(
 767        &self,
 768        path: Arc<RelPath>,
 769        text: Rope,
 770        line_ending: LineEnding,
 771        encoding: &'static Encoding,
 772        has_bom: bool,
 773        cx: &Context<Worktree>,
 774    ) -> Task<Result<Arc<File>>> {
 775        match self {
 776            Worktree::Local(this) => {
 777                this.write_file(path, text, line_ending, encoding, has_bom, cx)
 778            }
 779            Worktree::Remote(_) => {
 780                Task::ready(Err(anyhow!("remote worktree can't yet write files")))
 781            }
 782        }
 783    }
 784
 785    pub fn create_entry(
 786        &mut self,
 787        path: Arc<RelPath>,
 788        is_directory: bool,
 789        content: Option<Vec<u8>>,
 790        cx: &Context<Worktree>,
 791    ) -> Task<Result<CreatedEntry>> {
 792        let worktree_id = self.id();
 793        match self {
 794            Worktree::Local(this) => this.create_entry(path, is_directory, content, cx),
 795            Worktree::Remote(this) => {
 796                let project_id = this.project_id;
 797                let request = this.client.request(proto::CreateProjectEntry {
 798                    worktree_id: worktree_id.to_proto(),
 799                    project_id,
 800                    path: path.as_ref().to_proto(),
 801                    content,
 802                    is_directory,
 803                });
 804                cx.spawn(async move |this, cx| {
 805                    let response = request.await?;
 806                    match response.entry {
 807                        Some(entry) => this
 808                            .update(cx, |worktree, cx| {
 809                                worktree.as_remote_mut().unwrap().insert_entry(
 810                                    entry,
 811                                    response.worktree_scan_id as usize,
 812                                    cx,
 813                                )
 814                            })?
 815                            .await
 816                            .map(CreatedEntry::Included),
 817                        None => {
 818                            let abs_path =
 819                                this.read_with(cx, |worktree, _| worktree.absolutize(&path))?;
 820                            Ok(CreatedEntry::Excluded { abs_path })
 821                        }
 822                    }
 823                })
 824            }
 825        }
 826    }
 827
 828    pub fn delete_entry(
 829        &mut self,
 830        entry_id: ProjectEntryId,
 831        trash: bool,
 832        cx: &mut Context<Worktree>,
 833    ) -> Option<Task<Result<()>>> {
 834        let task = match self {
 835            Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
 836            Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
 837        }?;
 838
 839        let entry = match &*self {
 840            Worktree::Local(this) => this.entry_for_id(entry_id),
 841            Worktree::Remote(this) => this.entry_for_id(entry_id),
 842        }?;
 843
 844        let mut ids = vec![entry_id];
 845        let path = &*entry.path;
 846
 847        self.get_children_ids_recursive(path, &mut ids);
 848
 849        for id in ids {
 850            cx.emit(Event::DeletedEntry(id));
 851        }
 852        Some(task)
 853    }
 854
 855    fn get_children_ids_recursive(&self, path: &RelPath, ids: &mut Vec<ProjectEntryId>) {
 856        let children_iter = self.child_entries(path);
 857        for child in children_iter {
 858            ids.push(child.id);
 859            self.get_children_ids_recursive(&child.path, ids);
 860        }
 861    }
 862
 863    // pub fn rename_entry(
 864    //     &mut self,
 865    //     entry_id: ProjectEntryId,
 866    //     new_path: Arc<RelPath>,
 867    //     cx: &Context<Self>,
 868    // ) -> Task<Result<CreatedEntry>> {
 869    //     match self {
 870    //         Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
 871    //         Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
 872    //     }
 873    // }
 874
 875    pub fn copy_external_entries(
 876        &mut self,
 877        target_directory: Arc<RelPath>,
 878        paths: Vec<Arc<Path>>,
 879        fs: Arc<dyn Fs>,
 880        cx: &Context<Worktree>,
 881    ) -> Task<Result<Vec<ProjectEntryId>>> {
 882        match self {
 883            Worktree::Local(this) => this.copy_external_entries(target_directory, paths, cx),
 884            Worktree::Remote(this) => this.copy_external_entries(target_directory, paths, fs, cx),
 885        }
 886    }
 887
 888    pub fn expand_entry(
 889        &mut self,
 890        entry_id: ProjectEntryId,
 891        cx: &Context<Worktree>,
 892    ) -> Option<Task<Result<()>>> {
 893        match self {
 894            Worktree::Local(this) => this.expand_entry(entry_id, cx),
 895            Worktree::Remote(this) => {
 896                let response = this.client.request(proto::ExpandProjectEntry {
 897                    project_id: this.project_id,
 898                    entry_id: entry_id.to_proto(),
 899                });
 900                Some(cx.spawn(async move |this, cx| {
 901                    let response = response.await?;
 902                    this.update(cx, |this, _| {
 903                        this.as_remote_mut()
 904                            .unwrap()
 905                            .wait_for_snapshot(response.worktree_scan_id as usize)
 906                    })?
 907                    .await?;
 908                    Ok(())
 909                }))
 910            }
 911        }
 912    }
 913
 914    pub fn expand_all_for_entry(
 915        &mut self,
 916        entry_id: ProjectEntryId,
 917        cx: &Context<Worktree>,
 918    ) -> Option<Task<Result<()>>> {
 919        match self {
 920            Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
 921            Worktree::Remote(this) => {
 922                let response = this.client.request(proto::ExpandAllForProjectEntry {
 923                    project_id: this.project_id,
 924                    entry_id: entry_id.to_proto(),
 925                });
 926                Some(cx.spawn(async move |this, cx| {
 927                    let response = response.await?;
 928                    this.update(cx, |this, _| {
 929                        this.as_remote_mut()
 930                            .unwrap()
 931                            .wait_for_snapshot(response.worktree_scan_id as usize)
 932                    })?
 933                    .await?;
 934                    Ok(())
 935                }))
 936            }
 937        }
 938    }
 939
 940    pub async fn handle_create_entry(
 941        this: Entity<Self>,
 942        request: proto::CreateProjectEntry,
 943        mut cx: AsyncApp,
 944    ) -> Result<proto::ProjectEntryResponse> {
 945        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
 946            anyhow::Ok((
 947                this.scan_id(),
 948                this.create_entry(
 949                    RelPath::from_proto(&request.path).with_context(|| {
 950                        format!("received invalid relative path {:?}", request.path)
 951                    })?,
 952                    request.is_directory,
 953                    request.content,
 954                    cx,
 955                ),
 956            ))
 957        })?;
 958        Ok(proto::ProjectEntryResponse {
 959            entry: match &entry.await? {
 960                CreatedEntry::Included(entry) => Some(entry.into()),
 961                CreatedEntry::Excluded { .. } => None,
 962            },
 963            worktree_scan_id: scan_id as u64,
 964        })
 965    }
 966
 967    pub async fn handle_delete_entry(
 968        this: Entity<Self>,
 969        request: proto::DeleteProjectEntry,
 970        mut cx: AsyncApp,
 971    ) -> Result<proto::ProjectEntryResponse> {
 972        let (scan_id, task) = this.update(&mut cx, |this, cx| {
 973            (
 974                this.scan_id(),
 975                this.delete_entry(
 976                    ProjectEntryId::from_proto(request.entry_id),
 977                    request.use_trash,
 978                    cx,
 979                ),
 980            )
 981        });
 982        task.ok_or_else(|| anyhow::anyhow!("invalid entry"))?
 983            .await?;
 984        Ok(proto::ProjectEntryResponse {
 985            entry: None,
 986            worktree_scan_id: scan_id as u64,
 987        })
 988    }
 989
 990    pub async fn handle_expand_entry(
 991        this: Entity<Self>,
 992        request: proto::ExpandProjectEntry,
 993        mut cx: AsyncApp,
 994    ) -> Result<proto::ExpandProjectEntryResponse> {
 995        let task = this.update(&mut cx, |this, cx| {
 996            this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
 997        });
 998        task.ok_or_else(|| anyhow::anyhow!("no such entry"))?
 999            .await?;
1000        let scan_id = this.read_with(&cx, |this, _| this.scan_id());
1001        Ok(proto::ExpandProjectEntryResponse {
1002            worktree_scan_id: scan_id as u64,
1003        })
1004    }
1005
1006    pub async fn handle_expand_all_for_entry(
1007        this: Entity<Self>,
1008        request: proto::ExpandAllForProjectEntry,
1009        mut cx: AsyncApp,
1010    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1011        let task = this.update(&mut cx, |this, cx| {
1012            this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1013        });
1014        task.ok_or_else(|| anyhow::anyhow!("no such entry"))?
1015            .await?;
1016        let scan_id = this.read_with(&cx, |this, _| this.scan_id());
1017        Ok(proto::ExpandAllForProjectEntryResponse {
1018            worktree_scan_id: scan_id as u64,
1019        })
1020    }
1021
1022    pub fn is_single_file(&self) -> bool {
1023        self.root_dir().is_none()
1024    }
1025
1026    /// For visible worktrees, returns the path with the worktree name as the first component.
1027    /// Otherwise, returns an absolute path.
1028    pub fn full_path(&self, worktree_relative_path: &RelPath) -> PathBuf {
1029        if self.is_visible() {
1030            self.root_name()
1031                .join(worktree_relative_path)
1032                .display(self.path_style)
1033                .to_string()
1034                .into()
1035        } else {
1036            let full_path = self.abs_path();
1037            let mut full_path_string = if self.is_local()
1038                && let Ok(stripped) = full_path.strip_prefix(home_dir())
1039            {
1040                self.path_style
1041                    .join("~", &*stripped.to_string_lossy())
1042                    .unwrap()
1043            } else {
1044                full_path.to_string_lossy().into_owned()
1045            };
1046
1047            if worktree_relative_path.components().next().is_some() {
1048                full_path_string.push_str(self.path_style.primary_separator());
1049                full_path_string.push_str(&worktree_relative_path.display(self.path_style));
1050            }
1051
1052            full_path_string.into()
1053        }
1054    }
1055}
1056
1057impl LocalWorktree {
1058    pub fn fs(&self) -> &Arc<dyn Fs> {
1059        &self.fs
1060    }
1061
1062    pub fn is_path_private(&self, path: &RelPath) -> bool {
1063        !self.share_private_files && self.settings.is_path_private(path)
1064    }
1065
1066    pub fn fs_is_case_sensitive(&self) -> bool {
1067        self.fs_case_sensitive
1068    }
1069
1070    fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1071        let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1072        let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1073        self.scan_requests_tx = scan_requests_tx;
1074        self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1075
1076        self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1077        let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1078        log::debug!(
1079            "refreshing entries for the following always included paths: {:?}",
1080            always_included_entries
1081        );
1082
1083        // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1084        // nested always included entries may not get updated and will result in out-of-date info.
1085        self.refresh_entries_for_paths(always_included_entries);
1086    }
1087
1088    fn start_background_scanner(
1089        &mut self,
1090        scan_requests_rx: channel::Receiver<ScanRequest>,
1091        path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1092        cx: &Context<Worktree>,
1093    ) {
1094        let snapshot = self.snapshot();
1095        let share_private_files = self.share_private_files;
1096        let next_entry_id = self.next_entry_id.clone();
1097        let fs = self.fs.clone();
1098        let scanning_enabled = self.scanning_enabled;
1099        let settings = self.settings.clone();
1100        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1101        let background_scanner = cx.background_spawn({
1102            let abs_path = snapshot.abs_path.as_path().to_path_buf();
1103            let background = cx.background_executor().clone();
1104            async move {
1105                let (events, watcher) = if scanning_enabled {
1106                    fs.watch(&abs_path, FS_WATCH_LATENCY).await
1107                } else {
1108                    (Box::pin(stream::pending()) as _, Arc::new(NullWatcher) as _)
1109                };
1110                let fs_case_sensitive = fs.is_case_sensitive().await;
1111
1112                let is_single_file = snapshot.snapshot.root_dir().is_none();
1113                let mut scanner = BackgroundScanner {
1114                    fs,
1115                    fs_case_sensitive,
1116                    status_updates_tx: scan_states_tx,
1117                    executor: background,
1118                    scan_requests_rx,
1119                    path_prefixes_to_scan_rx,
1120                    next_entry_id,
1121                    state: async_lock::Mutex::new(BackgroundScannerState {
1122                        prev_snapshot: snapshot.snapshot.clone(),
1123                        snapshot,
1124                        scanned_dirs: Default::default(),
1125                        scanning_enabled,
1126                        path_prefixes_to_scan: Default::default(),
1127                        paths_to_scan: Default::default(),
1128                        removed_entries: Default::default(),
1129                        changed_paths: Default::default(),
1130                    }),
1131                    phase: BackgroundScannerPhase::InitialScan,
1132                    share_private_files,
1133                    settings,
1134                    watcher,
1135                    is_single_file,
1136                };
1137
1138                scanner
1139                    .run(Box::pin(events.map(|events| events.into_iter().collect())))
1140                    .await;
1141            }
1142        });
1143        let scan_state_updater = cx.spawn(async move |this, cx| {
1144            while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
1145                this.update(cx, |this, cx| {
1146                    let this = this.as_local_mut().unwrap();
1147                    match state {
1148                        ScanState::Started => {
1149                            *this.is_scanning.0.borrow_mut() = true;
1150                        }
1151                        ScanState::Updated {
1152                            snapshot,
1153                            changes,
1154                            barrier,
1155                            scanning,
1156                        } => {
1157                            *this.is_scanning.0.borrow_mut() = scanning;
1158                            this.set_snapshot(snapshot, changes, cx);
1159                            drop(barrier);
1160                        }
1161                        ScanState::RootUpdated { new_path } => {
1162                            this.update_abs_path_and_refresh(new_path, cx);
1163                        }
1164                        ScanState::RootDeleted => {
1165                            log::info!(
1166                                "worktree root {} no longer exists, closing worktree",
1167                                this.abs_path().display()
1168                            );
1169                            cx.emit(Event::Deleted);
1170                        }
1171                    }
1172                });
1173            }
1174        });
1175        self._background_scanner_tasks = vec![background_scanner, scan_state_updater];
1176        *self.is_scanning.0.borrow_mut() = true;
1177    }
1178
1179    fn set_snapshot(
1180        &mut self,
1181        mut new_snapshot: LocalSnapshot,
1182        entry_changes: UpdatedEntriesSet,
1183        cx: &mut Context<Worktree>,
1184    ) {
1185        let repo_changes = self.changed_repos(&self.snapshot, &mut new_snapshot);
1186        self.snapshot = new_snapshot;
1187
1188        if let Some(share) = self.update_observer.as_mut() {
1189            share
1190                .snapshots_tx
1191                .unbounded_send((self.snapshot.clone(), entry_changes.clone()))
1192                .ok();
1193        }
1194
1195        if !entry_changes.is_empty() {
1196            cx.emit(Event::UpdatedEntries(entry_changes));
1197        }
1198        if !repo_changes.is_empty() {
1199            cx.emit(Event::UpdatedGitRepositories(repo_changes));
1200        }
1201
1202        while let Some((scan_id, _)) = self.snapshot_subscriptions.front() {
1203            if self.snapshot.completed_scan_id >= *scan_id {
1204                let (_, tx) = self.snapshot_subscriptions.pop_front().unwrap();
1205                tx.send(()).ok();
1206            } else {
1207                break;
1208            }
1209        }
1210    }
1211
1212    fn changed_repos(
1213        &self,
1214        old_snapshot: &LocalSnapshot,
1215        new_snapshot: &mut LocalSnapshot,
1216    ) -> UpdatedGitRepositoriesSet {
1217        let mut changes = Vec::new();
1218        let mut old_repos = old_snapshot.git_repositories.iter().peekable();
1219        let new_repos = new_snapshot.git_repositories.clone();
1220        let mut new_repos = new_repos.iter().peekable();
1221
1222        loop {
1223            match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1224                (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1225                    match Ord::cmp(&new_entry_id, &old_entry_id) {
1226                        Ordering::Less => {
1227                            changes.push(UpdatedGitRepository {
1228                                work_directory_id: new_entry_id,
1229                                old_work_directory_abs_path: None,
1230                                new_work_directory_abs_path: Some(
1231                                    new_repo.work_directory_abs_path.clone(),
1232                                ),
1233                                dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1234                                repository_dir_abs_path: Some(
1235                                    new_repo.repository_dir_abs_path.clone(),
1236                                ),
1237                                common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1238                            });
1239                            new_repos.next();
1240                        }
1241                        Ordering::Equal => {
1242                            if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id
1243                                || new_repo.work_directory_abs_path
1244                                    != old_repo.work_directory_abs_path
1245                            {
1246                                changes.push(UpdatedGitRepository {
1247                                    work_directory_id: new_entry_id,
1248                                    old_work_directory_abs_path: Some(
1249                                        old_repo.work_directory_abs_path.clone(),
1250                                    ),
1251                                    new_work_directory_abs_path: Some(
1252                                        new_repo.work_directory_abs_path.clone(),
1253                                    ),
1254                                    dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1255                                    repository_dir_abs_path: Some(
1256                                        new_repo.repository_dir_abs_path.clone(),
1257                                    ),
1258                                    common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1259                                });
1260                            }
1261                            new_repos.next();
1262                            old_repos.next();
1263                        }
1264                        Ordering::Greater => {
1265                            changes.push(UpdatedGitRepository {
1266                                work_directory_id: old_entry_id,
1267                                old_work_directory_abs_path: Some(
1268                                    old_repo.work_directory_abs_path.clone(),
1269                                ),
1270                                new_work_directory_abs_path: None,
1271                                dot_git_abs_path: None,
1272                                repository_dir_abs_path: None,
1273                                common_dir_abs_path: None,
1274                            });
1275                            old_repos.next();
1276                        }
1277                    }
1278                }
1279                (Some((entry_id, repo)), None) => {
1280                    changes.push(UpdatedGitRepository {
1281                        work_directory_id: entry_id,
1282                        old_work_directory_abs_path: None,
1283                        new_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1284                        dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1285                        repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1286                        common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1287                    });
1288                    new_repos.next();
1289                }
1290                (None, Some((entry_id, repo))) => {
1291                    changes.push(UpdatedGitRepository {
1292                        work_directory_id: entry_id,
1293                        old_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1294                        new_work_directory_abs_path: None,
1295                        dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1296                        repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1297                        common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1298                    });
1299                    old_repos.next();
1300                }
1301                (None, None) => break,
1302            }
1303        }
1304
1305        fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1306            (value.0.clone(), value.1.clone())
1307        }
1308
1309        changes.into()
1310    }
1311
1312    pub fn scan_complete(&self) -> impl Future<Output = ()> + use<> {
1313        let mut is_scanning_rx = self.is_scanning.1.clone();
1314        async move {
1315            let mut is_scanning = *is_scanning_rx.borrow();
1316            while is_scanning {
1317                if let Some(value) = is_scanning_rx.recv().await {
1318                    is_scanning = value;
1319                } else {
1320                    break;
1321                }
1322            }
1323        }
1324    }
1325
1326    pub fn wait_for_snapshot(
1327        &mut self,
1328        scan_id: usize,
1329    ) -> impl Future<Output = Result<()>> + use<> {
1330        let (tx, rx) = oneshot::channel();
1331        if self.snapshot.completed_scan_id >= scan_id {
1332            tx.send(()).ok();
1333        } else {
1334            match self
1335                .snapshot_subscriptions
1336                .binary_search_by_key(&scan_id, |probe| probe.0)
1337            {
1338                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1339            }
1340        }
1341
1342        async move {
1343            rx.await?;
1344            Ok(())
1345        }
1346    }
1347
1348    pub fn snapshot(&self) -> LocalSnapshot {
1349        self.snapshot.clone()
1350    }
1351
1352    pub fn settings(&self) -> WorktreeSettings {
1353        self.settings.clone()
1354    }
1355
1356    fn load_binary_file(
1357        &self,
1358        path: &RelPath,
1359        cx: &Context<Worktree>,
1360    ) -> Task<Result<LoadedBinaryFile>> {
1361        let path = Arc::from(path);
1362        let abs_path = self.absolutize(&path);
1363        let fs = self.fs.clone();
1364        let entry = self.refresh_entry(path.clone(), None, cx);
1365        let is_private = self.is_path_private(&path);
1366
1367        let worktree = cx.weak_entity();
1368        cx.background_spawn(async move {
1369            let content = fs.load_bytes(&abs_path).await?;
1370
1371            let worktree = worktree.upgrade().context("worktree was dropped")?;
1372            let file = match entry.await? {
1373                Some(entry) => File::for_entry(entry, worktree),
1374                None => {
1375                    let metadata = fs
1376                        .metadata(&abs_path)
1377                        .await
1378                        .with_context(|| {
1379                            format!("Loading metadata for excluded file {abs_path:?}")
1380                        })?
1381                        .with_context(|| {
1382                            format!("Excluded file {abs_path:?} got removed during loading")
1383                        })?;
1384                    Arc::new(File {
1385                        entry_id: None,
1386                        worktree,
1387                        path,
1388                        disk_state: DiskState::Present {
1389                            mtime: metadata.mtime,
1390                            size: metadata.len,
1391                        },
1392                        is_local: true,
1393                        is_private,
1394                    })
1395                }
1396            };
1397
1398            Ok(LoadedBinaryFile { file, content })
1399        })
1400    }
1401
1402    #[ztracing::instrument(skip_all)]
1403    fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1404        let path = Arc::from(path);
1405        let abs_path = self.absolutize(&path);
1406        let fs = self.fs.clone();
1407        let entry = self.refresh_entry(path.clone(), None, cx);
1408        let is_private = self.is_path_private(path.as_ref());
1409
1410        let this = cx.weak_entity();
1411        cx.background_spawn(async move {
1412            // WARN: Temporary workaround for #27283.
1413            //       We are not efficient with our memory usage per file, and use in excess of 64GB for a 10GB file
1414            //       Therefore, as a temporary workaround to prevent system freezes, we just bail before opening a file
1415            //       if it is too large
1416            //       5GB seems to be more reasonable, peaking at ~16GB, while 6GB jumps up to >24GB which seems like a
1417            //       reasonable limit
1418            {
1419                const FILE_SIZE_MAX: u64 = 6 * 1024 * 1024 * 1024; // 6GB
1420                if let Ok(Some(metadata)) = fs.metadata(&abs_path).await
1421                    && metadata.len >= FILE_SIZE_MAX
1422                {
1423                    anyhow::bail!("File is too large to load");
1424                }
1425            }
1426            let (text, encoding, has_bom) = decode_file_text(fs.as_ref(), &abs_path).await?;
1427
1428            let worktree = this.upgrade().context("worktree was dropped")?;
1429            let file = match entry.await? {
1430                Some(entry) => File::for_entry(entry, worktree),
1431                None => {
1432                    let metadata = fs
1433                        .metadata(&abs_path)
1434                        .await
1435                        .with_context(|| {
1436                            format!("Loading metadata for excluded file {abs_path:?}")
1437                        })?
1438                        .with_context(|| {
1439                            format!("Excluded file {abs_path:?} got removed during loading")
1440                        })?;
1441                    Arc::new(File {
1442                        entry_id: None,
1443                        worktree,
1444                        path,
1445                        disk_state: DiskState::Present {
1446                            mtime: metadata.mtime,
1447                            size: metadata.len,
1448                        },
1449                        is_local: true,
1450                        is_private,
1451                    })
1452                }
1453            };
1454
1455            Ok(LoadedFile {
1456                file,
1457                text,
1458                encoding,
1459                has_bom,
1460            })
1461        })
1462    }
1463
1464    /// Find the lowest path in the worktree's datastructures that is an ancestor
1465    fn lowest_ancestor(&self, path: &RelPath) -> Arc<RelPath> {
1466        let mut lowest_ancestor = None;
1467        for path in path.ancestors() {
1468            if self.entry_for_path(path).is_some() {
1469                lowest_ancestor = Some(path.into());
1470                break;
1471            }
1472        }
1473
1474        lowest_ancestor.unwrap_or_else(|| RelPath::empty().into())
1475    }
1476
1477    pub fn create_entry(
1478        &self,
1479        path: Arc<RelPath>,
1480        is_dir: bool,
1481        content: Option<Vec<u8>>,
1482        cx: &Context<Worktree>,
1483    ) -> Task<Result<CreatedEntry>> {
1484        let abs_path = self.absolutize(&path);
1485        let path_excluded = self.settings.is_path_excluded(&path);
1486        let fs = self.fs.clone();
1487        let task_abs_path = abs_path.clone();
1488        let write = cx.background_spawn(async move {
1489            if is_dir {
1490                fs.create_dir(&task_abs_path)
1491                    .await
1492                    .with_context(|| format!("creating directory {task_abs_path:?}"))
1493            } else {
1494                fs.write(&task_abs_path, content.as_deref().unwrap_or(&[]))
1495                    .await
1496                    .with_context(|| format!("creating file {task_abs_path:?}"))
1497            }
1498        });
1499
1500        let lowest_ancestor = self.lowest_ancestor(&path);
1501        cx.spawn(async move |this, cx| {
1502            write.await?;
1503            if path_excluded {
1504                return Ok(CreatedEntry::Excluded { abs_path });
1505            }
1506
1507            let (result, refreshes) = this.update(cx, |this, cx| {
1508                let mut refreshes = Vec::new();
1509                let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1510                for refresh_path in refresh_paths.ancestors() {
1511                    if refresh_path == RelPath::empty() {
1512                        continue;
1513                    }
1514                    let refresh_full_path = lowest_ancestor.join(refresh_path);
1515
1516                    refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1517                        refresh_full_path,
1518                        None,
1519                        cx,
1520                    ));
1521                }
1522                (
1523                    this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1524                    refreshes,
1525                )
1526            })?;
1527            for refresh in refreshes {
1528                refresh.await.log_err();
1529            }
1530
1531            Ok(result
1532                .await?
1533                .map(CreatedEntry::Included)
1534                .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1535        })
1536    }
1537
1538    pub fn write_file(
1539        &self,
1540        path: Arc<RelPath>,
1541        text: Rope,
1542        line_ending: LineEnding,
1543        encoding: &'static Encoding,
1544        has_bom: bool,
1545        cx: &Context<Worktree>,
1546    ) -> Task<Result<Arc<File>>> {
1547        let fs = self.fs.clone();
1548        let is_private = self.is_path_private(&path);
1549        let abs_path = self.absolutize(&path);
1550
1551        let write = cx.background_spawn({
1552            let fs = fs.clone();
1553            let abs_path = abs_path.clone();
1554            async move {
1555                // For UTF-8, use the optimized `fs.save` which writes Rope chunks directly to disk
1556                // without allocating a contiguous string.
1557                if encoding == encoding_rs::UTF_8 && !has_bom {
1558                    return fs.save(&abs_path, &text, line_ending).await;
1559                }
1560
1561                // For legacy encodings (e.g. Shift-JIS), we fall back to converting the entire Rope
1562                // to a String/Bytes in memory before writing.
1563                //
1564                // Note: This is inefficient for very large files compared to the streaming approach above,
1565                // but supporting streaming writes for arbitrary encodings would require a significant
1566                // refactor of the `fs` crate to expose a Writer interface.
1567                let text_string = text.to_string();
1568                let normalized_text = match line_ending {
1569                    LineEnding::Unix => text_string,
1570                    LineEnding::Windows => text_string.replace('\n', "\r\n"),
1571                };
1572
1573                // Create the byte vector manually for UTF-16 encodings because encoding_rs encodes to UTF-8 by default (per WHATWG standards),
1574                //  which is not what we want for saving files.
1575                let bytes = if encoding == encoding_rs::UTF_16BE {
1576                    let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
1577                    if has_bom {
1578                        data.extend_from_slice(&[0xFE, 0xFF]); // BOM
1579                    }
1580                    let utf16be_bytes =
1581                        normalized_text.encode_utf16().flat_map(|u| u.to_be_bytes());
1582                    data.extend(utf16be_bytes);
1583                    data.into()
1584                } else if encoding == encoding_rs::UTF_16LE {
1585                    let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
1586                    if has_bom {
1587                        data.extend_from_slice(&[0xFF, 0xFE]); // BOM
1588                    }
1589                    let utf16le_bytes =
1590                        normalized_text.encode_utf16().flat_map(|u| u.to_le_bytes());
1591                    data.extend(utf16le_bytes);
1592                    data.into()
1593                } else {
1594                    // For other encodings (Shift-JIS, UTF-8 with BOM, etc.), delegate to encoding_rs.
1595                    let bom_bytes = if has_bom {
1596                        if encoding == encoding_rs::UTF_8 {
1597                            vec![0xEF, 0xBB, 0xBF]
1598                        } else {
1599                            vec![]
1600                        }
1601                    } else {
1602                        vec![]
1603                    };
1604                    let (cow, _, _) = encoding.encode(&normalized_text);
1605                    if !bom_bytes.is_empty() {
1606                        let mut bytes = bom_bytes;
1607                        bytes.extend_from_slice(&cow);
1608                        bytes.into()
1609                    } else {
1610                        cow
1611                    }
1612                };
1613
1614                fs.write(&abs_path, &bytes).await
1615            }
1616        });
1617
1618        cx.spawn(async move |this, cx| {
1619            write.await?;
1620            let entry = this
1621                .update(cx, |this, cx| {
1622                    this.as_local_mut()
1623                        .unwrap()
1624                        .refresh_entry(path.clone(), None, cx)
1625                })?
1626                .await?;
1627            let worktree = this.upgrade().context("worktree dropped")?;
1628            if let Some(entry) = entry {
1629                Ok(File::for_entry(entry, worktree))
1630            } else {
1631                let metadata = fs
1632                    .metadata(&abs_path)
1633                    .await
1634                    .with_context(|| {
1635                        format!("Fetching metadata after saving the excluded buffer {abs_path:?}")
1636                    })?
1637                    .with_context(|| {
1638                        format!("Excluded buffer {path:?} got removed during saving")
1639                    })?;
1640                Ok(Arc::new(File {
1641                    worktree,
1642                    path,
1643                    disk_state: DiskState::Present {
1644                        mtime: metadata.mtime,
1645                        size: metadata.len,
1646                    },
1647                    entry_id: None,
1648                    is_local: true,
1649                    is_private,
1650                }))
1651            }
1652        })
1653    }
1654
1655    pub fn delete_entry(
1656        &self,
1657        entry_id: ProjectEntryId,
1658        trash: bool,
1659        cx: &Context<Worktree>,
1660    ) -> Option<Task<Result<()>>> {
1661        let entry = self.entry_for_id(entry_id)?.clone();
1662        let abs_path = self.absolutize(&entry.path);
1663        let fs = self.fs.clone();
1664
1665        let delete = cx.background_spawn(async move {
1666            if entry.is_file() {
1667                if trash {
1668                    fs.trash_file(&abs_path, Default::default()).await?;
1669                } else {
1670                    fs.remove_file(&abs_path, Default::default()).await?;
1671                }
1672            } else if trash {
1673                fs.trash_dir(
1674                    &abs_path,
1675                    RemoveOptions {
1676                        recursive: true,
1677                        ignore_if_not_exists: false,
1678                    },
1679                )
1680                .await?;
1681            } else {
1682                fs.remove_dir(
1683                    &abs_path,
1684                    RemoveOptions {
1685                        recursive: true,
1686                        ignore_if_not_exists: false,
1687                    },
1688                )
1689                .await?;
1690            }
1691            anyhow::Ok(entry.path)
1692        });
1693
1694        Some(cx.spawn(async move |this, cx| {
1695            let path = delete.await?;
1696            this.update(cx, |this, _| {
1697                this.as_local_mut()
1698                    .unwrap()
1699                    .refresh_entries_for_paths(vec![path])
1700            })?
1701            .recv()
1702            .await;
1703            Ok(())
1704        }))
1705    }
1706
1707    pub fn copy_external_entries(
1708        &self,
1709        target_directory: Arc<RelPath>,
1710        paths: Vec<Arc<Path>>,
1711        cx: &Context<Worktree>,
1712    ) -> Task<Result<Vec<ProjectEntryId>>> {
1713        let target_directory = self.absolutize(&target_directory);
1714        let worktree_path = self.abs_path().clone();
1715        let fs = self.fs.clone();
1716        let paths = paths
1717            .into_iter()
1718            .filter_map(|source| {
1719                let file_name = source.file_name()?;
1720                let mut target = target_directory.clone();
1721                target.push(file_name);
1722
1723                // Do not allow copying the same file to itself.
1724                if source.as_ref() != target.as_path() {
1725                    Some((source, target))
1726                } else {
1727                    None
1728                }
1729            })
1730            .collect::<Vec<_>>();
1731
1732        let paths_to_refresh = paths
1733            .iter()
1734            .filter_map(|(_, target)| {
1735                RelPath::new(
1736                    target.strip_prefix(&worktree_path).ok()?,
1737                    PathStyle::local(),
1738                )
1739                .ok()
1740                .map(|path| path.into_arc())
1741            })
1742            .collect::<Vec<_>>();
1743
1744        cx.spawn(async move |this, cx| {
1745            cx.background_spawn(async move {
1746                for (source, target) in paths {
1747                    copy_recursive(
1748                        fs.as_ref(),
1749                        &source,
1750                        &target,
1751                        fs::CopyOptions {
1752                            overwrite: true,
1753                            ..Default::default()
1754                        },
1755                    )
1756                    .await
1757                    .with_context(|| {
1758                        format!("Failed to copy file from {source:?} to {target:?}")
1759                    })?;
1760                }
1761                anyhow::Ok(())
1762            })
1763            .await
1764            .log_err();
1765            let mut refresh = cx.read_entity(
1766                &this.upgrade().with_context(|| "Dropped worktree")?,
1767                |this, _| {
1768                    anyhow::Ok::<postage::barrier::Receiver>(
1769                        this.as_local()
1770                            .with_context(|| "Worktree is not local")?
1771                            .refresh_entries_for_paths(paths_to_refresh.clone()),
1772                    )
1773                },
1774            )?;
1775
1776            cx.background_spawn(async move {
1777                refresh.next().await;
1778                anyhow::Ok(())
1779            })
1780            .await
1781            .log_err();
1782
1783            let this = this.upgrade().with_context(|| "Dropped worktree")?;
1784            Ok(cx.read_entity(&this, |this, _| {
1785                paths_to_refresh
1786                    .iter()
1787                    .filter_map(|path| Some(this.entry_for_path(path)?.id))
1788                    .collect()
1789            }))
1790        })
1791    }
1792
1793    fn expand_entry(
1794        &self,
1795        entry_id: ProjectEntryId,
1796        cx: &Context<Worktree>,
1797    ) -> Option<Task<Result<()>>> {
1798        let path = self.entry_for_id(entry_id)?.path.clone();
1799        let mut refresh = self.refresh_entries_for_paths(vec![path]);
1800        Some(cx.background_spawn(async move {
1801            refresh.next().await;
1802            Ok(())
1803        }))
1804    }
1805
1806    fn expand_all_for_entry(
1807        &self,
1808        entry_id: ProjectEntryId,
1809        cx: &Context<Worktree>,
1810    ) -> Option<Task<Result<()>>> {
1811        let path = self.entry_for_id(entry_id).unwrap().path.clone();
1812        let mut rx = self.add_path_prefix_to_scan(path);
1813        Some(cx.background_spawn(async move {
1814            rx.next().await;
1815            Ok(())
1816        }))
1817    }
1818
1819    pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<RelPath>>) -> barrier::Receiver {
1820        let (tx, rx) = barrier::channel();
1821        self.scan_requests_tx
1822            .try_send(ScanRequest {
1823                relative_paths: paths,
1824                done: smallvec![tx],
1825            })
1826            .ok();
1827        rx
1828    }
1829
1830    #[cfg(feature = "test-support")]
1831    pub fn manually_refresh_entries_for_paths(
1832        &self,
1833        paths: Vec<Arc<RelPath>>,
1834    ) -> barrier::Receiver {
1835        self.refresh_entries_for_paths(paths)
1836    }
1837
1838    pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<RelPath>) -> barrier::Receiver {
1839        let (tx, rx) = barrier::channel();
1840        self.path_prefixes_to_scan_tx
1841            .try_send(PathPrefixScanRequest {
1842                path: path_prefix,
1843                done: smallvec![tx],
1844            })
1845            .ok();
1846        rx
1847    }
1848
1849    pub fn refresh_entry(
1850        &self,
1851        path: Arc<RelPath>,
1852        old_path: Option<Arc<RelPath>>,
1853        cx: &Context<Worktree>,
1854    ) -> Task<Result<Option<Entry>>> {
1855        if self.settings.is_path_excluded(&path) {
1856            return Task::ready(Ok(None));
1857        }
1858        let paths = if let Some(old_path) = old_path.as_ref() {
1859            vec![old_path.clone(), path.clone()]
1860        } else {
1861            vec![path.clone()]
1862        };
1863        let t0 = Instant::now();
1864        let mut refresh = self.refresh_entries_for_paths(paths);
1865        // todo(lw): Hot foreground spawn
1866        cx.spawn(async move |this, cx| {
1867            refresh.recv().await;
1868            log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
1869            let new_entry = this.read_with(cx, |this, _| {
1870                this.entry_for_path(&path).cloned().with_context(|| {
1871                    format!("Could not find entry in worktree for {path:?} after refresh")
1872                })
1873            })??;
1874            Ok(Some(new_entry))
1875        })
1876    }
1877
1878    pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1879    where
1880        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1881        Fut: 'static + Send + Future<Output = bool>,
1882    {
1883        if let Some(observer) = self.update_observer.as_mut() {
1884            *observer.resume_updates.borrow_mut() = ();
1885            return;
1886        }
1887
1888        let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1889        let (snapshots_tx, mut snapshots_rx) =
1890            mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet)>();
1891        snapshots_tx
1892            .unbounded_send((self.snapshot(), Arc::default()))
1893            .ok();
1894
1895        let worktree_id = self.id.to_proto();
1896        let _maintain_remote_snapshot = cx.background_spawn(async move {
1897            let mut is_first = true;
1898            while let Some((snapshot, entry_changes)) = snapshots_rx.next().await {
1899                let update = if is_first {
1900                    is_first = false;
1901                    snapshot.build_initial_update(project_id, worktree_id)
1902                } else {
1903                    snapshot.build_update(project_id, worktree_id, entry_changes)
1904                };
1905
1906                for update in proto::split_worktree_update(update) {
1907                    let _ = resume_updates_rx.try_recv();
1908                    loop {
1909                        let result = callback(update.clone());
1910                        if result.await {
1911                            break;
1912                        } else {
1913                            log::info!("waiting to resume updates");
1914                            if resume_updates_rx.next().await.is_none() {
1915                                return Some(());
1916                            }
1917                        }
1918                    }
1919                }
1920            }
1921            Some(())
1922        });
1923
1924        self.update_observer = Some(UpdateObservationState {
1925            snapshots_tx,
1926            resume_updates: resume_updates_tx,
1927            _maintain_remote_snapshot,
1928        });
1929    }
1930
1931    pub fn share_private_files(&mut self, cx: &Context<Worktree>) {
1932        self.share_private_files = true;
1933        self.restart_background_scanners(cx);
1934    }
1935
1936    pub fn update_abs_path_and_refresh(
1937        &mut self,
1938        new_path: Arc<SanitizedPath>,
1939        cx: &Context<Worktree>,
1940    ) {
1941        self.snapshot.git_repositories = Default::default();
1942        self.snapshot.ignores_by_parent_abs_path = Default::default();
1943        let root_name = new_path
1944            .as_path()
1945            .file_name()
1946            .and_then(|f| f.to_str())
1947            .map_or(RelPath::empty().into(), |f| {
1948                RelPath::unix(f).unwrap().into()
1949            });
1950        self.snapshot.update_abs_path(new_path, root_name);
1951        self.restart_background_scanners(cx);
1952    }
1953    #[cfg(feature = "test-support")]
1954    pub fn repositories(&self) -> Vec<Arc<Path>> {
1955        self.git_repositories
1956            .values()
1957            .map(|entry| entry.work_directory_abs_path.clone())
1958            .collect::<Vec<_>>()
1959    }
1960}
1961
1962impl RemoteWorktree {
1963    pub fn project_id(&self) -> u64 {
1964        self.project_id
1965    }
1966
1967    pub fn client(&self) -> AnyProtoClient {
1968        self.client.clone()
1969    }
1970
1971    pub fn disconnected_from_host(&mut self) {
1972        self.updates_tx.take();
1973        self.snapshot_subscriptions.clear();
1974        self.disconnected = true;
1975    }
1976
1977    pub fn update_from_remote(&self, update: proto::UpdateWorktree) {
1978        if let Some(updates_tx) = &self.updates_tx {
1979            updates_tx
1980                .unbounded_send(update)
1981                .expect("consumer runs to completion");
1982        }
1983    }
1984
1985    fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1986    where
1987        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1988        Fut: 'static + Send + Future<Output = bool>,
1989    {
1990        let (tx, mut rx) = mpsc::unbounded();
1991        let initial_update = self
1992            .snapshot
1993            .build_initial_update(project_id, self.id().to_proto());
1994        self.update_observer = Some(tx);
1995        cx.spawn(async move |this, cx| {
1996            let mut update = initial_update;
1997            'outer: loop {
1998                // SSH projects use a special project ID of 0, and we need to
1999                // remap it to the correct one here.
2000                update.project_id = project_id;
2001
2002                for chunk in split_worktree_update(update) {
2003                    if !callback(chunk).await {
2004                        break 'outer;
2005                    }
2006                }
2007
2008                if let Some(next_update) = rx.next().await {
2009                    update = next_update;
2010                } else {
2011                    break;
2012                }
2013            }
2014            this.update(cx, |this, _| {
2015                let this = this.as_remote_mut().unwrap();
2016                this.update_observer.take();
2017            })
2018        })
2019        .detach();
2020    }
2021
2022    fn observed_snapshot(&self, scan_id: usize) -> bool {
2023        self.completed_scan_id >= scan_id
2024    }
2025
2026    pub fn wait_for_snapshot(
2027        &mut self,
2028        scan_id: usize,
2029    ) -> impl Future<Output = Result<()>> + use<> {
2030        let (tx, rx) = oneshot::channel();
2031        if self.observed_snapshot(scan_id) {
2032            let _ = tx.send(());
2033        } else if self.disconnected {
2034            drop(tx);
2035        } else {
2036            match self
2037                .snapshot_subscriptions
2038                .binary_search_by_key(&scan_id, |probe| probe.0)
2039            {
2040                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
2041            }
2042        }
2043
2044        async move {
2045            rx.await?;
2046            Ok(())
2047        }
2048    }
2049
2050    pub fn insert_entry(
2051        &mut self,
2052        entry: proto::Entry,
2053        scan_id: usize,
2054        cx: &Context<Worktree>,
2055    ) -> Task<Result<Entry>> {
2056        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
2057        cx.spawn(async move |this, cx| {
2058            wait_for_snapshot.await?;
2059            this.update(cx, |worktree, _| {
2060                let worktree = worktree.as_remote_mut().unwrap();
2061                let snapshot = &mut worktree.background_snapshot.lock().0;
2062                let entry = snapshot.insert_entry(entry, &worktree.file_scan_inclusions);
2063                worktree.snapshot = snapshot.clone();
2064                entry
2065            })?
2066        })
2067    }
2068
2069    fn delete_entry(
2070        &self,
2071        entry_id: ProjectEntryId,
2072        trash: bool,
2073        cx: &Context<Worktree>,
2074    ) -> Option<Task<Result<()>>> {
2075        let response = self.client.request(proto::DeleteProjectEntry {
2076            project_id: self.project_id,
2077            entry_id: entry_id.to_proto(),
2078            use_trash: trash,
2079        });
2080        Some(cx.spawn(async move |this, cx| {
2081            let response = response.await?;
2082            let scan_id = response.worktree_scan_id as usize;
2083
2084            this.update(cx, move |this, _| {
2085                this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)
2086            })?
2087            .await?;
2088
2089            this.update(cx, |this, _| {
2090                let this = this.as_remote_mut().unwrap();
2091                let snapshot = &mut this.background_snapshot.lock().0;
2092                snapshot.delete_entry(entry_id);
2093                this.snapshot = snapshot.clone();
2094            })
2095        }))
2096    }
2097
2098    // fn rename_entry(
2099    //     &self,
2100    //     entry_id: ProjectEntryId,
2101    //     new_path: impl Into<Arc<RelPath>>,
2102    //     cx: &Context<Worktree>,
2103    // ) -> Task<Result<CreatedEntry>> {
2104    //     let new_path: Arc<RelPath> = new_path.into();
2105    //     let response = self.client.request(proto::RenameProjectEntry {
2106    //         project_id: self.project_id,
2107    //         entry_id: entry_id.to_proto(),
2108    //         new_worktree_id: new_path.worktree_id,
2109    //         new_path: new_path.as_ref().to_proto(),
2110    //     });
2111    //     cx.spawn(async move |this, cx| {
2112    //         let response = response.await?;
2113    //         match response.entry {
2114    //             Some(entry) => this
2115    //                 .update(cx, |this, cx| {
2116    //                     this.as_remote_mut().unwrap().insert_entry(
2117    //                         entry,
2118    //                         response.worktree_scan_id as usize,
2119    //                         cx,
2120    //                     )
2121    //                 })?
2122    //                 .await
2123    //                 .map(CreatedEntry::Included),
2124    //             None => {
2125    //                 let abs_path =
2126    //                     this.read_with(cx, |worktree, _| worktree.absolutize(&new_path))?;
2127    //                 Ok(CreatedEntry::Excluded { abs_path })
2128    //             }
2129    //         }
2130    //     })
2131    // }
2132
2133    fn copy_external_entries(
2134        &self,
2135        target_directory: Arc<RelPath>,
2136        paths_to_copy: Vec<Arc<Path>>,
2137        local_fs: Arc<dyn Fs>,
2138        cx: &Context<Worktree>,
2139    ) -> Task<anyhow::Result<Vec<ProjectEntryId>>> {
2140        let client = self.client.clone();
2141        let worktree_id = self.id().to_proto();
2142        let project_id = self.project_id;
2143
2144        cx.background_spawn(async move {
2145            let mut requests = Vec::new();
2146            for root_path_to_copy in paths_to_copy {
2147                let Some(filename) = root_path_to_copy
2148                    .file_name()
2149                    .and_then(|name| name.to_str())
2150                    .and_then(|filename| RelPath::unix(filename).ok())
2151                else {
2152                    continue;
2153                };
2154                for (abs_path, is_directory) in
2155                    read_dir_items(local_fs.as_ref(), &root_path_to_copy).await?
2156                {
2157                    let Some(relative_path) = abs_path
2158                        .strip_prefix(&root_path_to_copy)
2159                        .map_err(|e| anyhow::Error::from(e))
2160                        .and_then(|relative_path| RelPath::new(relative_path, PathStyle::local()))
2161                        .log_err()
2162                    else {
2163                        continue;
2164                    };
2165                    let content = if is_directory {
2166                        None
2167                    } else {
2168                        Some(local_fs.load_bytes(&abs_path).await?)
2169                    };
2170
2171                    let mut target_path = target_directory.join(filename);
2172                    if relative_path.file_name().is_some() {
2173                        target_path = target_path.join(&relative_path);
2174                    }
2175
2176                    requests.push(proto::CreateProjectEntry {
2177                        project_id,
2178                        worktree_id,
2179                        path: target_path.to_proto(),
2180                        is_directory,
2181                        content,
2182                    });
2183                }
2184            }
2185            requests.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2186            requests.dedup();
2187
2188            let mut copied_entry_ids = Vec::new();
2189            for request in requests {
2190                let response = client.request(request).await?;
2191                copied_entry_ids.extend(response.entry.map(|e| ProjectEntryId::from_proto(e.id)));
2192            }
2193
2194            Ok(copied_entry_ids)
2195        })
2196    }
2197}
2198
2199impl Snapshot {
2200    pub fn new(
2201        id: WorktreeId,
2202        root_name: Arc<RelPath>,
2203        abs_path: Arc<Path>,
2204        path_style: PathStyle,
2205    ) -> Self {
2206        Snapshot {
2207            id,
2208            abs_path: SanitizedPath::from_arc(abs_path),
2209            path_style,
2210            root_char_bag: root_name
2211                .as_unix_str()
2212                .chars()
2213                .map(|c| c.to_ascii_lowercase())
2214                .collect(),
2215            root_name,
2216            always_included_entries: Default::default(),
2217            entries_by_path: Default::default(),
2218            entries_by_id: Default::default(),
2219            scan_id: 1,
2220            completed_scan_id: 0,
2221        }
2222    }
2223
2224    pub fn id(&self) -> WorktreeId {
2225        self.id
2226    }
2227
2228    // TODO:
2229    // Consider the following:
2230    //
2231    // ```rust
2232    // let abs_path: Arc<Path> = snapshot.abs_path(); // e.g. "C:\Users\user\Desktop\project"
2233    // let some_non_trimmed_path = Path::new("\\\\?\\C:\\Users\\user\\Desktop\\project\\main.rs");
2234    // // The caller perform some actions here:
2235    // some_non_trimmed_path.strip_prefix(abs_path);  // This fails
2236    // some_non_trimmed_path.starts_with(abs_path);   // This fails too
2237    // ```
2238    //
2239    // This is definitely a bug, but it's not clear if we should handle it here or not.
2240    pub fn abs_path(&self) -> &Arc<Path> {
2241        SanitizedPath::cast_arc_ref(&self.abs_path)
2242    }
2243
2244    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2245        let mut updated_entries = self
2246            .entries_by_path
2247            .iter()
2248            .map(proto::Entry::from)
2249            .collect::<Vec<_>>();
2250        updated_entries.sort_unstable_by_key(|e| e.id);
2251
2252        proto::UpdateWorktree {
2253            project_id,
2254            worktree_id,
2255            abs_path: self.abs_path().to_string_lossy().into_owned(),
2256            root_name: self.root_name().to_proto(),
2257            updated_entries,
2258            removed_entries: Vec::new(),
2259            scan_id: self.scan_id as u64,
2260            is_last_update: self.completed_scan_id == self.scan_id,
2261            // Sent in separate messages.
2262            updated_repositories: Vec::new(),
2263            removed_repositories: Vec::new(),
2264        }
2265    }
2266
2267    pub fn work_directory_abs_path(&self, work_directory: &WorkDirectory) -> PathBuf {
2268        match work_directory {
2269            WorkDirectory::InProject { relative_path } => self.absolutize(relative_path),
2270            WorkDirectory::AboveProject { absolute_path, .. } => absolute_path.as_ref().to_owned(),
2271        }
2272    }
2273
2274    pub fn absolutize(&self, path: &RelPath) -> PathBuf {
2275        if path.file_name().is_some() {
2276            let mut abs_path = self.abs_path.to_string();
2277            for component in path.components() {
2278                if !abs_path.ends_with(self.path_style.primary_separator()) {
2279                    abs_path.push_str(self.path_style.primary_separator());
2280                }
2281                abs_path.push_str(component);
2282            }
2283            PathBuf::from(abs_path)
2284        } else {
2285            self.abs_path.as_path().to_path_buf()
2286        }
2287    }
2288
2289    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
2290        self.entries_by_id.get(&entry_id, ()).is_some()
2291    }
2292
2293    fn insert_entry(
2294        &mut self,
2295        entry: proto::Entry,
2296        always_included_paths: &PathMatcher,
2297    ) -> Result<Entry> {
2298        let entry = Entry::try_from((&self.root_char_bag, always_included_paths, entry))?;
2299        let old_entry = self.entries_by_id.insert_or_replace(
2300            PathEntry {
2301                id: entry.id,
2302                path: entry.path.clone(),
2303                is_ignored: entry.is_ignored,
2304                scan_id: 0,
2305            },
2306            (),
2307        );
2308        if let Some(old_entry) = old_entry {
2309            self.entries_by_path.remove(&PathKey(old_entry.path), ());
2310        }
2311        self.entries_by_path.insert_or_replace(entry.clone(), ());
2312        Ok(entry)
2313    }
2314
2315    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<RelPath>> {
2316        let removed_entry = self.entries_by_id.remove(&entry_id, ())?;
2317        self.entries_by_path = {
2318            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>(());
2319            let mut new_entries_by_path =
2320                cursor.slice(&TraversalTarget::path(&removed_entry.path), Bias::Left);
2321            while let Some(entry) = cursor.item() {
2322                if entry.path.starts_with(&removed_entry.path) {
2323                    self.entries_by_id.remove(&entry.id, ());
2324                    cursor.next();
2325                } else {
2326                    break;
2327                }
2328            }
2329            new_entries_by_path.append(cursor.suffix(), ());
2330            new_entries_by_path
2331        };
2332
2333        Some(removed_entry.path)
2334    }
2335
2336    fn update_abs_path(&mut self, abs_path: Arc<SanitizedPath>, root_name: Arc<RelPath>) {
2337        self.abs_path = abs_path;
2338        if root_name != self.root_name {
2339            self.root_char_bag = root_name
2340                .as_unix_str()
2341                .chars()
2342                .map(|c| c.to_ascii_lowercase())
2343                .collect();
2344            self.root_name = root_name;
2345        }
2346    }
2347
2348    pub fn apply_remote_update(
2349        &mut self,
2350        update: proto::UpdateWorktree,
2351        always_included_paths: &PathMatcher,
2352    ) {
2353        log::debug!(
2354            "applying remote worktree update. {} entries updated, {} removed",
2355            update.updated_entries.len(),
2356            update.removed_entries.len()
2357        );
2358        if let Some(root_name) = RelPath::from_proto(&update.root_name).log_err() {
2359            self.update_abs_path(
2360                SanitizedPath::new_arc(&Path::new(&update.abs_path)),
2361                root_name,
2362            );
2363        }
2364
2365        let mut entries_by_path_edits = Vec::new();
2366        let mut entries_by_id_edits = Vec::new();
2367
2368        for entry_id in update.removed_entries {
2369            let entry_id = ProjectEntryId::from_proto(entry_id);
2370            entries_by_id_edits.push(Edit::Remove(entry_id));
2371            if let Some(entry) = self.entry_for_id(entry_id) {
2372                entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2373            }
2374        }
2375
2376        for entry in update.updated_entries {
2377            let Some(entry) =
2378                Entry::try_from((&self.root_char_bag, always_included_paths, entry)).log_err()
2379            else {
2380                continue;
2381            };
2382            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, ()) {
2383                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
2384            }
2385            if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2386                && old_entry.id != entry.id
2387            {
2388                entries_by_id_edits.push(Edit::Remove(old_entry.id));
2389            }
2390            entries_by_id_edits.push(Edit::Insert(PathEntry {
2391                id: entry.id,
2392                path: entry.path.clone(),
2393                is_ignored: entry.is_ignored,
2394                scan_id: 0,
2395            }));
2396            entries_by_path_edits.push(Edit::Insert(entry));
2397        }
2398
2399        self.entries_by_path.edit(entries_by_path_edits, ());
2400        self.entries_by_id.edit(entries_by_id_edits, ());
2401
2402        self.scan_id = update.scan_id as usize;
2403        if update.is_last_update {
2404            self.completed_scan_id = update.scan_id as usize;
2405        }
2406    }
2407
2408    pub fn entry_count(&self) -> usize {
2409        self.entries_by_path.summary().count
2410    }
2411
2412    pub fn visible_entry_count(&self) -> usize {
2413        self.entries_by_path.summary().non_ignored_count
2414    }
2415
2416    pub fn dir_count(&self) -> usize {
2417        let summary = self.entries_by_path.summary();
2418        summary.count - summary.file_count
2419    }
2420
2421    pub fn visible_dir_count(&self) -> usize {
2422        let summary = self.entries_by_path.summary();
2423        summary.non_ignored_count - summary.non_ignored_file_count
2424    }
2425
2426    pub fn file_count(&self) -> usize {
2427        self.entries_by_path.summary().file_count
2428    }
2429
2430    pub fn visible_file_count(&self) -> usize {
2431        self.entries_by_path.summary().non_ignored_file_count
2432    }
2433
2434    fn traverse_from_offset(
2435        &self,
2436        include_files: bool,
2437        include_dirs: bool,
2438        include_ignored: bool,
2439        start_offset: usize,
2440    ) -> Traversal<'_> {
2441        let mut cursor = self.entries_by_path.cursor(());
2442        cursor.seek(
2443            &TraversalTarget::Count {
2444                count: start_offset,
2445                include_files,
2446                include_dirs,
2447                include_ignored,
2448            },
2449            Bias::Right,
2450        );
2451        Traversal {
2452            snapshot: self,
2453            cursor,
2454            include_files,
2455            include_dirs,
2456            include_ignored,
2457        }
2458    }
2459
2460    pub fn traverse_from_path(
2461        &self,
2462        include_files: bool,
2463        include_dirs: bool,
2464        include_ignored: bool,
2465        path: &RelPath,
2466    ) -> Traversal<'_> {
2467        Traversal::new(self, include_files, include_dirs, include_ignored, path)
2468    }
2469
2470    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2471        self.traverse_from_offset(true, false, include_ignored, start)
2472    }
2473
2474    pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2475        self.traverse_from_offset(false, true, include_ignored, start)
2476    }
2477
2478    pub fn entries(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2479        self.traverse_from_offset(true, true, include_ignored, start)
2480    }
2481
2482    pub fn paths(&self) -> impl Iterator<Item = &RelPath> {
2483        self.entries_by_path
2484            .cursor::<()>(())
2485            .filter(move |entry| !entry.path.is_empty())
2486            .map(|entry| entry.path.as_ref())
2487    }
2488
2489    pub fn child_entries<'a>(&'a self, parent_path: &'a RelPath) -> ChildEntriesIter<'a> {
2490        let options = ChildEntriesOptions {
2491            include_files: true,
2492            include_dirs: true,
2493            include_ignored: true,
2494        };
2495        self.child_entries_with_options(parent_path, options)
2496    }
2497
2498    pub fn child_entries_with_options<'a>(
2499        &'a self,
2500        parent_path: &'a RelPath,
2501        options: ChildEntriesOptions,
2502    ) -> ChildEntriesIter<'a> {
2503        let mut cursor = self.entries_by_path.cursor(());
2504        cursor.seek(&TraversalTarget::path(parent_path), Bias::Right);
2505        let traversal = Traversal {
2506            snapshot: self,
2507            cursor,
2508            include_files: options.include_files,
2509            include_dirs: options.include_dirs,
2510            include_ignored: options.include_ignored,
2511        };
2512        ChildEntriesIter {
2513            traversal,
2514            parent_path,
2515        }
2516    }
2517
2518    pub fn root_entry(&self) -> Option<&Entry> {
2519        self.entries_by_path.first()
2520    }
2521
2522    /// Returns `None` for a single file worktree, or `Some(self.abs_path())` if
2523    /// it is a directory.
2524    pub fn root_dir(&self) -> Option<Arc<Path>> {
2525        self.root_entry()
2526            .filter(|entry| entry.is_dir())
2527            .map(|_| self.abs_path().clone())
2528    }
2529
2530    pub fn root_name(&self) -> &RelPath {
2531        &self.root_name
2532    }
2533
2534    pub fn root_name_str(&self) -> &str {
2535        self.root_name.as_unix_str()
2536    }
2537
2538    pub fn scan_id(&self) -> usize {
2539        self.scan_id
2540    }
2541
2542    pub fn entry_for_path(&self, path: &RelPath) -> Option<&Entry> {
2543        self.traverse_from_path(true, true, true, path)
2544            .entry()
2545            .and_then(|entry| {
2546                if entry.path.as_ref() == path {
2547                    Some(entry)
2548                } else {
2549                    None
2550                }
2551            })
2552    }
2553
2554    /// Resolves a path to an executable using the following heuristics:
2555    ///
2556    /// 1. If the path starts with `~`, it is expanded to the user's home directory.
2557    /// 2. If the path is relative and contains more than one component,
2558    ///    it is joined to the worktree root path.
2559    /// 3. If the path is relative and exists in the worktree
2560    ///    (even if falls under an exclusion filter),
2561    ///    it is joined to the worktree root path.
2562    /// 4. Otherwise the path is returned unmodified.
2563    ///
2564    /// Relative paths that do not exist in the worktree may
2565    /// still be found using the `PATH` environment variable.
2566    pub fn resolve_relative_path(&self, path: PathBuf) -> PathBuf {
2567        if let Some(path_str) = path.to_str() {
2568            if let Some(remaining_path) = path_str.strip_prefix("~/") {
2569                return home_dir().join(remaining_path);
2570            } else if path_str == "~" {
2571                return home_dir().to_path_buf();
2572            }
2573        }
2574
2575        if let Ok(rel_path) = RelPath::new(&path, self.path_style)
2576            && (path.components().count() > 1 || self.entry_for_path(&rel_path).is_some())
2577        {
2578            self.abs_path().join(path)
2579        } else {
2580            path
2581        }
2582    }
2583
2584    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2585        let entry = self.entries_by_id.get(&id, ())?;
2586        self.entry_for_path(&entry.path)
2587    }
2588
2589    pub fn path_style(&self) -> PathStyle {
2590        self.path_style
2591    }
2592}
2593
2594impl LocalSnapshot {
2595    fn local_repo_for_work_directory_path(&self, path: &RelPath) -> Option<&LocalRepositoryEntry> {
2596        self.git_repositories
2597            .iter()
2598            .map(|(_, entry)| entry)
2599            .find(|entry| entry.work_directory.path_key() == PathKey(path.into()))
2600    }
2601
2602    fn build_update(
2603        &self,
2604        project_id: u64,
2605        worktree_id: u64,
2606        entry_changes: UpdatedEntriesSet,
2607    ) -> proto::UpdateWorktree {
2608        let mut updated_entries = Vec::new();
2609        let mut removed_entries = Vec::new();
2610
2611        for (_, entry_id, path_change) in entry_changes.iter() {
2612            if let PathChange::Removed = path_change {
2613                removed_entries.push(entry_id.0 as u64);
2614            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2615                updated_entries.push(proto::Entry::from(entry));
2616            }
2617        }
2618
2619        removed_entries.sort_unstable();
2620        updated_entries.sort_unstable_by_key(|e| e.id);
2621
2622        // TODO - optimize, knowing that removed_entries are sorted.
2623        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2624
2625        proto::UpdateWorktree {
2626            project_id,
2627            worktree_id,
2628            abs_path: self.abs_path().to_string_lossy().into_owned(),
2629            root_name: self.root_name().to_proto(),
2630            updated_entries,
2631            removed_entries,
2632            scan_id: self.scan_id as u64,
2633            is_last_update: self.completed_scan_id == self.scan_id,
2634            // Sent in separate messages.
2635            updated_repositories: Vec::new(),
2636            removed_repositories: Vec::new(),
2637        }
2638    }
2639
2640    async fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2641        log::trace!("insert entry {:?}", entry.path);
2642        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2643            let abs_path = self.absolutize(&entry.path);
2644            match build_gitignore(&abs_path, fs).await {
2645                Ok(ignore) => {
2646                    self.ignores_by_parent_abs_path
2647                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2648                }
2649                Err(error) => {
2650                    log::error!(
2651                        "error loading .gitignore file {:?} - {:?}",
2652                        &entry.path,
2653                        error
2654                    );
2655                }
2656            }
2657        }
2658
2659        if entry.kind == EntryKind::PendingDir
2660            && let Some(existing_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2661        {
2662            entry.kind = existing_entry.kind;
2663        }
2664
2665        let scan_id = self.scan_id;
2666        let removed = self.entries_by_path.insert_or_replace(entry.clone(), ());
2667        if let Some(removed) = removed
2668            && removed.id != entry.id
2669        {
2670            self.entries_by_id.remove(&removed.id, ());
2671        }
2672        self.entries_by_id.insert_or_replace(
2673            PathEntry {
2674                id: entry.id,
2675                path: entry.path.clone(),
2676                is_ignored: entry.is_ignored,
2677                scan_id,
2678            },
2679            (),
2680        );
2681
2682        entry
2683    }
2684
2685    fn ancestor_inodes_for_path(&self, path: &RelPath) -> TreeSet<u64> {
2686        let mut inodes = TreeSet::default();
2687        for ancestor in path.ancestors().skip(1) {
2688            if let Some(entry) = self.entry_for_path(ancestor) {
2689                inodes.insert(entry.inode);
2690            }
2691        }
2692        inodes
2693    }
2694
2695    async fn ignore_stack_for_abs_path(
2696        &self,
2697        abs_path: &Path,
2698        is_dir: bool,
2699        fs: &dyn Fs,
2700    ) -> IgnoreStack {
2701        let mut new_ignores = Vec::new();
2702        let mut repo_root = None;
2703        for (index, ancestor) in abs_path.ancestors().enumerate() {
2704            if index > 0 {
2705                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2706                    new_ignores.push((ancestor, Some(ignore.clone())));
2707                } else {
2708                    new_ignores.push((ancestor, None));
2709                }
2710            }
2711
2712            let metadata = fs.metadata(&ancestor.join(DOT_GIT)).await.ok().flatten();
2713            if metadata.is_some() {
2714                repo_root = Some(Arc::from(ancestor));
2715                break;
2716            }
2717        }
2718
2719        let mut ignore_stack = if let Some(global_gitignore) = self.global_gitignore.clone() {
2720            IgnoreStack::global(global_gitignore)
2721        } else {
2722            IgnoreStack::none()
2723        };
2724
2725        if let Some((repo_exclude, _)) = repo_root
2726            .as_ref()
2727            .and_then(|abs_path| self.repo_exclude_by_work_dir_abs_path.get(abs_path))
2728        {
2729            ignore_stack = ignore_stack.append(IgnoreKind::RepoExclude, repo_exclude.clone());
2730        }
2731        ignore_stack.repo_root = repo_root;
2732        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2733            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2734                ignore_stack = IgnoreStack::all();
2735                break;
2736            } else if let Some(ignore) = ignore {
2737                ignore_stack =
2738                    ignore_stack.append(IgnoreKind::Gitignore(parent_abs_path.into()), ignore);
2739            }
2740        }
2741
2742        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2743            ignore_stack = IgnoreStack::all();
2744        }
2745
2746        ignore_stack
2747    }
2748
2749    #[cfg(feature = "test-support")]
2750    pub fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2751        self.entries_by_path
2752            .cursor::<()>(())
2753            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2754    }
2755
2756    #[cfg(feature = "test-support")]
2757    pub fn check_invariants(&self, git_state: bool) {
2758        use pretty_assertions::assert_eq;
2759
2760        assert_eq!(
2761            self.entries_by_path
2762                .cursor::<()>(())
2763                .map(|e| (&e.path, e.id))
2764                .collect::<Vec<_>>(),
2765            self.entries_by_id
2766                .cursor::<()>(())
2767                .map(|e| (&e.path, e.id))
2768                .collect::<collections::BTreeSet<_>>()
2769                .into_iter()
2770                .collect::<Vec<_>>(),
2771            "entries_by_path and entries_by_id are inconsistent"
2772        );
2773
2774        let mut files = self.files(true, 0);
2775        let mut visible_files = self.files(false, 0);
2776        for entry in self.entries_by_path.cursor::<()>(()) {
2777            if entry.is_file() {
2778                assert_eq!(files.next().unwrap().inode, entry.inode);
2779                if !entry.is_ignored || entry.is_always_included {
2780                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2781                }
2782            }
2783        }
2784
2785        assert!(files.next().is_none());
2786        assert!(visible_files.next().is_none());
2787
2788        let mut bfs_paths = Vec::new();
2789        let mut stack = self
2790            .root_entry()
2791            .map(|e| e.path.as_ref())
2792            .into_iter()
2793            .collect::<Vec<_>>();
2794        while let Some(path) = stack.pop() {
2795            bfs_paths.push(path);
2796            let ix = stack.len();
2797            for child_entry in self.child_entries(path) {
2798                stack.insert(ix, &child_entry.path);
2799            }
2800        }
2801
2802        let dfs_paths_via_iter = self
2803            .entries_by_path
2804            .cursor::<()>(())
2805            .map(|e| e.path.as_ref())
2806            .collect::<Vec<_>>();
2807        assert_eq!(bfs_paths, dfs_paths_via_iter);
2808
2809        let dfs_paths_via_traversal = self
2810            .entries(true, 0)
2811            .map(|e| e.path.as_ref())
2812            .collect::<Vec<_>>();
2813
2814        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2815
2816        if git_state {
2817            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2818                let ignore_parent_path = &RelPath::new(
2819                    ignore_parent_abs_path
2820                        .strip_prefix(self.abs_path.as_path())
2821                        .unwrap(),
2822                    PathStyle::local(),
2823                )
2824                .unwrap();
2825                assert!(self.entry_for_path(ignore_parent_path).is_some());
2826                assert!(
2827                    self.entry_for_path(
2828                        &ignore_parent_path.join(RelPath::unix(GITIGNORE).unwrap())
2829                    )
2830                    .is_some()
2831                );
2832            }
2833        }
2834    }
2835
2836    #[cfg(feature = "test-support")]
2837    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&RelPath, u64, bool)> {
2838        let mut paths = Vec::new();
2839        for entry in self.entries_by_path.cursor::<()>(()) {
2840            if include_ignored || !entry.is_ignored {
2841                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2842            }
2843        }
2844        paths.sort_by(|a, b| a.0.cmp(b.0));
2845        paths
2846    }
2847}
2848
2849impl BackgroundScannerState {
2850    fn should_scan_directory(&self, entry: &Entry) -> bool {
2851        (self.scanning_enabled && !entry.is_external && (!entry.is_ignored || entry.is_always_included))
2852            || entry.path.file_name() == Some(DOT_GIT)
2853            || entry.path.file_name() == Some(local_settings_folder_name())
2854            || entry.path.file_name() == Some(local_vscode_folder_name())
2855            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2856            || self
2857                .paths_to_scan
2858                .iter()
2859                .any(|p| p.starts_with(&entry.path))
2860            || self
2861                .path_prefixes_to_scan
2862                .iter()
2863                .any(|p| entry.path.starts_with(p))
2864    }
2865
2866    async fn enqueue_scan_dir(
2867        &self,
2868        abs_path: Arc<Path>,
2869        entry: &Entry,
2870        scan_job_tx: &Sender<ScanJob>,
2871        fs: &dyn Fs,
2872    ) {
2873        let path = entry.path.clone();
2874        let ignore_stack = self
2875            .snapshot
2876            .ignore_stack_for_abs_path(&abs_path, true, fs)
2877            .await;
2878        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2879
2880        if !ancestor_inodes.contains(&entry.inode) {
2881            ancestor_inodes.insert(entry.inode);
2882            scan_job_tx
2883                .try_send(ScanJob {
2884                    abs_path,
2885                    path,
2886                    ignore_stack,
2887                    scan_queue: scan_job_tx.clone(),
2888                    ancestor_inodes,
2889                    is_external: entry.is_external,
2890                })
2891                .unwrap();
2892        }
2893    }
2894
2895    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2896        if let Some(mtime) = entry.mtime {
2897            // If an entry with the same inode was removed from the worktree during this scan,
2898            // then it *might* represent the same file or directory. But the OS might also have
2899            // re-used the inode for a completely different file or directory.
2900            //
2901            // Conditionally reuse the old entry's id:
2902            // * if the mtime is the same, the file was probably been renamed.
2903            // * if the path is the same, the file may just have been updated
2904            if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2905                if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2906                    entry.id = removed_entry.id;
2907                }
2908            } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2909                entry.id = existing_entry.id;
2910            }
2911        }
2912    }
2913
2914    fn entry_id_for(
2915        &mut self,
2916        next_entry_id: &AtomicUsize,
2917        path: &RelPath,
2918        metadata: &fs::Metadata,
2919    ) -> ProjectEntryId {
2920        // If an entry with the same inode was removed from the worktree during this scan,
2921        // then it *might* represent the same file or directory. But the OS might also have
2922        // re-used the inode for a completely different file or directory.
2923        //
2924        // Conditionally reuse the old entry's id:
2925        // * if the mtime is the same, the file was probably been renamed.
2926        // * if the path is the same, the file may just have been updated
2927        if let Some(removed_entry) = self.removed_entries.remove(&metadata.inode) {
2928            if removed_entry.mtime == Some(metadata.mtime) || *removed_entry.path == *path {
2929                return removed_entry.id;
2930            }
2931        } else if let Some(existing_entry) = self.snapshot.entry_for_path(path) {
2932            return existing_entry.id;
2933        }
2934        ProjectEntryId::new(next_entry_id)
2935    }
2936
2937    async fn insert_entry(&mut self, entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2938        let entry = self.snapshot.insert_entry(entry, fs).await;
2939        if entry.path.file_name() == Some(&DOT_GIT) {
2940            self.insert_git_repository(entry.path.clone(), fs, watcher)
2941                .await;
2942        }
2943
2944        #[cfg(feature = "test-support")]
2945        self.snapshot.check_invariants(false);
2946
2947        entry
2948    }
2949
2950    fn populate_dir(
2951        &mut self,
2952        parent_path: Arc<RelPath>,
2953        entries: impl IntoIterator<Item = Entry>,
2954        ignore: Option<Arc<Gitignore>>,
2955    ) {
2956        let mut parent_entry = if let Some(parent_entry) = self
2957            .snapshot
2958            .entries_by_path
2959            .get(&PathKey(parent_path.clone()), ())
2960        {
2961            parent_entry.clone()
2962        } else {
2963            log::warn!(
2964                "populating a directory {:?} that has been removed",
2965                parent_path
2966            );
2967            return;
2968        };
2969
2970        match parent_entry.kind {
2971            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2972            EntryKind::Dir => {}
2973            _ => return,
2974        }
2975
2976        if let Some(ignore) = ignore {
2977            let abs_parent_path = self
2978                .snapshot
2979                .abs_path
2980                .as_path()
2981                .join(parent_path.as_std_path())
2982                .into();
2983            self.snapshot
2984                .ignores_by_parent_abs_path
2985                .insert(abs_parent_path, (ignore, false));
2986        }
2987
2988        let parent_entry_id = parent_entry.id;
2989        self.scanned_dirs.insert(parent_entry_id);
2990        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2991        let mut entries_by_id_edits = Vec::new();
2992
2993        for entry in entries {
2994            entries_by_id_edits.push(Edit::Insert(PathEntry {
2995                id: entry.id,
2996                path: entry.path.clone(),
2997                is_ignored: entry.is_ignored,
2998                scan_id: self.snapshot.scan_id,
2999            }));
3000            entries_by_path_edits.push(Edit::Insert(entry));
3001        }
3002
3003        self.snapshot
3004            .entries_by_path
3005            .edit(entries_by_path_edits, ());
3006        self.snapshot.entries_by_id.edit(entries_by_id_edits, ());
3007
3008        if let Err(ix) = self.changed_paths.binary_search(&parent_path) {
3009            self.changed_paths.insert(ix, parent_path.clone());
3010        }
3011
3012        #[cfg(feature = "test-support")]
3013        self.snapshot.check_invariants(false);
3014    }
3015
3016    fn remove_path(&mut self, path: &RelPath, watcher: &dyn Watcher) {
3017        log::trace!("background scanner removing path {path:?}");
3018        let mut new_entries;
3019        let removed_entries;
3020        {
3021            let mut cursor = self
3022                .snapshot
3023                .entries_by_path
3024                .cursor::<TraversalProgress>(());
3025            new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left);
3026            removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left);
3027            new_entries.append(cursor.suffix(), ());
3028        }
3029        self.snapshot.entries_by_path = new_entries;
3030
3031        let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
3032        let mut removed_dir_abs_paths = Vec::new();
3033        for entry in removed_entries.cursor::<()>(()) {
3034            if entry.is_dir() {
3035                removed_dir_abs_paths.push(self.snapshot.absolutize(&entry.path));
3036            }
3037
3038            match self.removed_entries.entry(entry.inode) {
3039                hash_map::Entry::Occupied(mut e) => {
3040                    let prev_removed_entry = e.get_mut();
3041                    if entry.id > prev_removed_entry.id {
3042                        *prev_removed_entry = entry.clone();
3043                    }
3044                }
3045                hash_map::Entry::Vacant(e) => {
3046                    e.insert(entry.clone());
3047                }
3048            }
3049
3050            if entry.path.file_name() == Some(GITIGNORE) {
3051                let abs_parent_path = self.snapshot.absolutize(&entry.path.parent().unwrap());
3052                if let Some((_, needs_update)) = self
3053                    .snapshot
3054                    .ignores_by_parent_abs_path
3055                    .get_mut(abs_parent_path.as_path())
3056                {
3057                    *needs_update = true;
3058                }
3059            }
3060
3061            if let Err(ix) = removed_ids.binary_search(&entry.id) {
3062                removed_ids.insert(ix, entry.id);
3063            }
3064        }
3065
3066        self.snapshot
3067            .entries_by_id
3068            .edit(removed_ids.iter().map(|&id| Edit::Remove(id)).collect(), ());
3069        self.snapshot
3070            .git_repositories
3071            .retain(|id, _| removed_ids.binary_search(id).is_err());
3072
3073        for removed_dir_abs_path in removed_dir_abs_paths {
3074            watcher.remove(&removed_dir_abs_path).log_err();
3075        }
3076
3077        #[cfg(feature = "test-support")]
3078        self.snapshot.check_invariants(false);
3079    }
3080
3081    async fn insert_git_repository(
3082        &mut self,
3083        dot_git_path: Arc<RelPath>,
3084        fs: &dyn Fs,
3085        watcher: &dyn Watcher,
3086    ) {
3087        let work_dir_path: Arc<RelPath> = match dot_git_path.parent() {
3088            Some(parent_dir) => {
3089                // Guard against repositories inside the repository metadata
3090                if parent_dir
3091                    .components()
3092                    .any(|component| component == DOT_GIT)
3093                {
3094                    log::debug!(
3095                        "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3096                    );
3097                    return;
3098                };
3099
3100                parent_dir.into()
3101            }
3102            None => {
3103                // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3104                // no files inside that directory are tracked by git, so no need to build the repo around it
3105                log::debug!(
3106                    "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3107                );
3108                return;
3109            }
3110        };
3111
3112        let dot_git_abs_path = Arc::from(self.snapshot.absolutize(&dot_git_path).as_ref());
3113
3114        self.insert_git_repository_for_path(
3115            WorkDirectory::InProject {
3116                relative_path: work_dir_path,
3117            },
3118            dot_git_abs_path,
3119            fs,
3120            watcher,
3121        )
3122        .await
3123        .log_err();
3124    }
3125
3126    async fn insert_git_repository_for_path(
3127        &mut self,
3128        work_directory: WorkDirectory,
3129        dot_git_abs_path: Arc<Path>,
3130        fs: &dyn Fs,
3131        watcher: &dyn Watcher,
3132    ) -> Result<LocalRepositoryEntry> {
3133        let work_dir_entry = self
3134            .snapshot
3135            .entry_for_path(&work_directory.path_key().0)
3136            .with_context(|| {
3137                format!(
3138                    "working directory `{}` not indexed",
3139                    work_directory
3140                        .path_key()
3141                        .0
3142                        .display(self.snapshot.path_style)
3143                )
3144            })?;
3145        let work_directory_abs_path = self.snapshot.work_directory_abs_path(&work_directory);
3146
3147        let (repository_dir_abs_path, common_dir_abs_path) =
3148            discover_git_paths(&dot_git_abs_path, fs).await;
3149        watcher
3150            .add(&common_dir_abs_path)
3151            .context("failed to add common directory to watcher")
3152            .log_err();
3153        watcher
3154            .add(&repository_dir_abs_path)
3155            .context("failed to add repository directory to watcher")
3156            .log_err();
3157
3158        let work_directory_id = work_dir_entry.id;
3159
3160        let local_repository = LocalRepositoryEntry {
3161            work_directory_id,
3162            work_directory,
3163            work_directory_abs_path: work_directory_abs_path.as_path().into(),
3164            git_dir_scan_id: 0,
3165            dot_git_abs_path,
3166            common_dir_abs_path,
3167            repository_dir_abs_path,
3168        };
3169
3170        self.snapshot
3171            .git_repositories
3172            .insert(work_directory_id, local_repository.clone());
3173
3174        log::trace!("inserting new local git repository");
3175        Ok(local_repository)
3176    }
3177}
3178
3179async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3180    if let Some(file_name) = path.file_name()
3181        && file_name == DOT_GIT
3182    {
3183        return true;
3184    }
3185
3186    // If we're in a bare repository, we are not inside a `.git` folder. In a
3187    // bare repository, the root folder contains what would normally be in the
3188    // `.git` folder.
3189    let head_metadata = fs.metadata(&path.join("HEAD")).await;
3190    if !matches!(head_metadata, Ok(Some(_))) {
3191        return false;
3192    }
3193    let config_metadata = fs.metadata(&path.join("config")).await;
3194    matches!(config_metadata, Ok(Some(_)))
3195}
3196
3197async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3198    let contents = fs
3199        .load(abs_path)
3200        .await
3201        .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
3202    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3203    let mut builder = GitignoreBuilder::new(parent);
3204    for line in contents.lines() {
3205        builder.add_line(Some(abs_path.into()), line)?;
3206    }
3207    Ok(builder.build()?)
3208}
3209
3210impl Deref for Worktree {
3211    type Target = Snapshot;
3212
3213    fn deref(&self) -> &Self::Target {
3214        match self {
3215            Worktree::Local(worktree) => &worktree.snapshot,
3216            Worktree::Remote(worktree) => &worktree.snapshot,
3217        }
3218    }
3219}
3220
3221impl Deref for LocalWorktree {
3222    type Target = LocalSnapshot;
3223
3224    fn deref(&self) -> &Self::Target {
3225        &self.snapshot
3226    }
3227}
3228
3229impl Deref for RemoteWorktree {
3230    type Target = Snapshot;
3231
3232    fn deref(&self) -> &Self::Target {
3233        &self.snapshot
3234    }
3235}
3236
3237impl fmt::Debug for LocalWorktree {
3238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3239        self.snapshot.fmt(f)
3240    }
3241}
3242
3243impl fmt::Debug for Snapshot {
3244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3245        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3246        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3247
3248        impl fmt::Debug for EntriesByPath<'_> {
3249            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3250                f.debug_map()
3251                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3252                    .finish()
3253            }
3254        }
3255
3256        impl fmt::Debug for EntriesById<'_> {
3257            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3258                f.debug_list().entries(self.0.iter()).finish()
3259            }
3260        }
3261
3262        f.debug_struct("Snapshot")
3263            .field("id", &self.id)
3264            .field("root_name", &self.root_name)
3265            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3266            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3267            .finish()
3268    }
3269}
3270
3271#[derive(Debug, Clone, PartialEq)]
3272pub struct File {
3273    pub worktree: Entity<Worktree>,
3274    pub path: Arc<RelPath>,
3275    pub disk_state: DiskState,
3276    pub entry_id: Option<ProjectEntryId>,
3277    pub is_local: bool,
3278    pub is_private: bool,
3279}
3280
3281impl language::File for File {
3282    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3283        if self.is_local { Some(self) } else { None }
3284    }
3285
3286    fn disk_state(&self) -> DiskState {
3287        self.disk_state
3288    }
3289
3290    fn path(&self) -> &Arc<RelPath> {
3291        &self.path
3292    }
3293
3294    fn full_path(&self, cx: &App) -> PathBuf {
3295        self.worktree.read(cx).full_path(&self.path)
3296    }
3297
3298    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3299    /// of its worktree, then this method will return the name of the worktree itself.
3300    fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3301        self.path
3302            .file_name()
3303            .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3304    }
3305
3306    fn worktree_id(&self, cx: &App) -> WorktreeId {
3307        self.worktree.read(cx).id()
3308    }
3309
3310    fn to_proto(&self, cx: &App) -> rpc::proto::File {
3311        rpc::proto::File {
3312            worktree_id: self.worktree.read(cx).id().to_proto(),
3313            entry_id: self.entry_id.map(|id| id.to_proto()),
3314            path: self.path.as_ref().to_proto(),
3315            mtime: self.disk_state.mtime().map(|time| time.into()),
3316            is_deleted: self.disk_state.is_deleted(),
3317            is_historic: matches!(self.disk_state, DiskState::Historic { .. }),
3318        }
3319    }
3320
3321    fn is_private(&self) -> bool {
3322        self.is_private
3323    }
3324
3325    fn path_style(&self, cx: &App) -> PathStyle {
3326        self.worktree.read(cx).path_style()
3327    }
3328
3329    fn can_open(&self) -> bool {
3330        true
3331    }
3332}
3333
3334impl language::LocalFile for File {
3335    fn abs_path(&self, cx: &App) -> PathBuf {
3336        self.worktree.read(cx).absolutize(&self.path)
3337    }
3338
3339    fn load(&self, cx: &App) -> Task<Result<String>> {
3340        let worktree = self.worktree.read(cx).as_local().unwrap();
3341        let abs_path = worktree.absolutize(&self.path);
3342        let fs = worktree.fs.clone();
3343        cx.background_spawn(async move { fs.load(&abs_path).await })
3344    }
3345
3346    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3347        let worktree = self.worktree.read(cx).as_local().unwrap();
3348        let abs_path = worktree.absolutize(&self.path);
3349        let fs = worktree.fs.clone();
3350        cx.background_spawn(async move { fs.load_bytes(&abs_path).await })
3351    }
3352}
3353
3354impl File {
3355    pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3356        Arc::new(Self {
3357            worktree,
3358            path: entry.path.clone(),
3359            disk_state: if let Some(mtime) = entry.mtime {
3360                DiskState::Present {
3361                    mtime,
3362                    size: entry.size,
3363                }
3364            } else {
3365                DiskState::New
3366            },
3367            entry_id: Some(entry.id),
3368            is_local: true,
3369            is_private: entry.is_private,
3370        })
3371    }
3372
3373    pub fn from_proto(
3374        proto: rpc::proto::File,
3375        worktree: Entity<Worktree>,
3376        cx: &App,
3377    ) -> Result<Self> {
3378        let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
3379
3380        anyhow::ensure!(
3381            worktree_id.to_proto() == proto.worktree_id,
3382            "worktree id does not match file"
3383        );
3384
3385        let disk_state = if proto.is_historic {
3386            DiskState::Historic {
3387                was_deleted: proto.is_deleted,
3388            }
3389        } else if proto.is_deleted {
3390            DiskState::Deleted
3391        } else if let Some(mtime) = proto.mtime.map(&Into::into) {
3392            DiskState::Present { mtime, size: 0 }
3393        } else {
3394            DiskState::New
3395        };
3396
3397        Ok(Self {
3398            worktree,
3399            path: RelPath::from_proto(&proto.path).context("invalid path in file protobuf")?,
3400            disk_state,
3401            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3402            is_local: false,
3403            is_private: false,
3404        })
3405    }
3406
3407    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3408        file.and_then(|f| {
3409            let f: &dyn language::File = f.borrow();
3410            let f: &dyn Any = f;
3411            f.downcast_ref()
3412        })
3413    }
3414
3415    pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3416        self.worktree.read(cx).id()
3417    }
3418
3419    pub fn project_entry_id(&self) -> Option<ProjectEntryId> {
3420        match self.disk_state {
3421            DiskState::Deleted => None,
3422            _ => self.entry_id,
3423        }
3424    }
3425}
3426
3427#[derive(Clone, Debug, PartialEq, Eq)]
3428pub struct Entry {
3429    pub id: ProjectEntryId,
3430    pub kind: EntryKind,
3431    pub path: Arc<RelPath>,
3432    pub inode: u64,
3433    pub mtime: Option<MTime>,
3434
3435    pub canonical_path: Option<Arc<Path>>,
3436    /// Whether this entry is ignored by Git.
3437    ///
3438    /// We only scan ignored entries once the directory is expanded and
3439    /// exclude them from searches.
3440    pub is_ignored: bool,
3441
3442    /// Whether this entry is hidden or inside hidden directory.
3443    ///
3444    /// We only scan hidden entries once the directory is expanded.
3445    pub is_hidden: bool,
3446
3447    /// Whether this entry is always included in searches.
3448    ///
3449    /// This is used for entries that are always included in searches, even
3450    /// if they are ignored by git. Overridden by file_scan_exclusions.
3451    pub is_always_included: bool,
3452
3453    /// Whether this entry's canonical path is outside of the worktree.
3454    /// This means the entry is only accessible from the worktree root via a
3455    /// symlink.
3456    ///
3457    /// We only scan entries outside of the worktree once the symlinked
3458    /// directory is expanded.
3459    pub is_external: bool,
3460
3461    /// Whether this entry is considered to be a `.env` file.
3462    pub is_private: bool,
3463    /// The entry's size on disk, in bytes.
3464    pub size: u64,
3465    pub char_bag: CharBag,
3466    pub is_fifo: bool,
3467}
3468
3469#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3470pub enum EntryKind {
3471    UnloadedDir,
3472    PendingDir,
3473    Dir,
3474    File,
3475}
3476
3477#[derive(Clone, Copy, Debug, PartialEq)]
3478pub enum PathChange {
3479    /// A filesystem entry was was created.
3480    Added,
3481    /// A filesystem entry was removed.
3482    Removed,
3483    /// A filesystem entry was updated.
3484    Updated,
3485    /// A filesystem entry was either updated or added. We don't know
3486    /// whether or not it already existed, because the path had not
3487    /// been loaded before the event.
3488    AddedOrUpdated,
3489    /// A filesystem entry was found during the initial scan of the worktree.
3490    Loaded,
3491}
3492
3493#[derive(Clone, Debug, PartialEq, Eq)]
3494pub struct UpdatedGitRepository {
3495    /// ID of the repository's working directory.
3496    ///
3497    /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3498    /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3499    pub work_directory_id: ProjectEntryId,
3500    pub old_work_directory_abs_path: Option<Arc<Path>>,
3501    pub new_work_directory_abs_path: Option<Arc<Path>>,
3502    /// For a normal git repository checkout, the absolute path to the .git directory.
3503    /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3504    pub dot_git_abs_path: Option<Arc<Path>>,
3505    pub repository_dir_abs_path: Option<Arc<Path>>,
3506    pub common_dir_abs_path: Option<Arc<Path>>,
3507}
3508
3509pub type UpdatedEntriesSet = Arc<[(Arc<RelPath>, ProjectEntryId, PathChange)]>;
3510pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3511
3512#[derive(Clone, Debug)]
3513pub struct PathProgress<'a> {
3514    pub max_path: &'a RelPath,
3515}
3516
3517#[derive(Clone, Debug)]
3518pub struct PathSummary<S> {
3519    pub max_path: Arc<RelPath>,
3520    pub item_summary: S,
3521}
3522
3523impl<S: Summary> Summary for PathSummary<S> {
3524    type Context<'a> = S::Context<'a>;
3525
3526    fn zero(cx: Self::Context<'_>) -> Self {
3527        Self {
3528            max_path: RelPath::empty().into(),
3529            item_summary: S::zero(cx),
3530        }
3531    }
3532
3533    fn add_summary(&mut self, rhs: &Self, cx: Self::Context<'_>) {
3534        self.max_path = rhs.max_path.clone();
3535        self.item_summary.add_summary(&rhs.item_summary, cx);
3536    }
3537}
3538
3539impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3540    fn zero(_: <PathSummary<S> as Summary>::Context<'_>) -> Self {
3541        Self {
3542            max_path: RelPath::empty(),
3543        }
3544    }
3545
3546    fn add_summary(
3547        &mut self,
3548        summary: &'a PathSummary<S>,
3549        _: <PathSummary<S> as Summary>::Context<'_>,
3550    ) {
3551        self.max_path = summary.max_path.as_ref()
3552    }
3553}
3554
3555impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3556    fn zero(_cx: ()) -> Self {
3557        Default::default()
3558    }
3559
3560    fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: ()) {
3561        *self += summary.item_summary
3562    }
3563}
3564
3565impl<'a>
3566    sum_tree::SeekTarget<'a, PathSummary<GitSummary>, Dimensions<TraversalProgress<'a>, GitSummary>>
3567    for PathTarget<'_>
3568{
3569    fn cmp(
3570        &self,
3571        cursor_location: &Dimensions<TraversalProgress<'a>, GitSummary>,
3572        _: (),
3573    ) -> Ordering {
3574        self.cmp_path(cursor_location.0.max_path)
3575    }
3576}
3577
3578impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3579    fn zero(_: S::Context<'_>) -> Self {
3580        Default::default()
3581    }
3582
3583    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3584        self.0 = summary.max_path.clone();
3585    }
3586}
3587
3588impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3589    fn zero(_cx: S::Context<'_>) -> Self {
3590        Default::default()
3591    }
3592
3593    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3594        self.max_path = summary.max_path.as_ref();
3595    }
3596}
3597
3598impl Entry {
3599    fn new(
3600        path: Arc<RelPath>,
3601        metadata: &fs::Metadata,
3602        id: ProjectEntryId,
3603        root_char_bag: CharBag,
3604        canonical_path: Option<Arc<Path>>,
3605    ) -> Self {
3606        let char_bag = char_bag_for_path(root_char_bag, &path);
3607        Self {
3608            id,
3609            kind: if metadata.is_dir {
3610                EntryKind::PendingDir
3611            } else {
3612                EntryKind::File
3613            },
3614            path,
3615            inode: metadata.inode,
3616            mtime: Some(metadata.mtime),
3617            size: metadata.len,
3618            canonical_path,
3619            is_ignored: false,
3620            is_hidden: false,
3621            is_always_included: false,
3622            is_external: false,
3623            is_private: false,
3624            char_bag,
3625            is_fifo: metadata.is_fifo,
3626        }
3627    }
3628
3629    pub fn is_created(&self) -> bool {
3630        self.mtime.is_some()
3631    }
3632
3633    pub fn is_dir(&self) -> bool {
3634        self.kind.is_dir()
3635    }
3636
3637    pub fn is_file(&self) -> bool {
3638        self.kind.is_file()
3639    }
3640}
3641
3642impl EntryKind {
3643    pub fn is_dir(&self) -> bool {
3644        matches!(
3645            self,
3646            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3647        )
3648    }
3649
3650    pub fn is_unloaded(&self) -> bool {
3651        matches!(self, EntryKind::UnloadedDir)
3652    }
3653
3654    pub fn is_file(&self) -> bool {
3655        matches!(self, EntryKind::File)
3656    }
3657}
3658
3659impl sum_tree::Item for Entry {
3660    type Summary = EntrySummary;
3661
3662    fn summary(&self, _cx: ()) -> Self::Summary {
3663        let non_ignored_count = if self.is_ignored && !self.is_always_included {
3664            0
3665        } else {
3666            1
3667        };
3668        let file_count;
3669        let non_ignored_file_count;
3670        if self.is_file() {
3671            file_count = 1;
3672            non_ignored_file_count = non_ignored_count;
3673        } else {
3674            file_count = 0;
3675            non_ignored_file_count = 0;
3676        }
3677
3678        EntrySummary {
3679            max_path: self.path.clone(),
3680            count: 1,
3681            non_ignored_count,
3682            file_count,
3683            non_ignored_file_count,
3684        }
3685    }
3686}
3687
3688impl sum_tree::KeyedItem for Entry {
3689    type Key = PathKey;
3690
3691    fn key(&self) -> Self::Key {
3692        PathKey(self.path.clone())
3693    }
3694}
3695
3696#[derive(Clone, Debug)]
3697pub struct EntrySummary {
3698    max_path: Arc<RelPath>,
3699    count: usize,
3700    non_ignored_count: usize,
3701    file_count: usize,
3702    non_ignored_file_count: usize,
3703}
3704
3705impl Default for EntrySummary {
3706    fn default() -> Self {
3707        Self {
3708            max_path: Arc::from(RelPath::empty()),
3709            count: 0,
3710            non_ignored_count: 0,
3711            file_count: 0,
3712            non_ignored_file_count: 0,
3713        }
3714    }
3715}
3716
3717impl sum_tree::ContextLessSummary for EntrySummary {
3718    fn zero() -> Self {
3719        Default::default()
3720    }
3721
3722    fn add_summary(&mut self, rhs: &Self) {
3723        self.max_path = rhs.max_path.clone();
3724        self.count += rhs.count;
3725        self.non_ignored_count += rhs.non_ignored_count;
3726        self.file_count += rhs.file_count;
3727        self.non_ignored_file_count += rhs.non_ignored_file_count;
3728    }
3729}
3730
3731#[derive(Clone, Debug)]
3732struct PathEntry {
3733    id: ProjectEntryId,
3734    path: Arc<RelPath>,
3735    is_ignored: bool,
3736    scan_id: usize,
3737}
3738
3739impl sum_tree::Item for PathEntry {
3740    type Summary = PathEntrySummary;
3741
3742    fn summary(&self, _cx: ()) -> Self::Summary {
3743        PathEntrySummary { max_id: self.id }
3744    }
3745}
3746
3747impl sum_tree::KeyedItem for PathEntry {
3748    type Key = ProjectEntryId;
3749
3750    fn key(&self) -> Self::Key {
3751        self.id
3752    }
3753}
3754
3755#[derive(Clone, Debug, Default)]
3756struct PathEntrySummary {
3757    max_id: ProjectEntryId,
3758}
3759
3760impl sum_tree::ContextLessSummary for PathEntrySummary {
3761    fn zero() -> Self {
3762        Default::default()
3763    }
3764
3765    fn add_summary(&mut self, summary: &Self) {
3766        self.max_id = summary.max_id;
3767    }
3768}
3769
3770impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3771    fn zero(_cx: ()) -> Self {
3772        Default::default()
3773    }
3774
3775    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: ()) {
3776        *self = summary.max_id;
3777    }
3778}
3779
3780#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3781pub struct PathKey(pub Arc<RelPath>);
3782
3783impl Default for PathKey {
3784    fn default() -> Self {
3785        Self(RelPath::empty().into())
3786    }
3787}
3788
3789impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3790    fn zero(_cx: ()) -> Self {
3791        Default::default()
3792    }
3793
3794    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
3795        self.0 = summary.max_path.clone();
3796    }
3797}
3798
3799struct BackgroundScanner {
3800    state: async_lock::Mutex<BackgroundScannerState>,
3801    fs: Arc<dyn Fs>,
3802    fs_case_sensitive: bool,
3803    status_updates_tx: UnboundedSender<ScanState>,
3804    executor: BackgroundExecutor,
3805    scan_requests_rx: channel::Receiver<ScanRequest>,
3806    path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3807    next_entry_id: Arc<AtomicUsize>,
3808    phase: BackgroundScannerPhase,
3809    watcher: Arc<dyn Watcher>,
3810    settings: WorktreeSettings,
3811    share_private_files: bool,
3812    /// Whether this is a single-file worktree (root is a file, not a directory).
3813    /// Used to determine if we should give up after repeated canonicalization failures.
3814    is_single_file: bool,
3815}
3816
3817#[derive(Copy, Clone, PartialEq)]
3818enum BackgroundScannerPhase {
3819    InitialScan,
3820    EventsReceivedDuringInitialScan,
3821    Events,
3822}
3823
3824impl BackgroundScanner {
3825    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3826        let root_abs_path;
3827        let scanning_enabled;
3828        {
3829            let state = self.state.lock().await;
3830            root_abs_path = state.snapshot.abs_path.clone();
3831            scanning_enabled = state.scanning_enabled;
3832        }
3833
3834        // If the worktree root does not contain a git repository, then find
3835        // the git repository in an ancestor directory. Find any gitignore files
3836        // in ancestor directories.
3837        let repo = if scanning_enabled {
3838            let (ignores, exclude, repo) =
3839                discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3840            self.state
3841                .lock()
3842                .await
3843                .snapshot
3844                .ignores_by_parent_abs_path
3845                .extend(ignores);
3846            if let Some(exclude) = exclude {
3847                self.state
3848                    .lock()
3849                    .await
3850                    .snapshot
3851                    .repo_exclude_by_work_dir_abs_path
3852                    .insert(root_abs_path.as_path().into(), (exclude, false));
3853            }
3854
3855            repo
3856        } else {
3857            None
3858        };
3859
3860        let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo
3861            && scanning_enabled
3862        {
3863            maybe!(async {
3864                self.state
3865                    .lock()
3866                    .await
3867                    .insert_git_repository_for_path(
3868                        work_directory,
3869                        ancestor_dot_git.clone().into(),
3870                        self.fs.as_ref(),
3871                        self.watcher.as_ref(),
3872                    )
3873                    .await
3874                    .log_err()?;
3875                Some(ancestor_dot_git)
3876            })
3877            .await
3878        } else {
3879            None
3880        };
3881
3882        log::trace!("containing git repository: {containing_git_repository:?}");
3883
3884        let global_gitignore_file = paths::global_gitignore_path();
3885        let mut global_gitignore_events = if let Some(global_gitignore_path) =
3886            &global_gitignore_file
3887            && scanning_enabled
3888        {
3889            let is_file = self.fs.is_file(&global_gitignore_path).await;
3890            self.state.lock().await.snapshot.global_gitignore = if is_file {
3891                build_gitignore(global_gitignore_path, self.fs.as_ref())
3892                    .await
3893                    .ok()
3894                    .map(Arc::new)
3895            } else {
3896                None
3897            };
3898            if is_file {
3899                self.fs
3900                    .watch(global_gitignore_path, FS_WATCH_LATENCY)
3901                    .await
3902                    .0
3903            } else {
3904                Box::pin(futures::stream::pending())
3905            }
3906        } else {
3907            self.state.lock().await.snapshot.global_gitignore = None;
3908            Box::pin(futures::stream::pending())
3909        };
3910
3911        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3912        {
3913            let mut state = self.state.lock().await;
3914            state.snapshot.scan_id += 1;
3915            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3916                let ignore_stack = state
3917                    .snapshot
3918                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true, self.fs.as_ref())
3919                    .await;
3920                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3921                    root_entry.is_ignored = true;
3922                    let mut root_entry = root_entry.clone();
3923                    state.reuse_entry_id(&mut root_entry);
3924                    state
3925                        .insert_entry(root_entry, self.fs.as_ref(), self.watcher.as_ref())
3926                        .await;
3927                }
3928                if root_entry.is_dir() && state.scanning_enabled {
3929                    state
3930                        .enqueue_scan_dir(
3931                            root_abs_path.as_path().into(),
3932                            &root_entry,
3933                            &scan_job_tx,
3934                            self.fs.as_ref(),
3935                        )
3936                        .await;
3937                }
3938            }
3939        };
3940
3941        // Perform an initial scan of the directory.
3942        drop(scan_job_tx);
3943        self.scan_dirs(true, scan_job_rx).await;
3944        {
3945            let mut state = self.state.lock().await;
3946            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3947        }
3948
3949        self.send_status_update(false, SmallVec::new(), &[]).await;
3950
3951        // Process any any FS events that occurred while performing the initial scan.
3952        // For these events, update events cannot be as precise, because we didn't
3953        // have the previous state loaded yet.
3954        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3955        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3956            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3957                paths.extend(more_paths);
3958            }
3959            self.process_events(
3960                paths
3961                    .into_iter()
3962                    .filter(|event| event.kind.is_some())
3963                    .collect(),
3964            )
3965            .await;
3966        }
3967        if let Some(abs_path) = containing_git_repository {
3968            self.process_events(vec![PathEvent {
3969                path: abs_path,
3970                kind: Some(fs::PathEventKind::Changed),
3971            }])
3972            .await;
3973        }
3974
3975        // Continue processing events until the worktree is dropped.
3976        self.phase = BackgroundScannerPhase::Events;
3977
3978        loop {
3979            select_biased! {
3980                // Process any path refresh requests from the worktree. Prioritize
3981                // these before handling changes reported by the filesystem.
3982                request = self.next_scan_request().fuse() => {
3983                    let Ok(request) = request else { break };
3984                    if !self.process_scan_request(request, false).await {
3985                        return;
3986                    }
3987                }
3988
3989                path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3990                    let Ok(request) = path_prefix_request else { break };
3991                    log::trace!("adding path prefix {:?}", request.path);
3992
3993                    let did_scan = self.forcibly_load_paths(std::slice::from_ref(&request.path)).await;
3994                    if did_scan {
3995                        let abs_path =
3996                        {
3997                            let mut state = self.state.lock().await;
3998                            state.path_prefixes_to_scan.insert(request.path.clone());
3999                            state.snapshot.absolutize(&request.path)
4000                        };
4001
4002                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
4003                            self.process_events(vec![PathEvent {
4004                                path: abs_path,
4005                                kind: Some(fs::PathEventKind::Changed),
4006                            }])
4007                            .await;
4008                        }
4009                    }
4010                    self.send_status_update(false, request.done, &[]).await;
4011                }
4012
4013                paths = fs_events_rx.next().fuse() => {
4014                    let Some(mut paths) = paths else { break };
4015                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4016                        paths.extend(more_paths);
4017                    }
4018                    self.process_events(paths.into_iter().filter(|event| event.kind.is_some()).collect()).await;
4019                }
4020
4021                _ = global_gitignore_events.next().fuse() => {
4022                    if let Some(path) = &global_gitignore_file {
4023                        self.update_global_gitignore(&path).await;
4024                    }
4025                }
4026            }
4027        }
4028    }
4029
4030    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
4031        log::debug!("rescanning paths {:?}", request.relative_paths);
4032
4033        request.relative_paths.sort_unstable();
4034        self.forcibly_load_paths(&request.relative_paths).await;
4035
4036        let root_path = self.state.lock().await.snapshot.abs_path.clone();
4037        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
4038        let root_canonical_path = match &root_canonical_path {
4039            Ok(path) => SanitizedPath::new(path),
4040            Err(err) => {
4041                log::error!("failed to canonicalize root path {root_path:?}: {err:#}");
4042                return true;
4043            }
4044        };
4045        let abs_paths = request
4046            .relative_paths
4047            .iter()
4048            .map(|path| {
4049                if path.file_name().is_some() {
4050                    root_canonical_path.as_path().join(path.as_std_path())
4051                } else {
4052                    root_canonical_path.as_path().to_path_buf()
4053                }
4054            })
4055            .collect::<Vec<_>>();
4056
4057        {
4058            let mut state = self.state.lock().await;
4059            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
4060            state.snapshot.scan_id += 1;
4061            if is_idle {
4062                state.snapshot.completed_scan_id = state.snapshot.scan_id;
4063            }
4064        }
4065
4066        self.reload_entries_for_paths(
4067            &root_path,
4068            &root_canonical_path,
4069            &request.relative_paths,
4070            abs_paths,
4071            None,
4072        )
4073        .await;
4074
4075        self.send_status_update(scanning, request.done, &[]).await
4076    }
4077
4078    async fn process_events(&self, mut events: Vec<PathEvent>) {
4079        let root_path = self.state.lock().await.snapshot.abs_path.clone();
4080        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
4081        let root_canonical_path = match &root_canonical_path {
4082            Ok(path) => SanitizedPath::new(path),
4083            Err(err) => {
4084                let new_path = self
4085                    .state
4086                    .lock()
4087                    .await
4088                    .snapshot
4089                    .root_file_handle
4090                    .clone()
4091                    .and_then(|handle| match handle.current_path(&self.fs) {
4092                        Ok(new_path) => Some(new_path),
4093                        Err(e) => {
4094                            log::error!("Failed to refresh worktree root path: {e:#}");
4095                            None
4096                        }
4097                    })
4098                    .map(|path| SanitizedPath::new_arc(&path))
4099                    .filter(|new_path| *new_path != root_path);
4100
4101                if let Some(new_path) = new_path {
4102                    log::info!(
4103                        "root renamed from {:?} to {:?}",
4104                        root_path.as_path(),
4105                        new_path.as_path(),
4106                    );
4107                    self.status_updates_tx
4108                        .unbounded_send(ScanState::RootUpdated { new_path })
4109                        .ok();
4110                } else {
4111                    log::error!("root path could not be canonicalized: {err:#}");
4112
4113                    // For single-file worktrees, if we can't canonicalize and the file handle
4114                    // fallback also failed, the file is gone - close the worktree
4115                    if self.is_single_file {
4116                        log::info!(
4117                            "single-file worktree root {:?} no longer exists, marking as deleted",
4118                            root_path.as_path()
4119                        );
4120                        self.status_updates_tx
4121                            .unbounded_send(ScanState::RootDeleted)
4122                            .ok();
4123                    }
4124                }
4125                return;
4126            }
4127        };
4128
4129        // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4130        // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4131        let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];
4132        let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];
4133
4134        let mut relative_paths = Vec::with_capacity(events.len());
4135        let mut dot_git_abs_paths = Vec::new();
4136        let mut work_dirs_needing_exclude_update = Vec::new();
4137        events.sort_unstable_by(|left, right| left.path.cmp(&right.path));
4138        events.dedup_by(|left, right| {
4139            if left.path == right.path {
4140                if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {
4141                    right.kind = left.kind;
4142                }
4143                true
4144            } else if left.path.starts_with(&right.path) {
4145                if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {
4146                    right.kind = left.kind;
4147                }
4148                true
4149            } else {
4150                false
4151            }
4152        });
4153        {
4154            let snapshot = &self.state.lock().await.snapshot;
4155
4156            let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();
4157
4158            fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {
4159                if let Some(last_range) = ranges.last_mut()
4160                    && last_range.end == ix
4161                {
4162                    last_range.end += 1;
4163                } else {
4164                    ranges.push(ix..ix + 1);
4165                }
4166            }
4167
4168            for (ix, event) in events.iter().enumerate() {
4169                let abs_path = SanitizedPath::new(&event.path);
4170
4171                let mut is_git_related = false;
4172                let mut dot_git_paths = None;
4173
4174                for ancestor in abs_path.as_path().ancestors() {
4175                    if is_git_dir(ancestor, self.fs.as_ref()).await {
4176                        let path_in_git_dir = abs_path
4177                            .as_path()
4178                            .strip_prefix(ancestor)
4179                            .expect("stripping off the ancestor");
4180                        dot_git_paths = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
4181                        break;
4182                    }
4183                }
4184
4185                if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4186                    // We ignore `""` as well, as that is going to be the
4187                    // `.git` folder itself. WE do not care about it, if
4188                    // there are changes within we will see them, we need
4189                    // this ignore to prevent us from accidentally observing
4190                    // the ignored created file due to the events not being
4191                    // empty after filtering.
4192
4193                    let is_dot_git_changed = {
4194                        path_in_git_dir == Path::new("")
4195                            && event.kind == Some(PathEventKind::Changed)
4196                            && abs_path
4197                                .strip_prefix(root_canonical_path)
4198                                .ok()
4199                                .and_then(|it| RelPath::new(it, PathStyle::local()).ok())
4200                                .is_some_and(|it| {
4201                                    snapshot
4202                                        .entry_for_path(&it)
4203                                        .is_some_and(|entry| entry.kind == EntryKind::Dir)
4204                                })
4205                    };
4206                    let condition = skipped_files_in_dot_git.iter().any(|skipped| {
4207                        OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str()
4208                    }) || skipped_dirs_in_dot_git
4209                        .iter()
4210                        .any(|skipped_git_subdir| path_in_git_dir.starts_with(skipped_git_subdir))
4211                        || is_dot_git_changed;
4212                    if condition {
4213                        log::debug!(
4214                            "ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories"
4215                        );
4216                        skip_ix(&mut ranges_to_drop, ix);
4217                        continue;
4218                    }
4219
4220                    is_git_related = true;
4221                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4222                        dot_git_abs_paths.push(dot_git_abs_path);
4223                    }
4224                }
4225
4226                let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)
4227                    && let Ok(path) = RelPath::new(path, PathStyle::local())
4228                {
4229                    path
4230                } else {
4231                    if is_git_related {
4232                        log::debug!(
4233                            "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4234                        );
4235                    } else {
4236                        log::error!(
4237                            "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4238                        );
4239                    }
4240                    skip_ix(&mut ranges_to_drop, ix);
4241                    continue;
4242                };
4243
4244                let absolute_path = abs_path.to_path_buf();
4245                if absolute_path.ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE)) {
4246                    if let Some(repository) = snapshot
4247                        .git_repositories
4248                        .values()
4249                        .find(|repo| repo.common_dir_abs_path.join(REPO_EXCLUDE) == absolute_path)
4250                    {
4251                        work_dirs_needing_exclude_update
4252                            .push(repository.work_directory_abs_path.clone());
4253                    }
4254                }
4255
4256                if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
4257                    for (_, repo) in snapshot
4258                        .git_repositories
4259                        .iter()
4260                        .filter(|(_, repo)| repo.directory_contains(&relative_path))
4261                    {
4262                        if !dot_git_abs_paths.iter().any(|dot_git_abs_path| {
4263                            dot_git_abs_path == repo.common_dir_abs_path.as_ref()
4264                        }) {
4265                            dot_git_abs_paths.push(repo.common_dir_abs_path.to_path_buf());
4266                        }
4267                    }
4268                }
4269
4270                let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
4271                    snapshot
4272                        .entry_for_path(parent)
4273                        .is_some_and(|entry| entry.kind == EntryKind::Dir)
4274                });
4275                if !parent_dir_is_loaded {
4276                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
4277                    skip_ix(&mut ranges_to_drop, ix);
4278                    continue;
4279                }
4280
4281                if self.settings.is_path_excluded(&relative_path) {
4282                    if !is_git_related {
4283                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
4284                    }
4285                    skip_ix(&mut ranges_to_drop, ix);
4286                    continue;
4287                }
4288
4289                relative_paths.push(EventRoot {
4290                    path: relative_path.into_arc(),
4291                    was_rescanned: matches!(event.kind, Some(fs::PathEventKind::Rescan)),
4292                });
4293            }
4294
4295            for range_to_drop in ranges_to_drop.into_iter().rev() {
4296                events.drain(range_to_drop);
4297            }
4298        }
4299
4300        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4301            return;
4302        }
4303
4304        if !work_dirs_needing_exclude_update.is_empty() {
4305            let mut state = self.state.lock().await;
4306            for work_dir_abs_path in work_dirs_needing_exclude_update {
4307                if let Some((_, needs_update)) = state
4308                    .snapshot
4309                    .repo_exclude_by_work_dir_abs_path
4310                    .get_mut(&work_dir_abs_path)
4311                {
4312                    *needs_update = true;
4313                }
4314            }
4315        }
4316
4317        self.state.lock().await.snapshot.scan_id += 1;
4318
4319        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4320        log::debug!(
4321            "received fs events {:?}",
4322            relative_paths
4323                .iter()
4324                .map(|event_root| &event_root.path)
4325                .collect::<Vec<_>>()
4326        );
4327        self.reload_entries_for_paths(
4328            &root_path,
4329            &root_canonical_path,
4330            &relative_paths
4331                .iter()
4332                .map(|event_root| event_root.path.clone())
4333                .collect::<Vec<_>>(),
4334            events
4335                .into_iter()
4336                .map(|event| event.path)
4337                .collect::<Vec<_>>(),
4338            Some(scan_job_tx.clone()),
4339        )
4340        .await;
4341
4342        let affected_repo_roots = if !dot_git_abs_paths.is_empty() {
4343            self.update_git_repositories(dot_git_abs_paths).await
4344        } else {
4345            Vec::new()
4346        };
4347
4348        {
4349            let mut ignores_to_update = self.ignores_needing_update().await;
4350            ignores_to_update.extend(affected_repo_roots);
4351            let ignores_to_update = self.order_ignores(ignores_to_update).await;
4352            let snapshot = self.state.lock().await.snapshot.clone();
4353            self.update_ignore_statuses_for_paths(scan_job_tx, snapshot, ignores_to_update)
4354                .await;
4355            self.scan_dirs(false, scan_job_rx).await;
4356        }
4357
4358        {
4359            let mut state = self.state.lock().await;
4360            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4361            for (_, entry) in mem::take(&mut state.removed_entries) {
4362                state.scanned_dirs.remove(&entry.id);
4363            }
4364        }
4365        self.send_status_update(false, SmallVec::new(), &relative_paths)
4366            .await;
4367    }
4368
4369    async fn update_global_gitignore(&self, abs_path: &Path) {
4370        let ignore = build_gitignore(abs_path, self.fs.as_ref())
4371            .await
4372            .log_err()
4373            .map(Arc::new);
4374        let (prev_snapshot, ignore_stack, abs_path) = {
4375            let mut state = self.state.lock().await;
4376            state.snapshot.global_gitignore = ignore;
4377            let abs_path = state.snapshot.abs_path().clone();
4378            let ignore_stack = state
4379                .snapshot
4380                .ignore_stack_for_abs_path(&abs_path, true, self.fs.as_ref())
4381                .await;
4382            (state.snapshot.clone(), ignore_stack, abs_path)
4383        };
4384        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4385        self.update_ignore_statuses_for_paths(
4386            scan_job_tx,
4387            prev_snapshot,
4388            vec![(abs_path, ignore_stack)],
4389        )
4390        .await;
4391        self.scan_dirs(false, scan_job_rx).await;
4392        self.send_status_update(false, SmallVec::new(), &[]).await;
4393    }
4394
4395    async fn forcibly_load_paths(&self, paths: &[Arc<RelPath>]) -> bool {
4396        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4397        {
4398            let mut state = self.state.lock().await;
4399            let root_path = state.snapshot.abs_path.clone();
4400            for path in paths {
4401                for ancestor in path.ancestors() {
4402                    if let Some(entry) = state.snapshot.entry_for_path(ancestor)
4403                        && entry.kind == EntryKind::UnloadedDir
4404                    {
4405                        let abs_path = root_path.join(ancestor.as_std_path());
4406                        state
4407                            .enqueue_scan_dir(
4408                                abs_path.into(),
4409                                entry,
4410                                &scan_job_tx,
4411                                self.fs.as_ref(),
4412                            )
4413                            .await;
4414                        state.paths_to_scan.insert(path.clone());
4415                        break;
4416                    }
4417                }
4418            }
4419            drop(scan_job_tx);
4420        }
4421        while let Ok(job) = scan_job_rx.recv().await {
4422            self.scan_dir(&job).await.log_err();
4423        }
4424
4425        !mem::take(&mut self.state.lock().await.paths_to_scan).is_empty()
4426    }
4427
4428    async fn scan_dirs(
4429        &self,
4430        enable_progress_updates: bool,
4431        scan_jobs_rx: channel::Receiver<ScanJob>,
4432    ) {
4433        if self
4434            .status_updates_tx
4435            .unbounded_send(ScanState::Started)
4436            .is_err()
4437        {
4438            return;
4439        }
4440
4441        let progress_update_count = AtomicUsize::new(0);
4442        self.executor
4443            .scoped_priority(Priority::Low, |scope| {
4444                for _ in 0..self.executor.num_cpus() {
4445                    scope.spawn(async {
4446                        let mut last_progress_update_count = 0;
4447                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4448                        futures::pin_mut!(progress_update_timer);
4449
4450                        loop {
4451                            select_biased! {
4452                                // Process any path refresh requests before moving on to process
4453                                // the scan queue, so that user operations are prioritized.
4454                                request = self.next_scan_request().fuse() => {
4455                                    let Ok(request) = request else { break };
4456                                    if !self.process_scan_request(request, true).await {
4457                                        return;
4458                                    }
4459                                }
4460
4461                                // Send periodic progress updates to the worktree. Use an atomic counter
4462                                // to ensure that only one of the workers sends a progress update after
4463                                // the update interval elapses.
4464                                _ = progress_update_timer => {
4465                                    match progress_update_count.compare_exchange(
4466                                        last_progress_update_count,
4467                                        last_progress_update_count + 1,
4468                                        SeqCst,
4469                                        SeqCst
4470                                    ) {
4471                                        Ok(_) => {
4472                                            last_progress_update_count += 1;
4473                                            self.send_status_update(true, SmallVec::new(), &[])
4474                                                .await;
4475                                        }
4476                                        Err(count) => {
4477                                            last_progress_update_count = count;
4478                                        }
4479                                    }
4480                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4481                                }
4482
4483                                // Recursively load directories from the file system.
4484                                job = scan_jobs_rx.recv().fuse() => {
4485                                    let Ok(job) = job else { break };
4486                                    if let Err(err) = self.scan_dir(&job).await
4487                                        && job.path.is_empty() {
4488                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4489                                        }
4490                                }
4491                            }
4492                        }
4493                    });
4494                }
4495            })
4496            .await;
4497    }
4498
4499    async fn send_status_update(
4500        &self,
4501        scanning: bool,
4502        barrier: SmallVec<[barrier::Sender; 1]>,
4503        event_roots: &[EventRoot],
4504    ) -> bool {
4505        let mut state = self.state.lock().await;
4506        if state.changed_paths.is_empty() && event_roots.is_empty() && scanning {
4507            return true;
4508        }
4509
4510        let merged_event_roots = merge_event_roots(&state.changed_paths, event_roots);
4511
4512        let new_snapshot = state.snapshot.clone();
4513        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4514        let changes = build_diff(
4515            self.phase,
4516            &old_snapshot,
4517            &new_snapshot,
4518            &merged_event_roots,
4519        );
4520        state.changed_paths.clear();
4521
4522        self.status_updates_tx
4523            .unbounded_send(ScanState::Updated {
4524                snapshot: new_snapshot,
4525                changes,
4526                scanning,
4527                barrier,
4528            })
4529            .is_ok()
4530    }
4531
4532    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4533        let root_abs_path;
4534        let root_char_bag;
4535        {
4536            let snapshot = &self.state.lock().await.snapshot;
4537            if self.settings.is_path_excluded(&job.path) {
4538                log::error!("skipping excluded directory {:?}", job.path);
4539                return Ok(());
4540            }
4541            log::trace!("scanning directory {:?}", job.path);
4542            root_abs_path = snapshot.abs_path().clone();
4543            root_char_bag = snapshot.root_char_bag;
4544        }
4545
4546        let next_entry_id = self.next_entry_id.clone();
4547        let mut ignore_stack = job.ignore_stack.clone();
4548        let mut new_ignore = None;
4549        let mut root_canonical_path = None;
4550        let mut new_entries: Vec<Entry> = Vec::new();
4551        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4552        let mut child_paths = self
4553            .fs
4554            .read_dir(&job.abs_path)
4555            .await?
4556            .filter_map(|entry| async {
4557                match entry {
4558                    Ok(entry) => Some(entry),
4559                    Err(error) => {
4560                        log::error!("error processing entry {:?}", error);
4561                        None
4562                    }
4563                }
4564            })
4565            .collect::<Vec<_>>()
4566            .await;
4567
4568        // Ensure that .git and .gitignore are processed first.
4569        swap_to_front(&mut child_paths, GITIGNORE);
4570        swap_to_front(&mut child_paths, DOT_GIT);
4571
4572        if let Some(path) = child_paths.first()
4573            && path.ends_with(DOT_GIT)
4574        {
4575            ignore_stack.repo_root = Some(job.abs_path.clone());
4576        }
4577
4578        for child_abs_path in child_paths {
4579            let child_abs_path: Arc<Path> = child_abs_path.into();
4580            let child_name = child_abs_path.file_name().unwrap();
4581            let Some(child_path) = child_name
4582                .to_str()
4583                .and_then(|name| Some(job.path.join(RelPath::unix(name).ok()?)))
4584            else {
4585                continue;
4586            };
4587
4588            if child_name == DOT_GIT {
4589                let mut state = self.state.lock().await;
4590                state
4591                    .insert_git_repository(
4592                        child_path.clone(),
4593                        self.fs.as_ref(),
4594                        self.watcher.as_ref(),
4595                    )
4596                    .await;
4597            } else if child_name == GITIGNORE {
4598                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4599                    Ok(ignore) => {
4600                        let ignore = Arc::new(ignore);
4601                        ignore_stack = ignore_stack
4602                            .append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4603                        new_ignore = Some(ignore);
4604                    }
4605                    Err(error) => {
4606                        log::error!(
4607                            "error loading .gitignore file {:?} - {:?}",
4608                            child_name,
4609                            error
4610                        );
4611                    }
4612                }
4613            }
4614
4615            if self.settings.is_path_excluded(&child_path) {
4616                log::debug!("skipping excluded child entry {child_path:?}");
4617                self.state
4618                    .lock()
4619                    .await
4620                    .remove_path(&child_path, self.watcher.as_ref());
4621                continue;
4622            }
4623
4624            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4625                Ok(Some(metadata)) => metadata,
4626                Ok(None) => continue,
4627                Err(err) => {
4628                    log::error!("error processing {:?}: {err:#}", child_abs_path.display());
4629                    continue;
4630                }
4631            };
4632
4633            let mut child_entry = Entry::new(
4634                child_path.clone(),
4635                &child_metadata,
4636                ProjectEntryId::new(&next_entry_id),
4637                root_char_bag,
4638                None,
4639            );
4640
4641            if job.is_external {
4642                child_entry.is_external = true;
4643            } else if child_metadata.is_symlink {
4644                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4645                    Ok(path) => path,
4646                    Err(err) => {
4647                        log::error!("error reading target of symlink {child_abs_path:?}: {err:#}",);
4648                        continue;
4649                    }
4650                };
4651
4652                // lazily canonicalize the root path in order to determine if
4653                // symlinks point outside of the worktree.
4654                let root_canonical_path = match &root_canonical_path {
4655                    Some(path) => path,
4656                    None => match self.fs.canonicalize(&root_abs_path).await {
4657                        Ok(path) => root_canonical_path.insert(path),
4658                        Err(err) => {
4659                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4660                            continue;
4661                        }
4662                    },
4663                };
4664
4665                if !canonical_path.starts_with(root_canonical_path) {
4666                    child_entry.is_external = true;
4667                }
4668
4669                child_entry.canonical_path = Some(canonical_path.into());
4670            }
4671
4672            if child_entry.is_dir() {
4673                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4674                child_entry.is_always_included =
4675                    self.settings.is_path_always_included(&child_path, true);
4676
4677                // Avoid recursing until crash in the case of a recursive symlink
4678                if job.ancestor_inodes.contains(&child_entry.inode) {
4679                    new_jobs.push(None);
4680                } else {
4681                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4682                    ancestor_inodes.insert(child_entry.inode);
4683
4684                    new_jobs.push(Some(ScanJob {
4685                        abs_path: child_abs_path.clone(),
4686                        path: child_path,
4687                        is_external: child_entry.is_external,
4688                        ignore_stack: if child_entry.is_ignored {
4689                            IgnoreStack::all()
4690                        } else {
4691                            ignore_stack.clone()
4692                        },
4693                        ancestor_inodes,
4694                        scan_queue: job.scan_queue.clone(),
4695                    }));
4696                }
4697            } else {
4698                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4699                child_entry.is_always_included =
4700                    self.settings.is_path_always_included(&child_path, false);
4701            }
4702
4703            {
4704                let relative_path = job
4705                    .path
4706                    .join(RelPath::unix(child_name.to_str().unwrap()).unwrap());
4707                if self.is_path_private(&relative_path) {
4708                    log::debug!("detected private file: {relative_path:?}");
4709                    child_entry.is_private = true;
4710                }
4711                if self.settings.is_path_hidden(&relative_path) {
4712                    log::debug!("detected hidden file: {relative_path:?}");
4713                    child_entry.is_hidden = true;
4714                }
4715            }
4716
4717            new_entries.push(child_entry);
4718        }
4719
4720        let mut state = self.state.lock().await;
4721
4722        // Identify any subdirectories that should not be scanned.
4723        let mut job_ix = 0;
4724        for entry in &mut new_entries {
4725            state.reuse_entry_id(entry);
4726            if entry.is_dir() {
4727                if state.should_scan_directory(entry) {
4728                    job_ix += 1;
4729                } else {
4730                    log::debug!("defer scanning directory {:?}", entry.path);
4731                    entry.kind = EntryKind::UnloadedDir;
4732                    new_jobs.remove(job_ix);
4733                }
4734            }
4735            if entry.is_always_included {
4736                state
4737                    .snapshot
4738                    .always_included_entries
4739                    .push(entry.path.clone());
4740            }
4741        }
4742
4743        state.populate_dir(job.path.clone(), new_entries, new_ignore);
4744        self.watcher.add(job.abs_path.as_ref()).log_err();
4745
4746        for new_job in new_jobs.into_iter().flatten() {
4747            job.scan_queue
4748                .try_send(new_job)
4749                .expect("channel is unbounded");
4750        }
4751
4752        Ok(())
4753    }
4754
4755    /// All list arguments should be sorted before calling this function
4756    async fn reload_entries_for_paths(
4757        &self,
4758        root_abs_path: &SanitizedPath,
4759        root_canonical_path: &SanitizedPath,
4760        relative_paths: &[Arc<RelPath>],
4761        abs_paths: Vec<PathBuf>,
4762        scan_queue_tx: Option<Sender<ScanJob>>,
4763    ) {
4764        // grab metadata for all requested paths
4765        let metadata = futures::future::join_all(
4766            abs_paths
4767                .iter()
4768                .map(|abs_path| async move {
4769                    let metadata = self.fs.metadata(abs_path).await?;
4770                    if let Some(metadata) = metadata {
4771                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4772
4773                        // If we're on a case-insensitive filesystem (default on macOS), we want
4774                        // to only ignore metadata for non-symlink files if their absolute-path matches
4775                        // the canonical-path.
4776                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4777                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4778                        // treated as removed.
4779                        if !self.fs_case_sensitive && !metadata.is_symlink {
4780                            let canonical_file_name = canonical_path.file_name();
4781                            let file_name = abs_path.file_name();
4782                            if canonical_file_name != file_name {
4783                                return Ok(None);
4784                            }
4785                        }
4786
4787                        anyhow::Ok(Some((metadata, SanitizedPath::new_arc(&canonical_path))))
4788                    } else {
4789                        Ok(None)
4790                    }
4791                })
4792                .collect::<Vec<_>>(),
4793        )
4794        .await;
4795
4796        let mut new_ancestor_repo = if relative_paths.iter().any(|path| path.is_empty()) {
4797            Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4798        } else {
4799            None
4800        };
4801
4802        let mut state = self.state.lock().await;
4803        let doing_recursive_update = scan_queue_tx.is_some();
4804
4805        // Remove any entries for paths that no longer exist or are being recursively
4806        // refreshed. Do this before adding any new entries, so that renames can be
4807        // detected regardless of the order of the paths.
4808        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4809            if matches!(metadata, Ok(None)) || doing_recursive_update {
4810                state.remove_path(path, self.watcher.as_ref());
4811            }
4812        }
4813
4814        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4815            let abs_path: Arc<Path> = root_abs_path.join(path.as_std_path()).into();
4816            match metadata {
4817                Ok(Some((metadata, canonical_path))) => {
4818                    let ignore_stack = state
4819                        .snapshot
4820                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir, self.fs.as_ref())
4821                        .await;
4822                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4823                    let entry_id = state.entry_id_for(self.next_entry_id.as_ref(), path, &metadata);
4824                    let mut fs_entry = Entry::new(
4825                        path.clone(),
4826                        &metadata,
4827                        entry_id,
4828                        state.snapshot.root_char_bag,
4829                        if metadata.is_symlink {
4830                            Some(canonical_path.as_path().to_path_buf().into())
4831                        } else {
4832                            None
4833                        },
4834                    );
4835
4836                    let is_dir = fs_entry.is_dir();
4837                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4838                    fs_entry.is_external = is_external;
4839                    fs_entry.is_private = self.is_path_private(path);
4840                    fs_entry.is_always_included =
4841                        self.settings.is_path_always_included(path, is_dir);
4842                    fs_entry.is_hidden = self.settings.is_path_hidden(path);
4843
4844                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4845                        if state.should_scan_directory(&fs_entry)
4846                            || (fs_entry.path.is_empty()
4847                                && abs_path.file_name() == Some(OsStr::new(DOT_GIT)))
4848                        {
4849                            state
4850                                .enqueue_scan_dir(
4851                                    abs_path,
4852                                    &fs_entry,
4853                                    scan_queue_tx,
4854                                    self.fs.as_ref(),
4855                                )
4856                                .await;
4857                        } else {
4858                            fs_entry.kind = EntryKind::UnloadedDir;
4859                        }
4860                    }
4861
4862                    state
4863                        .insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
4864                        .await;
4865
4866                    if path.is_empty()
4867                        && let Some((ignores, exclude, repo)) = new_ancestor_repo.take()
4868                    {
4869                        log::trace!("updating ancestor git repository");
4870                        state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4871                        if let Some((ancestor_dot_git, work_directory)) = repo {
4872                            if let Some(exclude) = exclude {
4873                                let work_directory_abs_path = self
4874                                    .state
4875                                    .lock()
4876                                    .await
4877                                    .snapshot
4878                                    .work_directory_abs_path(&work_directory);
4879
4880                                state
4881                                    .snapshot
4882                                    .repo_exclude_by_work_dir_abs_path
4883                                    .insert(work_directory_abs_path.into(), (exclude, false));
4884                            }
4885                            state
4886                                .insert_git_repository_for_path(
4887                                    work_directory,
4888                                    ancestor_dot_git.into(),
4889                                    self.fs.as_ref(),
4890                                    self.watcher.as_ref(),
4891                                )
4892                                .await
4893                                .log_err();
4894                        }
4895                    }
4896                }
4897                Ok(None) => {
4898                    self.remove_repo_path(path.clone(), &mut state.snapshot);
4899                }
4900                Err(err) => {
4901                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4902                }
4903            }
4904        }
4905
4906        util::extend_sorted(
4907            &mut state.changed_paths,
4908            relative_paths.iter().cloned(),
4909            usize::MAX,
4910            Ord::cmp,
4911        );
4912    }
4913
4914    fn remove_repo_path(&self, path: Arc<RelPath>, snapshot: &mut LocalSnapshot) -> Option<()> {
4915        if !path.components().any(|component| component == DOT_GIT)
4916            && let Some(local_repo) = snapshot.local_repo_for_work_directory_path(&path)
4917        {
4918            let id = local_repo.work_directory_id;
4919            log::debug!("remove repo path: {:?}", path);
4920            snapshot.git_repositories.remove(&id);
4921            return Some(());
4922        }
4923
4924        Some(())
4925    }
4926
4927    async fn update_ignore_statuses_for_paths(
4928        &self,
4929        scan_job_tx: Sender<ScanJob>,
4930        prev_snapshot: LocalSnapshot,
4931        ignores_to_update: Vec<(Arc<Path>, IgnoreStack)>,
4932    ) {
4933        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4934        {
4935            for (parent_abs_path, ignore_stack) in ignores_to_update {
4936                ignore_queue_tx
4937                    .send_blocking(UpdateIgnoreStatusJob {
4938                        abs_path: parent_abs_path,
4939                        ignore_stack,
4940                        ignore_queue: ignore_queue_tx.clone(),
4941                        scan_queue: scan_job_tx.clone(),
4942                    })
4943                    .unwrap();
4944            }
4945        }
4946        drop(ignore_queue_tx);
4947
4948        self.executor
4949            .scoped(|scope| {
4950                for _ in 0..self.executor.num_cpus() {
4951                    scope.spawn(async {
4952                        loop {
4953                            select_biased! {
4954                                // Process any path refresh requests before moving on to process
4955                                // the queue of ignore statuses.
4956                                request = self.next_scan_request().fuse() => {
4957                                    let Ok(request) = request else { break };
4958                                    if !self.process_scan_request(request, true).await {
4959                                        return;
4960                                    }
4961                                }
4962
4963                                // Recursively process directories whose ignores have changed.
4964                                job = ignore_queue_rx.recv().fuse() => {
4965                                    let Ok(job) = job else { break };
4966                                    self.update_ignore_status(job, &prev_snapshot).await;
4967                                }
4968                            }
4969                        }
4970                    });
4971                }
4972            })
4973            .await;
4974    }
4975
4976    async fn ignores_needing_update(&self) -> Vec<Arc<Path>> {
4977        let mut ignores_to_update = Vec::new();
4978        let mut excludes_to_load: Vec<(Arc<Path>, PathBuf)> = Vec::new();
4979
4980        // First pass: collect updates and drop stale entries without awaiting.
4981        {
4982            let snapshot = &mut self.state.lock().await.snapshot;
4983            let abs_path = snapshot.abs_path.clone();
4984            let mut repo_exclude_keys_to_remove: Vec<Arc<Path>> = Vec::new();
4985
4986            for (work_dir_abs_path, (_, needs_update)) in
4987                snapshot.repo_exclude_by_work_dir_abs_path.iter_mut()
4988            {
4989                let repository = snapshot
4990                    .git_repositories
4991                    .iter()
4992                    .find(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path);
4993
4994                if *needs_update {
4995                    *needs_update = false;
4996                    ignores_to_update.push(work_dir_abs_path.clone());
4997
4998                    if let Some((_, repository)) = repository {
4999                        let exclude_abs_path = repository.common_dir_abs_path.join(REPO_EXCLUDE);
5000                        excludes_to_load.push((work_dir_abs_path.clone(), exclude_abs_path));
5001                    }
5002                }
5003
5004                if repository.is_none() {
5005                    repo_exclude_keys_to_remove.push(work_dir_abs_path.clone());
5006                }
5007            }
5008
5009            for key in repo_exclude_keys_to_remove {
5010                snapshot.repo_exclude_by_work_dir_abs_path.remove(&key);
5011            }
5012
5013            snapshot
5014                .ignores_by_parent_abs_path
5015                .retain(|parent_abs_path, (_, needs_update)| {
5016                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
5017                        && let Some(parent_path) =
5018                            RelPath::new(&parent_path, PathStyle::local()).log_err()
5019                    {
5020                        if *needs_update {
5021                            *needs_update = false;
5022                            if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
5023                                ignores_to_update.push(parent_abs_path.clone());
5024                            }
5025                        }
5026
5027                        let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
5028                        if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
5029                            return false;
5030                        }
5031                    }
5032                    true
5033                });
5034        }
5035
5036        // Load gitignores asynchronously (outside the lock)
5037        let mut loaded_excludes: Vec<(Arc<Path>, Arc<Gitignore>)> = Vec::new();
5038        for (work_dir_abs_path, exclude_abs_path) in excludes_to_load {
5039            if let Ok(current_exclude) = build_gitignore(&exclude_abs_path, self.fs.as_ref()).await
5040            {
5041                loaded_excludes.push((work_dir_abs_path, Arc::new(current_exclude)));
5042            }
5043        }
5044
5045        // Second pass: apply updates.
5046        if !loaded_excludes.is_empty() {
5047            let snapshot = &mut self.state.lock().await.snapshot;
5048
5049            for (work_dir_abs_path, exclude) in loaded_excludes {
5050                if let Some((existing_exclude, _)) = snapshot
5051                    .repo_exclude_by_work_dir_abs_path
5052                    .get_mut(&work_dir_abs_path)
5053                {
5054                    *existing_exclude = exclude;
5055                }
5056            }
5057        }
5058
5059        ignores_to_update
5060    }
5061
5062    async fn order_ignores(&self, mut ignores: Vec<Arc<Path>>) -> Vec<(Arc<Path>, IgnoreStack)> {
5063        let fs = self.fs.clone();
5064        let snapshot = self.state.lock().await.snapshot.clone();
5065        ignores.sort_unstable();
5066        let mut ignores_to_update = ignores.into_iter().peekable();
5067
5068        let mut result = vec![];
5069        while let Some(parent_abs_path) = ignores_to_update.next() {
5070            while ignores_to_update
5071                .peek()
5072                .map_or(false, |p| p.starts_with(&parent_abs_path))
5073            {
5074                ignores_to_update.next().unwrap();
5075            }
5076            let ignore_stack = snapshot
5077                .ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref())
5078                .await;
5079            result.push((parent_abs_path, ignore_stack));
5080        }
5081
5082        result
5083    }
5084
5085    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
5086        log::trace!("update ignore status {:?}", job.abs_path);
5087
5088        let mut ignore_stack = job.ignore_stack;
5089        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
5090            ignore_stack =
5091                ignore_stack.append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
5092        }
5093
5094        let mut entries_by_id_edits = Vec::new();
5095        let mut entries_by_path_edits = Vec::new();
5096        let Some(path) = job
5097            .abs_path
5098            .strip_prefix(snapshot.abs_path.as_path())
5099            .map_err(|_| {
5100                anyhow::anyhow!(
5101                    "Failed to strip prefix '{}' from path '{}'",
5102                    snapshot.abs_path.as_path().display(),
5103                    job.abs_path.display()
5104                )
5105            })
5106            .log_err()
5107        else {
5108            return;
5109        };
5110
5111        let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
5112            return;
5113        };
5114
5115        if let Ok(Some(metadata)) = self.fs.metadata(&job.abs_path.join(DOT_GIT)).await
5116            && metadata.is_dir
5117        {
5118            ignore_stack.repo_root = Some(job.abs_path.clone());
5119        }
5120
5121        for mut entry in snapshot.child_entries(&path).cloned() {
5122            let was_ignored = entry.is_ignored;
5123            let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
5124            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
5125
5126            if entry.is_dir() {
5127                let child_ignore_stack = if entry.is_ignored {
5128                    IgnoreStack::all()
5129                } else {
5130                    ignore_stack.clone()
5131                };
5132
5133                // Scan any directories that were previously ignored and weren't previously scanned.
5134                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
5135                    let state = self.state.lock().await;
5136                    if state.should_scan_directory(&entry) {
5137                        state
5138                            .enqueue_scan_dir(
5139                                abs_path.clone(),
5140                                &entry,
5141                                &job.scan_queue,
5142                                self.fs.as_ref(),
5143                            )
5144                            .await;
5145                    }
5146                }
5147
5148                job.ignore_queue
5149                    .send(UpdateIgnoreStatusJob {
5150                        abs_path: abs_path.clone(),
5151                        ignore_stack: child_ignore_stack,
5152                        ignore_queue: job.ignore_queue.clone(),
5153                        scan_queue: job.scan_queue.clone(),
5154                    })
5155                    .await
5156                    .unwrap();
5157            }
5158
5159            if entry.is_ignored != was_ignored {
5160                let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
5161                path_entry.scan_id = snapshot.scan_id;
5162                path_entry.is_ignored = entry.is_ignored;
5163                entries_by_id_edits.push(Edit::Insert(path_entry));
5164                entries_by_path_edits.push(Edit::Insert(entry));
5165            }
5166        }
5167
5168        let state = &mut self.state.lock().await;
5169        for edit in &entries_by_path_edits {
5170            if let Edit::Insert(entry) = edit
5171                && let Err(ix) = state.changed_paths.binary_search(&entry.path)
5172            {
5173                state.changed_paths.insert(ix, entry.path.clone());
5174            }
5175        }
5176
5177        state
5178            .snapshot
5179            .entries_by_path
5180            .edit(entries_by_path_edits, ());
5181        state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
5182    }
5183
5184    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
5185        log::trace!("reloading repositories: {dot_git_paths:?}");
5186        let mut state = self.state.lock().await;
5187        let scan_id = state.snapshot.scan_id;
5188        let mut affected_repo_roots = Vec::new();
5189        for dot_git_dir in dot_git_paths {
5190            let existing_repository_entry =
5191                state
5192                    .snapshot
5193                    .git_repositories
5194                    .iter()
5195                    .find_map(|(_, repo)| {
5196                        let dot_git_dir = SanitizedPath::new(&dot_git_dir);
5197                        if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
5198                            || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
5199                                == dot_git_dir
5200                        {
5201                            Some(repo.clone())
5202                        } else {
5203                            None
5204                        }
5205                    });
5206
5207            match existing_repository_entry {
5208                None => {
5209                    let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
5210                        debug_panic!(
5211                            "update_git_repositories called with .git directory outside the worktree root"
5212                        );
5213                        return Vec::new();
5214                    };
5215                    affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
5216                    state
5217                        .insert_git_repository(
5218                            RelPath::new(relative, PathStyle::local())
5219                                .unwrap()
5220                                .into_arc(),
5221                            self.fs.as_ref(),
5222                            self.watcher.as_ref(),
5223                        )
5224                        .await;
5225                }
5226                Some(local_repository) => {
5227                    state.snapshot.git_repositories.update(
5228                        &local_repository.work_directory_id,
5229                        |entry| {
5230                            entry.git_dir_scan_id = scan_id;
5231                        },
5232                    );
5233                }
5234            };
5235        }
5236
5237        // Remove any git repositories whose .git entry no longer exists.
5238        let snapshot = &mut state.snapshot;
5239        let mut ids_to_preserve = HashSet::default();
5240        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5241            let exists_in_snapshot =
5242                snapshot
5243                    .entry_for_id(work_directory_id)
5244                    .is_some_and(|entry| {
5245                        snapshot
5246                            .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
5247                            .is_some()
5248                    });
5249
5250            if exists_in_snapshot
5251                || matches!(
5252                    self.fs.metadata(&entry.common_dir_abs_path).await,
5253                    Ok(Some(_))
5254                )
5255            {
5256                ids_to_preserve.insert(work_directory_id);
5257            }
5258        }
5259
5260        snapshot
5261            .git_repositories
5262            .retain(|work_directory_id, entry| {
5263                let preserve = ids_to_preserve.contains(work_directory_id);
5264                if !preserve {
5265                    affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
5266                    snapshot
5267                        .repo_exclude_by_work_dir_abs_path
5268                        .remove(&entry.work_directory_abs_path);
5269                }
5270                preserve
5271            });
5272
5273        affected_repo_roots
5274    }
5275
5276    async fn progress_timer(&self, running: bool) {
5277        if !running {
5278            return futures::future::pending().await;
5279        }
5280
5281        #[cfg(feature = "test-support")]
5282        if self.fs.is_fake() {
5283            return self.executor.simulate_random_delay().await;
5284        }
5285
5286        self.executor.timer(FS_WATCH_LATENCY).await
5287    }
5288
5289    fn is_path_private(&self, path: &RelPath) -> bool {
5290        !self.share_private_files && self.settings.is_path_private(path)
5291    }
5292
5293    async fn next_scan_request(&self) -> Result<ScanRequest> {
5294        let mut request = self.scan_requests_rx.recv().await?;
5295        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5296            request.relative_paths.extend(next_request.relative_paths);
5297            request.done.extend(next_request.done);
5298        }
5299        Ok(request)
5300    }
5301}
5302
5303async fn discover_ancestor_git_repo(
5304    fs: Arc<dyn Fs>,
5305    root_abs_path: &SanitizedPath,
5306) -> (
5307    HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
5308    Option<Arc<Gitignore>>,
5309    Option<(PathBuf, WorkDirectory)>,
5310) {
5311    let mut exclude = None;
5312    let mut ignores = HashMap::default();
5313    for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
5314        if index != 0 {
5315            if ancestor == paths::home_dir() {
5316                // Unless $HOME is itself the worktree root, don't consider it as a
5317                // containing git repository---expensive and likely unwanted.
5318                break;
5319            } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
5320            {
5321                ignores.insert(ancestor.into(), (ignore.into(), false));
5322            }
5323        }
5324
5325        let ancestor_dot_git = ancestor.join(DOT_GIT);
5326        log::trace!("considering ancestor: {ancestor_dot_git:?}");
5327        // Check whether the directory or file called `.git` exists (in the
5328        // case of worktrees it's a file.)
5329        if fs
5330            .metadata(&ancestor_dot_git)
5331            .await
5332            .is_ok_and(|metadata| metadata.is_some())
5333        {
5334            if index != 0 {
5335                // We canonicalize, since the FS events use the canonicalized path.
5336                if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
5337                    let location_in_repo = root_abs_path
5338                        .as_path()
5339                        .strip_prefix(ancestor)
5340                        .unwrap()
5341                        .into();
5342                    log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
5343                    // We associate the external git repo with our root folder and
5344                    // also mark where in the git repo the root folder is located.
5345                    return (
5346                        ignores,
5347                        exclude,
5348                        Some((
5349                            ancestor_dot_git,
5350                            WorkDirectory::AboveProject {
5351                                absolute_path: ancestor.into(),
5352                                location_in_repo,
5353                            },
5354                        )),
5355                    );
5356                };
5357            }
5358
5359            let repo_exclude_abs_path = ancestor_dot_git.join(REPO_EXCLUDE);
5360            if let Ok(repo_exclude) = build_gitignore(&repo_exclude_abs_path, fs.as_ref()).await {
5361                exclude = Some(Arc::new(repo_exclude));
5362            }
5363
5364            // Reached root of git repository.
5365            break;
5366        }
5367    }
5368
5369    (ignores, exclude, None)
5370}
5371
5372fn merge_event_roots(changed_paths: &[Arc<RelPath>], event_roots: &[EventRoot]) -> Vec<EventRoot> {
5373    let mut merged_event_roots = Vec::with_capacity(changed_paths.len() + event_roots.len());
5374    let mut changed_paths = changed_paths.iter().peekable();
5375    let mut event_roots = event_roots.iter().peekable();
5376    while let (Some(path), Some(event_root)) = (changed_paths.peek(), event_roots.peek()) {
5377        match path.cmp(&&event_root.path) {
5378            Ordering::Less => {
5379                merged_event_roots.push(EventRoot {
5380                    path: (*changed_paths.next().expect("peeked changed path")).clone(),
5381                    was_rescanned: false,
5382                });
5383            }
5384            Ordering::Equal => {
5385                merged_event_roots.push((*event_roots.next().expect("peeked event root")).clone());
5386                changed_paths.next();
5387            }
5388            Ordering::Greater => {
5389                merged_event_roots.push((*event_roots.next().expect("peeked event root")).clone());
5390            }
5391        }
5392    }
5393    merged_event_roots.extend(changed_paths.map(|path| EventRoot {
5394        path: path.clone(),
5395        was_rescanned: false,
5396    }));
5397    merged_event_roots.extend(event_roots.cloned());
5398    merged_event_roots
5399}
5400
5401fn build_diff(
5402    phase: BackgroundScannerPhase,
5403    old_snapshot: &Snapshot,
5404    new_snapshot: &Snapshot,
5405    event_roots: &[EventRoot],
5406) -> UpdatedEntriesSet {
5407    use BackgroundScannerPhase::*;
5408    use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5409
5410    // Identify which paths have changed. Use the known set of changed
5411    // parent paths to optimize the search.
5412    let mut changes = Vec::new();
5413
5414    let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
5415    let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
5416    let mut last_newly_loaded_dir_path = None;
5417    old_paths.next();
5418    new_paths.next();
5419    for event_root in event_roots {
5420        let path = PathKey(event_root.path.clone());
5421        if old_paths.item().is_some_and(|e| e.path < path.0) {
5422            old_paths.seek_forward(&path, Bias::Left);
5423        }
5424        if new_paths.item().is_some_and(|e| e.path < path.0) {
5425            new_paths.seek_forward(&path, Bias::Left);
5426        }
5427        loop {
5428            match (old_paths.item(), new_paths.item()) {
5429                (Some(old_entry), Some(new_entry)) => {
5430                    if old_entry.path > path.0
5431                        && new_entry.path > path.0
5432                        && !old_entry.path.starts_with(&path.0)
5433                        && !new_entry.path.starts_with(&path.0)
5434                    {
5435                        break;
5436                    }
5437
5438                    match Ord::cmp(&old_entry.path, &new_entry.path) {
5439                        Ordering::Less => {
5440                            changes.push((old_entry.path.clone(), old_entry.id, Removed));
5441                            old_paths.next();
5442                        }
5443                        Ordering::Equal => {
5444                            if phase == EventsReceivedDuringInitialScan {
5445                                if old_entry.id != new_entry.id {
5446                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5447                                }
5448                                // If the worktree was not fully initialized when this event was generated,
5449                                // we can't know whether this entry was added during the scan or whether
5450                                // it was merely updated.
5451                                changes.push((
5452                                    new_entry.path.clone(),
5453                                    new_entry.id,
5454                                    AddedOrUpdated,
5455                                ));
5456                            } else if old_entry.id != new_entry.id {
5457                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
5458                                changes.push((new_entry.path.clone(), new_entry.id, Added));
5459                            } else if old_entry != new_entry {
5460                                if old_entry.kind.is_unloaded() {
5461                                    last_newly_loaded_dir_path = Some(&new_entry.path);
5462                                    changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5463                                } else {
5464                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
5465                                }
5466                            } else if event_root.was_rescanned {
5467                                changes.push((new_entry.path.clone(), new_entry.id, Updated));
5468                            }
5469                            old_paths.next();
5470                            new_paths.next();
5471                        }
5472                        Ordering::Greater => {
5473                            let is_newly_loaded = phase == InitialScan
5474                                || last_newly_loaded_dir_path
5475                                    .as_ref()
5476                                    .is_some_and(|dir| new_entry.path.starts_with(dir));
5477                            changes.push((
5478                                new_entry.path.clone(),
5479                                new_entry.id,
5480                                if is_newly_loaded { Loaded } else { Added },
5481                            ));
5482                            new_paths.next();
5483                        }
5484                    }
5485                }
5486                (Some(old_entry), None) => {
5487                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5488                    old_paths.next();
5489                }
5490                (None, Some(new_entry)) => {
5491                    let is_newly_loaded = phase == InitialScan
5492                        || last_newly_loaded_dir_path
5493                            .as_ref()
5494                            .is_some_and(|dir| new_entry.path.starts_with(dir));
5495                    changes.push((
5496                        new_entry.path.clone(),
5497                        new_entry.id,
5498                        if is_newly_loaded { Loaded } else { Added },
5499                    ));
5500                    new_paths.next();
5501                }
5502                (None, None) => break,
5503            }
5504        }
5505    }
5506
5507    changes.into()
5508}
5509
5510fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
5511    let position = child_paths
5512        .iter()
5513        .position(|path| path.file_name().unwrap() == file);
5514    if let Some(position) = position {
5515        let temp = child_paths.remove(position);
5516        child_paths.insert(0, temp);
5517    }
5518}
5519
5520fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
5521    let mut result = root_char_bag;
5522    result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
5523    result
5524}
5525
5526#[derive(Debug)]
5527struct ScanJob {
5528    abs_path: Arc<Path>,
5529    path: Arc<RelPath>,
5530    ignore_stack: IgnoreStack,
5531    scan_queue: Sender<ScanJob>,
5532    ancestor_inodes: TreeSet<u64>,
5533    is_external: bool,
5534}
5535
5536struct UpdateIgnoreStatusJob {
5537    abs_path: Arc<Path>,
5538    ignore_stack: IgnoreStack,
5539    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5540    scan_queue: Sender<ScanJob>,
5541}
5542
5543pub trait WorktreeModelHandle {
5544    #[cfg(feature = "test-support")]
5545    fn flush_fs_events<'a>(
5546        &self,
5547        cx: &'a mut gpui::TestAppContext,
5548    ) -> futures::future::LocalBoxFuture<'a, ()>;
5549
5550    #[cfg(feature = "test-support")]
5551    fn flush_fs_events_in_root_git_repository<'a>(
5552        &self,
5553        cx: &'a mut gpui::TestAppContext,
5554    ) -> futures::future::LocalBoxFuture<'a, ()>;
5555}
5556
5557impl WorktreeModelHandle for Entity<Worktree> {
5558    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5559    // occurred before the worktree was constructed. These events can cause the worktree to perform
5560    // extra directory scans, and emit extra scan-state notifications.
5561    //
5562    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5563    // to ensure that all redundant FS events have already been processed.
5564    #[cfg(feature = "test-support")]
5565    fn flush_fs_events<'a>(
5566        &self,
5567        cx: &'a mut gpui::TestAppContext,
5568    ) -> futures::future::LocalBoxFuture<'a, ()> {
5569        let file_name = "fs-event-sentinel";
5570
5571        let tree = self.clone();
5572        let (fs, root_path) = self.read_with(cx, |tree, _| {
5573            let tree = tree.as_local().unwrap();
5574            (tree.fs.clone(), tree.abs_path.clone())
5575        });
5576
5577        async move {
5578            // Subscribe to events BEFORE creating the file to avoid race condition
5579            // where events fire before subscription is set up
5580            let mut events = cx.events(&tree);
5581
5582            fs.create_file(&root_path.join(file_name), Default::default())
5583                .await
5584                .unwrap();
5585
5586            // Check if condition is already met before waiting for events
5587            let file_exists = || {
5588                tree.read_with(cx, |tree, _| {
5589                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5590                        .is_some()
5591                })
5592            };
5593
5594            // Use select to avoid blocking indefinitely if events are delayed
5595            while !file_exists() {
5596                futures::select_biased! {
5597                    _ = events.next() => {}
5598                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5599                }
5600            }
5601
5602            fs.remove_file(&root_path.join(file_name), Default::default())
5603                .await
5604                .unwrap();
5605
5606            // Check if condition is already met before waiting for events
5607            let file_gone = || {
5608                tree.read_with(cx, |tree, _| {
5609                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5610                        .is_none()
5611                })
5612            };
5613
5614            // Use select to avoid blocking indefinitely if events are delayed
5615            while !file_gone() {
5616                futures::select_biased! {
5617                    _ = events.next() => {}
5618                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5619                }
5620            }
5621
5622            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5623                .await;
5624        }
5625        .boxed_local()
5626    }
5627
5628    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5629    // the .git folder of the root repository.
5630    // The reason for its existence is that a repository's .git folder might live *outside* of the
5631    // worktree and thus its FS events might go through a different path.
5632    // In order to flush those, we need to create artificial events in the .git folder and wait
5633    // for the repository to be reloaded.
5634    #[cfg(feature = "test-support")]
5635    fn flush_fs_events_in_root_git_repository<'a>(
5636        &self,
5637        cx: &'a mut gpui::TestAppContext,
5638    ) -> futures::future::LocalBoxFuture<'a, ()> {
5639        let file_name = "fs-event-sentinel";
5640
5641        let tree = self.clone();
5642        let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5643            let tree = tree.as_local().unwrap();
5644            let local_repo_entry = tree
5645                .git_repositories
5646                .values()
5647                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5648                .unwrap();
5649            (
5650                tree.fs.clone(),
5651                local_repo_entry.common_dir_abs_path.clone(),
5652                local_repo_entry.git_dir_scan_id,
5653            )
5654        });
5655
5656        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5657            let tree = tree.as_local().unwrap();
5658            // let repository = tree.repositories.first().unwrap();
5659            let local_repo_entry = tree
5660                .git_repositories
5661                .values()
5662                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5663                .unwrap();
5664
5665            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5666                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5667                true
5668            } else {
5669                false
5670            }
5671        };
5672
5673        async move {
5674            // Subscribe to events BEFORE creating the file to avoid race condition
5675            // where events fire before subscription is set up
5676            let mut events = cx.events(&tree);
5677
5678            fs.create_file(&root_path.join(file_name), Default::default())
5679                .await
5680                .unwrap();
5681
5682            // Use select to avoid blocking indefinitely if events are delayed
5683            while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5684                futures::select_biased! {
5685                    _ = events.next() => {}
5686                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5687                }
5688            }
5689
5690            fs.remove_file(&root_path.join(file_name), Default::default())
5691                .await
5692                .unwrap();
5693
5694            // Use select to avoid blocking indefinitely if events are delayed
5695            while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5696                futures::select_biased! {
5697                    _ = events.next() => {}
5698                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5699                }
5700            }
5701
5702            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5703                .await;
5704        }
5705        .boxed_local()
5706    }
5707}
5708
5709#[derive(Clone, Debug)]
5710struct TraversalProgress<'a> {
5711    max_path: &'a RelPath,
5712    count: usize,
5713    non_ignored_count: usize,
5714    file_count: usize,
5715    non_ignored_file_count: usize,
5716}
5717
5718impl TraversalProgress<'_> {
5719    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5720        match (include_files, include_dirs, include_ignored) {
5721            (true, true, true) => self.count,
5722            (true, true, false) => self.non_ignored_count,
5723            (true, false, true) => self.file_count,
5724            (true, false, false) => self.non_ignored_file_count,
5725            (false, true, true) => self.count - self.file_count,
5726            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5727            (false, false, _) => 0,
5728        }
5729    }
5730}
5731
5732impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5733    fn zero(_cx: ()) -> Self {
5734        Default::default()
5735    }
5736
5737    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5738        self.max_path = summary.max_path.as_ref();
5739        self.count += summary.count;
5740        self.non_ignored_count += summary.non_ignored_count;
5741        self.file_count += summary.file_count;
5742        self.non_ignored_file_count += summary.non_ignored_file_count;
5743    }
5744}
5745
5746impl Default for TraversalProgress<'_> {
5747    fn default() -> Self {
5748        Self {
5749            max_path: RelPath::empty(),
5750            count: 0,
5751            non_ignored_count: 0,
5752            file_count: 0,
5753            non_ignored_file_count: 0,
5754        }
5755    }
5756}
5757
5758#[derive(Debug)]
5759pub struct Traversal<'a> {
5760    snapshot: &'a Snapshot,
5761    cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5762    include_ignored: bool,
5763    include_files: bool,
5764    include_dirs: bool,
5765}
5766
5767impl<'a> Traversal<'a> {
5768    fn new(
5769        snapshot: &'a Snapshot,
5770        include_files: bool,
5771        include_dirs: bool,
5772        include_ignored: bool,
5773        start_path: &RelPath,
5774    ) -> Self {
5775        let mut cursor = snapshot.entries_by_path.cursor(());
5776        cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5777        let mut traversal = Self {
5778            snapshot,
5779            cursor,
5780            include_files,
5781            include_dirs,
5782            include_ignored,
5783        };
5784        if traversal.end_offset() == traversal.start_offset() {
5785            traversal.next();
5786        }
5787        traversal
5788    }
5789
5790    pub fn advance(&mut self) -> bool {
5791        self.advance_by(1)
5792    }
5793
5794    pub fn advance_by(&mut self, count: usize) -> bool {
5795        self.cursor.seek_forward(
5796            &TraversalTarget::Count {
5797                count: self.end_offset() + count,
5798                include_dirs: self.include_dirs,
5799                include_files: self.include_files,
5800                include_ignored: self.include_ignored,
5801            },
5802            Bias::Left,
5803        )
5804    }
5805
5806    pub fn advance_to_sibling(&mut self) -> bool {
5807        while let Some(entry) = self.cursor.item() {
5808            self.cursor
5809                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5810            if let Some(entry) = self.cursor.item()
5811                && (self.include_files || !entry.is_file())
5812                && (self.include_dirs || !entry.is_dir())
5813                && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5814            {
5815                return true;
5816            }
5817        }
5818        false
5819    }
5820
5821    pub fn back_to_parent(&mut self) -> bool {
5822        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5823            return false;
5824        };
5825        self.cursor
5826            .seek(&TraversalTarget::path(parent_path), Bias::Left)
5827    }
5828
5829    pub fn entry(&self) -> Option<&'a Entry> {
5830        self.cursor.item()
5831    }
5832
5833    pub fn snapshot(&self) -> &'a Snapshot {
5834        self.snapshot
5835    }
5836
5837    pub fn start_offset(&self) -> usize {
5838        self.cursor
5839            .start()
5840            .count(self.include_files, self.include_dirs, self.include_ignored)
5841    }
5842
5843    pub fn end_offset(&self) -> usize {
5844        self.cursor
5845            .end()
5846            .count(self.include_files, self.include_dirs, self.include_ignored)
5847    }
5848}
5849
5850impl<'a> Iterator for Traversal<'a> {
5851    type Item = &'a Entry;
5852
5853    fn next(&mut self) -> Option<Self::Item> {
5854        if let Some(item) = self.entry() {
5855            self.advance();
5856            Some(item)
5857        } else {
5858            None
5859        }
5860    }
5861}
5862
5863#[derive(Debug, Clone, Copy)]
5864pub enum PathTarget<'a> {
5865    Path(&'a RelPath),
5866    Successor(&'a RelPath),
5867}
5868
5869impl PathTarget<'_> {
5870    fn cmp_path(&self, other: &RelPath) -> Ordering {
5871        match self {
5872            PathTarget::Path(path) => path.cmp(&other),
5873            PathTarget::Successor(path) => {
5874                if other.starts_with(path) {
5875                    Ordering::Greater
5876                } else {
5877                    Ordering::Equal
5878                }
5879            }
5880        }
5881    }
5882}
5883
5884impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5885    fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5886        self.cmp_path(cursor_location.max_path)
5887    }
5888}
5889
5890impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5891    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5892        self.cmp_path(cursor_location.max_path)
5893    }
5894}
5895
5896#[derive(Debug)]
5897enum TraversalTarget<'a> {
5898    Path(PathTarget<'a>),
5899    Count {
5900        count: usize,
5901        include_files: bool,
5902        include_ignored: bool,
5903        include_dirs: bool,
5904    },
5905}
5906
5907impl<'a> TraversalTarget<'a> {
5908    fn path(path: &'a RelPath) -> Self {
5909        Self::Path(PathTarget::Path(path))
5910    }
5911
5912    fn successor(path: &'a RelPath) -> Self {
5913        Self::Path(PathTarget::Successor(path))
5914    }
5915
5916    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5917        match self {
5918            TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5919            TraversalTarget::Count {
5920                count,
5921                include_files,
5922                include_dirs,
5923                include_ignored,
5924            } => Ord::cmp(
5925                count,
5926                &progress.count(*include_files, *include_dirs, *include_ignored),
5927            ),
5928        }
5929    }
5930}
5931
5932impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5933    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5934        self.cmp_progress(cursor_location)
5935    }
5936}
5937
5938impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5939    for TraversalTarget<'_>
5940{
5941    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5942        self.cmp_progress(cursor_location)
5943    }
5944}
5945
5946pub struct ChildEntriesOptions {
5947    pub include_files: bool,
5948    pub include_dirs: bool,
5949    pub include_ignored: bool,
5950}
5951
5952pub struct ChildEntriesIter<'a> {
5953    parent_path: &'a RelPath,
5954    traversal: Traversal<'a>,
5955}
5956
5957impl<'a> Iterator for ChildEntriesIter<'a> {
5958    type Item = &'a Entry;
5959
5960    fn next(&mut self) -> Option<Self::Item> {
5961        if let Some(item) = self.traversal.entry()
5962            && item.path.starts_with(self.parent_path)
5963        {
5964            self.traversal.advance_to_sibling();
5965            return Some(item);
5966        }
5967        None
5968    }
5969}
5970
5971impl<'a> From<&'a Entry> for proto::Entry {
5972    fn from(entry: &'a Entry) -> Self {
5973        Self {
5974            id: entry.id.to_proto(),
5975            is_dir: entry.is_dir(),
5976            path: entry.path.as_ref().to_proto(),
5977            inode: entry.inode,
5978            mtime: entry.mtime.map(|time| time.into()),
5979            is_ignored: entry.is_ignored,
5980            is_hidden: entry.is_hidden,
5981            is_external: entry.is_external,
5982            is_fifo: entry.is_fifo,
5983            size: Some(entry.size),
5984            canonical_path: entry
5985                .canonical_path
5986                .as_ref()
5987                .map(|path| path.to_string_lossy().into_owned()),
5988        }
5989    }
5990}
5991
5992impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5993    type Error = anyhow::Error;
5994
5995    fn try_from(
5996        (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5997    ) -> Result<Self> {
5998        let kind = if entry.is_dir {
5999            EntryKind::Dir
6000        } else {
6001            EntryKind::File
6002        };
6003
6004        let path =
6005            RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
6006        let char_bag = char_bag_for_path(*root_char_bag, &path);
6007        let is_always_included = always_included.is_match(&path);
6008        Ok(Entry {
6009            id: ProjectEntryId::from_proto(entry.id),
6010            kind,
6011            path,
6012            inode: entry.inode,
6013            mtime: entry.mtime.map(|time| time.into()),
6014            size: entry.size.unwrap_or(0),
6015            canonical_path: entry
6016                .canonical_path
6017                .map(|path_string| Arc::from(PathBuf::from(path_string))),
6018            is_ignored: entry.is_ignored,
6019            is_hidden: entry.is_hidden,
6020            is_always_included,
6021            is_external: entry.is_external,
6022            is_private: false,
6023            char_bag,
6024            is_fifo: entry.is_fifo,
6025        })
6026    }
6027}
6028
6029#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
6030pub struct ProjectEntryId(usize);
6031
6032impl ProjectEntryId {
6033    pub const MAX: Self = Self(usize::MAX);
6034    pub const MIN: Self = Self(usize::MIN);
6035
6036    pub fn new(counter: &AtomicUsize) -> Self {
6037        Self(counter.fetch_add(1, SeqCst))
6038    }
6039
6040    pub fn from_proto(id: u64) -> Self {
6041        Self(id as usize)
6042    }
6043
6044    pub fn to_proto(self) -> u64 {
6045        self.0 as u64
6046    }
6047
6048    pub fn from_usize(id: usize) -> Self {
6049        ProjectEntryId(id)
6050    }
6051
6052    pub fn to_usize(self) -> usize {
6053        self.0
6054    }
6055}
6056
6057#[cfg(feature = "test-support")]
6058impl CreatedEntry {
6059    pub fn into_included(self) -> Option<Entry> {
6060        match self {
6061            CreatedEntry::Included(entry) => Some(entry),
6062            CreatedEntry::Excluded { .. } => None,
6063        }
6064    }
6065}
6066
6067fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
6068    let path = content
6069        .strip_prefix("gitdir:")
6070        .with_context(|| format!("parsing gitfile content {content:?}"))?;
6071    Ok(Path::new(path.trim()))
6072}
6073
6074async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
6075    let mut repository_dir_abs_path = dot_git_abs_path.clone();
6076    let mut common_dir_abs_path = dot_git_abs_path.clone();
6077
6078    if let Some(path) = fs
6079        .load(dot_git_abs_path)
6080        .await
6081        .ok()
6082        .as_ref()
6083        .and_then(|contents| parse_gitfile(contents).log_err())
6084    {
6085        let path = dot_git_abs_path
6086            .parent()
6087            .unwrap_or(Path::new(""))
6088            .join(path);
6089        if let Some(path) = fs.canonicalize(&path).await.log_err() {
6090            repository_dir_abs_path = Path::new(&path).into();
6091            common_dir_abs_path = repository_dir_abs_path.clone();
6092
6093            if let Some(commondir_contents) = fs.load(&path.join("commondir")).await.ok()
6094                && let Some(commondir_path) = fs
6095                    .canonicalize(&path.join(commondir_contents.trim()))
6096                    .await
6097                    .log_err()
6098            {
6099                common_dir_abs_path = commondir_path.as_path().into();
6100            }
6101        }
6102    };
6103    (repository_dir_abs_path, common_dir_abs_path)
6104}
6105
6106struct NullWatcher;
6107
6108impl fs::Watcher for NullWatcher {
6109    fn add(&self, _path: &Path) -> Result<()> {
6110        Ok(())
6111    }
6112
6113    fn remove(&self, _path: &Path) -> Result<()> {
6114        Ok(())
6115    }
6116}
6117
6118const FILE_ANALYSIS_BYTES: usize = 1024;
6119
6120async fn decode_file_text(
6121    fs: &dyn Fs,
6122    abs_path: &Path,
6123) -> Result<(String, &'static Encoding, bool)> {
6124    let mut file = fs
6125        .open_sync(&abs_path)
6126        .await
6127        .with_context(|| format!("opening file {abs_path:?}"))?;
6128
6129    // First, read the beginning of the file to determine its kind and encoding.
6130    // We do not want to load an entire large blob into memory only to discard it.
6131    let mut file_first_bytes = Vec::with_capacity(FILE_ANALYSIS_BYTES);
6132    let mut buf = [0u8; FILE_ANALYSIS_BYTES];
6133    let mut reached_eof = false;
6134    loop {
6135        if file_first_bytes.len() >= FILE_ANALYSIS_BYTES {
6136            break;
6137        }
6138        let n = file
6139            .read(&mut buf)
6140            .with_context(|| format!("reading bytes of the file {abs_path:?}"))?;
6141        if n == 0 {
6142            reached_eof = true;
6143            break;
6144        }
6145        file_first_bytes.extend_from_slice(&buf[..n]);
6146    }
6147    let (bom_encoding, byte_content) = decode_byte_header(&file_first_bytes);
6148    anyhow::ensure!(
6149        byte_content != ByteContent::Binary,
6150        "Binary files are not supported"
6151    );
6152
6153    // If the file is eligible for opening, read the rest of the file.
6154    let mut content = file_first_bytes;
6155    if !reached_eof {
6156        let mut buf = [0u8; 8 * 1024];
6157        loop {
6158            let n = file
6159                .read(&mut buf)
6160                .with_context(|| format!("reading remaining bytes of the file {abs_path:?}"))?;
6161            if n == 0 {
6162                break;
6163            }
6164            content.extend_from_slice(&buf[..n]);
6165        }
6166    }
6167    decode_byte_full(content, bom_encoding, byte_content)
6168}
6169
6170fn decode_byte_header(prefix: &[u8]) -> (Option<&'static Encoding>, ByteContent) {
6171    if let Some((encoding, _bom_len)) = Encoding::for_bom(prefix) {
6172        return (Some(encoding), ByteContent::Unknown);
6173    }
6174    (None, analyze_byte_content(prefix))
6175}
6176
6177fn decode_byte_full(
6178    bytes: Vec<u8>,
6179    bom_encoding: Option<&'static Encoding>,
6180    byte_content: ByteContent,
6181) -> Result<(String, &'static Encoding, bool)> {
6182    if let Some(encoding) = bom_encoding {
6183        let (cow, _) = encoding.decode_with_bom_removal(&bytes);
6184        return Ok((cow.into_owned(), encoding, true));
6185    }
6186
6187    match byte_content {
6188        ByteContent::Utf16Le => {
6189            let encoding = encoding_rs::UTF_16LE;
6190            let (cow, _, _) = encoding.decode(&bytes);
6191            return Ok((cow.into_owned(), encoding, false));
6192        }
6193        ByteContent::Utf16Be => {
6194            let encoding = encoding_rs::UTF_16BE;
6195            let (cow, _, _) = encoding.decode(&bytes);
6196            return Ok((cow.into_owned(), encoding, false));
6197        }
6198        ByteContent::Binary => {
6199            anyhow::bail!("Binary files are not supported");
6200        }
6201        ByteContent::Unknown => {}
6202    }
6203
6204    fn detect_encoding(bytes: Vec<u8>) -> (String, &'static Encoding) {
6205        let mut detector = EncodingDetector::new();
6206        detector.feed(&bytes, true);
6207
6208        let encoding = detector.guess(None, true); // Use None for TLD hint to ensure neutral detection logic.
6209
6210        let (cow, _, _) = encoding.decode(&bytes);
6211        (cow.into_owned(), encoding)
6212    }
6213
6214    match String::from_utf8(bytes) {
6215        Ok(text) => {
6216            // ISO-2022-JP (and other ISO-2022 variants) consists entirely of 7-bit ASCII bytes,
6217            // so it is valid UTF-8. However, it contains escape sequences starting with '\x1b'.
6218            // If we find an escape character, we double-check the encoding to prevent
6219            // displaying raw escape sequences instead of the correct characters.
6220            if text.contains('\x1b') {
6221                let (s, enc) = detect_encoding(text.into_bytes());
6222                Ok((s, enc, false))
6223            } else {
6224                Ok((text, encoding_rs::UTF_8, false))
6225            }
6226        }
6227        Err(e) => {
6228            let (s, enc) = detect_encoding(e.into_bytes());
6229            Ok((s, enc, false))
6230        }
6231    }
6232}
6233
6234#[derive(Debug, PartialEq)]
6235enum ByteContent {
6236    Utf16Le,
6237    Utf16Be,
6238    Binary,
6239    Unknown,
6240}
6241
6242// Heuristic check using null byte distribution plus a generic text-likeness
6243// heuristic. This prefers UTF-16 when many bytes are NUL and otherwise
6244// distinguishes between text-like and binary-like content.
6245fn analyze_byte_content(bytes: &[u8]) -> ByteContent {
6246    if bytes.len() < 2 {
6247        return ByteContent::Unknown;
6248    }
6249
6250    if is_known_binary_header(bytes) {
6251        return ByteContent::Binary;
6252    }
6253
6254    let limit = bytes.len().min(FILE_ANALYSIS_BYTES);
6255    let mut even_null_count = 0usize;
6256    let mut odd_null_count = 0usize;
6257    let mut non_text_like_count = 0usize;
6258
6259    for (i, &byte) in bytes[..limit].iter().enumerate() {
6260        if byte == 0 {
6261            if i % 2 == 0 {
6262                even_null_count += 1;
6263            } else {
6264                odd_null_count += 1;
6265            }
6266            non_text_like_count += 1;
6267            continue;
6268        }
6269
6270        let is_text_like = match byte {
6271            b'\t' | b'\n' | b'\r' | 0x0C => true,
6272            0x20..=0x7E => true,
6273            // Treat bytes that are likely part of UTF-8 or single-byte encodings as text-like.
6274            0x80..=0xBF | 0xC2..=0xF4 => true,
6275            _ => false,
6276        };
6277
6278        if !is_text_like {
6279            non_text_like_count += 1;
6280        }
6281    }
6282
6283    let total_null_count = even_null_count + odd_null_count;
6284
6285    // If there are no NUL bytes at all, this is overwhelmingly likely to be text.
6286    if total_null_count == 0 {
6287        return ByteContent::Unknown;
6288    }
6289
6290    let has_significant_nulls = total_null_count >= limit / 16;
6291    let nulls_skew_to_even = even_null_count > odd_null_count * 4;
6292    let nulls_skew_to_odd = odd_null_count > even_null_count * 4;
6293
6294    if has_significant_nulls {
6295        let sample = &bytes[..limit];
6296
6297        // UTF-16BE ASCII: [0x00, char] — nulls at even positions (high byte first)
6298        // UTF-16LE ASCII: [char, 0x00] — nulls at odd positions (low byte first)
6299
6300        if nulls_skew_to_even && is_plausible_utf16_text(sample, false) {
6301            return ByteContent::Utf16Be;
6302        }
6303
6304        if nulls_skew_to_odd && is_plausible_utf16_text(sample, true) {
6305            return ByteContent::Utf16Le;
6306        }
6307
6308        return ByteContent::Binary;
6309    }
6310
6311    if non_text_like_count * 100 < limit * 8 {
6312        ByteContent::Unknown
6313    } else {
6314        ByteContent::Binary
6315    }
6316}
6317
6318fn is_known_binary_header(bytes: &[u8]) -> bool {
6319    bytes.starts_with(b"%PDF-") // PDF
6320        || bytes.starts_with(b"PK\x03\x04") // ZIP local header
6321        || bytes.starts_with(b"PK\x05\x06") // ZIP end of central directory
6322        || bytes.starts_with(b"PK\x07\x08") // ZIP spanning/splitting
6323        || bytes.starts_with(b"\x89PNG\r\n\x1a\n") // PNG
6324        || bytes.starts_with(b"\xFF\xD8\xFF") // JPEG
6325        || bytes.starts_with(b"GIF87a") // GIF87a
6326        || bytes.starts_with(b"GIF89a") // GIF89a
6327        || bytes.starts_with(b"IWAD") // Doom IWAD archive
6328        || bytes.starts_with(b"PWAD") // Doom PWAD archive
6329        || bytes.starts_with(b"RIFF") // WAV, AVI, WebP
6330        || bytes.starts_with(b"OggS") // OGG (Vorbis, Opus, FLAC)
6331        || bytes.starts_with(b"fLaC") // FLAC
6332        || bytes.starts_with(b"ID3") // MP3 with ID3v2 tag
6333        || bytes.starts_with(b"\xFF\xFB") // MP3 frame sync (MPEG1 Layer3)
6334        || bytes.starts_with(b"\xFF\xFA") // MP3 frame sync (MPEG1 Layer3)
6335        || bytes.starts_with(b"\xFF\xF3") // MP3 frame sync (MPEG2 Layer3)
6336        || bytes.starts_with(b"\xFF\xF2") // MP3 frame sync (MPEG2 Layer3)
6337}
6338
6339// Null byte skew alone is not enough to identify UTF-16 -- binary formats with
6340// small 16-bit values (like PCM audio) produce the same pattern. Decode the
6341// bytes as UTF-16 and reject if too many code units land in control character
6342// ranges or form unpaired surrogates, which real text almost never contains.
6343fn is_plausible_utf16_text(bytes: &[u8], little_endian: bool) -> bool {
6344    let mut suspicious_count = 0usize;
6345    let mut total = 0usize;
6346
6347    let mut i = 0;
6348    while let Some(code_unit) = read_u16(bytes, i, little_endian) {
6349        total += 1;
6350
6351        match code_unit {
6352            0x0009 | 0x000A | 0x000C | 0x000D => {}
6353            // C0/C1 control characters and non-characters
6354            0x0000..=0x001F | 0x007F..=0x009F | 0xFFFE | 0xFFFF => suspicious_count += 1,
6355            0xD800..=0xDBFF => {
6356                let next_offset = i + 2;
6357                let has_low_surrogate = read_u16(bytes, next_offset, little_endian)
6358                    .is_some_and(|next| (0xDC00..=0xDFFF).contains(&next));
6359                if has_low_surrogate {
6360                    total += 1;
6361                    i += 2;
6362                } else {
6363                    suspicious_count += 1;
6364                }
6365            }
6366            // Lone low surrogate without a preceding high surrogate
6367            0xDC00..=0xDFFF => suspicious_count += 1,
6368            _ => {}
6369        }
6370
6371        i += 2;
6372    }
6373
6374    if total == 0 {
6375        return false;
6376    }
6377
6378    // Real UTF-16 text has near-zero control characters; binary data with
6379    // small 16-bit values typically exceeds 5%. 2% provides a safe margin.
6380    suspicious_count * 100 < total * 2
6381}
6382
6383fn read_u16(bytes: &[u8], offset: usize, little_endian: bool) -> Option<u16> {
6384    let pair = [*bytes.get(offset)?, *bytes.get(offset + 1)?];
6385    if little_endian {
6386        return Some(u16::from_le_bytes(pair));
6387    }
6388    Some(u16::from_be_bytes(pair))
6389}
6390
6391#[cfg(test)]
6392mod tests {
6393    use super::*;
6394
6395    /// reproduction of issue #50785
6396    fn build_pcm16_wav_bytes() -> Vec<u8> {
6397        let header: Vec<u8> = vec![
6398            /*  RIFF header  */
6399            0x52, 0x49, 0x46, 0x46, // "RIFF"
6400            0xc6, 0xcf, 0x00, 0x00, // file size: 8
6401            0x57, 0x41, 0x56, 0x45, // "WAVE"
6402            /*  fmt chunk  */
6403            0x66, 0x6d, 0x74, 0x20, // "fmt "
6404            0x10, 0x00, 0x00, 0x00, // chunk size: 16
6405            0x01, 0x00, // format: PCM (1)
6406            0x01, 0x00, // channels: 1 (mono)
6407            0x80, 0x3e, 0x00, 0x00, // sample rate: 16000
6408            0x00, 0x7d, 0x00, 0x00, // byte rate: 32000
6409            0x02, 0x00, // block align: 2
6410            0x10, 0x00, // bits per sample: 16
6411            /*  LIST chunk  */
6412            0x4c, 0x49, 0x53, 0x54, // "LIST"
6413            0x1a, 0x00, 0x00, 0x00, // chunk size: 26
6414            0x49, 0x4e, 0x46, 0x4f, // "INFO"
6415            0x49, 0x53, 0x46, 0x54, // "ISFT"
6416            0x0d, 0x00, 0x00, 0x00, // sub-chunk size: 13
6417            0x4c, 0x61, 0x76, 0x66, 0x36, 0x32, 0x2e, 0x33, // "Lavf62.3"
6418            0x2e, 0x31, 0x30, 0x30, 0x00, // ".100\0"
6419            /* padding byte for word alignment */
6420            0x00, // data chunk header
6421            0x64, 0x61, 0x74, 0x61, // "data"
6422            0x80, 0xcf, 0x00, 0x00, // chunk size
6423        ];
6424
6425        let mut bytes = header;
6426
6427        // fill remaining space up to `FILE_ANALYSIS_BYTES` with synthetic PCM
6428        let audio_bytes_needed = FILE_ANALYSIS_BYTES - bytes.len();
6429        for i in 0..(audio_bytes_needed / 2) {
6430            let sample = (i & 0xFF) as u8;
6431            bytes.push(sample); // low byte: varies
6432            bytes.push(0x00); // high byte: zero for small values
6433        }
6434
6435        bytes
6436    }
6437
6438    #[test]
6439    fn test_pcm16_wav_detected_as_binary() {
6440        let wav_bytes = build_pcm16_wav_bytes();
6441        assert_eq!(wav_bytes.len(), FILE_ANALYSIS_BYTES);
6442
6443        let result = analyze_byte_content(&wav_bytes);
6444        assert_eq!(
6445            result,
6446            ByteContent::Binary,
6447            "PCM 16-bit WAV should be detected as Binary via RIFF header"
6448        );
6449    }
6450
6451    #[test]
6452    fn test_le16_binary_not_misdetected_as_utf16le() {
6453        let mut bytes = b"FAKE".to_vec();
6454        while bytes.len() < FILE_ANALYSIS_BYTES {
6455            let sample = (bytes.len() & 0xFF) as u8;
6456            bytes.push(sample);
6457            bytes.push(0x00);
6458        }
6459        bytes.truncate(FILE_ANALYSIS_BYTES);
6460
6461        let result = analyze_byte_content(&bytes);
6462        assert_eq!(
6463            result,
6464            ByteContent::Binary,
6465            "LE 16-bit binary with control characters should be detected as Binary"
6466        );
6467    }
6468
6469    #[test]
6470    fn test_be16_binary_not_misdetected_as_utf16be() {
6471        let mut bytes = b"FAKE".to_vec();
6472        while bytes.len() < FILE_ANALYSIS_BYTES {
6473            bytes.push(0x00);
6474            let sample = (bytes.len() & 0xFF) as u8;
6475            bytes.push(sample);
6476        }
6477        bytes.truncate(FILE_ANALYSIS_BYTES);
6478
6479        let result = analyze_byte_content(&bytes);
6480        assert_eq!(
6481            result,
6482            ByteContent::Binary,
6483            "BE 16-bit binary with control characters should be detected as Binary"
6484        );
6485    }
6486
6487    #[test]
6488    fn test_utf16le_text_detected_as_utf16le() {
6489        let text = "Hello, world! This is a UTF-16 test string. ";
6490        let mut bytes = Vec::new();
6491        while bytes.len() < FILE_ANALYSIS_BYTES {
6492            bytes.extend(text.encode_utf16().flat_map(|u| u.to_le_bytes()));
6493        }
6494        bytes.truncate(FILE_ANALYSIS_BYTES);
6495
6496        assert_eq!(analyze_byte_content(&bytes), ByteContent::Utf16Le);
6497    }
6498
6499    #[test]
6500    fn test_utf16be_text_detected_as_utf16be() {
6501        let text = "Hello, world! This is a UTF-16 test string. ";
6502        let mut bytes = Vec::new();
6503        while bytes.len() < FILE_ANALYSIS_BYTES {
6504            bytes.extend(text.encode_utf16().flat_map(|u| u.to_be_bytes()));
6505        }
6506        bytes.truncate(FILE_ANALYSIS_BYTES);
6507
6508        assert_eq!(analyze_byte_content(&bytes), ByteContent::Utf16Be);
6509    }
6510
6511    #[test]
6512    fn test_known_binary_headers() {
6513        let cases: &[(&[u8], &str)] = &[
6514            (b"RIFF\x00\x00\x00\x00WAVE", "WAV"),
6515            (b"RIFF\x00\x00\x00\x00AVI ", "AVI"),
6516            (b"OggS\x00\x02", "OGG"),
6517            (b"fLaC\x00\x00", "FLAC"),
6518            (b"ID3\x03\x00", "MP3 ID3v2"),
6519            (b"\xFF\xFB\x90\x00", "MP3 MPEG1 Layer3"),
6520            (b"\xFF\xF3\x90\x00", "MP3 MPEG2 Layer3"),
6521        ];
6522
6523        for (header, label) in cases {
6524            let mut bytes = header.to_vec();
6525            bytes.resize(FILE_ANALYSIS_BYTES, 0x41); // pad with 'A'
6526            assert_eq!(
6527                analyze_byte_content(&bytes),
6528                ByteContent::Binary,
6529                "{label} should be detected as Binary"
6530            );
6531        }
6532    }
6533}