worktree.rs

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