worktree.rs

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