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_relative_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        watcher
3077            .add(&repository_dir_abs_path)
3078            .context("failed to add repository directory to watcher")
3079            .log_err();
3080
3081        let work_directory_id = work_dir_entry.id;
3082
3083        let local_repository = LocalRepositoryEntry {
3084            work_directory_id,
3085            work_directory,
3086            work_directory_abs_path: work_directory_abs_path.as_path().into(),
3087            git_dir_scan_id: 0,
3088            dot_git_abs_path,
3089            common_dir_abs_path,
3090            repository_dir_abs_path,
3091        };
3092
3093        self.snapshot
3094            .git_repositories
3095            .insert(work_directory_id, local_repository.clone());
3096
3097        log::trace!("inserting new local git repository");
3098        Ok(local_repository)
3099    }
3100}
3101
3102async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3103    if let Some(file_name) = path.file_name()
3104        && file_name == DOT_GIT
3105    {
3106        return true;
3107    }
3108
3109    // If we're in a bare repository, we are not inside a `.git` folder. In a
3110    // bare repository, the root folder contains what would normally be in the
3111    // `.git` folder.
3112    let head_metadata = fs.metadata(&path.join("HEAD")).await;
3113    if !matches!(head_metadata, Ok(Some(_))) {
3114        return false;
3115    }
3116    let config_metadata = fs.metadata(&path.join("config")).await;
3117    matches!(config_metadata, Ok(Some(_)))
3118}
3119
3120async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3121    let contents = fs
3122        .load(abs_path)
3123        .await
3124        .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
3125    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3126    let mut builder = GitignoreBuilder::new(parent);
3127    for line in contents.lines() {
3128        builder.add_line(Some(abs_path.into()), line)?;
3129    }
3130    Ok(builder.build()?)
3131}
3132
3133impl Deref for Worktree {
3134    type Target = Snapshot;
3135
3136    fn deref(&self) -> &Self::Target {
3137        match self {
3138            Worktree::Local(worktree) => &worktree.snapshot,
3139            Worktree::Remote(worktree) => &worktree.snapshot,
3140        }
3141    }
3142}
3143
3144impl Deref for LocalWorktree {
3145    type Target = LocalSnapshot;
3146
3147    fn deref(&self) -> &Self::Target {
3148        &self.snapshot
3149    }
3150}
3151
3152impl Deref for RemoteWorktree {
3153    type Target = Snapshot;
3154
3155    fn deref(&self) -> &Self::Target {
3156        &self.snapshot
3157    }
3158}
3159
3160impl fmt::Debug for LocalWorktree {
3161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3162        self.snapshot.fmt(f)
3163    }
3164}
3165
3166impl fmt::Debug for Snapshot {
3167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3168        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3169        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3170
3171        impl fmt::Debug for EntriesByPath<'_> {
3172            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3173                f.debug_map()
3174                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3175                    .finish()
3176            }
3177        }
3178
3179        impl fmt::Debug for EntriesById<'_> {
3180            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3181                f.debug_list().entries(self.0.iter()).finish()
3182            }
3183        }
3184
3185        f.debug_struct("Snapshot")
3186            .field("id", &self.id)
3187            .field("root_name", &self.root_name)
3188            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3189            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3190            .finish()
3191    }
3192}
3193
3194#[derive(Debug, Clone, PartialEq)]
3195pub struct File {
3196    pub worktree: Entity<Worktree>,
3197    pub path: Arc<RelPath>,
3198    pub disk_state: DiskState,
3199    pub entry_id: Option<ProjectEntryId>,
3200    pub is_local: bool,
3201    pub is_private: bool,
3202}
3203
3204impl language::File for File {
3205    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3206        if self.is_local { Some(self) } else { None }
3207    }
3208
3209    fn disk_state(&self) -> DiskState {
3210        self.disk_state
3211    }
3212
3213    fn path(&self) -> &Arc<RelPath> {
3214        &self.path
3215    }
3216
3217    fn full_path(&self, cx: &App) -> PathBuf {
3218        self.worktree.read(cx).full_path(&self.path)
3219    }
3220
3221    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3222    /// of its worktree, then this method will return the name of the worktree itself.
3223    fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3224        self.path
3225            .file_name()
3226            .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3227    }
3228
3229    fn worktree_id(&self, cx: &App) -> WorktreeId {
3230        self.worktree.read(cx).id()
3231    }
3232
3233    fn to_proto(&self, cx: &App) -> rpc::proto::File {
3234        rpc::proto::File {
3235            worktree_id: self.worktree.read(cx).id().to_proto(),
3236            entry_id: self.entry_id.map(|id| id.to_proto()),
3237            path: self.path.as_ref().to_proto(),
3238            mtime: self.disk_state.mtime().map(|time| time.into()),
3239            is_deleted: self.disk_state.is_deleted(),
3240            is_historic: matches!(self.disk_state, DiskState::Historic { .. }),
3241        }
3242    }
3243
3244    fn is_private(&self) -> bool {
3245        self.is_private
3246    }
3247
3248    fn path_style(&self, cx: &App) -> PathStyle {
3249        self.worktree.read(cx).path_style()
3250    }
3251
3252    fn can_open(&self) -> bool {
3253        true
3254    }
3255}
3256
3257impl language::LocalFile for File {
3258    fn abs_path(&self, cx: &App) -> PathBuf {
3259        self.worktree.read(cx).absolutize(&self.path)
3260    }
3261
3262    fn load(&self, cx: &App) -> Task<Result<String>> {
3263        let worktree = self.worktree.read(cx).as_local().unwrap();
3264        let abs_path = worktree.absolutize(&self.path);
3265        let fs = worktree.fs.clone();
3266        cx.background_spawn(async move { fs.load(&abs_path).await })
3267    }
3268
3269    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3270        let worktree = self.worktree.read(cx).as_local().unwrap();
3271        let abs_path = worktree.absolutize(&self.path);
3272        let fs = worktree.fs.clone();
3273        cx.background_spawn(async move { fs.load_bytes(&abs_path).await })
3274    }
3275}
3276
3277impl File {
3278    pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3279        Arc::new(Self {
3280            worktree,
3281            path: entry.path.clone(),
3282            disk_state: if let Some(mtime) = entry.mtime {
3283                DiskState::Present { mtime }
3284            } else {
3285                DiskState::New
3286            },
3287            entry_id: Some(entry.id),
3288            is_local: true,
3289            is_private: entry.is_private,
3290        })
3291    }
3292
3293    pub fn from_proto(
3294        proto: rpc::proto::File,
3295        worktree: Entity<Worktree>,
3296        cx: &App,
3297    ) -> Result<Self> {
3298        let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
3299
3300        anyhow::ensure!(
3301            worktree_id.to_proto() == proto.worktree_id,
3302            "worktree id does not match file"
3303        );
3304
3305        let disk_state = if proto.is_historic {
3306            DiskState::Historic {
3307                was_deleted: proto.is_deleted,
3308            }
3309        } else if proto.is_deleted {
3310            DiskState::Deleted
3311        } else if let Some(mtime) = proto.mtime.map(&Into::into) {
3312            DiskState::Present { mtime }
3313        } else {
3314            DiskState::New
3315        };
3316
3317        Ok(Self {
3318            worktree,
3319            path: RelPath::from_proto(&proto.path).context("invalid path in file protobuf")?,
3320            disk_state,
3321            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3322            is_local: false,
3323            is_private: false,
3324        })
3325    }
3326
3327    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3328        file.and_then(|f| {
3329            let f: &dyn language::File = f.borrow();
3330            let f: &dyn Any = f;
3331            f.downcast_ref()
3332        })
3333    }
3334
3335    pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3336        self.worktree.read(cx).id()
3337    }
3338
3339    pub fn project_entry_id(&self) -> Option<ProjectEntryId> {
3340        match self.disk_state {
3341            DiskState::Deleted => None,
3342            _ => self.entry_id,
3343        }
3344    }
3345}
3346
3347#[derive(Clone, Debug, PartialEq, Eq)]
3348pub struct Entry {
3349    pub id: ProjectEntryId,
3350    pub kind: EntryKind,
3351    pub path: Arc<RelPath>,
3352    pub inode: u64,
3353    pub mtime: Option<MTime>,
3354
3355    pub canonical_path: Option<Arc<Path>>,
3356    /// Whether this entry is ignored by Git.
3357    ///
3358    /// We only scan ignored entries once the directory is expanded and
3359    /// exclude them from searches.
3360    pub is_ignored: bool,
3361
3362    /// Whether this entry is hidden or inside hidden directory.
3363    ///
3364    /// We only scan hidden entries once the directory is expanded.
3365    pub is_hidden: bool,
3366
3367    /// Whether this entry is always included in searches.
3368    ///
3369    /// This is used for entries that are always included in searches, even
3370    /// if they are ignored by git. Overridden by file_scan_exclusions.
3371    pub is_always_included: bool,
3372
3373    /// Whether this entry's canonical path is outside of the worktree.
3374    /// This means the entry is only accessible from the worktree root via a
3375    /// symlink.
3376    ///
3377    /// We only scan entries outside of the worktree once the symlinked
3378    /// directory is expanded. External entries are treated like gitignored
3379    /// entries in that they are not included in searches.
3380    pub is_external: bool,
3381
3382    /// Whether this entry is considered to be a `.env` file.
3383    pub is_private: bool,
3384    /// The entry's size on disk, in bytes.
3385    pub size: u64,
3386    pub char_bag: CharBag,
3387    pub is_fifo: bool,
3388}
3389
3390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3391pub enum EntryKind {
3392    UnloadedDir,
3393    PendingDir,
3394    Dir,
3395    File,
3396}
3397
3398#[derive(Clone, Copy, Debug, PartialEq)]
3399pub enum PathChange {
3400    /// A filesystem entry was was created.
3401    Added,
3402    /// A filesystem entry was removed.
3403    Removed,
3404    /// A filesystem entry was updated.
3405    Updated,
3406    /// A filesystem entry was either updated or added. We don't know
3407    /// whether or not it already existed, because the path had not
3408    /// been loaded before the event.
3409    AddedOrUpdated,
3410    /// A filesystem entry was found during the initial scan of the worktree.
3411    Loaded,
3412}
3413
3414#[derive(Clone, Debug, PartialEq, Eq)]
3415pub struct UpdatedGitRepository {
3416    /// ID of the repository's working directory.
3417    ///
3418    /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3419    /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3420    pub work_directory_id: ProjectEntryId,
3421    pub old_work_directory_abs_path: Option<Arc<Path>>,
3422    pub new_work_directory_abs_path: Option<Arc<Path>>,
3423    /// For a normal git repository checkout, the absolute path to the .git directory.
3424    /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3425    pub dot_git_abs_path: Option<Arc<Path>>,
3426    pub repository_dir_abs_path: Option<Arc<Path>>,
3427    pub common_dir_abs_path: Option<Arc<Path>>,
3428}
3429
3430pub type UpdatedEntriesSet = Arc<[(Arc<RelPath>, ProjectEntryId, PathChange)]>;
3431pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3432
3433#[derive(Clone, Debug)]
3434pub struct PathProgress<'a> {
3435    pub max_path: &'a RelPath,
3436}
3437
3438#[derive(Clone, Debug)]
3439pub struct PathSummary<S> {
3440    pub max_path: Arc<RelPath>,
3441    pub item_summary: S,
3442}
3443
3444impl<S: Summary> Summary for PathSummary<S> {
3445    type Context<'a> = S::Context<'a>;
3446
3447    fn zero(cx: Self::Context<'_>) -> Self {
3448        Self {
3449            max_path: RelPath::empty().into(),
3450            item_summary: S::zero(cx),
3451        }
3452    }
3453
3454    fn add_summary(&mut self, rhs: &Self, cx: Self::Context<'_>) {
3455        self.max_path = rhs.max_path.clone();
3456        self.item_summary.add_summary(&rhs.item_summary, cx);
3457    }
3458}
3459
3460impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3461    fn zero(_: <PathSummary<S> as Summary>::Context<'_>) -> Self {
3462        Self {
3463            max_path: RelPath::empty(),
3464        }
3465    }
3466
3467    fn add_summary(
3468        &mut self,
3469        summary: &'a PathSummary<S>,
3470        _: <PathSummary<S> as Summary>::Context<'_>,
3471    ) {
3472        self.max_path = summary.max_path.as_ref()
3473    }
3474}
3475
3476impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3477    fn zero(_cx: ()) -> Self {
3478        Default::default()
3479    }
3480
3481    fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: ()) {
3482        *self += summary.item_summary
3483    }
3484}
3485
3486impl<'a>
3487    sum_tree::SeekTarget<'a, PathSummary<GitSummary>, Dimensions<TraversalProgress<'a>, GitSummary>>
3488    for PathTarget<'_>
3489{
3490    fn cmp(
3491        &self,
3492        cursor_location: &Dimensions<TraversalProgress<'a>, GitSummary>,
3493        _: (),
3494    ) -> Ordering {
3495        self.cmp_path(cursor_location.0.max_path)
3496    }
3497}
3498
3499impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3500    fn zero(_: S::Context<'_>) -> Self {
3501        Default::default()
3502    }
3503
3504    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3505        self.0 = summary.max_path.clone();
3506    }
3507}
3508
3509impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3510    fn zero(_cx: S::Context<'_>) -> Self {
3511        Default::default()
3512    }
3513
3514    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3515        self.max_path = summary.max_path.as_ref();
3516    }
3517}
3518
3519impl Entry {
3520    fn new(
3521        path: Arc<RelPath>,
3522        metadata: &fs::Metadata,
3523        id: ProjectEntryId,
3524        root_char_bag: CharBag,
3525        canonical_path: Option<Arc<Path>>,
3526    ) -> Self {
3527        let char_bag = char_bag_for_path(root_char_bag, &path);
3528        Self {
3529            id,
3530            kind: if metadata.is_dir {
3531                EntryKind::PendingDir
3532            } else {
3533                EntryKind::File
3534            },
3535            path,
3536            inode: metadata.inode,
3537            mtime: Some(metadata.mtime),
3538            size: metadata.len,
3539            canonical_path,
3540            is_ignored: false,
3541            is_hidden: false,
3542            is_always_included: false,
3543            is_external: false,
3544            is_private: false,
3545            char_bag,
3546            is_fifo: metadata.is_fifo,
3547        }
3548    }
3549
3550    pub fn is_created(&self) -> bool {
3551        self.mtime.is_some()
3552    }
3553
3554    pub fn is_dir(&self) -> bool {
3555        self.kind.is_dir()
3556    }
3557
3558    pub fn is_file(&self) -> bool {
3559        self.kind.is_file()
3560    }
3561}
3562
3563impl EntryKind {
3564    pub fn is_dir(&self) -> bool {
3565        matches!(
3566            self,
3567            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3568        )
3569    }
3570
3571    pub fn is_unloaded(&self) -> bool {
3572        matches!(self, EntryKind::UnloadedDir)
3573    }
3574
3575    pub fn is_file(&self) -> bool {
3576        matches!(self, EntryKind::File)
3577    }
3578}
3579
3580impl sum_tree::Item for Entry {
3581    type Summary = EntrySummary;
3582
3583    fn summary(&self, _cx: ()) -> Self::Summary {
3584        let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3585        {
3586            0
3587        } else {
3588            1
3589        };
3590        let file_count;
3591        let non_ignored_file_count;
3592        if self.is_file() {
3593            file_count = 1;
3594            non_ignored_file_count = non_ignored_count;
3595        } else {
3596            file_count = 0;
3597            non_ignored_file_count = 0;
3598        }
3599
3600        EntrySummary {
3601            max_path: self.path.clone(),
3602            count: 1,
3603            non_ignored_count,
3604            file_count,
3605            non_ignored_file_count,
3606        }
3607    }
3608}
3609
3610impl sum_tree::KeyedItem for Entry {
3611    type Key = PathKey;
3612
3613    fn key(&self) -> Self::Key {
3614        PathKey(self.path.clone())
3615    }
3616}
3617
3618#[derive(Clone, Debug)]
3619pub struct EntrySummary {
3620    max_path: Arc<RelPath>,
3621    count: usize,
3622    non_ignored_count: usize,
3623    file_count: usize,
3624    non_ignored_file_count: usize,
3625}
3626
3627impl Default for EntrySummary {
3628    fn default() -> Self {
3629        Self {
3630            max_path: Arc::from(RelPath::empty()),
3631            count: 0,
3632            non_ignored_count: 0,
3633            file_count: 0,
3634            non_ignored_file_count: 0,
3635        }
3636    }
3637}
3638
3639impl sum_tree::ContextLessSummary for EntrySummary {
3640    fn zero() -> Self {
3641        Default::default()
3642    }
3643
3644    fn add_summary(&mut self, rhs: &Self) {
3645        self.max_path = rhs.max_path.clone();
3646        self.count += rhs.count;
3647        self.non_ignored_count += rhs.non_ignored_count;
3648        self.file_count += rhs.file_count;
3649        self.non_ignored_file_count += rhs.non_ignored_file_count;
3650    }
3651}
3652
3653#[derive(Clone, Debug)]
3654struct PathEntry {
3655    id: ProjectEntryId,
3656    path: Arc<RelPath>,
3657    is_ignored: bool,
3658    scan_id: usize,
3659}
3660
3661impl sum_tree::Item for PathEntry {
3662    type Summary = PathEntrySummary;
3663
3664    fn summary(&self, _cx: ()) -> Self::Summary {
3665        PathEntrySummary { max_id: self.id }
3666    }
3667}
3668
3669impl sum_tree::KeyedItem for PathEntry {
3670    type Key = ProjectEntryId;
3671
3672    fn key(&self) -> Self::Key {
3673        self.id
3674    }
3675}
3676
3677#[derive(Clone, Debug, Default)]
3678struct PathEntrySummary {
3679    max_id: ProjectEntryId,
3680}
3681
3682impl sum_tree::ContextLessSummary for PathEntrySummary {
3683    fn zero() -> Self {
3684        Default::default()
3685    }
3686
3687    fn add_summary(&mut self, summary: &Self) {
3688        self.max_id = summary.max_id;
3689    }
3690}
3691
3692impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3693    fn zero(_cx: ()) -> Self {
3694        Default::default()
3695    }
3696
3697    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: ()) {
3698        *self = summary.max_id;
3699    }
3700}
3701
3702#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3703pub struct PathKey(pub Arc<RelPath>);
3704
3705impl Default for PathKey {
3706    fn default() -> Self {
3707        Self(RelPath::empty().into())
3708    }
3709}
3710
3711impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3712    fn zero(_cx: ()) -> Self {
3713        Default::default()
3714    }
3715
3716    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
3717        self.0 = summary.max_path.clone();
3718    }
3719}
3720
3721struct BackgroundScanner {
3722    state: async_lock::Mutex<BackgroundScannerState>,
3723    fs: Arc<dyn Fs>,
3724    fs_case_sensitive: bool,
3725    status_updates_tx: UnboundedSender<ScanState>,
3726    executor: BackgroundExecutor,
3727    scan_requests_rx: channel::Receiver<ScanRequest>,
3728    path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3729    next_entry_id: Arc<AtomicUsize>,
3730    phase: BackgroundScannerPhase,
3731    watcher: Arc<dyn Watcher>,
3732    settings: WorktreeSettings,
3733    share_private_files: bool,
3734}
3735
3736#[derive(Copy, Clone, PartialEq)]
3737enum BackgroundScannerPhase {
3738    InitialScan,
3739    EventsReceivedDuringInitialScan,
3740    Events,
3741}
3742
3743impl BackgroundScanner {
3744    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3745        let root_abs_path;
3746        let scanning_enabled;
3747        {
3748            let state = self.state.lock().await;
3749            root_abs_path = state.snapshot.abs_path.clone();
3750            scanning_enabled = state.scanning_enabled;
3751        }
3752
3753        // If the worktree root does not contain a git repository, then find
3754        // the git repository in an ancestor directory. Find any gitignore files
3755        // in ancestor directories.
3756        let repo = if scanning_enabled {
3757            let (ignores, exclude, repo) =
3758                discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3759            self.state
3760                .lock()
3761                .await
3762                .snapshot
3763                .ignores_by_parent_abs_path
3764                .extend(ignores);
3765            if let Some(exclude) = exclude {
3766                self.state
3767                    .lock()
3768                    .await
3769                    .snapshot
3770                    .repo_exclude_by_work_dir_abs_path
3771                    .insert(root_abs_path.as_path().into(), (exclude, false));
3772            }
3773
3774            repo
3775        } else {
3776            None
3777        };
3778
3779        let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo
3780            && scanning_enabled
3781        {
3782            maybe!(async {
3783                self.state
3784                    .lock()
3785                    .await
3786                    .insert_git_repository_for_path(
3787                        work_directory,
3788                        ancestor_dot_git.clone().into(),
3789                        self.fs.as_ref(),
3790                        self.watcher.as_ref(),
3791                    )
3792                    .await
3793                    .log_err()?;
3794                Some(ancestor_dot_git)
3795            })
3796            .await
3797        } else {
3798            None
3799        };
3800
3801        log::trace!("containing git repository: {containing_git_repository:?}");
3802
3803        let global_gitignore_file = paths::global_gitignore_path();
3804        let mut global_gitignore_events = if let Some(global_gitignore_path) =
3805            &global_gitignore_file
3806            && scanning_enabled
3807        {
3808            let is_file = self.fs.is_file(&global_gitignore_path).await;
3809            self.state.lock().await.snapshot.global_gitignore = if is_file {
3810                build_gitignore(global_gitignore_path, self.fs.as_ref())
3811                    .await
3812                    .ok()
3813                    .map(Arc::new)
3814            } else {
3815                None
3816            };
3817            if is_file {
3818                self.fs
3819                    .watch(global_gitignore_path, FS_WATCH_LATENCY)
3820                    .await
3821                    .0
3822            } else {
3823                Box::pin(futures::stream::pending())
3824            }
3825        } else {
3826            self.state.lock().await.snapshot.global_gitignore = None;
3827            Box::pin(futures::stream::pending())
3828        };
3829
3830        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3831        {
3832            let mut state = self.state.lock().await;
3833            state.snapshot.scan_id += 1;
3834            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3835                let ignore_stack = state
3836                    .snapshot
3837                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true, self.fs.as_ref())
3838                    .await;
3839                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3840                    root_entry.is_ignored = true;
3841                    let mut root_entry = root_entry.clone();
3842                    state.reuse_entry_id(&mut root_entry);
3843                    state
3844                        .insert_entry(root_entry, self.fs.as_ref(), self.watcher.as_ref())
3845                        .await;
3846                }
3847                if root_entry.is_dir() && state.scanning_enabled {
3848                    state
3849                        .enqueue_scan_dir(
3850                            root_abs_path.as_path().into(),
3851                            &root_entry,
3852                            &scan_job_tx,
3853                            self.fs.as_ref(),
3854                        )
3855                        .await;
3856                }
3857            }
3858        };
3859
3860        // Perform an initial scan of the directory.
3861        drop(scan_job_tx);
3862        self.scan_dirs(true, scan_job_rx).await;
3863        {
3864            let mut state = self.state.lock().await;
3865            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3866        }
3867
3868        self.send_status_update(false, SmallVec::new()).await;
3869
3870        // Process any any FS events that occurred while performing the initial scan.
3871        // For these events, update events cannot be as precise, because we didn't
3872        // have the previous state loaded yet.
3873        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3874        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3875            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3876                paths.extend(more_paths);
3877            }
3878            self.process_events(
3879                paths
3880                    .into_iter()
3881                    .filter(|e| e.kind.is_some())
3882                    .map(Into::into)
3883                    .collect(),
3884            )
3885            .await;
3886        }
3887        if let Some(abs_path) = containing_git_repository {
3888            self.process_events(vec![abs_path]).await;
3889        }
3890
3891        // Continue processing events until the worktree is dropped.
3892        self.phase = BackgroundScannerPhase::Events;
3893
3894        loop {
3895            select_biased! {
3896                // Process any path refresh requests from the worktree. Prioritize
3897                // these before handling changes reported by the filesystem.
3898                request = self.next_scan_request().fuse() => {
3899                    let Ok(request) = request else { break };
3900                    if !self.process_scan_request(request, false).await {
3901                        return;
3902                    }
3903                }
3904
3905                path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3906                    let Ok(request) = path_prefix_request else { break };
3907                    log::trace!("adding path prefix {:?}", request.path);
3908
3909                    let did_scan = self.forcibly_load_paths(std::slice::from_ref(&request.path)).await;
3910                    if did_scan {
3911                        let abs_path =
3912                        {
3913                            let mut state = self.state.lock().await;
3914                            state.path_prefixes_to_scan.insert(request.path.clone());
3915                            state.snapshot.absolutize(&request.path)
3916                        };
3917
3918                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3919                            self.process_events(vec![abs_path]).await;
3920                        }
3921                    }
3922                    self.send_status_update(false, request.done).await;
3923                }
3924
3925                paths = fs_events_rx.next().fuse() => {
3926                    let Some(mut paths) = paths else { break };
3927                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3928                        paths.extend(more_paths);
3929                    }
3930                    self.process_events(paths.into_iter().filter(|e| e.kind.is_some()).map(Into::into).collect()).await;
3931                }
3932
3933                _ = global_gitignore_events.next().fuse() => {
3934                    if let Some(path) = &global_gitignore_file {
3935                        self.update_global_gitignore(&path).await;
3936                    }
3937                }
3938            }
3939        }
3940    }
3941
3942    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3943        log::debug!("rescanning paths {:?}", request.relative_paths);
3944
3945        request.relative_paths.sort_unstable();
3946        self.forcibly_load_paths(&request.relative_paths).await;
3947
3948        let root_path = self.state.lock().await.snapshot.abs_path.clone();
3949        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3950        let root_canonical_path = match &root_canonical_path {
3951            Ok(path) => SanitizedPath::new(path),
3952            Err(err) => {
3953                log::error!("failed to canonicalize root path {root_path:?}: {err:#}");
3954                return true;
3955            }
3956        };
3957        let abs_paths = request
3958            .relative_paths
3959            .iter()
3960            .map(|path| {
3961                if path.file_name().is_some() {
3962                    root_canonical_path.as_path().join(path.as_std_path())
3963                } else {
3964                    root_canonical_path.as_path().to_path_buf()
3965                }
3966            })
3967            .collect::<Vec<_>>();
3968
3969        {
3970            let mut state = self.state.lock().await;
3971            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3972            state.snapshot.scan_id += 1;
3973            if is_idle {
3974                state.snapshot.completed_scan_id = state.snapshot.scan_id;
3975            }
3976        }
3977
3978        self.reload_entries_for_paths(
3979            &root_path,
3980            &root_canonical_path,
3981            &request.relative_paths,
3982            abs_paths,
3983            None,
3984        )
3985        .await;
3986
3987        self.send_status_update(scanning, request.done).await
3988    }
3989
3990    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3991        log::trace!("process events: {abs_paths:?}");
3992        let root_path = self.state.lock().await.snapshot.abs_path.clone();
3993        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3994        let root_canonical_path = match &root_canonical_path {
3995            Ok(path) => SanitizedPath::new(path),
3996            Err(err) => {
3997                let new_path = self
3998                    .state
3999                    .lock()
4000                    .await
4001                    .snapshot
4002                    .root_file_handle
4003                    .clone()
4004                    .and_then(|handle| match handle.current_path(&self.fs) {
4005                        Ok(new_path) => Some(new_path),
4006                        Err(e) => {
4007                            log::error!("Failed to refresh worktree root path: {e:#}");
4008                            None
4009                        }
4010                    })
4011                    .map(|path| SanitizedPath::new_arc(&path))
4012                    .filter(|new_path| *new_path != root_path);
4013
4014                if let Some(new_path) = new_path {
4015                    log::info!(
4016                        "root renamed from {:?} to {:?}",
4017                        root_path.as_path(),
4018                        new_path.as_path(),
4019                    );
4020                    self.status_updates_tx
4021                        .unbounded_send(ScanState::RootUpdated { new_path })
4022                        .ok();
4023                } else {
4024                    log::error!("root path could not be canonicalized: {err:#}");
4025                }
4026                return;
4027            }
4028        };
4029
4030        // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4031        // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4032        let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];
4033        let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];
4034
4035        let mut relative_paths = Vec::with_capacity(abs_paths.len());
4036        let mut dot_git_abs_paths = Vec::new();
4037        let mut work_dirs_needing_exclude_update = Vec::new();
4038        abs_paths.sort_unstable();
4039        abs_paths.dedup_by(|a, b| a.starts_with(b));
4040        {
4041            let snapshot = &self.state.lock().await.snapshot;
4042
4043            let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();
4044
4045            fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {
4046                if let Some(last_range) = ranges.last_mut()
4047                    && last_range.end == ix
4048                {
4049                    last_range.end += 1;
4050                } else {
4051                    ranges.push(ix..ix + 1);
4052                }
4053            }
4054
4055            for (ix, abs_path) in abs_paths.iter().enumerate() {
4056                let abs_path = &SanitizedPath::new(&abs_path);
4057
4058                let mut is_git_related = false;
4059                let mut dot_git_paths = None;
4060
4061                for ancestor in abs_path.as_path().ancestors() {
4062                    if is_git_dir(ancestor, self.fs.as_ref()).await {
4063                        let path_in_git_dir = abs_path
4064                            .as_path()
4065                            .strip_prefix(ancestor)
4066                            .expect("stripping off the ancestor");
4067                        dot_git_paths = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
4068                        break;
4069                    }
4070                }
4071
4072                if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4073                    if skipped_files_in_dot_git
4074                        .iter()
4075                        .any(|skipped| OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str())
4076                        || skipped_dirs_in_dot_git.iter().any(|skipped_git_subdir| {
4077                            path_in_git_dir.starts_with(skipped_git_subdir)
4078                        })
4079                    {
4080                        log::debug!(
4081                            "ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories"
4082                        );
4083                        skip_ix(&mut ranges_to_drop, ix);
4084                        continue;
4085                    }
4086
4087                    is_git_related = true;
4088                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4089                        dot_git_abs_paths.push(dot_git_abs_path);
4090                    }
4091                }
4092
4093                let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)
4094                    && let Ok(path) = RelPath::new(path, PathStyle::local())
4095                {
4096                    path
4097                } else {
4098                    if is_git_related {
4099                        log::debug!(
4100                            "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4101                        );
4102                    } else {
4103                        log::error!(
4104                            "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4105                        );
4106                    }
4107                    skip_ix(&mut ranges_to_drop, ix);
4108                    continue;
4109                };
4110
4111                let absolute_path = abs_path.to_path_buf();
4112                if absolute_path.ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE)) {
4113                    if let Some(repository) = snapshot
4114                        .git_repositories
4115                        .values()
4116                        .find(|repo| repo.common_dir_abs_path.join(REPO_EXCLUDE) == absolute_path)
4117                    {
4118                        work_dirs_needing_exclude_update
4119                            .push(repository.work_directory_abs_path.clone());
4120                    }
4121                }
4122
4123                if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
4124                    for (_, repo) in snapshot
4125                        .git_repositories
4126                        .iter()
4127                        .filter(|(_, repo)| repo.directory_contains(&relative_path))
4128                    {
4129                        if !dot_git_abs_paths.iter().any(|dot_git_abs_path| {
4130                            dot_git_abs_path == repo.common_dir_abs_path.as_ref()
4131                        }) {
4132                            dot_git_abs_paths.push(repo.common_dir_abs_path.to_path_buf());
4133                        }
4134                    }
4135                }
4136
4137                let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
4138                    snapshot
4139                        .entry_for_path(parent)
4140                        .is_some_and(|entry| entry.kind == EntryKind::Dir)
4141                });
4142                if !parent_dir_is_loaded {
4143                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
4144                    skip_ix(&mut ranges_to_drop, ix);
4145                    continue;
4146                }
4147
4148                if self.settings.is_path_excluded(&relative_path) {
4149                    if !is_git_related {
4150                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
4151                    }
4152                    skip_ix(&mut ranges_to_drop, ix);
4153                    continue;
4154                }
4155
4156                relative_paths.push(relative_path.into_arc());
4157            }
4158
4159            for range_to_drop in ranges_to_drop.into_iter().rev() {
4160                abs_paths.drain(range_to_drop);
4161            }
4162        }
4163
4164        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4165            return;
4166        }
4167
4168        if !work_dirs_needing_exclude_update.is_empty() {
4169            let mut state = self.state.lock().await;
4170            for work_dir_abs_path in work_dirs_needing_exclude_update {
4171                if let Some((_, needs_update)) = state
4172                    .snapshot
4173                    .repo_exclude_by_work_dir_abs_path
4174                    .get_mut(&work_dir_abs_path)
4175                {
4176                    *needs_update = true;
4177                }
4178            }
4179        }
4180
4181        self.state.lock().await.snapshot.scan_id += 1;
4182
4183        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4184        log::debug!("received fs events {:?}", relative_paths);
4185        self.reload_entries_for_paths(
4186            &root_path,
4187            &root_canonical_path,
4188            &relative_paths,
4189            abs_paths,
4190            Some(scan_job_tx.clone()),
4191        )
4192        .await;
4193
4194        let affected_repo_roots = if !dot_git_abs_paths.is_empty() {
4195            self.update_git_repositories(dot_git_abs_paths).await
4196        } else {
4197            Vec::new()
4198        };
4199
4200        {
4201            let mut ignores_to_update = self.ignores_needing_update().await;
4202            ignores_to_update.extend(affected_repo_roots);
4203            let ignores_to_update = self.order_ignores(ignores_to_update).await;
4204            let snapshot = self.state.lock().await.snapshot.clone();
4205            self.update_ignore_statuses_for_paths(scan_job_tx, snapshot, ignores_to_update)
4206                .await;
4207            self.scan_dirs(false, scan_job_rx).await;
4208        }
4209
4210        {
4211            let mut state = self.state.lock().await;
4212            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4213            for (_, entry) in mem::take(&mut state.removed_entries) {
4214                state.scanned_dirs.remove(&entry.id);
4215            }
4216        }
4217        self.send_status_update(false, SmallVec::new()).await;
4218    }
4219
4220    async fn update_global_gitignore(&self, abs_path: &Path) {
4221        let ignore = build_gitignore(abs_path, self.fs.as_ref())
4222            .await
4223            .log_err()
4224            .map(Arc::new);
4225        let (prev_snapshot, ignore_stack, abs_path) = {
4226            let mut state = self.state.lock().await;
4227            state.snapshot.global_gitignore = ignore;
4228            let abs_path = state.snapshot.abs_path().clone();
4229            let ignore_stack = state
4230                .snapshot
4231                .ignore_stack_for_abs_path(&abs_path, true, self.fs.as_ref())
4232                .await;
4233            (state.snapshot.clone(), ignore_stack, abs_path)
4234        };
4235        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4236        self.update_ignore_statuses_for_paths(
4237            scan_job_tx,
4238            prev_snapshot,
4239            vec![(abs_path, ignore_stack)],
4240        )
4241        .await;
4242        self.scan_dirs(false, scan_job_rx).await;
4243        self.send_status_update(false, SmallVec::new()).await;
4244    }
4245
4246    async fn forcibly_load_paths(&self, paths: &[Arc<RelPath>]) -> bool {
4247        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4248        {
4249            let mut state = self.state.lock().await;
4250            let root_path = state.snapshot.abs_path.clone();
4251            for path in paths {
4252                for ancestor in path.ancestors() {
4253                    if let Some(entry) = state.snapshot.entry_for_path(ancestor)
4254                        && entry.kind == EntryKind::UnloadedDir
4255                    {
4256                        let abs_path = root_path.join(ancestor.as_std_path());
4257                        state
4258                            .enqueue_scan_dir(
4259                                abs_path.into(),
4260                                entry,
4261                                &scan_job_tx,
4262                                self.fs.as_ref(),
4263                            )
4264                            .await;
4265                        state.paths_to_scan.insert(path.clone());
4266                        break;
4267                    }
4268                }
4269            }
4270            drop(scan_job_tx);
4271        }
4272        while let Ok(job) = scan_job_rx.recv().await {
4273            self.scan_dir(&job).await.log_err();
4274        }
4275
4276        !mem::take(&mut self.state.lock().await.paths_to_scan).is_empty()
4277    }
4278
4279    async fn scan_dirs(
4280        &self,
4281        enable_progress_updates: bool,
4282        scan_jobs_rx: channel::Receiver<ScanJob>,
4283    ) {
4284        if self
4285            .status_updates_tx
4286            .unbounded_send(ScanState::Started)
4287            .is_err()
4288        {
4289            return;
4290        }
4291
4292        let progress_update_count = AtomicUsize::new(0);
4293        self.executor
4294            .scoped_priority(Priority::Low, |scope| {
4295                for _ in 0..self.executor.num_cpus() {
4296                    scope.spawn(async {
4297                        let mut last_progress_update_count = 0;
4298                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4299                        futures::pin_mut!(progress_update_timer);
4300
4301                        loop {
4302                            select_biased! {
4303                                // Process any path refresh requests before moving on to process
4304                                // the scan queue, so that user operations are prioritized.
4305                                request = self.next_scan_request().fuse() => {
4306                                    let Ok(request) = request else { break };
4307                                    if !self.process_scan_request(request, true).await {
4308                                        return;
4309                                    }
4310                                }
4311
4312                                // Send periodic progress updates to the worktree. Use an atomic counter
4313                                // to ensure that only one of the workers sends a progress update after
4314                                // the update interval elapses.
4315                                _ = progress_update_timer => {
4316                                    match progress_update_count.compare_exchange(
4317                                        last_progress_update_count,
4318                                        last_progress_update_count + 1,
4319                                        SeqCst,
4320                                        SeqCst
4321                                    ) {
4322                                        Ok(_) => {
4323                                            last_progress_update_count += 1;
4324                                            self.send_status_update(true, SmallVec::new()).await;
4325                                        }
4326                                        Err(count) => {
4327                                            last_progress_update_count = count;
4328                                        }
4329                                    }
4330                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4331                                }
4332
4333                                // Recursively load directories from the file system.
4334                                job = scan_jobs_rx.recv().fuse() => {
4335                                    let Ok(job) = job else { break };
4336                                    if let Err(err) = self.scan_dir(&job).await
4337                                        && job.path.is_empty() {
4338                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4339                                        }
4340                                }
4341                            }
4342                        }
4343                    });
4344                }
4345            })
4346            .await;
4347    }
4348
4349    async fn send_status_update(
4350        &self,
4351        scanning: bool,
4352        barrier: SmallVec<[barrier::Sender; 1]>,
4353    ) -> bool {
4354        let mut state = self.state.lock().await;
4355        if state.changed_paths.is_empty() && scanning {
4356            return true;
4357        }
4358
4359        let new_snapshot = state.snapshot.clone();
4360        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4361        let changes = build_diff(
4362            self.phase,
4363            &old_snapshot,
4364            &new_snapshot,
4365            &state.changed_paths,
4366        );
4367        state.changed_paths.clear();
4368
4369        self.status_updates_tx
4370            .unbounded_send(ScanState::Updated {
4371                snapshot: new_snapshot,
4372                changes,
4373                scanning,
4374                barrier,
4375            })
4376            .is_ok()
4377    }
4378
4379    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4380        let root_abs_path;
4381        let root_char_bag;
4382        {
4383            let snapshot = &self.state.lock().await.snapshot;
4384            if self.settings.is_path_excluded(&job.path) {
4385                log::error!("skipping excluded directory {:?}", job.path);
4386                return Ok(());
4387            }
4388            log::trace!("scanning directory {:?}", job.path);
4389            root_abs_path = snapshot.abs_path().clone();
4390            root_char_bag = snapshot.root_char_bag;
4391        }
4392
4393        let next_entry_id = self.next_entry_id.clone();
4394        let mut ignore_stack = job.ignore_stack.clone();
4395        let mut new_ignore = None;
4396        let mut root_canonical_path = None;
4397        let mut new_entries: Vec<Entry> = Vec::new();
4398        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4399        let mut child_paths = self
4400            .fs
4401            .read_dir(&job.abs_path)
4402            .await?
4403            .filter_map(|entry| async {
4404                match entry {
4405                    Ok(entry) => Some(entry),
4406                    Err(error) => {
4407                        log::error!("error processing entry {:?}", error);
4408                        None
4409                    }
4410                }
4411            })
4412            .collect::<Vec<_>>()
4413            .await;
4414
4415        // Ensure that .git and .gitignore are processed first.
4416        swap_to_front(&mut child_paths, GITIGNORE);
4417        swap_to_front(&mut child_paths, DOT_GIT);
4418
4419        if let Some(path) = child_paths.first()
4420            && path.ends_with(DOT_GIT)
4421        {
4422            ignore_stack.repo_root = Some(job.abs_path.clone());
4423        }
4424
4425        for child_abs_path in child_paths {
4426            let child_abs_path: Arc<Path> = child_abs_path.into();
4427            let child_name = child_abs_path.file_name().unwrap();
4428            let Some(child_path) = child_name
4429                .to_str()
4430                .and_then(|name| Some(job.path.join(RelPath::unix(name).ok()?)))
4431            else {
4432                continue;
4433            };
4434
4435            if child_name == DOT_GIT {
4436                let mut state = self.state.lock().await;
4437                state
4438                    .insert_git_repository(
4439                        child_path.clone(),
4440                        self.fs.as_ref(),
4441                        self.watcher.as_ref(),
4442                    )
4443                    .await;
4444            } else if child_name == GITIGNORE {
4445                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4446                    Ok(ignore) => {
4447                        let ignore = Arc::new(ignore);
4448                        ignore_stack = ignore_stack
4449                            .append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4450                        new_ignore = Some(ignore);
4451                    }
4452                    Err(error) => {
4453                        log::error!(
4454                            "error loading .gitignore file {:?} - {:?}",
4455                            child_name,
4456                            error
4457                        );
4458                    }
4459                }
4460            }
4461
4462            if self.settings.is_path_excluded(&child_path) {
4463                log::debug!("skipping excluded child entry {child_path:?}");
4464                self.state.lock().await.remove_path(&child_path);
4465                continue;
4466            }
4467
4468            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4469                Ok(Some(metadata)) => metadata,
4470                Ok(None) => continue,
4471                Err(err) => {
4472                    log::error!("error processing {:?}: {err:#}", child_abs_path.display());
4473                    continue;
4474                }
4475            };
4476
4477            let mut child_entry = Entry::new(
4478                child_path.clone(),
4479                &child_metadata,
4480                ProjectEntryId::new(&next_entry_id),
4481                root_char_bag,
4482                None,
4483            );
4484
4485            if job.is_external {
4486                child_entry.is_external = true;
4487            } else if child_metadata.is_symlink {
4488                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4489                    Ok(path) => path,
4490                    Err(err) => {
4491                        log::error!("error reading target of symlink {child_abs_path:?}: {err:#}",);
4492                        continue;
4493                    }
4494                };
4495
4496                // lazily canonicalize the root path in order to determine if
4497                // symlinks point outside of the worktree.
4498                let root_canonical_path = match &root_canonical_path {
4499                    Some(path) => path,
4500                    None => match self.fs.canonicalize(&root_abs_path).await {
4501                        Ok(path) => root_canonical_path.insert(path),
4502                        Err(err) => {
4503                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4504                            continue;
4505                        }
4506                    },
4507                };
4508
4509                if !canonical_path.starts_with(root_canonical_path) {
4510                    child_entry.is_external = true;
4511                }
4512
4513                child_entry.canonical_path = Some(canonical_path.into());
4514            }
4515
4516            if child_entry.is_dir() {
4517                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4518                child_entry.is_always_included =
4519                    self.settings.is_path_always_included(&child_path, true);
4520
4521                // Avoid recursing until crash in the case of a recursive symlink
4522                if job.ancestor_inodes.contains(&child_entry.inode) {
4523                    new_jobs.push(None);
4524                } else {
4525                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4526                    ancestor_inodes.insert(child_entry.inode);
4527
4528                    new_jobs.push(Some(ScanJob {
4529                        abs_path: child_abs_path.clone(),
4530                        path: child_path,
4531                        is_external: child_entry.is_external,
4532                        ignore_stack: if child_entry.is_ignored {
4533                            IgnoreStack::all()
4534                        } else {
4535                            ignore_stack.clone()
4536                        },
4537                        ancestor_inodes,
4538                        scan_queue: job.scan_queue.clone(),
4539                    }));
4540                }
4541            } else {
4542                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4543                child_entry.is_always_included =
4544                    self.settings.is_path_always_included(&child_path, false);
4545            }
4546
4547            {
4548                let relative_path = job
4549                    .path
4550                    .join(RelPath::unix(child_name.to_str().unwrap()).unwrap());
4551                if self.is_path_private(&relative_path) {
4552                    log::debug!("detected private file: {relative_path:?}");
4553                    child_entry.is_private = true;
4554                }
4555                if self.settings.is_path_hidden(&relative_path) {
4556                    log::debug!("detected hidden file: {relative_path:?}");
4557                    child_entry.is_hidden = true;
4558                }
4559            }
4560
4561            new_entries.push(child_entry);
4562        }
4563
4564        let mut state = self.state.lock().await;
4565
4566        // Identify any subdirectories that should not be scanned.
4567        let mut job_ix = 0;
4568        for entry in &mut new_entries {
4569            state.reuse_entry_id(entry);
4570            if entry.is_dir() {
4571                if state.should_scan_directory(entry) {
4572                    job_ix += 1;
4573                } else {
4574                    log::debug!("defer scanning directory {:?}", entry.path);
4575                    entry.kind = EntryKind::UnloadedDir;
4576                    new_jobs.remove(job_ix);
4577                }
4578            }
4579            if entry.is_always_included {
4580                state
4581                    .snapshot
4582                    .always_included_entries
4583                    .push(entry.path.clone());
4584            }
4585        }
4586
4587        state.populate_dir(job.path.clone(), new_entries, new_ignore);
4588        self.watcher.add(job.abs_path.as_ref()).log_err();
4589
4590        for new_job in new_jobs.into_iter().flatten() {
4591            job.scan_queue
4592                .try_send(new_job)
4593                .expect("channel is unbounded");
4594        }
4595
4596        Ok(())
4597    }
4598
4599    /// All list arguments should be sorted before calling this function
4600    async fn reload_entries_for_paths(
4601        &self,
4602        root_abs_path: &SanitizedPath,
4603        root_canonical_path: &SanitizedPath,
4604        relative_paths: &[Arc<RelPath>],
4605        abs_paths: Vec<PathBuf>,
4606        scan_queue_tx: Option<Sender<ScanJob>>,
4607    ) {
4608        // grab metadata for all requested paths
4609        let metadata = futures::future::join_all(
4610            abs_paths
4611                .iter()
4612                .map(|abs_path| async move {
4613                    let metadata = self.fs.metadata(abs_path).await?;
4614                    if let Some(metadata) = metadata {
4615                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4616
4617                        // If we're on a case-insensitive filesystem (default on macOS), we want
4618                        // to only ignore metadata for non-symlink files if their absolute-path matches
4619                        // the canonical-path.
4620                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4621                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4622                        // treated as removed.
4623                        if !self.fs_case_sensitive && !metadata.is_symlink {
4624                            let canonical_file_name = canonical_path.file_name();
4625                            let file_name = abs_path.file_name();
4626                            if canonical_file_name != file_name {
4627                                return Ok(None);
4628                            }
4629                        }
4630
4631                        anyhow::Ok(Some((metadata, SanitizedPath::new_arc(&canonical_path))))
4632                    } else {
4633                        Ok(None)
4634                    }
4635                })
4636                .collect::<Vec<_>>(),
4637        )
4638        .await;
4639
4640        let mut new_ancestor_repo = if relative_paths.iter().any(|path| path.is_empty()) {
4641            Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4642        } else {
4643            None
4644        };
4645
4646        let mut state = self.state.lock().await;
4647        let doing_recursive_update = scan_queue_tx.is_some();
4648
4649        // Remove any entries for paths that no longer exist or are being recursively
4650        // refreshed. Do this before adding any new entries, so that renames can be
4651        // detected regardless of the order of the paths.
4652        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4653            if matches!(metadata, Ok(None)) || doing_recursive_update {
4654                state.remove_path(path);
4655            }
4656        }
4657
4658        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4659            let abs_path: Arc<Path> = root_abs_path.join(path.as_std_path()).into();
4660            match metadata {
4661                Ok(Some((metadata, canonical_path))) => {
4662                    let ignore_stack = state
4663                        .snapshot
4664                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir, self.fs.as_ref())
4665                        .await;
4666                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4667                    let entry_id = state.entry_id_for(self.next_entry_id.as_ref(), path, &metadata);
4668                    let mut fs_entry = Entry::new(
4669                        path.clone(),
4670                        &metadata,
4671                        entry_id,
4672                        state.snapshot.root_char_bag,
4673                        if metadata.is_symlink {
4674                            Some(canonical_path.as_path().to_path_buf().into())
4675                        } else {
4676                            None
4677                        },
4678                    );
4679
4680                    let is_dir = fs_entry.is_dir();
4681                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4682                    fs_entry.is_external = is_external;
4683                    fs_entry.is_private = self.is_path_private(path);
4684                    fs_entry.is_always_included =
4685                        self.settings.is_path_always_included(path, is_dir);
4686                    fs_entry.is_hidden = self.settings.is_path_hidden(path);
4687
4688                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4689                        if state.should_scan_directory(&fs_entry)
4690                            || (fs_entry.path.is_empty()
4691                                && abs_path.file_name() == Some(OsStr::new(DOT_GIT)))
4692                        {
4693                            state
4694                                .enqueue_scan_dir(
4695                                    abs_path,
4696                                    &fs_entry,
4697                                    scan_queue_tx,
4698                                    self.fs.as_ref(),
4699                                )
4700                                .await;
4701                        } else {
4702                            fs_entry.kind = EntryKind::UnloadedDir;
4703                        }
4704                    }
4705
4706                    state
4707                        .insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
4708                        .await;
4709
4710                    if path.is_empty()
4711                        && let Some((ignores, exclude, repo)) = new_ancestor_repo.take()
4712                    {
4713                        log::trace!("updating ancestor git repository");
4714                        state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4715                        if let Some((ancestor_dot_git, work_directory)) = repo {
4716                            if let Some(exclude) = exclude {
4717                                let work_directory_abs_path = self
4718                                    .state
4719                                    .lock()
4720                                    .await
4721                                    .snapshot
4722                                    .work_directory_abs_path(&work_directory);
4723
4724                                state
4725                                    .snapshot
4726                                    .repo_exclude_by_work_dir_abs_path
4727                                    .insert(work_directory_abs_path.into(), (exclude, false));
4728                            }
4729                            state
4730                                .insert_git_repository_for_path(
4731                                    work_directory,
4732                                    ancestor_dot_git.into(),
4733                                    self.fs.as_ref(),
4734                                    self.watcher.as_ref(),
4735                                )
4736                                .await
4737                                .log_err();
4738                        }
4739                    }
4740                }
4741                Ok(None) => {
4742                    self.remove_repo_path(path.clone(), &mut state.snapshot);
4743                }
4744                Err(err) => {
4745                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4746                }
4747            }
4748        }
4749
4750        util::extend_sorted(
4751            &mut state.changed_paths,
4752            relative_paths.iter().cloned(),
4753            usize::MAX,
4754            Ord::cmp,
4755        );
4756    }
4757
4758    fn remove_repo_path(&self, path: Arc<RelPath>, snapshot: &mut LocalSnapshot) -> Option<()> {
4759        if !path.components().any(|component| component == DOT_GIT)
4760            && let Some(local_repo) = snapshot.local_repo_for_work_directory_path(&path)
4761        {
4762            let id = local_repo.work_directory_id;
4763            log::debug!("remove repo path: {:?}", path);
4764            snapshot.git_repositories.remove(&id);
4765            return Some(());
4766        }
4767
4768        Some(())
4769    }
4770
4771    async fn update_ignore_statuses_for_paths(
4772        &self,
4773        scan_job_tx: Sender<ScanJob>,
4774        prev_snapshot: LocalSnapshot,
4775        ignores_to_update: Vec<(Arc<Path>, IgnoreStack)>,
4776    ) {
4777        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4778        {
4779            for (parent_abs_path, ignore_stack) in ignores_to_update {
4780                ignore_queue_tx
4781                    .send_blocking(UpdateIgnoreStatusJob {
4782                        abs_path: parent_abs_path,
4783                        ignore_stack,
4784                        ignore_queue: ignore_queue_tx.clone(),
4785                        scan_queue: scan_job_tx.clone(),
4786                    })
4787                    .unwrap();
4788            }
4789        }
4790        drop(ignore_queue_tx);
4791
4792        self.executor
4793            .scoped(|scope| {
4794                for _ in 0..self.executor.num_cpus() {
4795                    scope.spawn(async {
4796                        loop {
4797                            select_biased! {
4798                                // Process any path refresh requests before moving on to process
4799                                // the queue of ignore statuses.
4800                                request = self.next_scan_request().fuse() => {
4801                                    let Ok(request) = request else { break };
4802                                    if !self.process_scan_request(request, true).await {
4803                                        return;
4804                                    }
4805                                }
4806
4807                                // Recursively process directories whose ignores have changed.
4808                                job = ignore_queue_rx.recv().fuse() => {
4809                                    let Ok(job) = job else { break };
4810                                    self.update_ignore_status(job, &prev_snapshot).await;
4811                                }
4812                            }
4813                        }
4814                    });
4815                }
4816            })
4817            .await;
4818    }
4819
4820    async fn ignores_needing_update(&self) -> Vec<Arc<Path>> {
4821        let mut ignores_to_update = Vec::new();
4822        let mut excludes_to_load: Vec<(Arc<Path>, PathBuf)> = Vec::new();
4823
4824        // First pass: collect updates and drop stale entries without awaiting.
4825        {
4826            let snapshot = &mut self.state.lock().await.snapshot;
4827            let abs_path = snapshot.abs_path.clone();
4828            let mut repo_exclude_keys_to_remove: Vec<Arc<Path>> = Vec::new();
4829
4830            for (work_dir_abs_path, (_, needs_update)) in
4831                snapshot.repo_exclude_by_work_dir_abs_path.iter_mut()
4832            {
4833                let repository = snapshot
4834                    .git_repositories
4835                    .iter()
4836                    .find(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path);
4837
4838                if *needs_update {
4839                    *needs_update = false;
4840                    ignores_to_update.push(work_dir_abs_path.clone());
4841
4842                    if let Some((_, repository)) = repository {
4843                        let exclude_abs_path = repository.common_dir_abs_path.join(REPO_EXCLUDE);
4844                        excludes_to_load.push((work_dir_abs_path.clone(), exclude_abs_path));
4845                    }
4846                }
4847
4848                if repository.is_none() {
4849                    repo_exclude_keys_to_remove.push(work_dir_abs_path.clone());
4850                }
4851            }
4852
4853            for key in repo_exclude_keys_to_remove {
4854                snapshot.repo_exclude_by_work_dir_abs_path.remove(&key);
4855            }
4856
4857            snapshot
4858                .ignores_by_parent_abs_path
4859                .retain(|parent_abs_path, (_, needs_update)| {
4860                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
4861                        && let Some(parent_path) =
4862                            RelPath::new(&parent_path, PathStyle::local()).log_err()
4863                    {
4864                        if *needs_update {
4865                            *needs_update = false;
4866                            if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
4867                                ignores_to_update.push(parent_abs_path.clone());
4868                            }
4869                        }
4870
4871                        let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
4872                        if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
4873                            return false;
4874                        }
4875                    }
4876                    true
4877                });
4878        }
4879
4880        // Load gitignores asynchronously (outside the lock)
4881        let mut loaded_excludes: Vec<(Arc<Path>, Arc<Gitignore>)> = Vec::new();
4882        for (work_dir_abs_path, exclude_abs_path) in excludes_to_load {
4883            if let Ok(current_exclude) = build_gitignore(&exclude_abs_path, self.fs.as_ref()).await
4884            {
4885                loaded_excludes.push((work_dir_abs_path, Arc::new(current_exclude)));
4886            }
4887        }
4888
4889        // Second pass: apply updates.
4890        if !loaded_excludes.is_empty() {
4891            let snapshot = &mut self.state.lock().await.snapshot;
4892
4893            for (work_dir_abs_path, exclude) in loaded_excludes {
4894                if let Some((existing_exclude, _)) = snapshot
4895                    .repo_exclude_by_work_dir_abs_path
4896                    .get_mut(&work_dir_abs_path)
4897                {
4898                    *existing_exclude = exclude;
4899                }
4900            }
4901        }
4902
4903        ignores_to_update
4904    }
4905
4906    async fn order_ignores(&self, mut ignores: Vec<Arc<Path>>) -> Vec<(Arc<Path>, IgnoreStack)> {
4907        let fs = self.fs.clone();
4908        let snapshot = self.state.lock().await.snapshot.clone();
4909        ignores.sort_unstable();
4910        let mut ignores_to_update = ignores.into_iter().peekable();
4911
4912        let mut result = vec![];
4913        while let Some(parent_abs_path) = ignores_to_update.next() {
4914            while ignores_to_update
4915                .peek()
4916                .map_or(false, |p| p.starts_with(&parent_abs_path))
4917            {
4918                ignores_to_update.next().unwrap();
4919            }
4920            let ignore_stack = snapshot
4921                .ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref())
4922                .await;
4923            result.push((parent_abs_path, ignore_stack));
4924        }
4925
4926        result
4927    }
4928
4929    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4930        log::trace!("update ignore status {:?}", job.abs_path);
4931
4932        let mut ignore_stack = job.ignore_stack;
4933        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4934            ignore_stack =
4935                ignore_stack.append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
4936        }
4937
4938        let mut entries_by_id_edits = Vec::new();
4939        let mut entries_by_path_edits = Vec::new();
4940        let Some(path) = job
4941            .abs_path
4942            .strip_prefix(snapshot.abs_path.as_path())
4943            .map_err(|_| {
4944                anyhow::anyhow!(
4945                    "Failed to strip prefix '{}' from path '{}'",
4946                    snapshot.abs_path.as_path().display(),
4947                    job.abs_path.display()
4948                )
4949            })
4950            .log_err()
4951        else {
4952            return;
4953        };
4954
4955        let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
4956            return;
4957        };
4958
4959        if let Ok(Some(metadata)) = self.fs.metadata(&job.abs_path.join(DOT_GIT)).await
4960            && metadata.is_dir
4961        {
4962            ignore_stack.repo_root = Some(job.abs_path.clone());
4963        }
4964
4965        for mut entry in snapshot.child_entries(&path).cloned() {
4966            let was_ignored = entry.is_ignored;
4967            let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
4968            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4969
4970            if entry.is_dir() {
4971                let child_ignore_stack = if entry.is_ignored {
4972                    IgnoreStack::all()
4973                } else {
4974                    ignore_stack.clone()
4975                };
4976
4977                // Scan any directories that were previously ignored and weren't previously scanned.
4978                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4979                    let state = self.state.lock().await;
4980                    if state.should_scan_directory(&entry) {
4981                        state
4982                            .enqueue_scan_dir(
4983                                abs_path.clone(),
4984                                &entry,
4985                                &job.scan_queue,
4986                                self.fs.as_ref(),
4987                            )
4988                            .await;
4989                    }
4990                }
4991
4992                job.ignore_queue
4993                    .send(UpdateIgnoreStatusJob {
4994                        abs_path: abs_path.clone(),
4995                        ignore_stack: child_ignore_stack,
4996                        ignore_queue: job.ignore_queue.clone(),
4997                        scan_queue: job.scan_queue.clone(),
4998                    })
4999                    .await
5000                    .unwrap();
5001            }
5002
5003            if entry.is_ignored != was_ignored {
5004                let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
5005                path_entry.scan_id = snapshot.scan_id;
5006                path_entry.is_ignored = entry.is_ignored;
5007                entries_by_id_edits.push(Edit::Insert(path_entry));
5008                entries_by_path_edits.push(Edit::Insert(entry));
5009            }
5010        }
5011
5012        let state = &mut self.state.lock().await;
5013        for edit in &entries_by_path_edits {
5014            if let Edit::Insert(entry) = edit
5015                && let Err(ix) = state.changed_paths.binary_search(&entry.path)
5016            {
5017                state.changed_paths.insert(ix, entry.path.clone());
5018            }
5019        }
5020
5021        state
5022            .snapshot
5023            .entries_by_path
5024            .edit(entries_by_path_edits, ());
5025        state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
5026    }
5027
5028    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
5029        log::trace!("reloading repositories: {dot_git_paths:?}");
5030        let mut state = self.state.lock().await;
5031        let scan_id = state.snapshot.scan_id;
5032        let mut affected_repo_roots = Vec::new();
5033        for dot_git_dir in dot_git_paths {
5034            let existing_repository_entry =
5035                state
5036                    .snapshot
5037                    .git_repositories
5038                    .iter()
5039                    .find_map(|(_, repo)| {
5040                        let dot_git_dir = SanitizedPath::new(&dot_git_dir);
5041                        if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
5042                            || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
5043                                == dot_git_dir
5044                        {
5045                            Some(repo.clone())
5046                        } else {
5047                            None
5048                        }
5049                    });
5050
5051            match existing_repository_entry {
5052                None => {
5053                    let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
5054                        debug_panic!(
5055                            "update_git_repositories called with .git directory outside the worktree root"
5056                        );
5057                        return Vec::new();
5058                    };
5059                    affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
5060                    state
5061                        .insert_git_repository(
5062                            RelPath::new(relative, PathStyle::local())
5063                                .unwrap()
5064                                .into_arc(),
5065                            self.fs.as_ref(),
5066                            self.watcher.as_ref(),
5067                        )
5068                        .await;
5069                }
5070                Some(local_repository) => {
5071                    state.snapshot.git_repositories.update(
5072                        &local_repository.work_directory_id,
5073                        |entry| {
5074                            entry.git_dir_scan_id = scan_id;
5075                        },
5076                    );
5077                }
5078            };
5079        }
5080
5081        // Remove any git repositories whose .git entry no longer exists.
5082        let snapshot = &mut state.snapshot;
5083        let mut ids_to_preserve = HashSet::default();
5084        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5085            let exists_in_snapshot =
5086                snapshot
5087                    .entry_for_id(work_directory_id)
5088                    .is_some_and(|entry| {
5089                        snapshot
5090                            .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
5091                            .is_some()
5092                    });
5093
5094            if exists_in_snapshot
5095                || matches!(
5096                    self.fs.metadata(&entry.common_dir_abs_path).await,
5097                    Ok(Some(_))
5098                )
5099            {
5100                ids_to_preserve.insert(work_directory_id);
5101            }
5102        }
5103
5104        snapshot
5105            .git_repositories
5106            .retain(|work_directory_id, entry| {
5107                let preserve = ids_to_preserve.contains(work_directory_id);
5108                if !preserve {
5109                    affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
5110                    snapshot
5111                        .repo_exclude_by_work_dir_abs_path
5112                        .remove(&entry.work_directory_abs_path);
5113                }
5114                preserve
5115            });
5116
5117        affected_repo_roots
5118    }
5119
5120    async fn progress_timer(&self, running: bool) {
5121        if !running {
5122            return futures::future::pending().await;
5123        }
5124
5125        #[cfg(feature = "test-support")]
5126        if self.fs.is_fake() {
5127            return self.executor.simulate_random_delay().await;
5128        }
5129
5130        self.executor.timer(FS_WATCH_LATENCY).await
5131    }
5132
5133    fn is_path_private(&self, path: &RelPath) -> bool {
5134        !self.share_private_files && self.settings.is_path_private(path)
5135    }
5136
5137    async fn next_scan_request(&self) -> Result<ScanRequest> {
5138        let mut request = self.scan_requests_rx.recv().await?;
5139        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5140            request.relative_paths.extend(next_request.relative_paths);
5141            request.done.extend(next_request.done);
5142        }
5143        Ok(request)
5144    }
5145}
5146
5147async fn discover_ancestor_git_repo(
5148    fs: Arc<dyn Fs>,
5149    root_abs_path: &SanitizedPath,
5150) -> (
5151    HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
5152    Option<Arc<Gitignore>>,
5153    Option<(PathBuf, WorkDirectory)>,
5154) {
5155    let mut exclude = None;
5156    let mut ignores = HashMap::default();
5157    for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
5158        if index != 0 {
5159            if ancestor == paths::home_dir() {
5160                // Unless $HOME is itself the worktree root, don't consider it as a
5161                // containing git repository---expensive and likely unwanted.
5162                break;
5163            } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
5164            {
5165                ignores.insert(ancestor.into(), (ignore.into(), false));
5166            }
5167        }
5168
5169        let ancestor_dot_git = ancestor.join(DOT_GIT);
5170        log::trace!("considering ancestor: {ancestor_dot_git:?}");
5171        // Check whether the directory or file called `.git` exists (in the
5172        // case of worktrees it's a file.)
5173        if fs
5174            .metadata(&ancestor_dot_git)
5175            .await
5176            .is_ok_and(|metadata| metadata.is_some())
5177        {
5178            if index != 0 {
5179                // We canonicalize, since the FS events use the canonicalized path.
5180                if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
5181                    let location_in_repo = root_abs_path
5182                        .as_path()
5183                        .strip_prefix(ancestor)
5184                        .unwrap()
5185                        .into();
5186                    log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
5187                    // We associate the external git repo with our root folder and
5188                    // also mark where in the git repo the root folder is located.
5189                    return (
5190                        ignores,
5191                        exclude,
5192                        Some((
5193                            ancestor_dot_git,
5194                            WorkDirectory::AboveProject {
5195                                absolute_path: ancestor.into(),
5196                                location_in_repo,
5197                            },
5198                        )),
5199                    );
5200                };
5201            }
5202
5203            let repo_exclude_abs_path = ancestor_dot_git.join(REPO_EXCLUDE);
5204            if let Ok(repo_exclude) = build_gitignore(&repo_exclude_abs_path, fs.as_ref()).await {
5205                exclude = Some(Arc::new(repo_exclude));
5206            }
5207
5208            // Reached root of git repository.
5209            break;
5210        }
5211    }
5212
5213    (ignores, exclude, None)
5214}
5215
5216fn build_diff(
5217    phase: BackgroundScannerPhase,
5218    old_snapshot: &Snapshot,
5219    new_snapshot: &Snapshot,
5220    event_paths: &[Arc<RelPath>],
5221) -> UpdatedEntriesSet {
5222    use BackgroundScannerPhase::*;
5223    use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5224
5225    // Identify which paths have changed. Use the known set of changed
5226    // parent paths to optimize the search.
5227    let mut changes = Vec::new();
5228    let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
5229    let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
5230    let mut last_newly_loaded_dir_path = None;
5231    old_paths.next();
5232    new_paths.next();
5233    for path in event_paths {
5234        let path = PathKey(path.clone());
5235        if old_paths.item().is_some_and(|e| e.path < path.0) {
5236            old_paths.seek_forward(&path, Bias::Left);
5237        }
5238        if new_paths.item().is_some_and(|e| e.path < path.0) {
5239            new_paths.seek_forward(&path, Bias::Left);
5240        }
5241        loop {
5242            match (old_paths.item(), new_paths.item()) {
5243                (Some(old_entry), Some(new_entry)) => {
5244                    if old_entry.path > path.0
5245                        && new_entry.path > path.0
5246                        && !old_entry.path.starts_with(&path.0)
5247                        && !new_entry.path.starts_with(&path.0)
5248                    {
5249                        break;
5250                    }
5251
5252                    match Ord::cmp(&old_entry.path, &new_entry.path) {
5253                        Ordering::Less => {
5254                            changes.push((old_entry.path.clone(), old_entry.id, Removed));
5255                            old_paths.next();
5256                        }
5257                        Ordering::Equal => {
5258                            if phase == EventsReceivedDuringInitialScan {
5259                                if old_entry.id != new_entry.id {
5260                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5261                                }
5262                                // If the worktree was not fully initialized when this event was generated,
5263                                // we can't know whether this entry was added during the scan or whether
5264                                // it was merely updated.
5265                                changes.push((
5266                                    new_entry.path.clone(),
5267                                    new_entry.id,
5268                                    AddedOrUpdated,
5269                                ));
5270                            } else if old_entry.id != new_entry.id {
5271                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
5272                                changes.push((new_entry.path.clone(), new_entry.id, Added));
5273                            } else if old_entry != new_entry {
5274                                if old_entry.kind.is_unloaded() {
5275                                    last_newly_loaded_dir_path = Some(&new_entry.path);
5276                                    changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5277                                } else {
5278                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
5279                                }
5280                            }
5281                            old_paths.next();
5282                            new_paths.next();
5283                        }
5284                        Ordering::Greater => {
5285                            let is_newly_loaded = phase == InitialScan
5286                                || last_newly_loaded_dir_path
5287                                    .as_ref()
5288                                    .is_some_and(|dir| new_entry.path.starts_with(dir));
5289                            changes.push((
5290                                new_entry.path.clone(),
5291                                new_entry.id,
5292                                if is_newly_loaded { Loaded } else { Added },
5293                            ));
5294                            new_paths.next();
5295                        }
5296                    }
5297                }
5298                (Some(old_entry), None) => {
5299                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5300                    old_paths.next();
5301                }
5302                (None, Some(new_entry)) => {
5303                    let is_newly_loaded = phase == InitialScan
5304                        || last_newly_loaded_dir_path
5305                            .as_ref()
5306                            .is_some_and(|dir| new_entry.path.starts_with(dir));
5307                    changes.push((
5308                        new_entry.path.clone(),
5309                        new_entry.id,
5310                        if is_newly_loaded { Loaded } else { Added },
5311                    ));
5312                    new_paths.next();
5313                }
5314                (None, None) => break,
5315            }
5316        }
5317    }
5318
5319    changes.into()
5320}
5321
5322fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
5323    let position = child_paths
5324        .iter()
5325        .position(|path| path.file_name().unwrap() == file);
5326    if let Some(position) = position {
5327        let temp = child_paths.remove(position);
5328        child_paths.insert(0, temp);
5329    }
5330}
5331
5332fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
5333    let mut result = root_char_bag;
5334    result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
5335    result
5336}
5337
5338#[derive(Debug)]
5339struct ScanJob {
5340    abs_path: Arc<Path>,
5341    path: Arc<RelPath>,
5342    ignore_stack: IgnoreStack,
5343    scan_queue: Sender<ScanJob>,
5344    ancestor_inodes: TreeSet<u64>,
5345    is_external: bool,
5346}
5347
5348struct UpdateIgnoreStatusJob {
5349    abs_path: Arc<Path>,
5350    ignore_stack: IgnoreStack,
5351    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5352    scan_queue: Sender<ScanJob>,
5353}
5354
5355pub trait WorktreeModelHandle {
5356    #[cfg(feature = "test-support")]
5357    fn flush_fs_events<'a>(
5358        &self,
5359        cx: &'a mut gpui::TestAppContext,
5360    ) -> futures::future::LocalBoxFuture<'a, ()>;
5361
5362    #[cfg(feature = "test-support")]
5363    fn flush_fs_events_in_root_git_repository<'a>(
5364        &self,
5365        cx: &'a mut gpui::TestAppContext,
5366    ) -> futures::future::LocalBoxFuture<'a, ()>;
5367}
5368
5369impl WorktreeModelHandle for Entity<Worktree> {
5370    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5371    // occurred before the worktree was constructed. These events can cause the worktree to perform
5372    // extra directory scans, and emit extra scan-state notifications.
5373    //
5374    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5375    // to ensure that all redundant FS events have already been processed.
5376    #[cfg(feature = "test-support")]
5377    fn flush_fs_events<'a>(
5378        &self,
5379        cx: &'a mut gpui::TestAppContext,
5380    ) -> futures::future::LocalBoxFuture<'a, ()> {
5381        let file_name = "fs-event-sentinel";
5382
5383        let tree = self.clone();
5384        let (fs, root_path) = self.read_with(cx, |tree, _| {
5385            let tree = tree.as_local().unwrap();
5386            (tree.fs.clone(), tree.abs_path.clone())
5387        });
5388
5389        async move {
5390            // Subscribe to events BEFORE creating the file to avoid race condition
5391            // where events fire before subscription is set up
5392            let mut events = cx.events(&tree);
5393
5394            fs.create_file(&root_path.join(file_name), Default::default())
5395                .await
5396                .unwrap();
5397
5398            // Check if condition is already met before waiting for events
5399            let file_exists = || {
5400                tree.read_with(cx, |tree, _| {
5401                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5402                        .is_some()
5403                })
5404            };
5405
5406            // Use select to avoid blocking indefinitely if events are delayed
5407            while !file_exists() {
5408                futures::select_biased! {
5409                    _ = events.next() => {}
5410                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5411                }
5412            }
5413
5414            fs.remove_file(&root_path.join(file_name), Default::default())
5415                .await
5416                .unwrap();
5417
5418            // Check if condition is already met before waiting for events
5419            let file_gone = || {
5420                tree.read_with(cx, |tree, _| {
5421                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5422                        .is_none()
5423                })
5424            };
5425
5426            // Use select to avoid blocking indefinitely if events are delayed
5427            while !file_gone() {
5428                futures::select_biased! {
5429                    _ = events.next() => {}
5430                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5431                }
5432            }
5433
5434            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5435                .await;
5436        }
5437        .boxed_local()
5438    }
5439
5440    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5441    // the .git folder of the root repository.
5442    // The reason for its existence is that a repository's .git folder might live *outside* of the
5443    // worktree and thus its FS events might go through a different path.
5444    // In order to flush those, we need to create artificial events in the .git folder and wait
5445    // for the repository to be reloaded.
5446    #[cfg(feature = "test-support")]
5447    fn flush_fs_events_in_root_git_repository<'a>(
5448        &self,
5449        cx: &'a mut gpui::TestAppContext,
5450    ) -> futures::future::LocalBoxFuture<'a, ()> {
5451        let file_name = "fs-event-sentinel";
5452
5453        let tree = self.clone();
5454        let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5455            let tree = tree.as_local().unwrap();
5456            let local_repo_entry = tree
5457                .git_repositories
5458                .values()
5459                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5460                .unwrap();
5461            (
5462                tree.fs.clone(),
5463                local_repo_entry.common_dir_abs_path.clone(),
5464                local_repo_entry.git_dir_scan_id,
5465            )
5466        });
5467
5468        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5469            let tree = tree.as_local().unwrap();
5470            // let repository = tree.repositories.first().unwrap();
5471            let local_repo_entry = tree
5472                .git_repositories
5473                .values()
5474                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5475                .unwrap();
5476
5477            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5478                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5479                true
5480            } else {
5481                false
5482            }
5483        };
5484
5485        async move {
5486            // Subscribe to events BEFORE creating the file to avoid race condition
5487            // where events fire before subscription is set up
5488            let mut events = cx.events(&tree);
5489
5490            fs.create_file(&root_path.join(file_name), Default::default())
5491                .await
5492                .unwrap();
5493
5494            // Use select to avoid blocking indefinitely if events are delayed
5495            while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5496                futures::select_biased! {
5497                    _ = events.next() => {}
5498                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5499                }
5500            }
5501
5502            fs.remove_file(&root_path.join(file_name), Default::default())
5503                .await
5504                .unwrap();
5505
5506            // Use select to avoid blocking indefinitely if events are delayed
5507            while !tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5508                futures::select_biased! {
5509                    _ = events.next() => {}
5510                    _ = futures::FutureExt::fuse(cx.background_executor.timer(std::time::Duration::from_millis(10))) => {}
5511                }
5512            }
5513
5514            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5515                .await;
5516        }
5517        .boxed_local()
5518    }
5519}
5520
5521#[derive(Clone, Debug)]
5522struct TraversalProgress<'a> {
5523    max_path: &'a RelPath,
5524    count: usize,
5525    non_ignored_count: usize,
5526    file_count: usize,
5527    non_ignored_file_count: usize,
5528}
5529
5530impl TraversalProgress<'_> {
5531    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5532        match (include_files, include_dirs, include_ignored) {
5533            (true, true, true) => self.count,
5534            (true, true, false) => self.non_ignored_count,
5535            (true, false, true) => self.file_count,
5536            (true, false, false) => self.non_ignored_file_count,
5537            (false, true, true) => self.count - self.file_count,
5538            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5539            (false, false, _) => 0,
5540        }
5541    }
5542}
5543
5544impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5545    fn zero(_cx: ()) -> Self {
5546        Default::default()
5547    }
5548
5549    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5550        self.max_path = summary.max_path.as_ref();
5551        self.count += summary.count;
5552        self.non_ignored_count += summary.non_ignored_count;
5553        self.file_count += summary.file_count;
5554        self.non_ignored_file_count += summary.non_ignored_file_count;
5555    }
5556}
5557
5558impl Default for TraversalProgress<'_> {
5559    fn default() -> Self {
5560        Self {
5561            max_path: RelPath::empty(),
5562            count: 0,
5563            non_ignored_count: 0,
5564            file_count: 0,
5565            non_ignored_file_count: 0,
5566        }
5567    }
5568}
5569
5570#[derive(Debug)]
5571pub struct Traversal<'a> {
5572    snapshot: &'a Snapshot,
5573    cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5574    include_ignored: bool,
5575    include_files: bool,
5576    include_dirs: bool,
5577}
5578
5579impl<'a> Traversal<'a> {
5580    fn new(
5581        snapshot: &'a Snapshot,
5582        include_files: bool,
5583        include_dirs: bool,
5584        include_ignored: bool,
5585        start_path: &RelPath,
5586    ) -> Self {
5587        let mut cursor = snapshot.entries_by_path.cursor(());
5588        cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5589        let mut traversal = Self {
5590            snapshot,
5591            cursor,
5592            include_files,
5593            include_dirs,
5594            include_ignored,
5595        };
5596        if traversal.end_offset() == traversal.start_offset() {
5597            traversal.next();
5598        }
5599        traversal
5600    }
5601
5602    pub fn advance(&mut self) -> bool {
5603        self.advance_by(1)
5604    }
5605
5606    pub fn advance_by(&mut self, count: usize) -> bool {
5607        self.cursor.seek_forward(
5608            &TraversalTarget::Count {
5609                count: self.end_offset() + count,
5610                include_dirs: self.include_dirs,
5611                include_files: self.include_files,
5612                include_ignored: self.include_ignored,
5613            },
5614            Bias::Left,
5615        )
5616    }
5617
5618    pub fn advance_to_sibling(&mut self) -> bool {
5619        while let Some(entry) = self.cursor.item() {
5620            self.cursor
5621                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5622            if let Some(entry) = self.cursor.item()
5623                && (self.include_files || !entry.is_file())
5624                && (self.include_dirs || !entry.is_dir())
5625                && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5626            {
5627                return true;
5628            }
5629        }
5630        false
5631    }
5632
5633    pub fn back_to_parent(&mut self) -> bool {
5634        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5635            return false;
5636        };
5637        self.cursor
5638            .seek(&TraversalTarget::path(parent_path), Bias::Left)
5639    }
5640
5641    pub fn entry(&self) -> Option<&'a Entry> {
5642        self.cursor.item()
5643    }
5644
5645    pub fn snapshot(&self) -> &'a Snapshot {
5646        self.snapshot
5647    }
5648
5649    pub fn start_offset(&self) -> usize {
5650        self.cursor
5651            .start()
5652            .count(self.include_files, self.include_dirs, self.include_ignored)
5653    }
5654
5655    pub fn end_offset(&self) -> usize {
5656        self.cursor
5657            .end()
5658            .count(self.include_files, self.include_dirs, self.include_ignored)
5659    }
5660}
5661
5662impl<'a> Iterator for Traversal<'a> {
5663    type Item = &'a Entry;
5664
5665    fn next(&mut self) -> Option<Self::Item> {
5666        if let Some(item) = self.entry() {
5667            self.advance();
5668            Some(item)
5669        } else {
5670            None
5671        }
5672    }
5673}
5674
5675#[derive(Debug, Clone, Copy)]
5676pub enum PathTarget<'a> {
5677    Path(&'a RelPath),
5678    Successor(&'a RelPath),
5679}
5680
5681impl PathTarget<'_> {
5682    fn cmp_path(&self, other: &RelPath) -> Ordering {
5683        match self {
5684            PathTarget::Path(path) => path.cmp(&other),
5685            PathTarget::Successor(path) => {
5686                if other.starts_with(path) {
5687                    Ordering::Greater
5688                } else {
5689                    Ordering::Equal
5690                }
5691            }
5692        }
5693    }
5694}
5695
5696impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5697    fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5698        self.cmp_path(cursor_location.max_path)
5699    }
5700}
5701
5702impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5703    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5704        self.cmp_path(cursor_location.max_path)
5705    }
5706}
5707
5708#[derive(Debug)]
5709enum TraversalTarget<'a> {
5710    Path(PathTarget<'a>),
5711    Count {
5712        count: usize,
5713        include_files: bool,
5714        include_ignored: bool,
5715        include_dirs: bool,
5716    },
5717}
5718
5719impl<'a> TraversalTarget<'a> {
5720    fn path(path: &'a RelPath) -> Self {
5721        Self::Path(PathTarget::Path(path))
5722    }
5723
5724    fn successor(path: &'a RelPath) -> Self {
5725        Self::Path(PathTarget::Successor(path))
5726    }
5727
5728    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5729        match self {
5730            TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5731            TraversalTarget::Count {
5732                count,
5733                include_files,
5734                include_dirs,
5735                include_ignored,
5736            } => Ord::cmp(
5737                count,
5738                &progress.count(*include_files, *include_dirs, *include_ignored),
5739            ),
5740        }
5741    }
5742}
5743
5744impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5745    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5746        self.cmp_progress(cursor_location)
5747    }
5748}
5749
5750impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5751    for TraversalTarget<'_>
5752{
5753    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5754        self.cmp_progress(cursor_location)
5755    }
5756}
5757
5758pub struct ChildEntriesOptions {
5759    pub include_files: bool,
5760    pub include_dirs: bool,
5761    pub include_ignored: bool,
5762}
5763
5764pub struct ChildEntriesIter<'a> {
5765    parent_path: &'a RelPath,
5766    traversal: Traversal<'a>,
5767}
5768
5769impl<'a> Iterator for ChildEntriesIter<'a> {
5770    type Item = &'a Entry;
5771
5772    fn next(&mut self) -> Option<Self::Item> {
5773        if let Some(item) = self.traversal.entry()
5774            && item.path.starts_with(self.parent_path)
5775        {
5776            self.traversal.advance_to_sibling();
5777            return Some(item);
5778        }
5779        None
5780    }
5781}
5782
5783impl<'a> From<&'a Entry> for proto::Entry {
5784    fn from(entry: &'a Entry) -> Self {
5785        Self {
5786            id: entry.id.to_proto(),
5787            is_dir: entry.is_dir(),
5788            path: entry.path.as_ref().to_proto(),
5789            inode: entry.inode,
5790            mtime: entry.mtime.map(|time| time.into()),
5791            is_ignored: entry.is_ignored,
5792            is_hidden: entry.is_hidden,
5793            is_external: entry.is_external,
5794            is_fifo: entry.is_fifo,
5795            size: Some(entry.size),
5796            canonical_path: entry
5797                .canonical_path
5798                .as_ref()
5799                .map(|path| path.to_string_lossy().into_owned()),
5800        }
5801    }
5802}
5803
5804impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5805    type Error = anyhow::Error;
5806
5807    fn try_from(
5808        (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5809    ) -> Result<Self> {
5810        let kind = if entry.is_dir {
5811            EntryKind::Dir
5812        } else {
5813            EntryKind::File
5814        };
5815
5816        let path =
5817            RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
5818        let char_bag = char_bag_for_path(*root_char_bag, &path);
5819        let is_always_included = always_included.is_match(&path);
5820        Ok(Entry {
5821            id: ProjectEntryId::from_proto(entry.id),
5822            kind,
5823            path,
5824            inode: entry.inode,
5825            mtime: entry.mtime.map(|time| time.into()),
5826            size: entry.size.unwrap_or(0),
5827            canonical_path: entry
5828                .canonical_path
5829                .map(|path_string| Arc::from(PathBuf::from(path_string))),
5830            is_ignored: entry.is_ignored,
5831            is_hidden: entry.is_hidden,
5832            is_always_included,
5833            is_external: entry.is_external,
5834            is_private: false,
5835            char_bag,
5836            is_fifo: entry.is_fifo,
5837        })
5838    }
5839}
5840
5841#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5842pub struct ProjectEntryId(usize);
5843
5844impl ProjectEntryId {
5845    pub const MAX: Self = Self(usize::MAX);
5846    pub const MIN: Self = Self(usize::MIN);
5847
5848    pub fn new(counter: &AtomicUsize) -> Self {
5849        Self(counter.fetch_add(1, SeqCst))
5850    }
5851
5852    pub fn from_proto(id: u64) -> Self {
5853        Self(id as usize)
5854    }
5855
5856    pub fn to_proto(self) -> u64 {
5857        self.0 as u64
5858    }
5859
5860    pub fn from_usize(id: usize) -> Self {
5861        ProjectEntryId(id)
5862    }
5863
5864    pub fn to_usize(self) -> usize {
5865        self.0
5866    }
5867}
5868
5869#[cfg(feature = "test-support")]
5870impl CreatedEntry {
5871    pub fn into_included(self) -> Option<Entry> {
5872        match self {
5873            CreatedEntry::Included(entry) => Some(entry),
5874            CreatedEntry::Excluded { .. } => None,
5875        }
5876    }
5877}
5878
5879fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
5880    let path = content
5881        .strip_prefix("gitdir:")
5882        .with_context(|| format!("parsing gitfile content {content:?}"))?;
5883    Ok(Path::new(path.trim()))
5884}
5885
5886async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
5887    let mut repository_dir_abs_path = dot_git_abs_path.clone();
5888    let mut common_dir_abs_path = dot_git_abs_path.clone();
5889
5890    if let Some(path) = fs
5891        .load(dot_git_abs_path)
5892        .await
5893        .ok()
5894        .as_ref()
5895        .and_then(|contents| parse_gitfile(contents).log_err())
5896    {
5897        let path = dot_git_abs_path
5898            .parent()
5899            .unwrap_or(Path::new(""))
5900            .join(path);
5901        if let Some(path) = fs.canonicalize(&path).await.log_err() {
5902            repository_dir_abs_path = Path::new(&path).into();
5903            common_dir_abs_path = repository_dir_abs_path.clone();
5904
5905            if let Some(commondir_contents) = fs.load(&path.join("commondir")).await.ok()
5906                && let Some(commondir_path) = fs
5907                    .canonicalize(&path.join(commondir_contents.trim()))
5908                    .await
5909                    .log_err()
5910            {
5911                common_dir_abs_path = commondir_path.as_path().into();
5912            }
5913        }
5914    };
5915    (repository_dir_abs_path, common_dir_abs_path)
5916}
5917
5918struct NullWatcher;
5919
5920impl fs::Watcher for NullWatcher {
5921    fn add(&self, _path: &Path) -> Result<()> {
5922        Ok(())
5923    }
5924
5925    fn remove(&self, _path: &Path) -> Result<()> {
5926        Ok(())
5927    }
5928}
5929
5930const FILE_ANALYSIS_BYTES: usize = 1024;
5931
5932async fn decode_file_text(
5933    fs: &dyn Fs,
5934    abs_path: &Path,
5935) -> Result<(String, &'static Encoding, bool)> {
5936    let mut file = fs
5937        .open_sync(&abs_path)
5938        .await
5939        .with_context(|| format!("opening file {abs_path:?}"))?;
5940
5941    // First, read the beginning of the file to determine its kind and encoding.
5942    // We do not want to load an entire large blob into memory only to discard it.
5943    let mut file_first_bytes = Vec::with_capacity(FILE_ANALYSIS_BYTES);
5944    let mut buf = [0u8; FILE_ANALYSIS_BYTES];
5945    let mut reached_eof = false;
5946    loop {
5947        if file_first_bytes.len() >= FILE_ANALYSIS_BYTES {
5948            break;
5949        }
5950        let n = file
5951            .read(&mut buf)
5952            .with_context(|| format!("reading bytes of the file {abs_path:?}"))?;
5953        if n == 0 {
5954            reached_eof = true;
5955            break;
5956        }
5957        file_first_bytes.extend_from_slice(&buf[..n]);
5958    }
5959    let (bom_encoding, byte_content) = decode_byte_header(&file_first_bytes);
5960    anyhow::ensure!(
5961        byte_content != ByteContent::Binary,
5962        "Binary files are not supported"
5963    );
5964
5965    // If the file is eligible for opening, read the rest of the file.
5966    let mut content = file_first_bytes;
5967    if !reached_eof {
5968        let mut buf = [0u8; 8 * 1024];
5969        loop {
5970            let n = file
5971                .read(&mut buf)
5972                .with_context(|| format!("reading remaining bytes of the file {abs_path:?}"))?;
5973            if n == 0 {
5974                break;
5975            }
5976            content.extend_from_slice(&buf[..n]);
5977        }
5978    }
5979    decode_byte_full(content, bom_encoding, byte_content)
5980}
5981
5982fn decode_byte_header(prefix: &[u8]) -> (Option<&'static Encoding>, ByteContent) {
5983    if let Some((encoding, _bom_len)) = Encoding::for_bom(prefix) {
5984        return (Some(encoding), ByteContent::Unknown);
5985    }
5986    (None, analyze_byte_content(prefix))
5987}
5988
5989fn decode_byte_full(
5990    bytes: Vec<u8>,
5991    bom_encoding: Option<&'static Encoding>,
5992    byte_content: ByteContent,
5993) -> Result<(String, &'static Encoding, bool)> {
5994    if let Some(encoding) = bom_encoding {
5995        let (cow, _) = encoding.decode_with_bom_removal(&bytes);
5996        return Ok((cow.into_owned(), encoding, true));
5997    }
5998
5999    match byte_content {
6000        ByteContent::Utf16Le => {
6001            let encoding = encoding_rs::UTF_16LE;
6002            let (cow, _, _) = encoding.decode(&bytes);
6003            return Ok((cow.into_owned(), encoding, false));
6004        }
6005        ByteContent::Utf16Be => {
6006            let encoding = encoding_rs::UTF_16BE;
6007            let (cow, _, _) = encoding.decode(&bytes);
6008            return Ok((cow.into_owned(), encoding, false));
6009        }
6010        ByteContent::Binary => {
6011            anyhow::bail!("Binary files are not supported");
6012        }
6013        ByteContent::Unknown => {}
6014    }
6015
6016    fn detect_encoding(bytes: Vec<u8>) -> (String, &'static Encoding) {
6017        let mut detector = EncodingDetector::new();
6018        detector.feed(&bytes, true);
6019
6020        let encoding = detector.guess(None, true); // Use None for TLD hint to ensure neutral detection logic.
6021
6022        let (cow, _, _) = encoding.decode(&bytes);
6023        (cow.into_owned(), encoding)
6024    }
6025
6026    match String::from_utf8(bytes) {
6027        Ok(text) => {
6028            // ISO-2022-JP (and other ISO-2022 variants) consists entirely of 7-bit ASCII bytes,
6029            // so it is valid UTF-8. However, it contains escape sequences starting with '\x1b'.
6030            // If we find an escape character, we double-check the encoding to prevent
6031            // displaying raw escape sequences instead of the correct characters.
6032            if text.contains('\x1b') {
6033                let (s, enc) = detect_encoding(text.into_bytes());
6034                Ok((s, enc, false))
6035            } else {
6036                Ok((text, encoding_rs::UTF_8, false))
6037            }
6038        }
6039        Err(e) => {
6040            let (s, enc) = detect_encoding(e.into_bytes());
6041            Ok((s, enc, false))
6042        }
6043    }
6044}
6045
6046#[derive(PartialEq)]
6047enum ByteContent {
6048    Utf16Le,
6049    Utf16Be,
6050    Binary,
6051    Unknown,
6052}
6053
6054// Heuristic check using null byte distribution plus a generic text-likeness
6055// heuristic. This prefers UTF-16 when many bytes are NUL and otherwise
6056// distinguishes between text-like and binary-like content.
6057fn analyze_byte_content(bytes: &[u8]) -> ByteContent {
6058    if bytes.len() < 2 {
6059        return ByteContent::Unknown;
6060    }
6061
6062    if is_known_binary_header(bytes) {
6063        return ByteContent::Binary;
6064    }
6065
6066    let limit = bytes.len().min(FILE_ANALYSIS_BYTES);
6067    let mut even_null_count = 0usize;
6068    let mut odd_null_count = 0usize;
6069    let mut non_text_like_count = 0usize;
6070
6071    for (i, &byte) in bytes[..limit].iter().enumerate() {
6072        if byte == 0 {
6073            if i % 2 == 0 {
6074                even_null_count += 1;
6075            } else {
6076                odd_null_count += 1;
6077            }
6078            non_text_like_count += 1;
6079            continue;
6080        }
6081
6082        let is_text_like = match byte {
6083            b'\t' | b'\n' | b'\r' | 0x0C => true,
6084            0x20..=0x7E => true,
6085            // Treat bytes that are likely part of UTF-8 or single-byte encodings as text-like.
6086            0x80..=0xBF | 0xC2..=0xF4 => true,
6087            _ => false,
6088        };
6089
6090        if !is_text_like {
6091            non_text_like_count += 1;
6092        }
6093    }
6094
6095    let total_null_count = even_null_count + odd_null_count;
6096
6097    // If there are no NUL bytes at all, this is overwhelmingly likely to be text.
6098    if total_null_count == 0 {
6099        return ByteContent::Unknown;
6100    }
6101
6102    if total_null_count >= limit / 16 {
6103        if even_null_count > odd_null_count * 4 {
6104            return ByteContent::Utf16Be;
6105        }
6106        if odd_null_count > even_null_count * 4 {
6107            return ByteContent::Utf16Le;
6108        }
6109        return ByteContent::Binary;
6110    }
6111
6112    if non_text_like_count * 100 < limit * 8 {
6113        ByteContent::Unknown
6114    } else {
6115        ByteContent::Binary
6116    }
6117}
6118
6119fn is_known_binary_header(bytes: &[u8]) -> bool {
6120    bytes.starts_with(b"%PDF-") // PDF
6121        || bytes.starts_with(b"PK\x03\x04") // ZIP local header
6122        || bytes.starts_with(b"PK\x05\x06") // ZIP end of central directory
6123        || bytes.starts_with(b"PK\x07\x08") // ZIP spanning/splitting
6124        || bytes.starts_with(b"\x89PNG\r\n\x1a\n") // PNG
6125        || bytes.starts_with(b"\xFF\xD8\xFF") // JPEG
6126        || bytes.starts_with(b"GIF87a") // GIF87a
6127        || bytes.starts_with(b"GIF89a") // GIF89a
6128        || bytes.starts_with(b"IWAD") // Doom IWAD archive
6129        || bytes.starts_with(b"PWAD") // Doom PWAD archive
6130}