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