worktree.rs

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