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