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