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