worktree.rs

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