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