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