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    /// Get the repository whose work directory contains the given path.
2400    pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
2401        self.repository_entries
2402            .get(&RepositoryWorkDirectory(path.into()))
2403            .cloned()
2404    }
2405
2406    /// Get the repository whose work directory contains the given path.
2407    pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
2408        self.repository_and_work_directory_for_path(path)
2409            .map(|e| e.1)
2410    }
2411
2412    pub fn repository_and_work_directory_for_path(
2413        &self,
2414        path: &Path,
2415    ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
2416        self.repository_entries
2417            .iter()
2418            .filter(|(workdir_path, _)| path.starts_with(workdir_path))
2419            .last()
2420            .map(|(path, repo)| (path.clone(), repo.clone()))
2421    }
2422
2423    /// Given an ordered iterator of entries, returns an iterator of those entries,
2424    /// along with their containing git repository.
2425    pub fn entries_with_repositories<'a>(
2426        &'a self,
2427        entries: impl 'a + Iterator<Item = &'a Entry>,
2428    ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
2429        let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
2430        let mut repositories = self.repositories().peekable();
2431        entries.map(move |entry| {
2432            while let Some((repo_path, _)) = containing_repos.last() {
2433                if entry.path.starts_with(repo_path) {
2434                    break;
2435                } else {
2436                    containing_repos.pop();
2437                }
2438            }
2439            while let Some((repo_path, _)) = repositories.peek() {
2440                if entry.path.starts_with(repo_path) {
2441                    containing_repos.push(repositories.next().unwrap());
2442                } else {
2443                    break;
2444                }
2445            }
2446            let repo = containing_repos.last().map(|(_, repo)| *repo);
2447            (entry, repo)
2448        })
2449    }
2450
2451    /// Updates the `git_status` of the given entries such that files'
2452    /// statuses bubble up to their ancestor directories.
2453    pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
2454        let mut cursor = self
2455            .entries_by_path
2456            .cursor::<(TraversalProgress, GitStatuses)>(&());
2457        let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
2458
2459        let mut result_ix = 0;
2460        loop {
2461            let next_entry = result.get(result_ix);
2462            let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
2463
2464            let entry_to_finish = match (containing_entry, next_entry) {
2465                (Some(_), None) => entry_stack.pop(),
2466                (Some(containing_entry), Some(next_path)) => {
2467                    if next_path.path.starts_with(&containing_entry.path) {
2468                        None
2469                    } else {
2470                        entry_stack.pop()
2471                    }
2472                }
2473                (None, Some(_)) => None,
2474                (None, None) => break,
2475            };
2476
2477            if let Some((entry_ix, prev_statuses)) = entry_to_finish {
2478                cursor.seek_forward(
2479                    &TraversalTarget::PathSuccessor(&result[entry_ix].path),
2480                    Bias::Left,
2481                    &(),
2482                );
2483
2484                let statuses = cursor.start().1 - prev_statuses;
2485
2486                result[entry_ix].git_status = if statuses.conflict > 0 {
2487                    Some(GitFileStatus::Conflict)
2488                } else if statuses.modified > 0 {
2489                    Some(GitFileStatus::Modified)
2490                } else if statuses.added > 0 {
2491                    Some(GitFileStatus::Added)
2492                } else {
2493                    None
2494                };
2495            } else {
2496                if result[result_ix].is_dir() {
2497                    cursor.seek_forward(
2498                        &TraversalTarget::Path(&result[result_ix].path),
2499                        Bias::Left,
2500                        &(),
2501                    );
2502                    entry_stack.push((result_ix, cursor.start().1));
2503                }
2504                result_ix += 1;
2505            }
2506        }
2507    }
2508
2509    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
2510        let empty_path = Path::new("");
2511        self.entries_by_path
2512            .cursor::<()>(&())
2513            .filter(move |entry| entry.path.as_ref() != empty_path)
2514            .map(|entry| &entry.path)
2515    }
2516
2517    pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
2518        let mut cursor = self.entries_by_path.cursor(&());
2519        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
2520        let traversal = Traversal {
2521            cursor,
2522            include_files: true,
2523            include_dirs: true,
2524            include_ignored: true,
2525        };
2526        ChildEntriesIter {
2527            traversal,
2528            parent_path,
2529        }
2530    }
2531
2532    pub fn root_entry(&self) -> Option<&Entry> {
2533        self.entry_for_path("")
2534    }
2535
2536    pub fn root_dir(&self) -> Option<Arc<Path>> {
2537        self.root_entry()
2538            .filter(|entry| entry.is_dir())
2539            .map(|_| self.abs_path().clone())
2540    }
2541
2542    pub fn root_name(&self) -> &str {
2543        &self.root_name
2544    }
2545
2546    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
2547        self.repository_entries
2548            .get(&RepositoryWorkDirectory(Path::new("").into()))
2549            .map(|entry| entry.to_owned())
2550    }
2551
2552    pub fn git_entry(&self, work_directory_path: Arc<Path>) -> Option<RepositoryEntry> {
2553        self.repository_entries
2554            .get(&RepositoryWorkDirectory(work_directory_path))
2555            .map(|entry| entry.to_owned())
2556    }
2557
2558    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
2559        self.repository_entries.values()
2560    }
2561
2562    pub fn scan_id(&self) -> usize {
2563        self.scan_id
2564    }
2565
2566    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
2567        let path = path.as_ref();
2568        self.traverse_from_path(true, true, true, path)
2569            .entry()
2570            .and_then(|entry| {
2571                if entry.path.as_ref() == path {
2572                    Some(entry)
2573                } else {
2574                    None
2575                }
2576            })
2577    }
2578
2579    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2580        let entry = self.entries_by_id.get(&id, &())?;
2581        self.entry_for_path(&entry.path)
2582    }
2583
2584    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
2585        self.entry_for_path(path.as_ref()).map(|e| e.inode)
2586    }
2587}
2588
2589impl LocalSnapshot {
2590    pub fn repo_for_path(&self, path: &Path) -> Option<(RepositoryEntry, &LocalRepositoryEntry)> {
2591        let (_, repo_entry) = self.repository_and_work_directory_for_path(path)?;
2592        let work_directory_id = repo_entry.work_directory_id();
2593        Some((repo_entry, self.git_repositories.get(&work_directory_id)?))
2594    }
2595
2596    fn build_update(
2597        &self,
2598        project_id: u64,
2599        worktree_id: u64,
2600        entry_changes: UpdatedEntriesSet,
2601        repo_changes: UpdatedGitRepositoriesSet,
2602    ) -> proto::UpdateWorktree {
2603        let mut updated_entries = Vec::new();
2604        let mut removed_entries = Vec::new();
2605        let mut updated_repositories = Vec::new();
2606        let mut removed_repositories = Vec::new();
2607
2608        for (_, entry_id, path_change) in entry_changes.iter() {
2609            if let PathChange::Removed = path_change {
2610                removed_entries.push(entry_id.0 as u64);
2611            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2612                updated_entries.push(proto::Entry::from(entry));
2613            }
2614        }
2615
2616        for (work_dir_path, change) in repo_changes.iter() {
2617            let new_repo = self
2618                .repository_entries
2619                .get(&RepositoryWorkDirectory(work_dir_path.clone()));
2620            match (&change.old_repository, new_repo) {
2621                (Some(old_repo), Some(new_repo)) => {
2622                    updated_repositories.push(new_repo.build_update(old_repo));
2623                }
2624                (None, Some(new_repo)) => {
2625                    updated_repositories.push(proto::RepositoryEntry::from(new_repo));
2626                }
2627                (Some(old_repo), None) => {
2628                    removed_repositories.push(old_repo.work_directory.0.to_proto());
2629                }
2630                _ => {}
2631            }
2632        }
2633
2634        removed_entries.sort_unstable();
2635        updated_entries.sort_unstable_by_key(|e| e.id);
2636        removed_repositories.sort_unstable();
2637        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2638
2639        // TODO - optimize, knowing that removed_entries are sorted.
2640        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2641
2642        proto::UpdateWorktree {
2643            project_id,
2644            worktree_id,
2645            abs_path: self.abs_path().to_string_lossy().into(),
2646            root_name: self.root_name().to_string(),
2647            updated_entries,
2648            removed_entries,
2649            scan_id: self.scan_id as u64,
2650            is_last_update: self.completed_scan_id == self.scan_id,
2651            updated_repositories,
2652            removed_repositories,
2653        }
2654    }
2655
2656    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2657        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2658            let abs_path = self.abs_path.as_path().join(&entry.path);
2659            match smol::block_on(build_gitignore(&abs_path, fs)) {
2660                Ok(ignore) => {
2661                    self.ignores_by_parent_abs_path
2662                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2663                }
2664                Err(error) => {
2665                    log::error!(
2666                        "error loading .gitignore file {:?} - {:?}",
2667                        &entry.path,
2668                        error
2669                    );
2670                }
2671            }
2672        }
2673
2674        if entry.kind == EntryKind::PendingDir {
2675            if let Some(existing_entry) =
2676                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2677            {
2678                entry.kind = existing_entry.kind;
2679            }
2680        }
2681
2682        let scan_id = self.scan_id;
2683        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2684        if let Some(removed) = removed {
2685            if removed.id != entry.id {
2686                self.entries_by_id.remove(&removed.id, &());
2687            }
2688        }
2689        self.entries_by_id.insert_or_replace(
2690            PathEntry {
2691                id: entry.id,
2692                path: entry.path.clone(),
2693                is_ignored: entry.is_ignored,
2694                scan_id,
2695            },
2696            &(),
2697        );
2698
2699        entry
2700    }
2701
2702    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2703        let mut inodes = TreeSet::default();
2704        for ancestor in path.ancestors().skip(1) {
2705            if let Some(entry) = self.entry_for_path(ancestor) {
2706                inodes.insert(entry.inode);
2707            }
2708        }
2709        inodes
2710    }
2711
2712    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2713        let mut new_ignores = Vec::new();
2714        for (index, ancestor) in abs_path.ancestors().enumerate() {
2715            if index > 0 {
2716                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2717                    new_ignores.push((ancestor, Some(ignore.clone())));
2718                } else {
2719                    new_ignores.push((ancestor, None));
2720                }
2721            }
2722            if ancestor.join(*DOT_GIT).exists() {
2723                break;
2724            }
2725        }
2726
2727        let mut ignore_stack = IgnoreStack::none();
2728        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2729            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2730                ignore_stack = IgnoreStack::all();
2731                break;
2732            } else if let Some(ignore) = ignore {
2733                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2734            }
2735        }
2736
2737        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2738            ignore_stack = IgnoreStack::all();
2739        }
2740
2741        ignore_stack
2742    }
2743
2744    #[cfg(test)]
2745    pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2746        self.entries_by_path
2747            .cursor::<()>(&())
2748            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2749    }
2750
2751    #[cfg(test)]
2752    pub fn check_invariants(&self, git_state: bool) {
2753        use pretty_assertions::assert_eq;
2754
2755        assert_eq!(
2756            self.entries_by_path
2757                .cursor::<()>(&())
2758                .map(|e| (&e.path, e.id))
2759                .collect::<Vec<_>>(),
2760            self.entries_by_id
2761                .cursor::<()>(&())
2762                .map(|e| (&e.path, e.id))
2763                .collect::<collections::BTreeSet<_>>()
2764                .into_iter()
2765                .collect::<Vec<_>>(),
2766            "entries_by_path and entries_by_id are inconsistent"
2767        );
2768
2769        let mut files = self.files(true, 0);
2770        let mut visible_files = self.files(false, 0);
2771        for entry in self.entries_by_path.cursor::<()>(&()) {
2772            if entry.is_file() {
2773                assert_eq!(files.next().unwrap().inode, entry.inode);
2774                if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2775                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2776                }
2777            }
2778        }
2779
2780        assert!(files.next().is_none());
2781        assert!(visible_files.next().is_none());
2782
2783        let mut bfs_paths = Vec::new();
2784        let mut stack = self
2785            .root_entry()
2786            .map(|e| e.path.as_ref())
2787            .into_iter()
2788            .collect::<Vec<_>>();
2789        while let Some(path) = stack.pop() {
2790            bfs_paths.push(path);
2791            let ix = stack.len();
2792            for child_entry in self.child_entries(path) {
2793                stack.insert(ix, &child_entry.path);
2794            }
2795        }
2796
2797        let dfs_paths_via_iter = self
2798            .entries_by_path
2799            .cursor::<()>(&())
2800            .map(|e| e.path.as_ref())
2801            .collect::<Vec<_>>();
2802        assert_eq!(bfs_paths, dfs_paths_via_iter);
2803
2804        let dfs_paths_via_traversal = self
2805            .entries(true, 0)
2806            .map(|e| e.path.as_ref())
2807            .collect::<Vec<_>>();
2808        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2809
2810        if git_state {
2811            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2812                let ignore_parent_path = ignore_parent_abs_path
2813                    .strip_prefix(self.abs_path.as_path())
2814                    .unwrap();
2815                assert!(self.entry_for_path(ignore_parent_path).is_some());
2816                assert!(self
2817                    .entry_for_path(ignore_parent_path.join(*GITIGNORE))
2818                    .is_some());
2819            }
2820        }
2821    }
2822
2823    #[cfg(test)]
2824    fn check_git_invariants(&self) {
2825        let dotgit_paths = self
2826            .git_repositories
2827            .iter()
2828            .map(|repo| repo.1.dot_git_dir_abs_path.clone())
2829            .collect::<HashSet<_>>();
2830        let work_dir_paths = self
2831            .repository_entries
2832            .iter()
2833            .map(|repo| repo.0.clone().0)
2834            .collect::<HashSet<_>>();
2835        assert_eq!(dotgit_paths.len(), work_dir_paths.len());
2836        assert_eq!(self.repository_entries.iter().count(), work_dir_paths.len());
2837        assert_eq!(self.git_repositories.iter().count(), work_dir_paths.len());
2838        for (_, entry) in self.repository_entries.iter() {
2839            self.git_repositories.get(&entry.work_directory).unwrap();
2840        }
2841    }
2842
2843    #[cfg(test)]
2844    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2845        let mut paths = Vec::new();
2846        for entry in self.entries_by_path.cursor::<()>(&()) {
2847            if include_ignored || !entry.is_ignored {
2848                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2849            }
2850        }
2851        paths.sort_by(|a, b| a.0.cmp(b.0));
2852        paths
2853    }
2854}
2855
2856impl BackgroundScannerState {
2857    fn should_scan_directory(&self, entry: &Entry) -> bool {
2858        (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
2859            || entry.path.file_name() == Some(*DOT_GIT)
2860            || entry.path.file_name() == Some(local_settings_folder_relative_path().as_os_str())
2861            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2862            || self
2863                .paths_to_scan
2864                .iter()
2865                .any(|p| p.starts_with(&entry.path))
2866            || self
2867                .path_prefixes_to_scan
2868                .iter()
2869                .any(|p| entry.path.starts_with(p))
2870    }
2871
2872    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2873        let path = entry.path.clone();
2874        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2875        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2876        let mut containing_repository = None;
2877        if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2878            if let Some((repo_entry, repo)) = self.snapshot.repo_for_path(&path) {
2879                if let Some(workdir_path) = repo_entry.work_directory(&self.snapshot) {
2880                    if let Ok(repo_path) = repo_entry.relativize(&self.snapshot, &path) {
2881                        containing_repository = Some(ScanJobContainingRepository {
2882                            work_directory: workdir_path,
2883                            statuses: repo
2884                                .repo_ptr
2885                                .status(&[repo_path.0])
2886                                .log_err()
2887                                .unwrap_or_default(),
2888                        });
2889                    }
2890                }
2891            }
2892        }
2893        if !ancestor_inodes.contains(&entry.inode) {
2894            ancestor_inodes.insert(entry.inode);
2895            scan_job_tx
2896                .try_send(ScanJob {
2897                    abs_path,
2898                    path,
2899                    ignore_stack,
2900                    scan_queue: scan_job_tx.clone(),
2901                    ancestor_inodes,
2902                    is_external: entry.is_external,
2903                    containing_repository,
2904                })
2905                .unwrap();
2906        }
2907    }
2908
2909    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2910        if let Some(mtime) = entry.mtime {
2911            // If an entry with the same inode was removed from the worktree during this scan,
2912            // then it *might* represent the same file or directory. But the OS might also have
2913            // re-used the inode for a completely different file or directory.
2914            //
2915            // Conditionally reuse the old entry's id:
2916            // * if the mtime is the same, the file was probably been renamed.
2917            // * if the path is the same, the file may just have been updated
2918            if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2919                if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2920                    entry.id = removed_entry.id;
2921                }
2922            } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2923                entry.id = existing_entry.id;
2924            }
2925        }
2926    }
2927
2928    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2929        self.reuse_entry_id(&mut entry);
2930        let entry = self.snapshot.insert_entry(entry, fs);
2931        if entry.path.file_name() == Some(&DOT_GIT) {
2932            self.insert_git_repository(entry.path.clone(), fs, watcher);
2933        }
2934
2935        #[cfg(test)]
2936        self.snapshot.check_invariants(false);
2937
2938        entry
2939    }
2940
2941    fn populate_dir(
2942        &mut self,
2943        parent_path: &Arc<Path>,
2944        entries: impl IntoIterator<Item = Entry>,
2945        ignore: Option<Arc<Gitignore>>,
2946    ) {
2947        let mut parent_entry = if let Some(parent_entry) = self
2948            .snapshot
2949            .entries_by_path
2950            .get(&PathKey(parent_path.clone()), &())
2951        {
2952            parent_entry.clone()
2953        } else {
2954            log::warn!(
2955                "populating a directory {:?} that has been removed",
2956                parent_path
2957            );
2958            return;
2959        };
2960
2961        match parent_entry.kind {
2962            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2963            EntryKind::Dir => {}
2964            _ => return,
2965        }
2966
2967        if let Some(ignore) = ignore {
2968            let abs_parent_path = self.snapshot.abs_path.as_path().join(parent_path).into();
2969            self.snapshot
2970                .ignores_by_parent_abs_path
2971                .insert(abs_parent_path, (ignore, false));
2972        }
2973
2974        let parent_entry_id = parent_entry.id;
2975        self.scanned_dirs.insert(parent_entry_id);
2976        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2977        let mut entries_by_id_edits = Vec::new();
2978
2979        for entry in entries {
2980            entries_by_id_edits.push(Edit::Insert(PathEntry {
2981                id: entry.id,
2982                path: entry.path.clone(),
2983                is_ignored: entry.is_ignored,
2984                scan_id: self.snapshot.scan_id,
2985            }));
2986            entries_by_path_edits.push(Edit::Insert(entry));
2987        }
2988
2989        self.snapshot
2990            .entries_by_path
2991            .edit(entries_by_path_edits, &());
2992        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2993
2994        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2995            self.changed_paths.insert(ix, parent_path.clone());
2996        }
2997
2998        #[cfg(test)]
2999        self.snapshot.check_invariants(false);
3000    }
3001
3002    fn remove_path(&mut self, path: &Path) {
3003        let mut new_entries;
3004        let removed_entries;
3005        {
3006            let mut cursor = self
3007                .snapshot
3008                .entries_by_path
3009                .cursor::<TraversalProgress>(&());
3010            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
3011            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
3012            new_entries.append(cursor.suffix(&()), &());
3013        }
3014        self.snapshot.entries_by_path = new_entries;
3015
3016        let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
3017        for entry in removed_entries.cursor::<()>(&()) {
3018            match self.removed_entries.entry(entry.inode) {
3019                hash_map::Entry::Occupied(mut e) => {
3020                    let prev_removed_entry = e.get_mut();
3021                    if entry.id > prev_removed_entry.id {
3022                        *prev_removed_entry = entry.clone();
3023                    }
3024                }
3025                hash_map::Entry::Vacant(e) => {
3026                    e.insert(entry.clone());
3027                }
3028            }
3029
3030            if entry.path.file_name() == Some(&GITIGNORE) {
3031                let abs_parent_path = self
3032                    .snapshot
3033                    .abs_path
3034                    .as_path()
3035                    .join(entry.path.parent().unwrap());
3036                if let Some((_, needs_update)) = self
3037                    .snapshot
3038                    .ignores_by_parent_abs_path
3039                    .get_mut(abs_parent_path.as_path())
3040                {
3041                    *needs_update = true;
3042                }
3043            }
3044
3045            if let Err(ix) = removed_ids.binary_search(&entry.id) {
3046                removed_ids.insert(ix, entry.id);
3047            }
3048        }
3049
3050        self.snapshot.entries_by_id.edit(
3051            removed_ids.iter().map(|&id| Edit::Remove(id)).collect(),
3052            &(),
3053        );
3054        self.snapshot
3055            .git_repositories
3056            .retain(|id, _| removed_ids.binary_search(id).is_err());
3057        self.snapshot
3058            .repository_entries
3059            .retain(|repo_path, _| !repo_path.0.starts_with(path));
3060
3061        #[cfg(test)]
3062        self.snapshot.check_invariants(false);
3063    }
3064
3065    fn insert_git_repository(
3066        &mut self,
3067        dot_git_path: Arc<Path>,
3068        fs: &dyn Fs,
3069        watcher: &dyn Watcher,
3070    ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
3071        let work_dir_path: Arc<Path> = match dot_git_path.parent() {
3072            Some(parent_dir) => {
3073                // Guard against repositories inside the repository metadata
3074                if parent_dir.iter().any(|component| component == *DOT_GIT) {
3075                    log::info!(
3076                        "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3077                    );
3078                    return None;
3079                };
3080                log::info!(
3081                    "building git repository, `.git` path in the worktree: {dot_git_path:?}"
3082                );
3083
3084                parent_dir.into()
3085            }
3086            None => {
3087                // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3088                // no files inside that directory are tracked by git, so no need to build the repo around it
3089                log::info!(
3090                    "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3091                );
3092                return None;
3093            }
3094        };
3095
3096        self.insert_git_repository_for_path(work_dir_path, dot_git_path, None, fs, watcher)
3097    }
3098
3099    fn insert_git_repository_for_path(
3100        &mut self,
3101        work_dir_path: Arc<Path>,
3102        dot_git_path: Arc<Path>,
3103        location_in_repo: Option<Arc<Path>>,
3104        fs: &dyn Fs,
3105        watcher: &dyn Watcher,
3106    ) -> Option<(RepositoryWorkDirectory, Arc<dyn GitRepository>)> {
3107        let work_dir_id = self
3108            .snapshot
3109            .entry_for_path(work_dir_path.clone())
3110            .map(|entry| entry.id)?;
3111
3112        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
3113            return None;
3114        }
3115
3116        let dot_git_abs_path = self.snapshot.abs_path.as_path().join(&dot_git_path);
3117
3118        let t0 = Instant::now();
3119        let repository = fs.open_repo(&dot_git_abs_path)?;
3120
3121        let actual_repo_path = repository.dot_git_dir();
3122
3123        let actual_dot_git_dir_abs_path = smol::block_on(find_git_dir(&actual_repo_path, fs))?;
3124        watcher.add(&actual_repo_path).log_err()?;
3125
3126        let dot_git_worktree_abs_path = if actual_dot_git_dir_abs_path.as_ref() == dot_git_abs_path
3127        {
3128            None
3129        } else {
3130            // The two paths could be different because we opened a git worktree.
3131            // When that happens, the .git path in the worktree (`dot_git_abs_path`) is a file that
3132            // points to the worktree-subdirectory in the actual .git directory (`git_dir_path`)
3133            watcher.add(&dot_git_abs_path).log_err()?;
3134            Some(Arc::from(dot_git_abs_path))
3135        };
3136
3137        log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
3138        let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
3139
3140        if let Some(git_hosting_provider_registry) = self.git_hosting_provider_registry.clone() {
3141            git_hosting_providers::register_additional_providers(
3142                git_hosting_provider_registry,
3143                repository.clone(),
3144            );
3145        }
3146
3147        self.snapshot.repository_entries.insert(
3148            work_directory.clone(),
3149            RepositoryEntry {
3150                work_directory: work_dir_id.into(),
3151                branch: repository.branch_name().map(Into::into),
3152                location_in_repo,
3153            },
3154        );
3155        self.snapshot.git_repositories.insert(
3156            work_dir_id,
3157            LocalRepositoryEntry {
3158                git_dir_scan_id: 0,
3159                repo_ptr: repository.clone(),
3160                dot_git_dir_abs_path: actual_dot_git_dir_abs_path,
3161                dot_git_worktree_abs_path,
3162            },
3163        );
3164
3165        Some((work_directory, repository))
3166    }
3167}
3168
3169async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3170    if path.file_name() == Some(&*DOT_GIT) {
3171        return true;
3172    }
3173
3174    // If we're in a bare repository, we are not inside a `.git` folder. In a
3175    // bare repository, the root folder contains what would normally be in the
3176    // `.git` folder.
3177    let head_metadata = fs.metadata(&path.join("HEAD")).await;
3178    if !matches!(head_metadata, Ok(Some(_))) {
3179        return false;
3180    }
3181    let config_metadata = fs.metadata(&path.join("config")).await;
3182    matches!(config_metadata, Ok(Some(_)))
3183}
3184
3185async fn find_git_dir(path: &Path, fs: &dyn Fs) -> Option<Arc<Path>> {
3186    for ancestor in path.ancestors() {
3187        if is_git_dir(ancestor, fs).await {
3188            return Some(Arc::from(ancestor));
3189        }
3190    }
3191    None
3192}
3193
3194async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3195    let contents = fs.load(abs_path).await?;
3196    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3197    let mut builder = GitignoreBuilder::new(parent);
3198    for line in contents.lines() {
3199        builder.add_line(Some(abs_path.into()), line)?;
3200    }
3201    Ok(builder.build()?)
3202}
3203
3204impl Deref for Worktree {
3205    type Target = Snapshot;
3206
3207    fn deref(&self) -> &Self::Target {
3208        match self {
3209            Worktree::Local(worktree) => &worktree.snapshot,
3210            Worktree::Remote(worktree) => &worktree.snapshot,
3211        }
3212    }
3213}
3214
3215impl Deref for LocalWorktree {
3216    type Target = LocalSnapshot;
3217
3218    fn deref(&self) -> &Self::Target {
3219        &self.snapshot
3220    }
3221}
3222
3223impl Deref for RemoteWorktree {
3224    type Target = Snapshot;
3225
3226    fn deref(&self) -> &Self::Target {
3227        &self.snapshot
3228    }
3229}
3230
3231impl fmt::Debug for LocalWorktree {
3232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3233        self.snapshot.fmt(f)
3234    }
3235}
3236
3237impl fmt::Debug for Snapshot {
3238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3239        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3240        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3241
3242        impl<'a> fmt::Debug for EntriesByPath<'a> {
3243            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3244                f.debug_map()
3245                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3246                    .finish()
3247            }
3248        }
3249
3250        impl<'a> fmt::Debug for EntriesById<'a> {
3251            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3252                f.debug_list().entries(self.0.iter()).finish()
3253            }
3254        }
3255
3256        f.debug_struct("Snapshot")
3257            .field("id", &self.id)
3258            .field("root_name", &self.root_name)
3259            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3260            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3261            .finish()
3262    }
3263}
3264
3265#[derive(Clone, PartialEq)]
3266pub struct File {
3267    pub worktree: Model<Worktree>,
3268    pub path: Arc<Path>,
3269    pub disk_state: DiskState,
3270    pub entry_id: Option<ProjectEntryId>,
3271    pub is_local: bool,
3272    pub is_private: bool,
3273}
3274
3275impl language::File for File {
3276    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3277        if self.is_local {
3278            Some(self)
3279        } else {
3280            None
3281        }
3282    }
3283
3284    fn disk_state(&self) -> DiskState {
3285        self.disk_state
3286    }
3287
3288    fn path(&self) -> &Arc<Path> {
3289        &self.path
3290    }
3291
3292    fn full_path(&self, cx: &AppContext) -> PathBuf {
3293        let mut full_path = PathBuf::new();
3294        let worktree = self.worktree.read(cx);
3295
3296        if worktree.is_visible() {
3297            full_path.push(worktree.root_name());
3298        } else {
3299            let path = worktree.abs_path();
3300
3301            if worktree.is_local() && path.starts_with(home_dir().as_path()) {
3302                full_path.push("~");
3303                full_path.push(path.strip_prefix(home_dir().as_path()).unwrap());
3304            } else {
3305                full_path.push(path)
3306            }
3307        }
3308
3309        if self.path.components().next().is_some() {
3310            full_path.push(&self.path);
3311        }
3312
3313        full_path
3314    }
3315
3316    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3317    /// of its worktree, then this method will return the name of the worktree itself.
3318    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
3319        self.path
3320            .file_name()
3321            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
3322    }
3323
3324    fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3325        self.worktree.read(cx).id()
3326    }
3327
3328    fn as_any(&self) -> &dyn Any {
3329        self
3330    }
3331
3332    fn to_proto(&self, cx: &AppContext) -> rpc::proto::File {
3333        rpc::proto::File {
3334            worktree_id: self.worktree.read(cx).id().to_proto(),
3335            entry_id: self.entry_id.map(|id| id.to_proto()),
3336            path: self.path.to_string_lossy().into(),
3337            mtime: self.disk_state.mtime().map(|time| time.into()),
3338            is_deleted: self.disk_state == DiskState::Deleted,
3339        }
3340    }
3341
3342    fn is_private(&self) -> bool {
3343        self.is_private
3344    }
3345}
3346
3347impl language::LocalFile for File {
3348    fn abs_path(&self, cx: &AppContext) -> PathBuf {
3349        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
3350        if self.path.as_ref() == Path::new("") {
3351            worktree_path.as_path().to_path_buf()
3352        } else {
3353            worktree_path.as_path().join(&self.path)
3354        }
3355    }
3356
3357    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
3358        let worktree = self.worktree.read(cx).as_local().unwrap();
3359        let abs_path = worktree.absolutize(&self.path);
3360        let fs = worktree.fs.clone();
3361        cx.background_executor()
3362            .spawn(async move { fs.load(&abs_path?).await })
3363    }
3364
3365    fn load_bytes(&self, cx: &AppContext) -> Task<Result<Vec<u8>>> {
3366        let worktree = self.worktree.read(cx).as_local().unwrap();
3367        let abs_path = worktree.absolutize(&self.path);
3368        let fs = worktree.fs.clone();
3369        cx.background_executor()
3370            .spawn(async move { fs.load_bytes(&abs_path?).await })
3371    }
3372}
3373
3374impl File {
3375    pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
3376        Arc::new(Self {
3377            worktree,
3378            path: entry.path.clone(),
3379            disk_state: if let Some(mtime) = entry.mtime {
3380                DiskState::Present { mtime }
3381            } else {
3382                DiskState::New
3383            },
3384            entry_id: Some(entry.id),
3385            is_local: true,
3386            is_private: entry.is_private,
3387        })
3388    }
3389
3390    pub fn from_proto(
3391        proto: rpc::proto::File,
3392        worktree: Model<Worktree>,
3393        cx: &AppContext,
3394    ) -> Result<Self> {
3395        let worktree_id = worktree
3396            .read(cx)
3397            .as_remote()
3398            .ok_or_else(|| anyhow!("not remote"))?
3399            .id();
3400
3401        if worktree_id.to_proto() != proto.worktree_id {
3402            return Err(anyhow!("worktree id does not match file"));
3403        }
3404
3405        let disk_state = if proto.is_deleted {
3406            DiskState::Deleted
3407        } else {
3408            if let Some(mtime) = proto.mtime.map(&Into::into) {
3409                DiskState::Present { mtime }
3410            } else {
3411                DiskState::New
3412            }
3413        };
3414
3415        Ok(Self {
3416            worktree,
3417            path: Path::new(&proto.path).into(),
3418            disk_state,
3419            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3420            is_local: false,
3421            is_private: false,
3422        })
3423    }
3424
3425    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3426        file.and_then(|f| f.as_any().downcast_ref())
3427    }
3428
3429    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3430        self.worktree.read(cx).id()
3431    }
3432
3433    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
3434        match self.disk_state {
3435            DiskState::Deleted => None,
3436            _ => self.entry_id,
3437        }
3438    }
3439}
3440
3441#[derive(Clone, Debug, PartialEq, Eq)]
3442pub struct Entry {
3443    pub id: ProjectEntryId,
3444    pub kind: EntryKind,
3445    pub path: Arc<Path>,
3446    pub inode: u64,
3447    pub mtime: Option<MTime>,
3448
3449    pub canonical_path: Option<Box<Path>>,
3450    /// Whether this entry is ignored by Git.
3451    ///
3452    /// We only scan ignored entries once the directory is expanded and
3453    /// exclude them from searches.
3454    pub is_ignored: bool,
3455
3456    /// Whether this entry is always included in searches.
3457    ///
3458    /// This is used for entries that are always included in searches, even
3459    /// if they are ignored by git. Overridden by file_scan_exclusions.
3460    pub is_always_included: bool,
3461
3462    /// Whether this entry's canonical path is outside of the worktree.
3463    /// This means the entry is only accessible from the worktree root via a
3464    /// symlink.
3465    ///
3466    /// We only scan entries outside of the worktree once the symlinked
3467    /// directory is expanded. External entries are treated like gitignored
3468    /// entries in that they are not included in searches.
3469    pub is_external: bool,
3470    pub git_status: Option<GitFileStatus>,
3471    /// Whether this entry is considered to be a `.env` file.
3472    pub is_private: bool,
3473    /// The entry's size on disk, in bytes.
3474    pub size: u64,
3475    pub char_bag: CharBag,
3476    pub is_fifo: bool,
3477}
3478
3479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3480pub enum EntryKind {
3481    UnloadedDir,
3482    PendingDir,
3483    Dir,
3484    File,
3485}
3486
3487#[derive(Clone, Copy, Debug, PartialEq)]
3488pub enum PathChange {
3489    /// A filesystem entry was was created.
3490    Added,
3491    /// A filesystem entry was removed.
3492    Removed,
3493    /// A filesystem entry was updated.
3494    Updated,
3495    /// A filesystem entry was either updated or added. We don't know
3496    /// whether or not it already existed, because the path had not
3497    /// been loaded before the event.
3498    AddedOrUpdated,
3499    /// A filesystem entry was found during the initial scan of the worktree.
3500    Loaded,
3501}
3502
3503pub struct GitRepositoryChange {
3504    /// The previous state of the repository, if it already existed.
3505    pub old_repository: Option<RepositoryEntry>,
3506}
3507
3508pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3509pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
3510
3511impl Entry {
3512    fn new(
3513        path: Arc<Path>,
3514        metadata: &fs::Metadata,
3515        next_entry_id: &AtomicUsize,
3516        root_char_bag: CharBag,
3517        canonical_path: Option<Box<Path>>,
3518    ) -> Self {
3519        let char_bag = char_bag_for_path(root_char_bag, &path);
3520        Self {
3521            id: ProjectEntryId::new(next_entry_id),
3522            kind: if metadata.is_dir {
3523                EntryKind::PendingDir
3524            } else {
3525                EntryKind::File
3526            },
3527            path,
3528            inode: metadata.inode,
3529            mtime: Some(metadata.mtime),
3530            size: metadata.len,
3531            canonical_path,
3532            is_ignored: false,
3533            is_always_included: false,
3534            is_external: false,
3535            is_private: false,
3536            git_status: None,
3537            char_bag,
3538            is_fifo: metadata.is_fifo,
3539        }
3540    }
3541
3542    pub fn is_created(&self) -> bool {
3543        self.mtime.is_some()
3544    }
3545
3546    pub fn is_dir(&self) -> bool {
3547        self.kind.is_dir()
3548    }
3549
3550    pub fn is_file(&self) -> bool {
3551        self.kind.is_file()
3552    }
3553
3554    pub fn git_status(&self) -> Option<GitFileStatus> {
3555        self.git_status
3556    }
3557}
3558
3559impl EntryKind {
3560    pub fn is_dir(&self) -> bool {
3561        matches!(
3562            self,
3563            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3564        )
3565    }
3566
3567    pub fn is_unloaded(&self) -> bool {
3568        matches!(self, EntryKind::UnloadedDir)
3569    }
3570
3571    pub fn is_file(&self) -> bool {
3572        matches!(self, EntryKind::File)
3573    }
3574}
3575
3576impl sum_tree::Item for Entry {
3577    type Summary = EntrySummary;
3578
3579    fn summary(&self, _cx: &()) -> Self::Summary {
3580        let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3581        {
3582            0
3583        } else {
3584            1
3585        };
3586        let file_count;
3587        let non_ignored_file_count;
3588        if self.is_file() {
3589            file_count = 1;
3590            non_ignored_file_count = non_ignored_count;
3591        } else {
3592            file_count = 0;
3593            non_ignored_file_count = 0;
3594        }
3595
3596        let mut statuses = GitStatuses::default();
3597        if let Some(status) = self.git_status {
3598            match status {
3599                GitFileStatus::Added => statuses.added = 1,
3600                GitFileStatus::Modified => statuses.modified = 1,
3601                GitFileStatus::Conflict => statuses.conflict = 1,
3602            }
3603        }
3604
3605        EntrySummary {
3606            max_path: self.path.clone(),
3607            count: 1,
3608            non_ignored_count,
3609            file_count,
3610            non_ignored_file_count,
3611            statuses,
3612        }
3613    }
3614}
3615
3616impl sum_tree::KeyedItem for Entry {
3617    type Key = PathKey;
3618
3619    fn key(&self) -> Self::Key {
3620        PathKey(self.path.clone())
3621    }
3622}
3623
3624#[derive(Clone, Debug)]
3625pub struct EntrySummary {
3626    max_path: Arc<Path>,
3627    count: usize,
3628    non_ignored_count: usize,
3629    file_count: usize,
3630    non_ignored_file_count: usize,
3631    statuses: GitStatuses,
3632}
3633
3634impl Default for EntrySummary {
3635    fn default() -> Self {
3636        Self {
3637            max_path: Arc::from(Path::new("")),
3638            count: 0,
3639            non_ignored_count: 0,
3640            file_count: 0,
3641            non_ignored_file_count: 0,
3642            statuses: Default::default(),
3643        }
3644    }
3645}
3646
3647impl sum_tree::Summary for EntrySummary {
3648    type Context = ();
3649
3650    fn zero(_cx: &()) -> Self {
3651        Default::default()
3652    }
3653
3654    fn add_summary(&mut self, rhs: &Self, _: &()) {
3655        self.max_path = rhs.max_path.clone();
3656        self.count += rhs.count;
3657        self.non_ignored_count += rhs.non_ignored_count;
3658        self.file_count += rhs.file_count;
3659        self.non_ignored_file_count += rhs.non_ignored_file_count;
3660        self.statuses += rhs.statuses;
3661    }
3662}
3663
3664#[derive(Clone, Debug)]
3665struct PathEntry {
3666    id: ProjectEntryId,
3667    path: Arc<Path>,
3668    is_ignored: bool,
3669    scan_id: usize,
3670}
3671
3672impl sum_tree::Item for PathEntry {
3673    type Summary = PathEntrySummary;
3674
3675    fn summary(&self, _cx: &()) -> Self::Summary {
3676        PathEntrySummary { max_id: self.id }
3677    }
3678}
3679
3680impl sum_tree::KeyedItem for PathEntry {
3681    type Key = ProjectEntryId;
3682
3683    fn key(&self) -> Self::Key {
3684        self.id
3685    }
3686}
3687
3688#[derive(Clone, Debug, Default)]
3689struct PathEntrySummary {
3690    max_id: ProjectEntryId,
3691}
3692
3693impl sum_tree::Summary for PathEntrySummary {
3694    type Context = ();
3695
3696    fn zero(_cx: &Self::Context) -> Self {
3697        Default::default()
3698    }
3699
3700    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3701        self.max_id = summary.max_id;
3702    }
3703}
3704
3705impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3706    fn zero(_cx: &()) -> Self {
3707        Default::default()
3708    }
3709
3710    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3711        *self = summary.max_id;
3712    }
3713}
3714
3715#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3716pub struct PathKey(Arc<Path>);
3717
3718impl Default for PathKey {
3719    fn default() -> Self {
3720        Self(Path::new("").into())
3721    }
3722}
3723
3724impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3725    fn zero(_cx: &()) -> Self {
3726        Default::default()
3727    }
3728
3729    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3730        self.0 = summary.max_path.clone();
3731    }
3732}
3733
3734struct BackgroundScanner {
3735    state: Mutex<BackgroundScannerState>,
3736    fs: Arc<dyn Fs>,
3737    fs_case_sensitive: bool,
3738    status_updates_tx: UnboundedSender<ScanState>,
3739    executor: BackgroundExecutor,
3740    scan_requests_rx: channel::Receiver<ScanRequest>,
3741    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3742    next_entry_id: Arc<AtomicUsize>,
3743    phase: BackgroundScannerPhase,
3744    watcher: Arc<dyn Watcher>,
3745    settings: WorktreeSettings,
3746    share_private_files: bool,
3747}
3748
3749#[derive(PartialEq)]
3750enum BackgroundScannerPhase {
3751    InitialScan,
3752    EventsReceivedDuringInitialScan,
3753    Events,
3754}
3755
3756impl BackgroundScanner {
3757    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3758        use futures::FutureExt as _;
3759
3760        // If the worktree root does not contain a git repository, then find
3761        // the git repository in an ancestor directory. Find any gitignore files
3762        // in ancestor directories.
3763        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3764        for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
3765            if index != 0 {
3766                if let Ok(ignore) =
3767                    build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
3768                {
3769                    self.state
3770                        .lock()
3771                        .snapshot
3772                        .ignores_by_parent_abs_path
3773                        .insert(ancestor.into(), (ignore.into(), false));
3774                }
3775            }
3776
3777            let ancestor_dot_git = ancestor.join(*DOT_GIT);
3778            // Check whether the directory or file called `.git` exists (in the
3779            // case of worktrees it's a file.)
3780            if self
3781                .fs
3782                .metadata(&ancestor_dot_git)
3783                .await
3784                .is_ok_and(|metadata| metadata.is_some())
3785            {
3786                if index != 0 {
3787                    // We canonicalize, since the FS events use the canonicalized path.
3788                    if let Some(ancestor_dot_git) =
3789                        self.fs.canonicalize(&ancestor_dot_git).await.log_err()
3790                    {
3791                        // We associate the external git repo with our root folder and
3792                        // also mark where in the git repo the root folder is located.
3793                        self.state.lock().insert_git_repository_for_path(
3794                            Path::new("").into(),
3795                            ancestor_dot_git.into(),
3796                            Some(
3797                                root_abs_path
3798                                    .as_path()
3799                                    .strip_prefix(ancestor)
3800                                    .unwrap()
3801                                    .into(),
3802                            ),
3803                            self.fs.as_ref(),
3804                            self.watcher.as_ref(),
3805                        );
3806                    };
3807                }
3808
3809                // Reached root of git repository.
3810                break;
3811            }
3812        }
3813
3814        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3815        {
3816            let mut state = self.state.lock();
3817            state.snapshot.scan_id += 1;
3818            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3819                let ignore_stack = state
3820                    .snapshot
3821                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
3822                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3823                    root_entry.is_ignored = true;
3824                    state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
3825                }
3826                state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
3827            }
3828        };
3829
3830        // Perform an initial scan of the directory.
3831        drop(scan_job_tx);
3832        self.scan_dirs(true, scan_job_rx).await;
3833        {
3834            let mut state = self.state.lock();
3835            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3836        }
3837
3838        self.send_status_update(false, SmallVec::new());
3839
3840        // Process any any FS events that occurred while performing the initial scan.
3841        // For these events, update events cannot be as precise, because we didn't
3842        // have the previous state loaded yet.
3843        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3844        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3845            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3846                paths.extend(more_paths);
3847            }
3848            self.process_events(paths.into_iter().map(Into::into).collect())
3849                .await;
3850        }
3851
3852        // Continue processing events until the worktree is dropped.
3853        self.phase = BackgroundScannerPhase::Events;
3854
3855        loop {
3856            select_biased! {
3857                // Process any path refresh requests from the worktree. Prioritize
3858                // these before handling changes reported by the filesystem.
3859                request = self.next_scan_request().fuse() => {
3860                    let Ok(request) = request else { break };
3861                    if !self.process_scan_request(request, false).await {
3862                        return;
3863                    }
3864                }
3865
3866                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3867                    let Ok(path_prefix) = path_prefix else { break };
3868                    log::trace!("adding path prefix {:?}", path_prefix);
3869
3870                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3871                    if did_scan {
3872                        let abs_path =
3873                        {
3874                            let mut state = self.state.lock();
3875                            state.path_prefixes_to_scan.insert(path_prefix.clone());
3876                            state.snapshot.abs_path.as_path().join(&path_prefix)
3877                        };
3878
3879                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3880                            self.process_events(vec![abs_path]).await;
3881                        }
3882                    }
3883                }
3884
3885                paths = fs_events_rx.next().fuse() => {
3886                    let Some(mut paths) = paths else { break };
3887                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3888                        paths.extend(more_paths);
3889                    }
3890                    self.process_events(paths.into_iter().map(Into::into).collect()).await;
3891                }
3892            }
3893        }
3894    }
3895
3896    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3897        log::debug!("rescanning paths {:?}", request.relative_paths);
3898
3899        request.relative_paths.sort_unstable();
3900        self.forcibly_load_paths(&request.relative_paths).await;
3901
3902        let root_path = self.state.lock().snapshot.abs_path.clone();
3903        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3904            Ok(path) => path,
3905            Err(err) => {
3906                log::error!("failed to canonicalize root path: {}", err);
3907                return true;
3908            }
3909        };
3910        let abs_paths = request
3911            .relative_paths
3912            .iter()
3913            .map(|path| {
3914                if path.file_name().is_some() {
3915                    root_canonical_path.join(path)
3916                } else {
3917                    root_canonical_path.clone()
3918                }
3919            })
3920            .collect::<Vec<_>>();
3921
3922        {
3923            let mut state = self.state.lock();
3924            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3925            state.snapshot.scan_id += 1;
3926            if is_idle {
3927                state.snapshot.completed_scan_id = state.snapshot.scan_id;
3928            }
3929        }
3930
3931        self.reload_entries_for_paths(
3932            root_path.into(),
3933            root_canonical_path,
3934            &request.relative_paths,
3935            abs_paths,
3936            None,
3937        )
3938        .await;
3939
3940        self.send_status_update(scanning, request.done)
3941    }
3942
3943    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3944        let root_path = self.state.lock().snapshot.abs_path.clone();
3945        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
3946            Ok(path) => path,
3947            Err(err) => {
3948                let new_path = self
3949                    .state
3950                    .lock()
3951                    .snapshot
3952                    .root_file_handle
3953                    .clone()
3954                    .and_then(|handle| handle.current_path(&self.fs).log_err())
3955                    .map(SanitizedPath::from)
3956                    .filter(|new_path| *new_path != root_path);
3957
3958                if let Some(new_path) = new_path.as_ref() {
3959                    log::info!(
3960                        "root renamed from {} to {}",
3961                        root_path.as_path().display(),
3962                        new_path.as_path().display()
3963                    )
3964                } else {
3965                    log::warn!("root path could not be canonicalized: {}", err);
3966                }
3967                self.status_updates_tx
3968                    .unbounded_send(ScanState::RootUpdated { new_path })
3969                    .ok();
3970                return;
3971            }
3972        };
3973
3974        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3975        let mut dot_git_abs_paths = Vec::new();
3976        abs_paths.sort_unstable();
3977        abs_paths.dedup_by(|a, b| a.starts_with(b));
3978        abs_paths.retain(|abs_path| {
3979            let snapshot = &self.state.lock().snapshot;
3980            {
3981                let mut is_git_related = false;
3982
3983                // We don't want to trigger .git rescan for events within .git/fsmonitor--daemon/cookies directory.
3984                #[derive(PartialEq)]
3985                enum FsMonitorParseState {
3986                    Cookies,
3987                    FsMonitor
3988                }
3989                let mut fsmonitor_parse_state = None;
3990                if let Some(dot_git_abs_path) = abs_path
3991                    .ancestors()
3992                    .find(|ancestor| {
3993                        let file_name = ancestor.file_name();
3994                        if file_name == Some(*COOKIES) {
3995                            fsmonitor_parse_state = Some(FsMonitorParseState::Cookies);
3996                            false
3997                        } else if fsmonitor_parse_state == Some(FsMonitorParseState::Cookies) && file_name == Some(*FSMONITOR_DAEMON) {
3998                            fsmonitor_parse_state = Some(FsMonitorParseState::FsMonitor);
3999                            false
4000                        } else if fsmonitor_parse_state != Some(FsMonitorParseState::FsMonitor) && smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4001                            true
4002                        } else {
4003                            fsmonitor_parse_state.take();
4004                            false
4005                        }
4006
4007                    })
4008                {
4009                    let dot_git_abs_path = dot_git_abs_path.to_path_buf();
4010                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4011                        dot_git_abs_paths.push(dot_git_abs_path);
4012                    }
4013                    is_git_related = true;
4014                }
4015
4016                let relative_path: Arc<Path> =
4017                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4018                        path.into()
4019                    } else {
4020                        if is_git_related {
4021                            log::debug!(
4022                              "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4023                            );
4024                        } else {
4025                            log::error!(
4026                              "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4027                            );
4028                        }
4029                        return false;
4030                    };
4031
4032                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4033                    snapshot
4034                        .entry_for_path(parent)
4035                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
4036                });
4037                if !parent_dir_is_loaded {
4038                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
4039                    return false;
4040                }
4041
4042                if self.settings.is_path_excluded(&relative_path) {
4043                    if !is_git_related {
4044                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
4045                    }
4046                    return false;
4047                }
4048
4049                relative_paths.push(relative_path);
4050                true
4051            }
4052        });
4053
4054        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4055            return;
4056        }
4057
4058        self.state.lock().snapshot.scan_id += 1;
4059
4060        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4061        log::debug!("received fs events {:?}", relative_paths);
4062        self.reload_entries_for_paths(
4063            root_path.into(),
4064            root_canonical_path,
4065            &relative_paths,
4066            abs_paths,
4067            Some(scan_job_tx.clone()),
4068        )
4069        .await;
4070
4071        self.update_ignore_statuses(scan_job_tx).await;
4072        self.scan_dirs(false, scan_job_rx).await;
4073
4074        if !dot_git_abs_paths.is_empty() {
4075            self.update_git_repositories(dot_git_abs_paths).await;
4076        }
4077
4078        {
4079            let mut state = self.state.lock();
4080            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4081            for (_, entry) in mem::take(&mut state.removed_entries) {
4082                state.scanned_dirs.remove(&entry.id);
4083            }
4084        }
4085
4086        #[cfg(test)]
4087        self.state.lock().snapshot.check_git_invariants();
4088
4089        self.send_status_update(false, SmallVec::new());
4090    }
4091
4092    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4093        let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
4094        {
4095            let mut state = self.state.lock();
4096            let root_path = state.snapshot.abs_path.clone();
4097            for path in paths {
4098                for ancestor in path.ancestors() {
4099                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4100                        if entry.kind == EntryKind::UnloadedDir {
4101                            let abs_path = root_path.as_path().join(ancestor);
4102                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4103                            state.paths_to_scan.insert(path.clone());
4104                            break;
4105                        }
4106                    }
4107                }
4108            }
4109            drop(scan_job_tx);
4110        }
4111        while let Some(job) = scan_job_rx.next().await {
4112            self.scan_dir(&job).await.log_err();
4113        }
4114
4115        !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4116    }
4117
4118    async fn scan_dirs(
4119        &self,
4120        enable_progress_updates: bool,
4121        scan_jobs_rx: channel::Receiver<ScanJob>,
4122    ) {
4123        use futures::FutureExt as _;
4124
4125        if self
4126            .status_updates_tx
4127            .unbounded_send(ScanState::Started)
4128            .is_err()
4129        {
4130            return;
4131        }
4132
4133        let progress_update_count = AtomicUsize::new(0);
4134        self.executor
4135            .scoped(|scope| {
4136                for _ in 0..self.executor.num_cpus() {
4137                    scope.spawn(async {
4138                        let mut last_progress_update_count = 0;
4139                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4140                        futures::pin_mut!(progress_update_timer);
4141
4142                        loop {
4143                            select_biased! {
4144                                // Process any path refresh requests before moving on to process
4145                                // the scan queue, so that user operations are prioritized.
4146                                request = self.next_scan_request().fuse() => {
4147                                    let Ok(request) = request else { break };
4148                                    if !self.process_scan_request(request, true).await {
4149                                        return;
4150                                    }
4151                                }
4152
4153                                // Send periodic progress updates to the worktree. Use an atomic counter
4154                                // to ensure that only one of the workers sends a progress update after
4155                                // the update interval elapses.
4156                                _ = progress_update_timer => {
4157                                    match progress_update_count.compare_exchange(
4158                                        last_progress_update_count,
4159                                        last_progress_update_count + 1,
4160                                        SeqCst,
4161                                        SeqCst
4162                                    ) {
4163                                        Ok(_) => {
4164                                            last_progress_update_count += 1;
4165                                            self.send_status_update(true, SmallVec::new());
4166                                        }
4167                                        Err(count) => {
4168                                            last_progress_update_count = count;
4169                                        }
4170                                    }
4171                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4172                                }
4173
4174                                // Recursively load directories from the file system.
4175                                job = scan_jobs_rx.recv().fuse() => {
4176                                    let Ok(job) = job else { break };
4177                                    if let Err(err) = self.scan_dir(&job).await {
4178                                        if job.path.as_ref() != Path::new("") {
4179                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4180                                        }
4181                                    }
4182                                }
4183                            }
4184                        }
4185                    })
4186                }
4187            })
4188            .await;
4189    }
4190
4191    fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4192        let mut state = self.state.lock();
4193        if state.changed_paths.is_empty() && scanning {
4194            return true;
4195        }
4196
4197        let new_snapshot = state.snapshot.clone();
4198        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4199        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
4200        state.changed_paths.clear();
4201
4202        self.status_updates_tx
4203            .unbounded_send(ScanState::Updated {
4204                snapshot: new_snapshot,
4205                changes,
4206                scanning,
4207                barrier,
4208            })
4209            .is_ok()
4210    }
4211
4212    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4213        let root_abs_path;
4214        let root_char_bag;
4215        {
4216            let snapshot = &self.state.lock().snapshot;
4217            if self.settings.is_path_excluded(&job.path) {
4218                log::error!("skipping excluded directory {:?}", job.path);
4219                return Ok(());
4220            }
4221            log::debug!("scanning directory {:?}", job.path);
4222            root_abs_path = snapshot.abs_path().clone();
4223            root_char_bag = snapshot.root_char_bag;
4224        }
4225
4226        let next_entry_id = self.next_entry_id.clone();
4227        let mut ignore_stack = job.ignore_stack.clone();
4228        let mut containing_repository = job.containing_repository.clone();
4229        let mut new_ignore = None;
4230        let mut root_canonical_path = None;
4231        let mut new_entries: Vec<Entry> = Vec::new();
4232        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4233        let mut child_paths = self
4234            .fs
4235            .read_dir(&job.abs_path)
4236            .await?
4237            .filter_map(|entry| async {
4238                match entry {
4239                    Ok(entry) => Some(entry),
4240                    Err(error) => {
4241                        log::error!("error processing entry {:?}", error);
4242                        None
4243                    }
4244                }
4245            })
4246            .collect::<Vec<_>>()
4247            .await;
4248
4249        // Ensure that .git and .gitignore are processed first.
4250        swap_to_front(&mut child_paths, *GITIGNORE);
4251        swap_to_front(&mut child_paths, *DOT_GIT);
4252
4253        for child_abs_path in child_paths {
4254            let child_abs_path: Arc<Path> = child_abs_path.into();
4255            let child_name = child_abs_path.file_name().unwrap();
4256            let child_path: Arc<Path> = job.path.join(child_name).into();
4257
4258            if child_name == *DOT_GIT {
4259                let repo = self.state.lock().insert_git_repository(
4260                    child_path.clone(),
4261                    self.fs.as_ref(),
4262                    self.watcher.as_ref(),
4263                );
4264
4265                if let Some((work_directory, repository)) = repo {
4266                    let t0 = Instant::now();
4267                    let statuses = repository
4268                        .status(&[PathBuf::from("")])
4269                        .log_err()
4270                        .unwrap_or_default();
4271                    log::trace!("computed git status in {:?}", t0.elapsed());
4272                    containing_repository = Some(ScanJobContainingRepository {
4273                        work_directory,
4274                        statuses,
4275                    });
4276                }
4277            } else if child_name == *GITIGNORE {
4278                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4279                    Ok(ignore) => {
4280                        let ignore = Arc::new(ignore);
4281                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4282                        new_ignore = Some(ignore);
4283                    }
4284                    Err(error) => {
4285                        log::error!(
4286                            "error loading .gitignore file {:?} - {:?}",
4287                            child_name,
4288                            error
4289                        );
4290                    }
4291                }
4292            }
4293
4294            if self.settings.is_path_excluded(&child_path) {
4295                log::debug!("skipping excluded child entry {child_path:?}");
4296                self.state.lock().remove_path(&child_path);
4297                continue;
4298            }
4299
4300            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4301                Ok(Some(metadata)) => metadata,
4302                Ok(None) => continue,
4303                Err(err) => {
4304                    log::error!("error processing {child_abs_path:?}: {err:?}");
4305                    continue;
4306                }
4307            };
4308
4309            let mut child_entry = Entry::new(
4310                child_path.clone(),
4311                &child_metadata,
4312                &next_entry_id,
4313                root_char_bag,
4314                None,
4315            );
4316
4317            if job.is_external {
4318                child_entry.is_external = true;
4319            } else if child_metadata.is_symlink {
4320                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4321                    Ok(path) => path,
4322                    Err(err) => {
4323                        log::error!(
4324                            "error reading target of symlink {:?}: {:?}",
4325                            child_abs_path,
4326                            err
4327                        );
4328                        continue;
4329                    }
4330                };
4331
4332                // lazily canonicalize the root path in order to determine if
4333                // symlinks point outside of the worktree.
4334                let root_canonical_path = match &root_canonical_path {
4335                    Some(path) => path,
4336                    None => match self.fs.canonicalize(&root_abs_path).await {
4337                        Ok(path) => root_canonical_path.insert(path),
4338                        Err(err) => {
4339                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4340                            continue;
4341                        }
4342                    },
4343                };
4344
4345                if !canonical_path.starts_with(root_canonical_path) {
4346                    child_entry.is_external = true;
4347                }
4348
4349                child_entry.canonical_path = Some(canonical_path.into());
4350            }
4351
4352            if child_entry.is_dir() {
4353                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4354                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4355
4356                // Avoid recursing until crash in the case of a recursive symlink
4357                if job.ancestor_inodes.contains(&child_entry.inode) {
4358                    new_jobs.push(None);
4359                } else {
4360                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4361                    ancestor_inodes.insert(child_entry.inode);
4362
4363                    new_jobs.push(Some(ScanJob {
4364                        abs_path: child_abs_path.clone(),
4365                        path: child_path,
4366                        is_external: child_entry.is_external,
4367                        ignore_stack: if child_entry.is_ignored {
4368                            IgnoreStack::all()
4369                        } else {
4370                            ignore_stack.clone()
4371                        },
4372                        ancestor_inodes,
4373                        scan_queue: job.scan_queue.clone(),
4374                        containing_repository: containing_repository.clone(),
4375                    }));
4376                }
4377            } else {
4378                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4379                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4380                if !child_entry.is_ignored {
4381                    if let Some(repo) = &containing_repository {
4382                        if let Ok(repo_path) = child_entry.path.strip_prefix(&repo.work_directory) {
4383                            let repo_path = RepoPath(repo_path.into());
4384                            child_entry.git_status = repo.statuses.get(&repo_path);
4385                        }
4386                    }
4387                }
4388            }
4389
4390            {
4391                let relative_path = job.path.join(child_name);
4392                if self.is_path_private(&relative_path) {
4393                    log::debug!("detected private file: {relative_path:?}");
4394                    child_entry.is_private = true;
4395                }
4396            }
4397
4398            new_entries.push(child_entry);
4399        }
4400
4401        let mut state = self.state.lock();
4402
4403        // Identify any subdirectories that should not be scanned.
4404        let mut job_ix = 0;
4405        for entry in &mut new_entries {
4406            state.reuse_entry_id(entry);
4407            if entry.is_dir() {
4408                if state.should_scan_directory(entry) {
4409                    job_ix += 1;
4410                } else {
4411                    log::debug!("defer scanning directory {:?}", entry.path);
4412                    entry.kind = EntryKind::UnloadedDir;
4413                    new_jobs.remove(job_ix);
4414                }
4415            }
4416            if entry.is_always_included {
4417                state
4418                    .snapshot
4419                    .always_included_entries
4420                    .push(entry.path.clone());
4421            }
4422        }
4423
4424        state.populate_dir(&job.path, new_entries, new_ignore);
4425        self.watcher.add(job.abs_path.as_ref()).log_err();
4426
4427        for new_job in new_jobs.into_iter().flatten() {
4428            job.scan_queue
4429                .try_send(new_job)
4430                .expect("channel is unbounded");
4431        }
4432
4433        Ok(())
4434    }
4435
4436    async fn reload_entries_for_paths(
4437        &self,
4438        root_abs_path: Arc<Path>,
4439        root_canonical_path: PathBuf,
4440        relative_paths: &[Arc<Path>],
4441        abs_paths: Vec<PathBuf>,
4442        scan_queue_tx: Option<Sender<ScanJob>>,
4443    ) {
4444        let metadata = futures::future::join_all(
4445            abs_paths
4446                .iter()
4447                .map(|abs_path| async move {
4448                    let metadata = self.fs.metadata(abs_path).await?;
4449                    if let Some(metadata) = metadata {
4450                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4451
4452                        // If we're on a case-insensitive filesystem (default on macOS), we want
4453                        // to only ignore metadata for non-symlink files if their absolute-path matches
4454                        // the canonical-path.
4455                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4456                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4457                        // treated as removed.
4458                        if !self.fs_case_sensitive && !metadata.is_symlink {
4459                            let canonical_file_name = canonical_path.file_name();
4460                            let file_name = abs_path.file_name();
4461                            if canonical_file_name != file_name {
4462                                return Ok(None);
4463                            }
4464                        }
4465
4466                        anyhow::Ok(Some((metadata, canonical_path)))
4467                    } else {
4468                        Ok(None)
4469                    }
4470                })
4471                .collect::<Vec<_>>(),
4472        )
4473        .await;
4474
4475        let mut state = self.state.lock();
4476        let doing_recursive_update = scan_queue_tx.is_some();
4477
4478        // Remove any entries for paths that no longer exist or are being recursively
4479        // refreshed. Do this before adding any new entries, so that renames can be
4480        // detected regardless of the order of the paths.
4481        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4482            if matches!(metadata, Ok(None)) || doing_recursive_update {
4483                log::trace!("remove path {:?}", path);
4484                state.remove_path(path);
4485            }
4486        }
4487
4488        // Group all relative paths by their git repository.
4489        let mut paths_by_git_repo = HashMap::default();
4490        for relative_path in relative_paths.iter() {
4491            if let Some((repo_entry, repo)) = state.snapshot.repo_for_path(relative_path) {
4492                if let Ok(repo_path) = repo_entry.relativize(&state.snapshot, relative_path) {
4493                    paths_by_git_repo
4494                        .entry(repo.dot_git_dir_abs_path.clone())
4495                        .or_insert_with(|| RepoPaths {
4496                            repo: repo.repo_ptr.clone(),
4497                            repo_paths: Vec::new(),
4498                            relative_paths: Vec::new(),
4499                        })
4500                        .add_paths(relative_path, repo_path);
4501                }
4502            }
4503        }
4504
4505        // Now call `git status` once per repository and collect each file's git status.
4506        let mut git_statuses_by_relative_path =
4507            paths_by_git_repo
4508                .into_values()
4509                .fold(HashMap::default(), |mut map, repo_paths| {
4510                    map.extend(repo_paths.into_git_file_statuses());
4511                    map
4512                });
4513
4514        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4515            let abs_path: Arc<Path> = root_abs_path.join(path).into();
4516            match metadata {
4517                Ok(Some((metadata, canonical_path))) => {
4518                    let ignore_stack = state
4519                        .snapshot
4520                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4521                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4522                    let mut fs_entry = Entry::new(
4523                        path.clone(),
4524                        &metadata,
4525                        self.next_entry_id.as_ref(),
4526                        state.snapshot.root_char_bag,
4527                        if metadata.is_symlink {
4528                            Some(canonical_path.into())
4529                        } else {
4530                            None
4531                        },
4532                    );
4533
4534                    let is_dir = fs_entry.is_dir();
4535                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4536                    fs_entry.is_external = is_external;
4537                    fs_entry.is_private = self.is_path_private(path);
4538                    fs_entry.is_always_included = self.settings.is_path_always_included(path);
4539
4540                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4541                        if state.should_scan_directory(&fs_entry)
4542                            || (fs_entry.path.as_os_str().is_empty()
4543                                && abs_path.file_name() == Some(*DOT_GIT))
4544                        {
4545                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4546                        } else {
4547                            fs_entry.kind = EntryKind::UnloadedDir;
4548                        }
4549                    }
4550
4551                    if !is_dir && !fs_entry.is_ignored && !fs_entry.is_external {
4552                        fs_entry.git_status = git_statuses_by_relative_path.remove(path);
4553                    }
4554
4555                    state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4556                }
4557                Ok(None) => {
4558                    self.remove_repo_path(path, &mut state.snapshot);
4559                }
4560                Err(err) => {
4561                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4562                }
4563            }
4564        }
4565
4566        util::extend_sorted(
4567            &mut state.changed_paths,
4568            relative_paths.iter().cloned(),
4569            usize::MAX,
4570            Ord::cmp,
4571        );
4572    }
4573
4574    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
4575        if !path
4576            .components()
4577            .any(|component| component.as_os_str() == *DOT_GIT)
4578        {
4579            if let Some(repository) = snapshot.repository_for_work_directory(path) {
4580                let entry = repository.work_directory.0;
4581                snapshot.git_repositories.remove(&entry);
4582                snapshot
4583                    .snapshot
4584                    .repository_entries
4585                    .remove(&RepositoryWorkDirectory(path.into()));
4586                return Some(());
4587            }
4588        }
4589
4590        Some(())
4591    }
4592
4593    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4594        use futures::FutureExt as _;
4595
4596        let mut ignores_to_update = Vec::new();
4597        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4598        let prev_snapshot;
4599        {
4600            let snapshot = &mut self.state.lock().snapshot;
4601            let abs_path = snapshot.abs_path.clone();
4602            snapshot
4603                .ignores_by_parent_abs_path
4604                .retain(|parent_abs_path, (_, needs_update)| {
4605                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
4606                        if *needs_update {
4607                            *needs_update = false;
4608                            if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4609                                ignores_to_update.push(parent_abs_path.clone());
4610                            }
4611                        }
4612
4613                        let ignore_path = parent_path.join(*GITIGNORE);
4614                        if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4615                            return false;
4616                        }
4617                    }
4618                    true
4619                });
4620
4621            ignores_to_update.sort_unstable();
4622            let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4623            while let Some(parent_abs_path) = ignores_to_update.next() {
4624                while ignores_to_update
4625                    .peek()
4626                    .map_or(false, |p| p.starts_with(&parent_abs_path))
4627                {
4628                    ignores_to_update.next().unwrap();
4629                }
4630
4631                let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4632                ignore_queue_tx
4633                    .send_blocking(UpdateIgnoreStatusJob {
4634                        abs_path: parent_abs_path,
4635                        ignore_stack,
4636                        ignore_queue: ignore_queue_tx.clone(),
4637                        scan_queue: scan_job_tx.clone(),
4638                    })
4639                    .unwrap();
4640            }
4641
4642            prev_snapshot = snapshot.clone();
4643        }
4644        drop(ignore_queue_tx);
4645
4646        self.executor
4647            .scoped(|scope| {
4648                for _ in 0..self.executor.num_cpus() {
4649                    scope.spawn(async {
4650                        loop {
4651                            select_biased! {
4652                                // Process any path refresh requests before moving on to process
4653                                // the queue of ignore statuses.
4654                                request = self.next_scan_request().fuse() => {
4655                                    let Ok(request) = request else { break };
4656                                    if !self.process_scan_request(request, true).await {
4657                                        return;
4658                                    }
4659                                }
4660
4661                                // Recursively process directories whose ignores have changed.
4662                                job = ignore_queue_rx.recv().fuse() => {
4663                                    let Ok(job) = job else { break };
4664                                    self.update_ignore_status(job, &prev_snapshot).await;
4665                                }
4666                            }
4667                        }
4668                    });
4669                }
4670            })
4671            .await;
4672    }
4673
4674    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4675        log::trace!("update ignore status {:?}", job.abs_path);
4676
4677        let mut ignore_stack = job.ignore_stack;
4678        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4679            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4680        }
4681
4682        let mut entries_by_id_edits = Vec::new();
4683        let mut entries_by_path_edits = Vec::new();
4684        let path = job
4685            .abs_path
4686            .strip_prefix(snapshot.abs_path.as_path())
4687            .unwrap();
4688        let repo = snapshot.repo_for_path(path);
4689        for mut entry in snapshot.child_entries(path).cloned() {
4690            let was_ignored = entry.is_ignored;
4691            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4692            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4693
4694            if entry.is_dir() {
4695                let child_ignore_stack = if entry.is_ignored {
4696                    IgnoreStack::all()
4697                } else {
4698                    ignore_stack.clone()
4699                };
4700
4701                // Scan any directories that were previously ignored and weren't previously scanned.
4702                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4703                    let state = self.state.lock();
4704                    if state.should_scan_directory(&entry) {
4705                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4706                    }
4707                }
4708
4709                job.ignore_queue
4710                    .send(UpdateIgnoreStatusJob {
4711                        abs_path: abs_path.clone(),
4712                        ignore_stack: child_ignore_stack,
4713                        ignore_queue: job.ignore_queue.clone(),
4714                        scan_queue: job.scan_queue.clone(),
4715                    })
4716                    .await
4717                    .unwrap();
4718            }
4719
4720            if entry.is_ignored != was_ignored {
4721                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4722                path_entry.scan_id = snapshot.scan_id;
4723                path_entry.is_ignored = entry.is_ignored;
4724                if !entry.is_dir() && !entry.is_ignored && !entry.is_external {
4725                    if let Some((ref repo_entry, local_repo)) = repo {
4726                        if let Ok(repo_path) = repo_entry.relativize(snapshot, &entry.path) {
4727                            let status = local_repo
4728                                .repo_ptr
4729                                .status(&[repo_path.0.clone()])
4730                                .ok()
4731                                .and_then(|status| status.get(&repo_path));
4732                            entry.git_status = status;
4733                        }
4734                    }
4735                }
4736                entries_by_id_edits.push(Edit::Insert(path_entry));
4737                entries_by_path_edits.push(Edit::Insert(entry));
4738            }
4739        }
4740
4741        let state = &mut self.state.lock();
4742        for edit in &entries_by_path_edits {
4743            if let Edit::Insert(entry) = edit {
4744                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4745                    state.changed_paths.insert(ix, entry.path.clone());
4746                }
4747            }
4748        }
4749
4750        state
4751            .snapshot
4752            .entries_by_path
4753            .edit(entries_by_path_edits, &());
4754        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4755    }
4756
4757    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
4758        log::debug!("reloading repositories: {dot_git_paths:?}");
4759
4760        let mut repo_updates = Vec::new();
4761        {
4762            let mut state = self.state.lock();
4763            let scan_id = state.snapshot.scan_id;
4764            for dot_git_dir in dot_git_paths {
4765                let existing_repository_entry =
4766                    state
4767                        .snapshot
4768                        .git_repositories
4769                        .iter()
4770                        .find_map(|(entry_id, repo)| {
4771                            if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
4772                                || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
4773                            {
4774                                Some((*entry_id, repo.clone()))
4775                            } else {
4776                                None
4777                            }
4778                        });
4779
4780                let (work_directory, repository) = match existing_repository_entry {
4781                    None => {
4782                        match state.insert_git_repository(
4783                            dot_git_dir.into(),
4784                            self.fs.as_ref(),
4785                            self.watcher.as_ref(),
4786                        ) {
4787                            Some(output) => output,
4788                            None => continue,
4789                        }
4790                    }
4791                    Some((entry_id, repository)) => {
4792                        if repository.git_dir_scan_id == scan_id {
4793                            continue;
4794                        }
4795                        let Some(work_dir) = state
4796                            .snapshot
4797                            .entry_for_id(entry_id)
4798                            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
4799                        else {
4800                            continue;
4801                        };
4802
4803                        let repo = &repository.repo_ptr;
4804                        let branch = repo.branch_name();
4805                        repo.reload_index();
4806
4807                        state
4808                            .snapshot
4809                            .git_repositories
4810                            .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
4811                        state
4812                            .snapshot
4813                            .snapshot
4814                            .repository_entries
4815                            .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
4816                        (work_dir, repository.repo_ptr.clone())
4817                    }
4818                };
4819
4820                repo_updates.push(UpdateGitStatusesJob {
4821                    location_in_repo: state
4822                        .snapshot
4823                        .repository_entries
4824                        .get(&work_directory)
4825                        .and_then(|repo| repo.location_in_repo.clone())
4826                        .clone(),
4827                    work_directory,
4828                    repository,
4829                });
4830            }
4831
4832            // Remove any git repositories whose .git entry no longer exists.
4833            let snapshot = &mut state.snapshot;
4834            let mut ids_to_preserve = HashSet::default();
4835            for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4836                let exists_in_snapshot = snapshot
4837                    .entry_for_id(work_directory_id)
4838                    .map_or(false, |entry| {
4839                        snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
4840                    });
4841
4842                if exists_in_snapshot
4843                    || matches!(
4844                        smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
4845                        Ok(Some(_))
4846                    )
4847                {
4848                    ids_to_preserve.insert(work_directory_id);
4849                }
4850            }
4851
4852            snapshot
4853                .git_repositories
4854                .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
4855            snapshot
4856                .repository_entries
4857                .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
4858        }
4859
4860        let (mut updates_done_tx, mut updates_done_rx) = barrier::channel();
4861        self.executor
4862            .scoped(|scope| {
4863                scope.spawn(async {
4864                    for repo_update in repo_updates {
4865                        self.update_git_statuses(repo_update);
4866                    }
4867                    updates_done_tx.blocking_send(()).ok();
4868                });
4869
4870                scope.spawn(async {
4871                    loop {
4872                        select_biased! {
4873                            // Process any path refresh requests before moving on to process
4874                            // the queue of git statuses.
4875                            request = self.next_scan_request().fuse() => {
4876                                let Ok(request) = request else { break };
4877                                if !self.process_scan_request(request, true).await {
4878                                    return;
4879                                }
4880                            }
4881                            _ = updates_done_rx.recv().fuse() =>  break,
4882                        }
4883                    }
4884                });
4885            })
4886            .await;
4887    }
4888
4889    /// Update the git statuses for a given batch of entries.
4890    fn update_git_statuses(&self, job: UpdateGitStatusesJob) {
4891        log::trace!("updating git statuses for repo {:?}", job.work_directory.0);
4892        let t0 = Instant::now();
4893        let Some(statuses) = job.repository.status(&[PathBuf::from("")]).log_err() else {
4894            return;
4895        };
4896        log::trace!(
4897            "computed git statuses for repo {:?} in {:?}",
4898            job.work_directory.0,
4899            t0.elapsed()
4900        );
4901
4902        let t0 = Instant::now();
4903        let mut changes = Vec::new();
4904        let snapshot = self.state.lock().snapshot.snapshot.clone();
4905        for file in snapshot.traverse_from_path(true, false, false, job.work_directory.0.as_ref()) {
4906            let Ok(repo_path) = file.path.strip_prefix(&job.work_directory.0) else {
4907                break;
4908            };
4909            let git_status = if let Some(location) = &job.location_in_repo {
4910                statuses.get(&location.join(repo_path))
4911            } else {
4912                statuses.get(repo_path)
4913            };
4914            if file.git_status != git_status {
4915                let mut entry = file.clone();
4916                entry.git_status = git_status;
4917                changes.push((entry.path, git_status));
4918            }
4919        }
4920
4921        let mut state = self.state.lock();
4922        let edits = changes
4923            .iter()
4924            .filter_map(|(path, git_status)| {
4925                let entry = state.snapshot.entry_for_path(path)?.clone();
4926                Some(Edit::Insert(Entry {
4927                    git_status: *git_status,
4928                    ..entry.clone()
4929                }))
4930            })
4931            .collect();
4932
4933        // Apply the git status changes.
4934        util::extend_sorted(
4935            &mut state.changed_paths,
4936            changes.iter().map(|p| p.0.clone()),
4937            usize::MAX,
4938            Ord::cmp,
4939        );
4940        state.snapshot.entries_by_path.edit(edits, &());
4941        log::trace!(
4942            "applied git status updates for repo {:?} in {:?}",
4943            job.work_directory.0,
4944            t0.elapsed(),
4945        );
4946    }
4947
4948    fn build_change_set(
4949        &self,
4950        old_snapshot: &Snapshot,
4951        new_snapshot: &Snapshot,
4952        event_paths: &[Arc<Path>],
4953    ) -> UpdatedEntriesSet {
4954        use BackgroundScannerPhase::*;
4955        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4956
4957        // Identify which paths have changed. Use the known set of changed
4958        // parent paths to optimize the search.
4959        let mut changes = Vec::new();
4960        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
4961        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
4962        let mut last_newly_loaded_dir_path = None;
4963        old_paths.next(&());
4964        new_paths.next(&());
4965        for path in event_paths {
4966            let path = PathKey(path.clone());
4967            if old_paths.item().map_or(false, |e| e.path < path.0) {
4968                old_paths.seek_forward(&path, Bias::Left, &());
4969            }
4970            if new_paths.item().map_or(false, |e| e.path < path.0) {
4971                new_paths.seek_forward(&path, Bias::Left, &());
4972            }
4973            loop {
4974                match (old_paths.item(), new_paths.item()) {
4975                    (Some(old_entry), Some(new_entry)) => {
4976                        if old_entry.path > path.0
4977                            && new_entry.path > path.0
4978                            && !old_entry.path.starts_with(&path.0)
4979                            && !new_entry.path.starts_with(&path.0)
4980                        {
4981                            break;
4982                        }
4983
4984                        match Ord::cmp(&old_entry.path, &new_entry.path) {
4985                            Ordering::Less => {
4986                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4987                                old_paths.next(&());
4988                            }
4989                            Ordering::Equal => {
4990                                if self.phase == EventsReceivedDuringInitialScan {
4991                                    if old_entry.id != new_entry.id {
4992                                        changes.push((
4993                                            old_entry.path.clone(),
4994                                            old_entry.id,
4995                                            Removed,
4996                                        ));
4997                                    }
4998                                    // If the worktree was not fully initialized when this event was generated,
4999                                    // we can't know whether this entry was added during the scan or whether
5000                                    // it was merely updated.
5001                                    changes.push((
5002                                        new_entry.path.clone(),
5003                                        new_entry.id,
5004                                        AddedOrUpdated,
5005                                    ));
5006                                } else if old_entry.id != new_entry.id {
5007                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5008                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
5009                                } else if old_entry != new_entry {
5010                                    if old_entry.kind.is_unloaded() {
5011                                        last_newly_loaded_dir_path = Some(&new_entry.path);
5012                                        changes.push((
5013                                            new_entry.path.clone(),
5014                                            new_entry.id,
5015                                            Loaded,
5016                                        ));
5017                                    } else {
5018                                        changes.push((
5019                                            new_entry.path.clone(),
5020                                            new_entry.id,
5021                                            Updated,
5022                                        ));
5023                                    }
5024                                }
5025                                old_paths.next(&());
5026                                new_paths.next(&());
5027                            }
5028                            Ordering::Greater => {
5029                                let is_newly_loaded = self.phase == InitialScan
5030                                    || last_newly_loaded_dir_path
5031                                        .as_ref()
5032                                        .map_or(false, |dir| new_entry.path.starts_with(dir));
5033                                changes.push((
5034                                    new_entry.path.clone(),
5035                                    new_entry.id,
5036                                    if is_newly_loaded { Loaded } else { Added },
5037                                ));
5038                                new_paths.next(&());
5039                            }
5040                        }
5041                    }
5042                    (Some(old_entry), None) => {
5043                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
5044                        old_paths.next(&());
5045                    }
5046                    (None, Some(new_entry)) => {
5047                        let is_newly_loaded = self.phase == InitialScan
5048                            || last_newly_loaded_dir_path
5049                                .as_ref()
5050                                .map_or(false, |dir| new_entry.path.starts_with(dir));
5051                        changes.push((
5052                            new_entry.path.clone(),
5053                            new_entry.id,
5054                            if is_newly_loaded { Loaded } else { Added },
5055                        ));
5056                        new_paths.next(&());
5057                    }
5058                    (None, None) => break,
5059                }
5060            }
5061        }
5062
5063        changes.into()
5064    }
5065
5066    async fn progress_timer(&self, running: bool) {
5067        if !running {
5068            return futures::future::pending().await;
5069        }
5070
5071        #[cfg(any(test, feature = "test-support"))]
5072        if self.fs.is_fake() {
5073            return self.executor.simulate_random_delay().await;
5074        }
5075
5076        smol::Timer::after(FS_WATCH_LATENCY).await;
5077    }
5078
5079    fn is_path_private(&self, path: &Path) -> bool {
5080        !self.share_private_files && self.settings.is_path_private(path)
5081    }
5082
5083    async fn next_scan_request(&self) -> Result<ScanRequest> {
5084        let mut request = self.scan_requests_rx.recv().await?;
5085        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5086            request.relative_paths.extend(next_request.relative_paths);
5087            request.done.extend(next_request.done);
5088        }
5089        Ok(request)
5090    }
5091}
5092
5093fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
5094    let position = child_paths
5095        .iter()
5096        .position(|path| path.file_name().unwrap() == file);
5097    if let Some(position) = position {
5098        let temp = child_paths.remove(position);
5099        child_paths.insert(0, temp);
5100    }
5101}
5102
5103fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
5104    let mut result = root_char_bag;
5105    result.extend(
5106        path.to_string_lossy()
5107            .chars()
5108            .map(|c| c.to_ascii_lowercase()),
5109    );
5110    result
5111}
5112
5113struct RepoPaths {
5114    repo: Arc<dyn GitRepository>,
5115    relative_paths: Vec<Arc<Path>>,
5116    repo_paths: Vec<PathBuf>,
5117}
5118
5119impl RepoPaths {
5120    fn add_paths(&mut self, relative_path: &Arc<Path>, repo_path: RepoPath) {
5121        self.relative_paths.push(relative_path.clone());
5122        self.repo_paths.push(repo_path.0);
5123    }
5124
5125    fn into_git_file_statuses(self) -> HashMap<Arc<Path>, GitFileStatus> {
5126        let mut statuses = HashMap::default();
5127        if let Ok(status) = self.repo.status(&self.repo_paths) {
5128            for (repo_path, relative_path) in self.repo_paths.into_iter().zip(self.relative_paths) {
5129                if let Some(path_status) = status.get(&repo_path) {
5130                    statuses.insert(relative_path, path_status);
5131                }
5132            }
5133        }
5134        statuses
5135    }
5136}
5137
5138struct ScanJob {
5139    abs_path: Arc<Path>,
5140    path: Arc<Path>,
5141    ignore_stack: Arc<IgnoreStack>,
5142    scan_queue: Sender<ScanJob>,
5143    ancestor_inodes: TreeSet<u64>,
5144    is_external: bool,
5145    containing_repository: Option<ScanJobContainingRepository>,
5146}
5147
5148#[derive(Clone)]
5149struct ScanJobContainingRepository {
5150    work_directory: RepositoryWorkDirectory,
5151    statuses: GitStatus,
5152}
5153
5154struct UpdateIgnoreStatusJob {
5155    abs_path: Arc<Path>,
5156    ignore_stack: Arc<IgnoreStack>,
5157    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5158    scan_queue: Sender<ScanJob>,
5159}
5160
5161struct UpdateGitStatusesJob {
5162    work_directory: RepositoryWorkDirectory,
5163    location_in_repo: Option<Arc<Path>>,
5164    repository: Arc<dyn GitRepository>,
5165}
5166
5167pub trait WorktreeModelHandle {
5168    #[cfg(any(test, feature = "test-support"))]
5169    fn flush_fs_events<'a>(
5170        &self,
5171        cx: &'a mut gpui::TestAppContext,
5172    ) -> futures::future::LocalBoxFuture<'a, ()>;
5173
5174    #[cfg(any(test, feature = "test-support"))]
5175    fn flush_fs_events_in_root_git_repository<'a>(
5176        &self,
5177        cx: &'a mut gpui::TestAppContext,
5178    ) -> futures::future::LocalBoxFuture<'a, ()>;
5179}
5180
5181impl WorktreeModelHandle for Model<Worktree> {
5182    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5183    // occurred before the worktree was constructed. These events can cause the worktree to perform
5184    // extra directory scans, and emit extra scan-state notifications.
5185    //
5186    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5187    // to ensure that all redundant FS events have already been processed.
5188    #[cfg(any(test, feature = "test-support"))]
5189    fn flush_fs_events<'a>(
5190        &self,
5191        cx: &'a mut gpui::TestAppContext,
5192    ) -> futures::future::LocalBoxFuture<'a, ()> {
5193        let file_name = "fs-event-sentinel";
5194
5195        let tree = self.clone();
5196        let (fs, root_path) = self.update(cx, |tree, _| {
5197            let tree = tree.as_local().unwrap();
5198            (tree.fs.clone(), tree.abs_path().clone())
5199        });
5200
5201        async move {
5202            fs.create_file(&root_path.join(file_name), Default::default())
5203                .await
5204                .unwrap();
5205
5206            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
5207                .await;
5208
5209            fs.remove_file(&root_path.join(file_name), Default::default())
5210                .await
5211                .unwrap();
5212            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
5213                .await;
5214
5215            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5216                .await;
5217        }
5218        .boxed_local()
5219    }
5220
5221    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5222    // the .git folder of the root repository.
5223    // The reason for its existence is that a repository's .git folder might live *outside* of the
5224    // worktree and thus its FS events might go through a different path.
5225    // In order to flush those, we need to create artificial events in the .git folder and wait
5226    // for the repository to be reloaded.
5227    #[cfg(any(test, feature = "test-support"))]
5228    fn flush_fs_events_in_root_git_repository<'a>(
5229        &self,
5230        cx: &'a mut gpui::TestAppContext,
5231    ) -> futures::future::LocalBoxFuture<'a, ()> {
5232        let file_name = "fs-event-sentinel";
5233
5234        let tree = self.clone();
5235        let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5236            let tree = tree.as_local().unwrap();
5237            let root_entry = tree.root_git_entry().unwrap();
5238            let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
5239            (
5240                tree.fs.clone(),
5241                local_repo_entry.dot_git_dir_abs_path.clone(),
5242                local_repo_entry.git_dir_scan_id,
5243            )
5244        });
5245
5246        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5247            let root_entry = tree.root_git_entry().unwrap();
5248            let local_repo_entry = tree
5249                .as_local()
5250                .unwrap()
5251                .get_local_repo(&root_entry)
5252                .unwrap();
5253
5254            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5255                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5256                true
5257            } else {
5258                false
5259            }
5260        };
5261
5262        async move {
5263            fs.create_file(&root_path.join(file_name), Default::default())
5264                .await
5265                .unwrap();
5266
5267            cx.condition(&tree, |tree, _| {
5268                scan_id_increased(tree, &mut git_dir_scan_id)
5269            })
5270            .await;
5271
5272            fs.remove_file(&root_path.join(file_name), Default::default())
5273                .await
5274                .unwrap();
5275
5276            cx.condition(&tree, |tree, _| {
5277                scan_id_increased(tree, &mut git_dir_scan_id)
5278            })
5279            .await;
5280
5281            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5282                .await;
5283        }
5284        .boxed_local()
5285    }
5286}
5287
5288#[derive(Clone, Debug)]
5289struct TraversalProgress<'a> {
5290    max_path: &'a Path,
5291    count: usize,
5292    non_ignored_count: usize,
5293    file_count: usize,
5294    non_ignored_file_count: usize,
5295}
5296
5297impl<'a> TraversalProgress<'a> {
5298    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5299        match (include_files, include_dirs, include_ignored) {
5300            (true, true, true) => self.count,
5301            (true, true, false) => self.non_ignored_count,
5302            (true, false, true) => self.file_count,
5303            (true, false, false) => self.non_ignored_file_count,
5304            (false, true, true) => self.count - self.file_count,
5305            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5306            (false, false, _) => 0,
5307        }
5308    }
5309}
5310
5311impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5312    fn zero(_cx: &()) -> Self {
5313        Default::default()
5314    }
5315
5316    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5317        self.max_path = summary.max_path.as_ref();
5318        self.count += summary.count;
5319        self.non_ignored_count += summary.non_ignored_count;
5320        self.file_count += summary.file_count;
5321        self.non_ignored_file_count += summary.non_ignored_file_count;
5322    }
5323}
5324
5325impl<'a> Default for TraversalProgress<'a> {
5326    fn default() -> Self {
5327        Self {
5328            max_path: Path::new(""),
5329            count: 0,
5330            non_ignored_count: 0,
5331            file_count: 0,
5332            non_ignored_file_count: 0,
5333        }
5334    }
5335}
5336
5337#[derive(Clone, Debug, Default, Copy)]
5338struct GitStatuses {
5339    added: usize,
5340    modified: usize,
5341    conflict: usize,
5342}
5343
5344impl AddAssign for GitStatuses {
5345    fn add_assign(&mut self, rhs: Self) {
5346        self.added += rhs.added;
5347        self.modified += rhs.modified;
5348        self.conflict += rhs.conflict;
5349    }
5350}
5351
5352impl Sub for GitStatuses {
5353    type Output = GitStatuses;
5354
5355    fn sub(self, rhs: Self) -> Self::Output {
5356        GitStatuses {
5357            added: self.added - rhs.added,
5358            modified: self.modified - rhs.modified,
5359            conflict: self.conflict - rhs.conflict,
5360        }
5361    }
5362}
5363
5364impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
5365    fn zero(_cx: &()) -> Self {
5366        Default::default()
5367    }
5368
5369    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5370        *self += summary.statuses
5371    }
5372}
5373
5374pub struct Traversal<'a> {
5375    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5376    include_ignored: bool,
5377    include_files: bool,
5378    include_dirs: bool,
5379}
5380
5381impl<'a> Traversal<'a> {
5382    fn new(
5383        entries: &'a SumTree<Entry>,
5384        include_files: bool,
5385        include_dirs: bool,
5386        include_ignored: bool,
5387        start_path: &Path,
5388    ) -> Self {
5389        let mut cursor = entries.cursor(&());
5390        cursor.seek(&TraversalTarget::Path(start_path), Bias::Left, &());
5391        let mut traversal = Self {
5392            cursor,
5393            include_files,
5394            include_dirs,
5395            include_ignored,
5396        };
5397        if traversal.end_offset() == traversal.start_offset() {
5398            traversal.next();
5399        }
5400        traversal
5401    }
5402    pub fn advance(&mut self) -> bool {
5403        self.advance_by(1)
5404    }
5405
5406    pub fn advance_by(&mut self, count: usize) -> bool {
5407        self.cursor.seek_forward(
5408            &TraversalTarget::Count {
5409                count: self.end_offset() + count,
5410                include_dirs: self.include_dirs,
5411                include_files: self.include_files,
5412                include_ignored: self.include_ignored,
5413            },
5414            Bias::Left,
5415            &(),
5416        )
5417    }
5418
5419    pub fn advance_to_sibling(&mut self) -> bool {
5420        while let Some(entry) = self.cursor.item() {
5421            self.cursor.seek_forward(
5422                &TraversalTarget::PathSuccessor(&entry.path),
5423                Bias::Left,
5424                &(),
5425            );
5426            if let Some(entry) = self.cursor.item() {
5427                if (self.include_files || !entry.is_file())
5428                    && (self.include_dirs || !entry.is_dir())
5429                    && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5430                {
5431                    return true;
5432                }
5433            }
5434        }
5435        false
5436    }
5437
5438    pub fn back_to_parent(&mut self) -> bool {
5439        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5440            return false;
5441        };
5442        self.cursor
5443            .seek(&TraversalTarget::Path(parent_path), Bias::Left, &())
5444    }
5445
5446    pub fn entry(&self) -> Option<&'a Entry> {
5447        self.cursor.item()
5448    }
5449
5450    pub fn start_offset(&self) -> usize {
5451        self.cursor
5452            .start()
5453            .count(self.include_files, self.include_dirs, self.include_ignored)
5454    }
5455
5456    pub fn end_offset(&self) -> usize {
5457        self.cursor
5458            .end(&())
5459            .count(self.include_files, self.include_dirs, self.include_ignored)
5460    }
5461}
5462
5463impl<'a> Iterator for Traversal<'a> {
5464    type Item = &'a Entry;
5465
5466    fn next(&mut self) -> Option<Self::Item> {
5467        if let Some(item) = self.entry() {
5468            self.advance();
5469            Some(item)
5470        } else {
5471            None
5472        }
5473    }
5474}
5475
5476#[derive(Debug)]
5477enum TraversalTarget<'a> {
5478    Path(&'a Path),
5479    PathSuccessor(&'a Path),
5480    Count {
5481        count: usize,
5482        include_files: bool,
5483        include_ignored: bool,
5484        include_dirs: bool,
5485    },
5486}
5487
5488impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
5489    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5490        match self {
5491            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
5492            TraversalTarget::PathSuccessor(path) => {
5493                if cursor_location.max_path.starts_with(path) {
5494                    Ordering::Greater
5495                } else {
5496                    Ordering::Equal
5497                }
5498            }
5499            TraversalTarget::Count {
5500                count,
5501                include_files,
5502                include_dirs,
5503                include_ignored,
5504            } => Ord::cmp(
5505                count,
5506                &cursor_location.count(*include_files, *include_dirs, *include_ignored),
5507            ),
5508        }
5509    }
5510}
5511
5512impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
5513    for TraversalTarget<'b>
5514{
5515    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
5516        self.cmp(&cursor_location.0, &())
5517    }
5518}
5519
5520pub struct ChildEntriesIter<'a> {
5521    parent_path: &'a Path,
5522    traversal: Traversal<'a>,
5523}
5524
5525impl<'a> Iterator for ChildEntriesIter<'a> {
5526    type Item = &'a Entry;
5527
5528    fn next(&mut self) -> Option<Self::Item> {
5529        if let Some(item) = self.traversal.entry() {
5530            if item.path.starts_with(self.parent_path) {
5531                self.traversal.advance_to_sibling();
5532                return Some(item);
5533            }
5534        }
5535        None
5536    }
5537}
5538
5539impl<'a> From<&'a Entry> for proto::Entry {
5540    fn from(entry: &'a Entry) -> Self {
5541        Self {
5542            id: entry.id.to_proto(),
5543            is_dir: entry.is_dir(),
5544            path: entry.path.to_string_lossy().into(),
5545            inode: entry.inode,
5546            mtime: entry.mtime.map(|time| time.into()),
5547            is_ignored: entry.is_ignored,
5548            is_external: entry.is_external,
5549            git_status: entry.git_status.map(git_status_to_proto),
5550            is_fifo: entry.is_fifo,
5551            size: Some(entry.size),
5552            canonical_path: entry
5553                .canonical_path
5554                .as_ref()
5555                .map(|path| path.to_string_lossy().to_string()),
5556        }
5557    }
5558}
5559
5560impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
5561    type Error = anyhow::Error;
5562
5563    fn try_from(
5564        (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
5565    ) -> Result<Self> {
5566        let kind = if entry.is_dir {
5567            EntryKind::Dir
5568        } else {
5569            EntryKind::File
5570        };
5571        let path: Arc<Path> = PathBuf::from(entry.path).into();
5572        let char_bag = char_bag_for_path(*root_char_bag, &path);
5573        Ok(Entry {
5574            id: ProjectEntryId::from_proto(entry.id),
5575            kind,
5576            path: path.clone(),
5577            inode: entry.inode,
5578            mtime: entry.mtime.map(|time| time.into()),
5579            size: entry.size.unwrap_or(0),
5580            canonical_path: entry
5581                .canonical_path
5582                .map(|path_string| Box::from(Path::new(&path_string))),
5583            is_ignored: entry.is_ignored,
5584            is_always_included: always_included.is_match(path.as_ref()),
5585            is_external: entry.is_external,
5586            git_status: git_status_from_proto(entry.git_status),
5587            is_private: false,
5588            char_bag,
5589            is_fifo: entry.is_fifo,
5590        })
5591    }
5592}
5593
5594fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
5595    git_status.and_then(|status| {
5596        proto::GitStatus::from_i32(status).map(|status| match status {
5597            proto::GitStatus::Added => GitFileStatus::Added,
5598            proto::GitStatus::Modified => GitFileStatus::Modified,
5599            proto::GitStatus::Conflict => GitFileStatus::Conflict,
5600        })
5601    })
5602}
5603
5604fn git_status_to_proto(status: GitFileStatus) -> i32 {
5605    match status {
5606        GitFileStatus::Added => proto::GitStatus::Added as i32,
5607        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
5608        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
5609    }
5610}
5611
5612#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5613pub struct ProjectEntryId(usize);
5614
5615impl ProjectEntryId {
5616    pub const MAX: Self = Self(usize::MAX);
5617    pub const MIN: Self = Self(usize::MIN);
5618
5619    pub fn new(counter: &AtomicUsize) -> Self {
5620        Self(counter.fetch_add(1, SeqCst))
5621    }
5622
5623    pub fn from_proto(id: u64) -> Self {
5624        Self(id as usize)
5625    }
5626
5627    pub fn to_proto(&self) -> u64 {
5628        self.0 as u64
5629    }
5630
5631    pub fn to_usize(&self) -> usize {
5632        self.0
5633    }
5634}
5635
5636#[cfg(any(test, feature = "test-support"))]
5637impl CreatedEntry {
5638    pub fn to_included(self) -> Option<Entry> {
5639        match self {
5640            CreatedEntry::Included(entry) => Some(entry),
5641            CreatedEntry::Excluded { .. } => None,
5642        }
5643    }
5644}