worktree.rs

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