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