worktree.rs

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