worktree.rs

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