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