worktree.rs

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