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