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