worktree.rs

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