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