worktree.rs

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