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