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