worktree.rs

   1use crate::{
   2    copy_recursive, ignore::IgnoreStack, project_settings::ProjectSettings, DiagnosticSummary,
   3    ProjectEntryId, RemoveOptions,
   4};
   5use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   6use anyhow::{anyhow, Context as _, Result};
   7use client::{proto, Client};
   8use clock::ReplicaId;
   9use collections::{HashMap, HashSet, VecDeque};
  10use fs::{
  11    repository::{GitFileStatus, GitRepository, RepoPath},
  12    Fs,
  13};
  14use futures::{
  15    channel::{
  16        mpsc::{self, UnboundedSender},
  17        oneshot,
  18    },
  19    select_biased,
  20    task::Poll,
  21    FutureExt as _, Stream, StreamExt,
  22};
  23use fuzzy::CharBag;
  24use git::{DOT_GIT, GITIGNORE};
  25use gpui::{
  26    AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, Model, ModelContext,
  27    Task,
  28};
  29use itertools::Itertools;
  30use language::{
  31    proto::{
  32        deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
  33        serialize_version,
  34    },
  35    Buffer, DiagnosticEntry, File as _, LineEnding, PointUtf16, Rope, RopeFingerprint, Unclipped,
  36};
  37use lsp::LanguageServerId;
  38use parking_lot::Mutex;
  39use postage::{
  40    barrier,
  41    prelude::{Sink as _, Stream as _},
  42    watch,
  43};
  44use settings::{Settings, SettingsStore};
  45use smol::channel::{self, Sender};
  46use std::{
  47    any::Any,
  48    cmp::{self, Ordering},
  49    convert::TryFrom,
  50    ffi::OsStr,
  51    fmt,
  52    future::Future,
  53    mem,
  54    ops::{AddAssign, Deref, DerefMut, Sub},
  55    path::{Path, PathBuf},
  56    pin::Pin,
  57    sync::{
  58        atomic::{AtomicUsize, Ordering::SeqCst},
  59        Arc,
  60    },
  61    time::{Duration, SystemTime},
  62};
  63use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  64use util::{
  65    paths::{PathMatcher, HOME},
  66    ResultExt,
  67};
  68
  69#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  70pub struct WorktreeId(usize);
  71
  72pub enum Worktree {
  73    Local(LocalWorktree),
  74    Remote(RemoteWorktree),
  75}
  76
  77pub struct LocalWorktree {
  78    snapshot: LocalSnapshot,
  79    scan_requests_tx: channel::Sender<ScanRequest>,
  80    path_prefixes_to_scan_tx: channel::Sender<Arc<Path>>,
  81    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
  82    _background_scanner_tasks: Vec<Task<()>>,
  83    share: Option<ShareState>,
  84    diagnostics: HashMap<
  85        Arc<Path>,
  86        Vec<(
  87            LanguageServerId,
  88            Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
  89        )>,
  90    >,
  91    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
  92    client: Arc<Client>,
  93    fs: Arc<dyn Fs>,
  94    visible: bool,
  95}
  96
  97struct ScanRequest {
  98    relative_paths: Vec<Arc<Path>>,
  99    done: barrier::Sender,
 100}
 101
 102pub struct RemoteWorktree {
 103    snapshot: Snapshot,
 104    background_snapshot: Arc<Mutex<Snapshot>>,
 105    project_id: u64,
 106    client: Arc<Client>,
 107    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
 108    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 109    replica_id: ReplicaId,
 110    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
 111    visible: bool,
 112    disconnected: bool,
 113}
 114
 115#[derive(Clone)]
 116pub struct Snapshot {
 117    id: WorktreeId,
 118    abs_path: Arc<Path>,
 119    root_name: String,
 120    root_char_bag: CharBag,
 121    entries_by_path: SumTree<Entry>,
 122    entries_by_id: SumTree<PathEntry>,
 123    repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
 124
 125    /// A number that increases every time the worktree begins scanning
 126    /// a set of paths from the filesystem. This scanning could be caused
 127    /// by some operation performed on the worktree, such as reading or
 128    /// writing a file, or by an event reported by the filesystem.
 129    scan_id: usize,
 130
 131    /// The latest scan id that has completed, and whose preceding scans
 132    /// have all completed. The current `scan_id` could be more than one
 133    /// greater than the `completed_scan_id` if operations are performed
 134    /// on the worktree while it is processing a file-system event.
 135    completed_scan_id: usize,
 136}
 137
 138#[derive(Clone, Debug, PartialEq, Eq)]
 139pub struct RepositoryEntry {
 140    pub(crate) work_directory: WorkDirectoryEntry,
 141    pub(crate) branch: Option<Arc<str>>,
 142}
 143
 144impl RepositoryEntry {
 145    pub fn branch(&self) -> Option<Arc<str>> {
 146        self.branch.clone()
 147    }
 148
 149    pub fn work_directory_id(&self) -> ProjectEntryId {
 150        *self.work_directory
 151    }
 152
 153    pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
 154        snapshot
 155            .entry_for_id(self.work_directory_id())
 156            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
 157    }
 158
 159    pub fn build_update(&self, _: &Self) -> proto::RepositoryEntry {
 160        proto::RepositoryEntry {
 161            work_directory_id: self.work_directory_id().to_proto(),
 162            branch: self.branch.as_ref().map(|str| str.to_string()),
 163        }
 164    }
 165}
 166
 167impl From<&RepositoryEntry> for proto::RepositoryEntry {
 168    fn from(value: &RepositoryEntry) -> Self {
 169        proto::RepositoryEntry {
 170            work_directory_id: value.work_directory.to_proto(),
 171            branch: value.branch.as_ref().map(|str| str.to_string()),
 172        }
 173    }
 174}
 175
 176/// This path corresponds to the 'content path' (the folder that contains the .git)
 177#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 178pub struct RepositoryWorkDirectory(pub(crate) Arc<Path>);
 179
 180impl Default for RepositoryWorkDirectory {
 181    fn default() -> Self {
 182        RepositoryWorkDirectory(Arc::from(Path::new("")))
 183    }
 184}
 185
 186impl AsRef<Path> for RepositoryWorkDirectory {
 187    fn as_ref(&self) -> &Path {
 188        self.0.as_ref()
 189    }
 190}
 191
 192#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 193pub struct WorkDirectoryEntry(ProjectEntryId);
 194
 195impl WorkDirectoryEntry {
 196    pub(crate) fn relativize(&self, worktree: &Snapshot, path: &Path) -> Option<RepoPath> {
 197        worktree.entry_for_id(self.0).and_then(|entry| {
 198            path.strip_prefix(&entry.path)
 199                .ok()
 200                .map(move |path| path.into())
 201        })
 202    }
 203}
 204
 205impl Deref for WorkDirectoryEntry {
 206    type Target = ProjectEntryId;
 207
 208    fn deref(&self) -> &Self::Target {
 209        &self.0
 210    }
 211}
 212
 213impl<'a> From<ProjectEntryId> for WorkDirectoryEntry {
 214    fn from(value: ProjectEntryId) -> Self {
 215        WorkDirectoryEntry(value)
 216    }
 217}
 218
 219#[derive(Debug, Clone)]
 220pub struct LocalSnapshot {
 221    snapshot: Snapshot,
 222    /// All of the gitignore files in the worktree, indexed by their relative path.
 223    /// The boolean indicates whether the gitignore needs to be updated.
 224    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 225    /// All of the git repositories in the worktree, indexed by the project entry
 226    /// id of their parent directory.
 227    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 228    file_scan_exclusions: Vec<PathMatcher>,
 229}
 230
 231struct BackgroundScannerState {
 232    snapshot: LocalSnapshot,
 233    scanned_dirs: HashSet<ProjectEntryId>,
 234    path_prefixes_to_scan: HashSet<Arc<Path>>,
 235    paths_to_scan: HashSet<Arc<Path>>,
 236    /// The ids of all of the entries that were removed from the snapshot
 237    /// as part of the current update. These entry ids may be re-used
 238    /// if the same inode is discovered at a new path, or if the given
 239    /// path is re-created after being deleted.
 240    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 241    changed_paths: Vec<Arc<Path>>,
 242    prev_snapshot: Snapshot,
 243}
 244
 245#[derive(Debug, Clone)]
 246pub struct LocalRepositoryEntry {
 247    pub(crate) git_dir_scan_id: usize,
 248    pub(crate) repo_ptr: Arc<Mutex<dyn GitRepository>>,
 249    /// Path to the actual .git folder.
 250    /// Note: if .git is a file, this points to the folder indicated by the .git file
 251    pub(crate) git_dir_path: Arc<Path>,
 252}
 253
 254impl Deref for LocalSnapshot {
 255    type Target = Snapshot;
 256
 257    fn deref(&self) -> &Self::Target {
 258        &self.snapshot
 259    }
 260}
 261
 262impl DerefMut for LocalSnapshot {
 263    fn deref_mut(&mut self) -> &mut Self::Target {
 264        &mut self.snapshot
 265    }
 266}
 267
 268enum ScanState {
 269    Started,
 270    Updated {
 271        snapshot: LocalSnapshot,
 272        changes: UpdatedEntriesSet,
 273        barrier: Option<barrier::Sender>,
 274        scanning: bool,
 275    },
 276}
 277
 278struct ShareState {
 279    project_id: u64,
 280    snapshots_tx:
 281        mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>,
 282    resume_updates: watch::Sender<()>,
 283    _maintain_remote_snapshot: Task<Option<()>>,
 284}
 285
 286#[derive(Clone)]
 287pub enum Event {
 288    UpdatedEntries(UpdatedEntriesSet),
 289    UpdatedGitRepositories(UpdatedGitRepositoriesSet),
 290}
 291
 292impl EventEmitter<Event> for Worktree {}
 293
 294impl Worktree {
 295    pub async fn local(
 296        client: Arc<Client>,
 297        path: impl Into<Arc<Path>>,
 298        visible: bool,
 299        fs: Arc<dyn Fs>,
 300        next_entry_id: Arc<AtomicUsize>,
 301        cx: &mut AsyncAppContext,
 302    ) -> Result<Model<Self>> {
 303        // After determining whether the root entry is a file or a directory, populate the
 304        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 305        let abs_path = path.into();
 306
 307        let metadata = fs
 308            .metadata(&abs_path)
 309            .await
 310            .context("failed to stat worktree path")?;
 311
 312        let closure_fs = Arc::clone(&fs);
 313        let closure_next_entry_id = Arc::clone(&next_entry_id);
 314        let closure_abs_path = abs_path.to_path_buf();
 315        cx.build_model(move |cx: &mut ModelContext<Worktree>| {
 316            cx.observe_global::<SettingsStore>(move |this, cx| {
 317                if let Self::Local(this) = this {
 318                    let new_file_scan_exclusions =
 319                        file_scan_exclusions(ProjectSettings::get_global(cx));
 320                    if new_file_scan_exclusions != this.snapshot.file_scan_exclusions {
 321                        this.snapshot.file_scan_exclusions = new_file_scan_exclusions;
 322                        log::info!(
 323                            "Re-scanning directories, new scan exclude files: {:?}",
 324                            this.snapshot
 325                                .file_scan_exclusions
 326                                .iter()
 327                                .map(ToString::to_string)
 328                                .collect::<Vec<_>>()
 329                        );
 330
 331                        let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 332                        let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) =
 333                            channel::unbounded();
 334                        this.scan_requests_tx = scan_requests_tx;
 335                        this.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
 336                        this._background_scanner_tasks = start_background_scan_tasks(
 337                            &closure_abs_path,
 338                            this.snapshot(),
 339                            scan_requests_rx,
 340                            path_prefixes_to_scan_rx,
 341                            Arc::clone(&closure_next_entry_id),
 342                            Arc::clone(&closure_fs),
 343                            cx,
 344                        );
 345                        this.is_scanning = watch::channel_with(true);
 346                    }
 347                }
 348            })
 349            .detach();
 350
 351            let root_name = abs_path
 352                .file_name()
 353                .map_or(String::new(), |f| f.to_string_lossy().to_string());
 354
 355            let mut snapshot = LocalSnapshot {
 356                file_scan_exclusions: file_scan_exclusions(ProjectSettings::get_global(cx)),
 357                ignores_by_parent_abs_path: Default::default(),
 358                git_repositories: Default::default(),
 359                snapshot: Snapshot {
 360                    id: WorktreeId::from_usize(cx.entity_id().as_u64() as usize),
 361                    abs_path: abs_path.to_path_buf().into(),
 362                    root_name: root_name.clone(),
 363                    root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
 364                    entries_by_path: Default::default(),
 365                    entries_by_id: Default::default(),
 366                    repository_entries: Default::default(),
 367                    scan_id: 1,
 368                    completed_scan_id: 0,
 369                },
 370            };
 371
 372            if let Some(metadata) = metadata {
 373                snapshot.insert_entry(
 374                    Entry::new(
 375                        Arc::from(Path::new("")),
 376                        &metadata,
 377                        &next_entry_id,
 378                        snapshot.root_char_bag,
 379                    ),
 380                    fs.as_ref(),
 381                );
 382            }
 383
 384            let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 385            let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 386            let task_snapshot = snapshot.clone();
 387            Worktree::Local(LocalWorktree {
 388                snapshot,
 389                is_scanning: watch::channel_with(true),
 390                share: None,
 391                scan_requests_tx,
 392                path_prefixes_to_scan_tx,
 393                _background_scanner_tasks: start_background_scan_tasks(
 394                    &abs_path,
 395                    task_snapshot,
 396                    scan_requests_rx,
 397                    path_prefixes_to_scan_rx,
 398                    Arc::clone(&next_entry_id),
 399                    Arc::clone(&fs),
 400                    cx,
 401                ),
 402                diagnostics: Default::default(),
 403                diagnostic_summaries: Default::default(),
 404                client,
 405                fs,
 406                visible,
 407            })
 408        })
 409    }
 410
 411    pub fn remote(
 412        project_remote_id: u64,
 413        replica_id: ReplicaId,
 414        worktree: proto::WorktreeMetadata,
 415        client: Arc<Client>,
 416        cx: &mut AppContext,
 417    ) -> Model<Self> {
 418        cx.build_model(|cx: &mut ModelContext<Self>| {
 419            let snapshot = Snapshot {
 420                id: WorktreeId(worktree.id as usize),
 421                abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
 422                root_name: worktree.root_name.clone(),
 423                root_char_bag: worktree
 424                    .root_name
 425                    .chars()
 426                    .map(|c| c.to_ascii_lowercase())
 427                    .collect(),
 428                entries_by_path: Default::default(),
 429                entries_by_id: Default::default(),
 430                repository_entries: Default::default(),
 431                scan_id: 1,
 432                completed_scan_id: 0,
 433            };
 434
 435            let (updates_tx, mut updates_rx) = mpsc::unbounded();
 436            let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 437            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 438
 439            cx.background_executor()
 440                .spawn({
 441                    let background_snapshot = background_snapshot.clone();
 442                    async move {
 443                        while let Some(update) = updates_rx.next().await {
 444                            if let Err(error) =
 445                                background_snapshot.lock().apply_remote_update(update)
 446                            {
 447                                log::error!("error applying worktree update: {}", error);
 448                            }
 449                            snapshot_updated_tx.send(()).await.ok();
 450                        }
 451                    }
 452                })
 453                .detach();
 454
 455            cx.spawn(|this, mut cx| async move {
 456                while (snapshot_updated_rx.recv().await).is_some() {
 457                    this.update(&mut cx, |this, cx| {
 458                        let this = this.as_remote_mut().unwrap();
 459                        this.snapshot = this.background_snapshot.lock().clone();
 460                        cx.emit(Event::UpdatedEntries(Arc::from([])));
 461                        cx.notify();
 462                        while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 463                            if this.observed_snapshot(*scan_id) {
 464                                let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 465                                let _ = tx.send(());
 466                            } else {
 467                                break;
 468                            }
 469                        }
 470                    })?;
 471                }
 472                anyhow::Ok(())
 473            })
 474            .detach();
 475
 476            Worktree::Remote(RemoteWorktree {
 477                project_id: project_remote_id,
 478                replica_id,
 479                snapshot: snapshot.clone(),
 480                background_snapshot,
 481                updates_tx: Some(updates_tx),
 482                snapshot_subscriptions: Default::default(),
 483                client: client.clone(),
 484                diagnostic_summaries: Default::default(),
 485                visible: worktree.visible,
 486                disconnected: false,
 487            })
 488        })
 489    }
 490
 491    pub fn as_local(&self) -> Option<&LocalWorktree> {
 492        if let Worktree::Local(worktree) = self {
 493            Some(worktree)
 494        } else {
 495            None
 496        }
 497    }
 498
 499    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 500        if let Worktree::Remote(worktree) = self {
 501            Some(worktree)
 502        } else {
 503            None
 504        }
 505    }
 506
 507    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 508        if let Worktree::Local(worktree) = self {
 509            Some(worktree)
 510        } else {
 511            None
 512        }
 513    }
 514
 515    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 516        if let Worktree::Remote(worktree) = self {
 517            Some(worktree)
 518        } else {
 519            None
 520        }
 521    }
 522
 523    pub fn is_local(&self) -> bool {
 524        matches!(self, Worktree::Local(_))
 525    }
 526
 527    pub fn is_remote(&self) -> bool {
 528        !self.is_local()
 529    }
 530
 531    pub fn snapshot(&self) -> Snapshot {
 532        match self {
 533            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 534            Worktree::Remote(worktree) => worktree.snapshot(),
 535        }
 536    }
 537
 538    pub fn scan_id(&self) -> usize {
 539        match self {
 540            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 541            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 542        }
 543    }
 544
 545    pub fn completed_scan_id(&self) -> usize {
 546        match self {
 547            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 548            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 549        }
 550    }
 551
 552    pub fn is_visible(&self) -> bool {
 553        match self {
 554            Worktree::Local(worktree) => worktree.visible,
 555            Worktree::Remote(worktree) => worktree.visible,
 556        }
 557    }
 558
 559    pub fn replica_id(&self) -> ReplicaId {
 560        match self {
 561            Worktree::Local(_) => 0,
 562            Worktree::Remote(worktree) => worktree.replica_id,
 563        }
 564    }
 565
 566    pub fn diagnostic_summaries(
 567        &self,
 568    ) -> impl Iterator<Item = (Arc<Path>, LanguageServerId, DiagnosticSummary)> + '_ {
 569        match self {
 570            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 571            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 572        }
 573        .iter()
 574        .flat_map(|(path, summaries)| {
 575            summaries
 576                .iter()
 577                .map(move |(&server_id, &summary)| (path.clone(), server_id, summary))
 578        })
 579    }
 580
 581    pub fn abs_path(&self) -> Arc<Path> {
 582        match self {
 583            Worktree::Local(worktree) => worktree.abs_path.clone(),
 584            Worktree::Remote(worktree) => worktree.abs_path.clone(),
 585        }
 586    }
 587
 588    pub fn root_file(&self, cx: &mut ModelContext<Self>) -> Option<Arc<File>> {
 589        let entry = self.root_entry()?;
 590        Some(File::for_entry(entry.clone(), cx.handle()))
 591    }
 592}
 593
 594fn start_background_scan_tasks(
 595    abs_path: &Path,
 596    snapshot: LocalSnapshot,
 597    scan_requests_rx: channel::Receiver<ScanRequest>,
 598    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
 599    next_entry_id: Arc<AtomicUsize>,
 600    fs: Arc<dyn Fs>,
 601    cx: &mut ModelContext<'_, Worktree>,
 602) -> Vec<Task<()>> {
 603    let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 604    let background_scanner = cx.background_executor().spawn({
 605        let abs_path = abs_path.to_path_buf();
 606        let background = cx.background_executor().clone();
 607        async move {
 608            let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 609            BackgroundScanner::new(
 610                snapshot,
 611                next_entry_id,
 612                fs,
 613                scan_states_tx,
 614                background,
 615                scan_requests_rx,
 616                path_prefixes_to_scan_rx,
 617            )
 618            .run(events)
 619            .await;
 620        }
 621    });
 622    let scan_state_updater = cx.spawn(|this, mut cx| async move {
 623        while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
 624            this.update(&mut cx, |this, cx| {
 625                let this = this.as_local_mut().unwrap();
 626                match state {
 627                    ScanState::Started => {
 628                        *this.is_scanning.0.borrow_mut() = true;
 629                    }
 630                    ScanState::Updated {
 631                        snapshot,
 632                        changes,
 633                        barrier,
 634                        scanning,
 635                    } => {
 636                        *this.is_scanning.0.borrow_mut() = scanning;
 637                        this.set_snapshot(snapshot, changes, cx);
 638                        drop(barrier);
 639                    }
 640                }
 641                cx.notify();
 642            })
 643            .ok();
 644        }
 645    });
 646    vec![background_scanner, scan_state_updater]
 647}
 648
 649fn file_scan_exclusions(project_settings: &ProjectSettings) -> Vec<PathMatcher> {
 650    project_settings.file_scan_exclusions.as_deref().unwrap_or(&[]).iter()
 651    .sorted()
 652    .filter_map(|pattern| {
 653        PathMatcher::new(pattern)
 654            .map(Some)
 655            .unwrap_or_else(|e| {
 656                log::error!(
 657                    "Skipping pattern {pattern} in `file_scan_exclusions` project settings due to parsing error: {e:#}"
 658                );
 659                None
 660            })
 661    })
 662    .collect()
 663}
 664
 665impl LocalWorktree {
 666    pub fn contains_abs_path(&self, path: &Path) -> bool {
 667        path.starts_with(&self.abs_path)
 668    }
 669
 670    pub(crate) fn load_buffer(
 671        &mut self,
 672        id: u64,
 673        path: &Path,
 674        cx: &mut ModelContext<Worktree>,
 675    ) -> Task<Result<Model<Buffer>>> {
 676        let path = Arc::from(path);
 677        cx.spawn(move |this, mut cx| async move {
 678            let (file, contents, diff_base) = this
 679                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))?
 680                .await?;
 681            let text_buffer = cx
 682                .background_executor()
 683                .spawn(async move { text::Buffer::new(0, id, contents) })
 684                .await;
 685            cx.build_model(|_| Buffer::build(text_buffer, diff_base, Some(Arc::new(file))))
 686        })
 687    }
 688
 689    pub fn diagnostics_for_path(
 690        &self,
 691        path: &Path,
 692    ) -> Vec<(
 693        LanguageServerId,
 694        Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 695    )> {
 696        self.diagnostics.get(path).cloned().unwrap_or_default()
 697    }
 698
 699    pub fn clear_diagnostics_for_language_server(
 700        &mut self,
 701        server_id: LanguageServerId,
 702        _: &mut ModelContext<Worktree>,
 703    ) {
 704        let worktree_id = self.id().to_proto();
 705        self.diagnostic_summaries
 706            .retain(|path, summaries_by_server_id| {
 707                if summaries_by_server_id.remove(&server_id).is_some() {
 708                    if let Some(share) = self.share.as_ref() {
 709                        self.client
 710                            .send(proto::UpdateDiagnosticSummary {
 711                                project_id: share.project_id,
 712                                worktree_id,
 713                                summary: Some(proto::DiagnosticSummary {
 714                                    path: path.to_string_lossy().to_string(),
 715                                    language_server_id: server_id.0 as u64,
 716                                    error_count: 0,
 717                                    warning_count: 0,
 718                                }),
 719                            })
 720                            .log_err();
 721                    }
 722                    !summaries_by_server_id.is_empty()
 723                } else {
 724                    true
 725                }
 726            });
 727
 728        self.diagnostics.retain(|_, diagnostics_by_server_id| {
 729            if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 730                diagnostics_by_server_id.remove(ix);
 731                !diagnostics_by_server_id.is_empty()
 732            } else {
 733                true
 734            }
 735        });
 736    }
 737
 738    pub fn update_diagnostics(
 739        &mut self,
 740        server_id: LanguageServerId,
 741        worktree_path: Arc<Path>,
 742        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 743        _: &mut ModelContext<Worktree>,
 744    ) -> Result<bool> {
 745        let summaries_by_server_id = self
 746            .diagnostic_summaries
 747            .entry(worktree_path.clone())
 748            .or_default();
 749
 750        let old_summary = summaries_by_server_id
 751            .remove(&server_id)
 752            .unwrap_or_default();
 753
 754        let new_summary = DiagnosticSummary::new(&diagnostics);
 755        if new_summary.is_empty() {
 756            if let Some(diagnostics_by_server_id) = self.diagnostics.get_mut(&worktree_path) {
 757                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 758                    diagnostics_by_server_id.remove(ix);
 759                }
 760                if diagnostics_by_server_id.is_empty() {
 761                    self.diagnostics.remove(&worktree_path);
 762                }
 763            }
 764        } else {
 765            summaries_by_server_id.insert(server_id, new_summary);
 766            let diagnostics_by_server_id =
 767                self.diagnostics.entry(worktree_path.clone()).or_default();
 768            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 769                Ok(ix) => {
 770                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 771                }
 772                Err(ix) => {
 773                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 774                }
 775            }
 776        }
 777
 778        if !old_summary.is_empty() || !new_summary.is_empty() {
 779            if let Some(share) = self.share.as_ref() {
 780                self.client
 781                    .send(proto::UpdateDiagnosticSummary {
 782                        project_id: share.project_id,
 783                        worktree_id: self.id().to_proto(),
 784                        summary: Some(proto::DiagnosticSummary {
 785                            path: worktree_path.to_string_lossy().to_string(),
 786                            language_server_id: server_id.0 as u64,
 787                            error_count: new_summary.error_count as u32,
 788                            warning_count: new_summary.warning_count as u32,
 789                        }),
 790                    })
 791                    .log_err();
 792            }
 793        }
 794
 795        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 796    }
 797
 798    fn set_snapshot(
 799        &mut self,
 800        new_snapshot: LocalSnapshot,
 801        entry_changes: UpdatedEntriesSet,
 802        cx: &mut ModelContext<Worktree>,
 803    ) {
 804        let repo_changes = self.changed_repos(&self.snapshot, &new_snapshot);
 805
 806        self.snapshot = new_snapshot;
 807
 808        if let Some(share) = self.share.as_mut() {
 809            share
 810                .snapshots_tx
 811                .unbounded_send((
 812                    self.snapshot.clone(),
 813                    entry_changes.clone(),
 814                    repo_changes.clone(),
 815                ))
 816                .ok();
 817        }
 818
 819        if !entry_changes.is_empty() {
 820            cx.emit(Event::UpdatedEntries(entry_changes));
 821        }
 822        if !repo_changes.is_empty() {
 823            cx.emit(Event::UpdatedGitRepositories(repo_changes));
 824        }
 825    }
 826
 827    fn changed_repos(
 828        &self,
 829        old_snapshot: &LocalSnapshot,
 830        new_snapshot: &LocalSnapshot,
 831    ) -> UpdatedGitRepositoriesSet {
 832        let mut changes = Vec::new();
 833        let mut old_repos = old_snapshot.git_repositories.iter().peekable();
 834        let mut new_repos = new_snapshot.git_repositories.iter().peekable();
 835        loop {
 836            match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
 837                (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
 838                    match Ord::cmp(&new_entry_id, &old_entry_id) {
 839                        Ordering::Less => {
 840                            if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
 841                                changes.push((
 842                                    entry.path.clone(),
 843                                    GitRepositoryChange {
 844                                        old_repository: None,
 845                                    },
 846                                ));
 847                            }
 848                            new_repos.next();
 849                        }
 850                        Ordering::Equal => {
 851                            if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id {
 852                                if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
 853                                    let old_repo = old_snapshot
 854                                        .repository_entries
 855                                        .get(&RepositoryWorkDirectory(entry.path.clone()))
 856                                        .cloned();
 857                                    changes.push((
 858                                        entry.path.clone(),
 859                                        GitRepositoryChange {
 860                                            old_repository: old_repo,
 861                                        },
 862                                    ));
 863                                }
 864                            }
 865                            new_repos.next();
 866                            old_repos.next();
 867                        }
 868                        Ordering::Greater => {
 869                            if let Some(entry) = old_snapshot.entry_for_id(old_entry_id) {
 870                                let old_repo = old_snapshot
 871                                    .repository_entries
 872                                    .get(&RepositoryWorkDirectory(entry.path.clone()))
 873                                    .cloned();
 874                                changes.push((
 875                                    entry.path.clone(),
 876                                    GitRepositoryChange {
 877                                        old_repository: old_repo,
 878                                    },
 879                                ));
 880                            }
 881                            old_repos.next();
 882                        }
 883                    }
 884                }
 885                (Some((entry_id, _)), None) => {
 886                    if let Some(entry) = new_snapshot.entry_for_id(entry_id) {
 887                        changes.push((
 888                            entry.path.clone(),
 889                            GitRepositoryChange {
 890                                old_repository: None,
 891                            },
 892                        ));
 893                    }
 894                    new_repos.next();
 895                }
 896                (None, Some((entry_id, _))) => {
 897                    if let Some(entry) = old_snapshot.entry_for_id(entry_id) {
 898                        let old_repo = old_snapshot
 899                            .repository_entries
 900                            .get(&RepositoryWorkDirectory(entry.path.clone()))
 901                            .cloned();
 902                        changes.push((
 903                            entry.path.clone(),
 904                            GitRepositoryChange {
 905                                old_repository: old_repo,
 906                            },
 907                        ));
 908                    }
 909                    old_repos.next();
 910                }
 911                (None, None) => break,
 912            }
 913        }
 914
 915        fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
 916            (value.0.clone(), value.1.clone())
 917        }
 918
 919        changes.into()
 920    }
 921
 922    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 923        let mut is_scanning_rx = self.is_scanning.1.clone();
 924        async move {
 925            let mut is_scanning = is_scanning_rx.borrow().clone();
 926            while is_scanning {
 927                if let Some(value) = is_scanning_rx.recv().await {
 928                    is_scanning = value;
 929                } else {
 930                    break;
 931                }
 932            }
 933        }
 934    }
 935
 936    pub fn snapshot(&self) -> LocalSnapshot {
 937        self.snapshot.clone()
 938    }
 939
 940    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 941        proto::WorktreeMetadata {
 942            id: self.id().to_proto(),
 943            root_name: self.root_name().to_string(),
 944            visible: self.visible,
 945            abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
 946        }
 947    }
 948
 949    fn load(
 950        &self,
 951        path: &Path,
 952        cx: &mut ModelContext<Worktree>,
 953    ) -> Task<Result<(File, String, Option<String>)>> {
 954        let path = Arc::from(path);
 955        let abs_path = self.absolutize(&path);
 956        let fs = self.fs.clone();
 957        let entry = self.refresh_entry(path.clone(), None, cx);
 958
 959        cx.spawn(|this, mut cx| async move {
 960            let text = fs.load(&abs_path).await?;
 961            let entry = entry.await?;
 962
 963            let mut index_task = None;
 964            let snapshot = this.update(&mut cx, |this, _| this.as_local().unwrap().snapshot())?;
 965            if let Some(repo) = snapshot.repository_for_path(&path) {
 966                let repo_path = repo.work_directory.relativize(&snapshot, &path).unwrap();
 967                if let Some(repo) = snapshot.git_repositories.get(&*repo.work_directory) {
 968                    let repo = repo.repo_ptr.clone();
 969                    index_task = Some(
 970                        cx.background_executor()
 971                            .spawn(async move { repo.lock().load_index_text(&repo_path) }),
 972                    );
 973                }
 974            }
 975
 976            let diff_base = if let Some(index_task) = index_task {
 977                index_task.await
 978            } else {
 979                None
 980            };
 981
 982            let worktree = this
 983                .upgrade()
 984                .ok_or_else(|| anyhow!("worktree was dropped"))?;
 985            Ok((
 986                File {
 987                    entry_id: entry.id,
 988                    worktree,
 989                    path: entry.path,
 990                    mtime: entry.mtime,
 991                    is_local: true,
 992                    is_deleted: false,
 993                },
 994                text,
 995                diff_base,
 996            ))
 997        })
 998    }
 999
1000    pub fn save_buffer(
1001        &self,
1002        buffer_handle: Model<Buffer>,
1003        path: Arc<Path>,
1004        has_changed_file: bool,
1005        cx: &mut ModelContext<Worktree>,
1006    ) -> Task<Result<()>> {
1007        let buffer = buffer_handle.read(cx);
1008
1009        let rpc = self.client.clone();
1010        let buffer_id = buffer.remote_id();
1011        let project_id = self.share.as_ref().map(|share| share.project_id);
1012
1013        let text = buffer.as_rope().clone();
1014        let fingerprint = text.fingerprint();
1015        let version = buffer.version();
1016        let save = self.write_file(path, text, buffer.line_ending(), cx);
1017
1018        cx.spawn(move |this, mut cx| async move {
1019            let entry = save.await?;
1020            let this = this.upgrade().context("worktree dropped")?;
1021
1022            if has_changed_file {
1023                let new_file = Arc::new(File {
1024                    entry_id: entry.id,
1025                    worktree: this,
1026                    path: entry.path,
1027                    mtime: entry.mtime,
1028                    is_local: true,
1029                    is_deleted: false,
1030                });
1031
1032                if let Some(project_id) = project_id {
1033                    rpc.send(proto::UpdateBufferFile {
1034                        project_id,
1035                        buffer_id,
1036                        file: Some(new_file.to_proto()),
1037                    })
1038                    .log_err();
1039                }
1040
1041                buffer_handle.update(&mut cx, |buffer, cx| {
1042                    if has_changed_file {
1043                        buffer.file_updated(new_file, cx);
1044                    }
1045                })?;
1046            }
1047
1048            if let Some(project_id) = project_id {
1049                rpc.send(proto::BufferSaved {
1050                    project_id,
1051                    buffer_id,
1052                    version: serialize_version(&version),
1053                    mtime: Some(entry.mtime.into()),
1054                    fingerprint: serialize_fingerprint(fingerprint),
1055                })?;
1056            }
1057
1058            buffer_handle.update(&mut cx, |buffer, cx| {
1059                buffer.did_save(version.clone(), fingerprint, entry.mtime, cx);
1060            })?;
1061
1062            Ok(())
1063        })
1064    }
1065
1066    /// Find the lowest path in the worktree's datastructures that is an ancestor
1067    fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1068        let mut lowest_ancestor = None;
1069        for path in path.ancestors() {
1070            if self.entry_for_path(path).is_some() {
1071                lowest_ancestor = Some(path.to_path_buf());
1072                break;
1073            }
1074        }
1075
1076        lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1077    }
1078
1079    pub fn create_entry(
1080        &self,
1081        path: impl Into<Arc<Path>>,
1082        is_dir: bool,
1083        cx: &mut ModelContext<Worktree>,
1084    ) -> Task<Result<Entry>> {
1085        let path = path.into();
1086        let lowest_ancestor = self.lowest_ancestor(&path);
1087        let abs_path = self.absolutize(&path);
1088        let fs = self.fs.clone();
1089        let write = cx.background_executor().spawn(async move {
1090            if is_dir {
1091                fs.create_dir(&abs_path).await
1092            } else {
1093                fs.save(&abs_path, &Default::default(), Default::default())
1094                    .await
1095            }
1096        });
1097
1098        cx.spawn(|this, mut cx| async move {
1099            write.await?;
1100            let (result, refreshes) = this.update(&mut cx, |this, cx| {
1101                let mut refreshes = Vec::<Task<anyhow::Result<Entry>>>::new();
1102                let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1103                for refresh_path in refresh_paths.ancestors() {
1104                    if refresh_path == Path::new("") {
1105                        continue;
1106                    }
1107                    let refresh_full_path = lowest_ancestor.join(refresh_path);
1108
1109                    refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1110                        refresh_full_path.into(),
1111                        None,
1112                        cx,
1113                    ));
1114                }
1115                (
1116                    this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1117                    refreshes,
1118                )
1119            })?;
1120            for refresh in refreshes {
1121                refresh.await.log_err();
1122            }
1123
1124            result.await
1125        })
1126    }
1127
1128    pub fn write_file(
1129        &self,
1130        path: impl Into<Arc<Path>>,
1131        text: Rope,
1132        line_ending: LineEnding,
1133        cx: &mut ModelContext<Worktree>,
1134    ) -> Task<Result<Entry>> {
1135        let path = path.into();
1136        let abs_path = self.absolutize(&path);
1137        let fs = self.fs.clone();
1138        let write = cx
1139            .background_executor()
1140            .spawn(async move { fs.save(&abs_path, &text, line_ending).await });
1141
1142        cx.spawn(|this, mut cx| async move {
1143            write.await?;
1144            this.update(&mut cx, |this, cx| {
1145                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1146            })?
1147            .await
1148        })
1149    }
1150
1151    pub fn delete_entry(
1152        &self,
1153        entry_id: ProjectEntryId,
1154        cx: &mut ModelContext<Worktree>,
1155    ) -> Option<Task<Result<()>>> {
1156        let entry = self.entry_for_id(entry_id)?.clone();
1157        let abs_path = self.absolutize(&entry.path);
1158        let fs = self.fs.clone();
1159
1160        let delete = cx.background_executor().spawn(async move {
1161            if entry.is_file() {
1162                fs.remove_file(&abs_path, Default::default()).await?;
1163            } else {
1164                fs.remove_dir(
1165                    &abs_path,
1166                    RemoveOptions {
1167                        recursive: true,
1168                        ignore_if_not_exists: false,
1169                    },
1170                )
1171                .await?;
1172            }
1173            anyhow::Ok(entry.path)
1174        });
1175
1176        Some(cx.spawn(|this, mut cx| async move {
1177            let path = delete.await?;
1178            this.update(&mut cx, |this, _| {
1179                this.as_local_mut()
1180                    .unwrap()
1181                    .refresh_entries_for_paths(vec![path])
1182            })?
1183            .recv()
1184            .await;
1185            Ok(())
1186        }))
1187    }
1188
1189    pub fn rename_entry(
1190        &self,
1191        entry_id: ProjectEntryId,
1192        new_path: impl Into<Arc<Path>>,
1193        cx: &mut ModelContext<Worktree>,
1194    ) -> Option<Task<Result<Entry>>> {
1195        let old_path = self.entry_for_id(entry_id)?.path.clone();
1196        let new_path = new_path.into();
1197        let abs_old_path = self.absolutize(&old_path);
1198        let abs_new_path = self.absolutize(&new_path);
1199        let fs = self.fs.clone();
1200        let rename = cx.background_executor().spawn(async move {
1201            fs.rename(&abs_old_path, &abs_new_path, Default::default())
1202                .await
1203        });
1204
1205        Some(cx.spawn(|this, mut cx| async move {
1206            rename.await?;
1207            this.update(&mut cx, |this, cx| {
1208                this.as_local_mut()
1209                    .unwrap()
1210                    .refresh_entry(new_path.clone(), Some(old_path), cx)
1211            })?
1212            .await
1213        }))
1214    }
1215
1216    pub fn copy_entry(
1217        &self,
1218        entry_id: ProjectEntryId,
1219        new_path: impl Into<Arc<Path>>,
1220        cx: &mut ModelContext<Worktree>,
1221    ) -> Option<Task<Result<Entry>>> {
1222        let old_path = self.entry_for_id(entry_id)?.path.clone();
1223        let new_path = new_path.into();
1224        let abs_old_path = self.absolutize(&old_path);
1225        let abs_new_path = self.absolutize(&new_path);
1226        let fs = self.fs.clone();
1227        let copy = cx.background_executor().spawn(async move {
1228            copy_recursive(
1229                fs.as_ref(),
1230                &abs_old_path,
1231                &abs_new_path,
1232                Default::default(),
1233            )
1234            .await
1235        });
1236
1237        Some(cx.spawn(|this, mut cx| async move {
1238            copy.await?;
1239            this.update(&mut cx, |this, cx| {
1240                this.as_local_mut()
1241                    .unwrap()
1242                    .refresh_entry(new_path.clone(), None, cx)
1243            })?
1244            .await
1245        }))
1246    }
1247
1248    pub fn expand_entry(
1249        &mut self,
1250        entry_id: ProjectEntryId,
1251        cx: &mut ModelContext<Worktree>,
1252    ) -> Option<Task<Result<()>>> {
1253        let path = self.entry_for_id(entry_id)?.path.clone();
1254        let mut refresh = self.refresh_entries_for_paths(vec![path]);
1255        Some(cx.background_executor().spawn(async move {
1256            refresh.next().await;
1257            Ok(())
1258        }))
1259    }
1260
1261    pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1262        let (tx, rx) = barrier::channel();
1263        self.scan_requests_tx
1264            .try_send(ScanRequest {
1265                relative_paths: paths,
1266                done: tx,
1267            })
1268            .ok();
1269        rx
1270    }
1271
1272    pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) {
1273        self.path_prefixes_to_scan_tx.try_send(path_prefix).ok();
1274    }
1275
1276    fn refresh_entry(
1277        &self,
1278        path: Arc<Path>,
1279        old_path: Option<Arc<Path>>,
1280        cx: &mut ModelContext<Worktree>,
1281    ) -> Task<Result<Entry>> {
1282        let paths = if let Some(old_path) = old_path.as_ref() {
1283            vec![old_path.clone(), path.clone()]
1284        } else {
1285            vec![path.clone()]
1286        };
1287        let mut refresh = self.refresh_entries_for_paths(paths);
1288        cx.spawn(move |this, mut cx| async move {
1289            refresh.recv().await;
1290            this.update(&mut cx, |this, _| {
1291                this.entry_for_path(path)
1292                    .cloned()
1293                    .ok_or_else(|| anyhow!("failed to read path after update"))
1294            })?
1295        })
1296    }
1297
1298    pub fn observe_updates<F, Fut>(
1299        &mut self,
1300        project_id: u64,
1301        cx: &mut ModelContext<Worktree>,
1302        callback: F,
1303    ) -> oneshot::Receiver<()>
1304    where
1305        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1306        Fut: Send + Future<Output = bool>,
1307    {
1308        #[cfg(any(test, feature = "test-support"))]
1309        const MAX_CHUNK_SIZE: usize = 2;
1310        #[cfg(not(any(test, feature = "test-support")))]
1311        const MAX_CHUNK_SIZE: usize = 256;
1312
1313        let (share_tx, share_rx) = oneshot::channel();
1314
1315        if let Some(share) = self.share.as_mut() {
1316            share_tx.send(()).ok();
1317            *share.resume_updates.borrow_mut() = ();
1318            return share_rx;
1319        }
1320
1321        let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1322        let (snapshots_tx, mut snapshots_rx) =
1323            mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>();
1324        snapshots_tx
1325            .unbounded_send((self.snapshot(), Arc::from([]), Arc::from([])))
1326            .ok();
1327
1328        let worktree_id = cx.entity_id().as_u64();
1329        let _maintain_remote_snapshot = cx.background_executor().spawn(async move {
1330            let mut is_first = true;
1331            while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
1332                let update;
1333                if is_first {
1334                    update = snapshot.build_initial_update(project_id, worktree_id);
1335                    is_first = false;
1336                } else {
1337                    update =
1338                        snapshot.build_update(project_id, worktree_id, entry_changes, repo_changes);
1339                }
1340
1341                for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1342                    let _ = resume_updates_rx.try_recv();
1343                    loop {
1344                        let result = callback(update.clone());
1345                        if result.await {
1346                            break;
1347                        } else {
1348                            log::info!("waiting to resume updates");
1349                            if resume_updates_rx.next().await.is_none() {
1350                                return Some(());
1351                            }
1352                        }
1353                    }
1354                }
1355            }
1356            share_tx.send(()).ok();
1357            Some(())
1358        });
1359
1360        self.share = Some(ShareState {
1361            project_id,
1362            snapshots_tx,
1363            resume_updates: resume_updates_tx,
1364            _maintain_remote_snapshot,
1365        });
1366        share_rx
1367    }
1368
1369    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1370        let client = self.client.clone();
1371
1372        for (path, summaries) in &self.diagnostic_summaries {
1373            for (&server_id, summary) in summaries {
1374                if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1375                    project_id,
1376                    worktree_id: cx.entity_id().as_u64(),
1377                    summary: Some(summary.to_proto(server_id, &path)),
1378                }) {
1379                    return Task::ready(Err(e));
1380                }
1381            }
1382        }
1383
1384        let rx = self.observe_updates(project_id, cx, move |update| {
1385            client.request(update).map(|result| result.is_ok())
1386        });
1387        cx.background_executor()
1388            .spawn(async move { rx.await.map_err(|_| anyhow!("share ended")) })
1389    }
1390
1391    pub fn unshare(&mut self) {
1392        self.share.take();
1393    }
1394
1395    pub fn is_shared(&self) -> bool {
1396        self.share.is_some()
1397    }
1398}
1399
1400impl RemoteWorktree {
1401    fn snapshot(&self) -> Snapshot {
1402        self.snapshot.clone()
1403    }
1404
1405    pub fn disconnected_from_host(&mut self) {
1406        self.updates_tx.take();
1407        self.snapshot_subscriptions.clear();
1408        self.disconnected = true;
1409    }
1410
1411    pub fn save_buffer(
1412        &self,
1413        buffer_handle: Model<Buffer>,
1414        cx: &mut ModelContext<Worktree>,
1415    ) -> Task<Result<()>> {
1416        let buffer = buffer_handle.read(cx);
1417        let buffer_id = buffer.remote_id();
1418        let version = buffer.version();
1419        let rpc = self.client.clone();
1420        let project_id = self.project_id;
1421        cx.spawn(move |_, mut cx| async move {
1422            let response = rpc
1423                .request(proto::SaveBuffer {
1424                    project_id,
1425                    buffer_id,
1426                    version: serialize_version(&version),
1427                })
1428                .await?;
1429            let version = deserialize_version(&response.version);
1430            let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1431            let mtime = response
1432                .mtime
1433                .ok_or_else(|| anyhow!("missing mtime"))?
1434                .into();
1435
1436            buffer_handle.update(&mut cx, |buffer, cx| {
1437                buffer.did_save(version.clone(), fingerprint, mtime, cx);
1438            })?;
1439
1440            Ok(())
1441        })
1442    }
1443
1444    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1445        if let Some(updates_tx) = &self.updates_tx {
1446            updates_tx
1447                .unbounded_send(update)
1448                .expect("consumer runs to completion");
1449        }
1450    }
1451
1452    fn observed_snapshot(&self, scan_id: usize) -> bool {
1453        self.completed_scan_id >= scan_id
1454    }
1455
1456    pub(crate) fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1457        let (tx, rx) = oneshot::channel();
1458        if self.observed_snapshot(scan_id) {
1459            let _ = tx.send(());
1460        } else if self.disconnected {
1461            drop(tx);
1462        } else {
1463            match self
1464                .snapshot_subscriptions
1465                .binary_search_by_key(&scan_id, |probe| probe.0)
1466            {
1467                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1468            }
1469        }
1470
1471        async move {
1472            rx.await?;
1473            Ok(())
1474        }
1475    }
1476
1477    pub fn update_diagnostic_summary(
1478        &mut self,
1479        path: Arc<Path>,
1480        summary: &proto::DiagnosticSummary,
1481    ) {
1482        let server_id = LanguageServerId(summary.language_server_id as usize);
1483        let summary = DiagnosticSummary {
1484            error_count: summary.error_count as usize,
1485            warning_count: summary.warning_count as usize,
1486        };
1487
1488        if summary.is_empty() {
1489            if let Some(summaries) = self.diagnostic_summaries.get_mut(&path) {
1490                summaries.remove(&server_id);
1491                if summaries.is_empty() {
1492                    self.diagnostic_summaries.remove(&path);
1493                }
1494            }
1495        } else {
1496            self.diagnostic_summaries
1497                .entry(path)
1498                .or_default()
1499                .insert(server_id, summary);
1500        }
1501    }
1502
1503    pub fn insert_entry(
1504        &mut self,
1505        entry: proto::Entry,
1506        scan_id: usize,
1507        cx: &mut ModelContext<Worktree>,
1508    ) -> Task<Result<Entry>> {
1509        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1510        cx.spawn(|this, mut cx| async move {
1511            wait_for_snapshot.await?;
1512            this.update(&mut cx, |worktree, _| {
1513                let worktree = worktree.as_remote_mut().unwrap();
1514                let mut snapshot = worktree.background_snapshot.lock();
1515                let entry = snapshot.insert_entry(entry);
1516                worktree.snapshot = snapshot.clone();
1517                entry
1518            })?
1519        })
1520    }
1521
1522    pub(crate) fn delete_entry(
1523        &mut self,
1524        id: ProjectEntryId,
1525        scan_id: usize,
1526        cx: &mut ModelContext<Worktree>,
1527    ) -> Task<Result<()>> {
1528        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1529        cx.spawn(move |this, mut cx| async move {
1530            wait_for_snapshot.await?;
1531            this.update(&mut cx, |worktree, _| {
1532                let worktree = worktree.as_remote_mut().unwrap();
1533                let mut snapshot = worktree.background_snapshot.lock();
1534                snapshot.delete_entry(id);
1535                worktree.snapshot = snapshot.clone();
1536            })?;
1537            Ok(())
1538        })
1539    }
1540}
1541
1542impl Snapshot {
1543    pub fn id(&self) -> WorktreeId {
1544        self.id
1545    }
1546
1547    pub fn abs_path(&self) -> &Arc<Path> {
1548        &self.abs_path
1549    }
1550
1551    pub fn absolutize(&self, path: &Path) -> PathBuf {
1552        if path.file_name().is_some() {
1553            self.abs_path.join(path)
1554        } else {
1555            self.abs_path.to_path_buf()
1556        }
1557    }
1558
1559    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1560        self.entries_by_id.get(&entry_id, &()).is_some()
1561    }
1562
1563    fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1564        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1565        let old_entry = self.entries_by_id.insert_or_replace(
1566            PathEntry {
1567                id: entry.id,
1568                path: entry.path.clone(),
1569                is_ignored: entry.is_ignored,
1570                scan_id: 0,
1571            },
1572            &(),
1573        );
1574        if let Some(old_entry) = old_entry {
1575            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1576        }
1577        self.entries_by_path.insert_or_replace(entry.clone(), &());
1578        Ok(entry)
1579    }
1580
1581    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1582        let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1583        self.entries_by_path = {
1584            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1585            let mut new_entries_by_path =
1586                cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1587            while let Some(entry) = cursor.item() {
1588                if entry.path.starts_with(&removed_entry.path) {
1589                    self.entries_by_id.remove(&entry.id, &());
1590                    cursor.next(&());
1591                } else {
1592                    break;
1593                }
1594            }
1595            new_entries_by_path.append(cursor.suffix(&()), &());
1596            new_entries_by_path
1597        };
1598
1599        Some(removed_entry.path)
1600    }
1601
1602    #[cfg(any(test, feature = "test-support"))]
1603    pub fn status_for_file(&self, path: impl Into<PathBuf>) -> Option<GitFileStatus> {
1604        let path = path.into();
1605        self.entries_by_path
1606            .get(&PathKey(Arc::from(path)), &())
1607            .and_then(|entry| entry.git_status)
1608    }
1609
1610    pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1611        let mut entries_by_path_edits = Vec::new();
1612        let mut entries_by_id_edits = Vec::new();
1613
1614        for entry_id in update.removed_entries {
1615            let entry_id = ProjectEntryId::from_proto(entry_id);
1616            entries_by_id_edits.push(Edit::Remove(entry_id));
1617            if let Some(entry) = self.entry_for_id(entry_id) {
1618                entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1619            }
1620        }
1621
1622        for entry in update.updated_entries {
1623            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1624            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1625                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1626            }
1627            if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
1628                if old_entry.id != entry.id {
1629                    entries_by_id_edits.push(Edit::Remove(old_entry.id));
1630                }
1631            }
1632            entries_by_id_edits.push(Edit::Insert(PathEntry {
1633                id: entry.id,
1634                path: entry.path.clone(),
1635                is_ignored: entry.is_ignored,
1636                scan_id: 0,
1637            }));
1638            entries_by_path_edits.push(Edit::Insert(entry));
1639        }
1640
1641        self.entries_by_path.edit(entries_by_path_edits, &());
1642        self.entries_by_id.edit(entries_by_id_edits, &());
1643
1644        update.removed_repositories.sort_unstable();
1645        self.repository_entries.retain(|_, entry| {
1646            if let Ok(_) = update
1647                .removed_repositories
1648                .binary_search(&entry.work_directory.to_proto())
1649            {
1650                false
1651            } else {
1652                true
1653            }
1654        });
1655
1656        for repository in update.updated_repositories {
1657            let work_directory_entry: WorkDirectoryEntry =
1658                ProjectEntryId::from_proto(repository.work_directory_id).into();
1659
1660            if let Some(entry) = self.entry_for_id(*work_directory_entry) {
1661                let work_directory = RepositoryWorkDirectory(entry.path.clone());
1662                if self.repository_entries.get(&work_directory).is_some() {
1663                    self.repository_entries.update(&work_directory, |repo| {
1664                        repo.branch = repository.branch.map(Into::into);
1665                    });
1666                } else {
1667                    self.repository_entries.insert(
1668                        work_directory,
1669                        RepositoryEntry {
1670                            work_directory: work_directory_entry,
1671                            branch: repository.branch.map(Into::into),
1672                        },
1673                    )
1674                }
1675            } else {
1676                log::error!("no work directory entry for repository {:?}", repository)
1677            }
1678        }
1679
1680        self.scan_id = update.scan_id as usize;
1681        if update.is_last_update {
1682            self.completed_scan_id = update.scan_id as usize;
1683        }
1684
1685        Ok(())
1686    }
1687
1688    pub fn file_count(&self) -> usize {
1689        self.entries_by_path.summary().file_count
1690    }
1691
1692    pub fn visible_file_count(&self) -> usize {
1693        self.entries_by_path.summary().non_ignored_file_count
1694    }
1695
1696    fn traverse_from_offset(
1697        &self,
1698        include_dirs: bool,
1699        include_ignored: bool,
1700        start_offset: usize,
1701    ) -> Traversal {
1702        let mut cursor = self.entries_by_path.cursor();
1703        cursor.seek(
1704            &TraversalTarget::Count {
1705                count: start_offset,
1706                include_dirs,
1707                include_ignored,
1708            },
1709            Bias::Right,
1710            &(),
1711        );
1712        Traversal {
1713            cursor,
1714            include_dirs,
1715            include_ignored,
1716        }
1717    }
1718
1719    fn traverse_from_path(
1720        &self,
1721        include_dirs: bool,
1722        include_ignored: bool,
1723        path: &Path,
1724    ) -> Traversal {
1725        let mut cursor = self.entries_by_path.cursor();
1726        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1727        Traversal {
1728            cursor,
1729            include_dirs,
1730            include_ignored,
1731        }
1732    }
1733
1734    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1735        self.traverse_from_offset(false, include_ignored, start)
1736    }
1737
1738    pub fn entries(&self, include_ignored: bool) -> Traversal {
1739        self.traverse_from_offset(true, include_ignored, 0)
1740    }
1741
1742    pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
1743        self.repository_entries
1744            .iter()
1745            .map(|(path, entry)| (&path.0, entry))
1746    }
1747
1748    /// Get the repository whose work directory contains the given path.
1749    pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
1750        self.repository_entries
1751            .get(&RepositoryWorkDirectory(path.into()))
1752            .cloned()
1753    }
1754
1755    /// Get the repository whose work directory contains the given path.
1756    pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
1757        self.repository_and_work_directory_for_path(path)
1758            .map(|e| e.1)
1759    }
1760
1761    pub fn repository_and_work_directory_for_path(
1762        &self,
1763        path: &Path,
1764    ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
1765        self.repository_entries
1766            .iter()
1767            .filter(|(workdir_path, _)| path.starts_with(workdir_path))
1768            .last()
1769            .map(|(path, repo)| (path.clone(), repo.clone()))
1770    }
1771
1772    /// Given an ordered iterator of entries, returns an iterator of those entries,
1773    /// along with their containing git repository.
1774    pub fn entries_with_repositories<'a>(
1775        &'a self,
1776        entries: impl 'a + Iterator<Item = &'a Entry>,
1777    ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
1778        let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
1779        let mut repositories = self.repositories().peekable();
1780        entries.map(move |entry| {
1781            while let Some((repo_path, _)) = containing_repos.last() {
1782                if !entry.path.starts_with(repo_path) {
1783                    containing_repos.pop();
1784                } else {
1785                    break;
1786                }
1787            }
1788            while let Some((repo_path, _)) = repositories.peek() {
1789                if entry.path.starts_with(repo_path) {
1790                    containing_repos.push(repositories.next().unwrap());
1791                } else {
1792                    break;
1793                }
1794            }
1795            let repo = containing_repos.last().map(|(_, repo)| *repo);
1796            (entry, repo)
1797        })
1798    }
1799
1800    /// Update the `git_status` of the given entries such that files'
1801    /// statuses bubble up to their ancestor directories.
1802    pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
1803        let mut cursor = self
1804            .entries_by_path
1805            .cursor::<(TraversalProgress, GitStatuses)>();
1806        let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
1807
1808        let mut result_ix = 0;
1809        loop {
1810            let next_entry = result.get(result_ix);
1811            let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
1812
1813            let entry_to_finish = match (containing_entry, next_entry) {
1814                (Some(_), None) => entry_stack.pop(),
1815                (Some(containing_entry), Some(next_path)) => {
1816                    if !next_path.path.starts_with(&containing_entry.path) {
1817                        entry_stack.pop()
1818                    } else {
1819                        None
1820                    }
1821                }
1822                (None, Some(_)) => None,
1823                (None, None) => break,
1824            };
1825
1826            if let Some((entry_ix, prev_statuses)) = entry_to_finish {
1827                cursor.seek_forward(
1828                    &TraversalTarget::PathSuccessor(&result[entry_ix].path),
1829                    Bias::Left,
1830                    &(),
1831                );
1832
1833                let statuses = cursor.start().1 - prev_statuses;
1834
1835                result[entry_ix].git_status = if statuses.conflict > 0 {
1836                    Some(GitFileStatus::Conflict)
1837                } else if statuses.modified > 0 {
1838                    Some(GitFileStatus::Modified)
1839                } else if statuses.added > 0 {
1840                    Some(GitFileStatus::Added)
1841                } else {
1842                    None
1843                };
1844            } else {
1845                if result[result_ix].is_dir() {
1846                    cursor.seek_forward(
1847                        &TraversalTarget::Path(&result[result_ix].path),
1848                        Bias::Left,
1849                        &(),
1850                    );
1851                    entry_stack.push((result_ix, cursor.start().1));
1852                }
1853                result_ix += 1;
1854            }
1855        }
1856    }
1857
1858    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1859        let empty_path = Path::new("");
1860        self.entries_by_path
1861            .cursor::<()>()
1862            .filter(move |entry| entry.path.as_ref() != empty_path)
1863            .map(|entry| &entry.path)
1864    }
1865
1866    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1867        let mut cursor = self.entries_by_path.cursor();
1868        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1869        let traversal = Traversal {
1870            cursor,
1871            include_dirs: true,
1872            include_ignored: true,
1873        };
1874        ChildEntriesIter {
1875            traversal,
1876            parent_path,
1877        }
1878    }
1879
1880    pub fn descendent_entries<'a>(
1881        &'a self,
1882        include_dirs: bool,
1883        include_ignored: bool,
1884        parent_path: &'a Path,
1885    ) -> DescendentEntriesIter<'a> {
1886        let mut cursor = self.entries_by_path.cursor();
1887        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Left, &());
1888        let mut traversal = Traversal {
1889            cursor,
1890            include_dirs,
1891            include_ignored,
1892        };
1893
1894        if traversal.end_offset() == traversal.start_offset() {
1895            traversal.advance();
1896        }
1897
1898        DescendentEntriesIter {
1899            traversal,
1900            parent_path,
1901        }
1902    }
1903
1904    pub fn root_entry(&self) -> Option<&Entry> {
1905        self.entry_for_path("")
1906    }
1907
1908    pub fn root_name(&self) -> &str {
1909        &self.root_name
1910    }
1911
1912    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1913        self.repository_entries
1914            .get(&RepositoryWorkDirectory(Path::new("").into()))
1915            .map(|entry| entry.to_owned())
1916    }
1917
1918    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1919        self.repository_entries.values()
1920    }
1921
1922    pub fn scan_id(&self) -> usize {
1923        self.scan_id
1924    }
1925
1926    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1927        let path = path.as_ref();
1928        self.traverse_from_path(true, true, path)
1929            .entry()
1930            .and_then(|entry| {
1931                if entry.path.as_ref() == path {
1932                    Some(entry)
1933                } else {
1934                    None
1935                }
1936            })
1937    }
1938
1939    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1940        let entry = self.entries_by_id.get(&id, &())?;
1941        self.entry_for_path(&entry.path)
1942    }
1943
1944    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1945        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1946    }
1947}
1948
1949impl LocalSnapshot {
1950    pub(crate) fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
1951        self.git_repositories.get(&repo.work_directory.0)
1952    }
1953
1954    pub(crate) fn local_repo_for_path(
1955        &self,
1956        path: &Path,
1957    ) -> Option<(RepositoryWorkDirectory, &LocalRepositoryEntry)> {
1958        let (path, repo) = self.repository_and_work_directory_for_path(path)?;
1959        Some((path, self.git_repositories.get(&repo.work_directory_id())?))
1960    }
1961
1962    fn build_update(
1963        &self,
1964        project_id: u64,
1965        worktree_id: u64,
1966        entry_changes: UpdatedEntriesSet,
1967        repo_changes: UpdatedGitRepositoriesSet,
1968    ) -> proto::UpdateWorktree {
1969        let mut updated_entries = Vec::new();
1970        let mut removed_entries = Vec::new();
1971        let mut updated_repositories = Vec::new();
1972        let mut removed_repositories = Vec::new();
1973
1974        for (_, entry_id, path_change) in entry_changes.iter() {
1975            if let PathChange::Removed = path_change {
1976                removed_entries.push(entry_id.0 as u64);
1977            } else if let Some(entry) = self.entry_for_id(*entry_id) {
1978                updated_entries.push(proto::Entry::from(entry));
1979            }
1980        }
1981
1982        for (work_dir_path, change) in repo_changes.iter() {
1983            let new_repo = self
1984                .repository_entries
1985                .get(&RepositoryWorkDirectory(work_dir_path.clone()));
1986            match (&change.old_repository, new_repo) {
1987                (Some(old_repo), Some(new_repo)) => {
1988                    updated_repositories.push(new_repo.build_update(old_repo));
1989                }
1990                (None, Some(new_repo)) => {
1991                    updated_repositories.push(proto::RepositoryEntry::from(new_repo));
1992                }
1993                (Some(old_repo), None) => {
1994                    removed_repositories.push(old_repo.work_directory.0.to_proto());
1995                }
1996                _ => {}
1997            }
1998        }
1999
2000        removed_entries.sort_unstable();
2001        updated_entries.sort_unstable_by_key(|e| e.id);
2002        removed_repositories.sort_unstable();
2003        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2004
2005        // TODO - optimize, knowing that removed_entries are sorted.
2006        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2007
2008        proto::UpdateWorktree {
2009            project_id,
2010            worktree_id,
2011            abs_path: self.abs_path().to_string_lossy().into(),
2012            root_name: self.root_name().to_string(),
2013            updated_entries,
2014            removed_entries,
2015            scan_id: self.scan_id as u64,
2016            is_last_update: self.completed_scan_id == self.scan_id,
2017            updated_repositories,
2018            removed_repositories,
2019        }
2020    }
2021
2022    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2023        let mut updated_entries = self
2024            .entries_by_path
2025            .iter()
2026            .map(proto::Entry::from)
2027            .collect::<Vec<_>>();
2028        updated_entries.sort_unstable_by_key(|e| e.id);
2029
2030        let mut updated_repositories = self
2031            .repository_entries
2032            .values()
2033            .map(proto::RepositoryEntry::from)
2034            .collect::<Vec<_>>();
2035        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2036
2037        proto::UpdateWorktree {
2038            project_id,
2039            worktree_id,
2040            abs_path: self.abs_path().to_string_lossy().into(),
2041            root_name: self.root_name().to_string(),
2042            updated_entries,
2043            removed_entries: Vec::new(),
2044            scan_id: self.scan_id as u64,
2045            is_last_update: self.completed_scan_id == self.scan_id,
2046            updated_repositories,
2047            removed_repositories: Vec::new(),
2048        }
2049    }
2050
2051    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2052        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2053            let abs_path = self.abs_path.join(&entry.path);
2054            match smol::block_on(build_gitignore(&abs_path, fs)) {
2055                Ok(ignore) => {
2056                    self.ignores_by_parent_abs_path
2057                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2058                }
2059                Err(error) => {
2060                    log::error!(
2061                        "error loading .gitignore file {:?} - {:?}",
2062                        &entry.path,
2063                        error
2064                    );
2065                }
2066            }
2067        }
2068
2069        if entry.kind == EntryKind::PendingDir {
2070            if let Some(existing_entry) =
2071                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2072            {
2073                entry.kind = existing_entry.kind;
2074            }
2075        }
2076
2077        let scan_id = self.scan_id;
2078        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2079        if let Some(removed) = removed {
2080            if removed.id != entry.id {
2081                self.entries_by_id.remove(&removed.id, &());
2082            }
2083        }
2084        self.entries_by_id.insert_or_replace(
2085            PathEntry {
2086                id: entry.id,
2087                path: entry.path.clone(),
2088                is_ignored: entry.is_ignored,
2089                scan_id,
2090            },
2091            &(),
2092        );
2093
2094        entry
2095    }
2096
2097    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2098        let mut inodes = TreeSet::default();
2099        for ancestor in path.ancestors().skip(1) {
2100            if let Some(entry) = self.entry_for_path(ancestor) {
2101                inodes.insert(entry.inode);
2102            }
2103        }
2104        inodes
2105    }
2106
2107    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2108        let mut new_ignores = Vec::new();
2109        for ancestor in abs_path.ancestors().skip(1) {
2110            if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2111                new_ignores.push((ancestor, Some(ignore.clone())));
2112            } else {
2113                new_ignores.push((ancestor, None));
2114            }
2115        }
2116
2117        let mut ignore_stack = IgnoreStack::none();
2118        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2119            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2120                ignore_stack = IgnoreStack::all();
2121                break;
2122            } else if let Some(ignore) = ignore {
2123                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2124            }
2125        }
2126
2127        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2128            ignore_stack = IgnoreStack::all();
2129        }
2130
2131        ignore_stack
2132    }
2133
2134    #[allow(dead_code)] // todo!("remove this when we use it")
2135    #[cfg(test)]
2136    pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2137        self.entries_by_path
2138            .cursor::<()>()
2139            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2140    }
2141
2142    #[cfg(test)]
2143    pub fn check_invariants(&self, git_state: bool) {
2144        use pretty_assertions::assert_eq;
2145
2146        assert_eq!(
2147            self.entries_by_path
2148                .cursor::<()>()
2149                .map(|e| (&e.path, e.id))
2150                .collect::<Vec<_>>(),
2151            self.entries_by_id
2152                .cursor::<()>()
2153                .map(|e| (&e.path, e.id))
2154                .collect::<collections::BTreeSet<_>>()
2155                .into_iter()
2156                .collect::<Vec<_>>(),
2157            "entries_by_path and entries_by_id are inconsistent"
2158        );
2159
2160        let mut files = self.files(true, 0);
2161        let mut visible_files = self.files(false, 0);
2162        for entry in self.entries_by_path.cursor::<()>() {
2163            if entry.is_file() {
2164                assert_eq!(files.next().unwrap().inode, entry.inode);
2165                if !entry.is_ignored && !entry.is_external {
2166                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2167                }
2168            }
2169        }
2170
2171        assert!(files.next().is_none());
2172        assert!(visible_files.next().is_none());
2173
2174        let mut bfs_paths = Vec::new();
2175        let mut stack = self
2176            .root_entry()
2177            .map(|e| e.path.as_ref())
2178            .into_iter()
2179            .collect::<Vec<_>>();
2180        while let Some(path) = stack.pop() {
2181            bfs_paths.push(path);
2182            let ix = stack.len();
2183            for child_entry in self.child_entries(path) {
2184                stack.insert(ix, &child_entry.path);
2185            }
2186        }
2187
2188        let dfs_paths_via_iter = self
2189            .entries_by_path
2190            .cursor::<()>()
2191            .map(|e| e.path.as_ref())
2192            .collect::<Vec<_>>();
2193        assert_eq!(bfs_paths, dfs_paths_via_iter);
2194
2195        let dfs_paths_via_traversal = self
2196            .entries(true)
2197            .map(|e| e.path.as_ref())
2198            .collect::<Vec<_>>();
2199        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2200
2201        if git_state {
2202            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2203                let ignore_parent_path =
2204                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2205                assert!(self.entry_for_path(&ignore_parent_path).is_some());
2206                assert!(self
2207                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2208                    .is_some());
2209            }
2210        }
2211    }
2212
2213    #[cfg(test)]
2214    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2215        let mut paths = Vec::new();
2216        for entry in self.entries_by_path.cursor::<()>() {
2217            if include_ignored || !entry.is_ignored {
2218                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2219            }
2220        }
2221        paths.sort_by(|a, b| a.0.cmp(b.0));
2222        paths
2223    }
2224
2225    fn is_path_excluded(&self, abs_path: &Path) -> bool {
2226        self.file_scan_exclusions
2227            .iter()
2228            .any(|exclude_matcher| exclude_matcher.is_match(abs_path))
2229    }
2230}
2231
2232impl BackgroundScannerState {
2233    fn should_scan_directory(&self, entry: &Entry) -> bool {
2234        (!entry.is_external && !entry.is_ignored)
2235            || entry.path.file_name() == Some(&*DOT_GIT)
2236            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2237            || self
2238                .paths_to_scan
2239                .iter()
2240                .any(|p| p.starts_with(&entry.path))
2241            || self
2242                .path_prefixes_to_scan
2243                .iter()
2244                .any(|p| entry.path.starts_with(p))
2245    }
2246
2247    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2248        let path = entry.path.clone();
2249        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2250        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2251        let mut containing_repository = None;
2252        if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2253            if let Some((workdir_path, repo)) = self.snapshot.local_repo_for_path(&path) {
2254                if let Ok(repo_path) = path.strip_prefix(&workdir_path.0) {
2255                    containing_repository = Some((
2256                        workdir_path,
2257                        repo.repo_ptr.clone(),
2258                        repo.repo_ptr.lock().staged_statuses(repo_path),
2259                    ));
2260                }
2261            }
2262        }
2263        if !ancestor_inodes.contains(&entry.inode) {
2264            ancestor_inodes.insert(entry.inode);
2265            scan_job_tx
2266                .try_send(ScanJob {
2267                    abs_path,
2268                    path,
2269                    ignore_stack,
2270                    scan_queue: scan_job_tx.clone(),
2271                    ancestor_inodes,
2272                    is_external: entry.is_external,
2273                    containing_repository,
2274                })
2275                .unwrap();
2276        }
2277    }
2278
2279    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2280        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2281            entry.id = removed_entry_id;
2282        } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2283            entry.id = existing_entry.id;
2284        }
2285    }
2286
2287    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2288        self.reuse_entry_id(&mut entry);
2289        let entry = self.snapshot.insert_entry(entry, fs);
2290        if entry.path.file_name() == Some(&DOT_GIT) {
2291            self.build_git_repository(entry.path.clone(), fs);
2292        }
2293
2294        #[cfg(test)]
2295        self.snapshot.check_invariants(false);
2296
2297        entry
2298    }
2299
2300    fn populate_dir(
2301        &mut self,
2302        parent_path: &Arc<Path>,
2303        entries: impl IntoIterator<Item = Entry>,
2304        ignore: Option<Arc<Gitignore>>,
2305    ) {
2306        let mut parent_entry = if let Some(parent_entry) = self
2307            .snapshot
2308            .entries_by_path
2309            .get(&PathKey(parent_path.clone()), &())
2310        {
2311            parent_entry.clone()
2312        } else {
2313            log::warn!(
2314                "populating a directory {:?} that has been removed",
2315                parent_path
2316            );
2317            return;
2318        };
2319
2320        match parent_entry.kind {
2321            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2322            EntryKind::Dir => {}
2323            _ => return,
2324        }
2325
2326        if let Some(ignore) = ignore {
2327            let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2328            self.snapshot
2329                .ignores_by_parent_abs_path
2330                .insert(abs_parent_path, (ignore, false));
2331        }
2332
2333        let parent_entry_id = parent_entry.id;
2334        self.scanned_dirs.insert(parent_entry_id);
2335        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2336        let mut entries_by_id_edits = Vec::new();
2337
2338        for entry in entries {
2339            entries_by_id_edits.push(Edit::Insert(PathEntry {
2340                id: entry.id,
2341                path: entry.path.clone(),
2342                is_ignored: entry.is_ignored,
2343                scan_id: self.snapshot.scan_id,
2344            }));
2345            entries_by_path_edits.push(Edit::Insert(entry));
2346        }
2347
2348        self.snapshot
2349            .entries_by_path
2350            .edit(entries_by_path_edits, &());
2351        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2352
2353        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2354            self.changed_paths.insert(ix, parent_path.clone());
2355        }
2356
2357        #[cfg(test)]
2358        self.snapshot.check_invariants(false);
2359    }
2360
2361    fn remove_path(&mut self, path: &Path) {
2362        let mut new_entries;
2363        let removed_entries;
2364        {
2365            let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2366            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2367            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2368            new_entries.append(cursor.suffix(&()), &());
2369        }
2370        self.snapshot.entries_by_path = new_entries;
2371
2372        let mut entries_by_id_edits = Vec::new();
2373        for entry in removed_entries.cursor::<()>() {
2374            let removed_entry_id = self
2375                .removed_entry_ids
2376                .entry(entry.inode)
2377                .or_insert(entry.id);
2378            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2379            entries_by_id_edits.push(Edit::Remove(entry.id));
2380        }
2381        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2382
2383        if path.file_name() == Some(&GITIGNORE) {
2384            let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2385            if let Some((_, needs_update)) = self
2386                .snapshot
2387                .ignores_by_parent_abs_path
2388                .get_mut(abs_parent_path.as_path())
2389            {
2390                *needs_update = true;
2391            }
2392        }
2393
2394        #[cfg(test)]
2395        self.snapshot.check_invariants(false);
2396    }
2397
2398    fn reload_repositories(&mut self, dot_git_dirs_to_reload: &HashSet<PathBuf>, fs: &dyn Fs) {
2399        let scan_id = self.snapshot.scan_id;
2400
2401        for dot_git_dir in dot_git_dirs_to_reload {
2402            // If there is already a repository for this .git directory, reload
2403            // the status for all of its files.
2404            let repository = self
2405                .snapshot
2406                .git_repositories
2407                .iter()
2408                .find_map(|(entry_id, repo)| {
2409                    (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2410                });
2411            match repository {
2412                None => {
2413                    self.build_git_repository(Arc::from(dot_git_dir.as_path()), fs);
2414                }
2415                Some((entry_id, repository)) => {
2416                    if repository.git_dir_scan_id == scan_id {
2417                        continue;
2418                    }
2419                    let Some(work_dir) = self
2420                        .snapshot
2421                        .entry_for_id(entry_id)
2422                        .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2423                    else {
2424                        continue;
2425                    };
2426
2427                    log::info!("reload git repository {dot_git_dir:?}");
2428                    let repository = repository.repo_ptr.lock();
2429                    let branch = repository.branch_name();
2430                    repository.reload_index();
2431
2432                    self.snapshot
2433                        .git_repositories
2434                        .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2435                    self.snapshot
2436                        .snapshot
2437                        .repository_entries
2438                        .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2439
2440                    self.update_git_statuses(&work_dir, &*repository);
2441                }
2442            }
2443        }
2444
2445        // Remove any git repositories whose .git entry no longer exists.
2446        let snapshot = &mut self.snapshot;
2447        let mut ids_to_preserve = HashSet::default();
2448        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
2449            let exists_in_snapshot = snapshot
2450                .entry_for_id(work_directory_id)
2451                .map_or(false, |entry| {
2452                    snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2453                });
2454            if exists_in_snapshot {
2455                ids_to_preserve.insert(work_directory_id);
2456            } else {
2457                let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
2458                let git_dir_excluded = snapshot.is_path_excluded(&entry.git_dir_path)
2459                    || snapshot.is_path_excluded(&git_dir_abs_path);
2460                if git_dir_excluded
2461                    && !matches!(smol::block_on(fs.metadata(&git_dir_abs_path)), Ok(None))
2462                {
2463                    ids_to_preserve.insert(work_directory_id);
2464                }
2465            }
2466        }
2467        snapshot
2468            .git_repositories
2469            .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
2470        snapshot
2471            .repository_entries
2472            .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
2473    }
2474
2475    fn build_git_repository(
2476        &mut self,
2477        dot_git_path: Arc<Path>,
2478        fs: &dyn Fs,
2479    ) -> Option<(
2480        RepositoryWorkDirectory,
2481        Arc<Mutex<dyn GitRepository>>,
2482        TreeMap<RepoPath, GitFileStatus>,
2483    )> {
2484        log::info!("build git repository {:?}", dot_git_path);
2485
2486        let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2487
2488        // Guard against repositories inside the repository metadata
2489        if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2490            return None;
2491        };
2492
2493        let work_dir_id = self
2494            .snapshot
2495            .entry_for_path(work_dir_path.clone())
2496            .map(|entry| entry.id)?;
2497
2498        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2499            return None;
2500        }
2501
2502        let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2503        let repository = fs.open_repo(abs_path.as_path())?;
2504        let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2505
2506        let repo_lock = repository.lock();
2507        self.snapshot.repository_entries.insert(
2508            work_directory.clone(),
2509            RepositoryEntry {
2510                work_directory: work_dir_id.into(),
2511                branch: repo_lock.branch_name().map(Into::into),
2512            },
2513        );
2514
2515        let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2516        drop(repo_lock);
2517
2518        self.snapshot.git_repositories.insert(
2519            work_dir_id,
2520            LocalRepositoryEntry {
2521                git_dir_scan_id: 0,
2522                repo_ptr: repository.clone(),
2523                git_dir_path: dot_git_path.clone(),
2524            },
2525        );
2526
2527        Some((work_directory, repository, staged_statuses))
2528    }
2529
2530    fn update_git_statuses(
2531        &mut self,
2532        work_directory: &RepositoryWorkDirectory,
2533        repo: &dyn GitRepository,
2534    ) -> TreeMap<RepoPath, GitFileStatus> {
2535        let staged_statuses = repo.staged_statuses(Path::new(""));
2536
2537        let mut changes = vec![];
2538        let mut edits = vec![];
2539
2540        for mut entry in self
2541            .snapshot
2542            .descendent_entries(false, false, &work_directory.0)
2543            .cloned()
2544        {
2545            let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2546                continue;
2547            };
2548            let repo_path = RepoPath(repo_path.to_path_buf());
2549            let git_file_status = combine_git_statuses(
2550                staged_statuses.get(&repo_path).copied(),
2551                repo.unstaged_status(&repo_path, entry.mtime),
2552            );
2553            if entry.git_status != git_file_status {
2554                entry.git_status = git_file_status;
2555                changes.push(entry.path.clone());
2556                edits.push(Edit::Insert(entry));
2557            }
2558        }
2559
2560        self.snapshot.entries_by_path.edit(edits, &());
2561        util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2562        staged_statuses
2563    }
2564}
2565
2566async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2567    let contents = fs.load(abs_path).await?;
2568    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2569    let mut builder = GitignoreBuilder::new(parent);
2570    for line in contents.lines() {
2571        builder.add_line(Some(abs_path.into()), line)?;
2572    }
2573    Ok(builder.build()?)
2574}
2575
2576impl WorktreeId {
2577    pub fn from_usize(handle_id: usize) -> Self {
2578        Self(handle_id)
2579    }
2580
2581    pub(crate) fn from_proto(id: u64) -> Self {
2582        Self(id as usize)
2583    }
2584
2585    pub fn to_proto(&self) -> u64 {
2586        self.0 as u64
2587    }
2588
2589    pub fn to_usize(&self) -> usize {
2590        self.0
2591    }
2592}
2593
2594impl fmt::Display for WorktreeId {
2595    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2596        self.0.fmt(f)
2597    }
2598}
2599
2600impl Deref for Worktree {
2601    type Target = Snapshot;
2602
2603    fn deref(&self) -> &Self::Target {
2604        match self {
2605            Worktree::Local(worktree) => &worktree.snapshot,
2606            Worktree::Remote(worktree) => &worktree.snapshot,
2607        }
2608    }
2609}
2610
2611impl Deref for LocalWorktree {
2612    type Target = LocalSnapshot;
2613
2614    fn deref(&self) -> &Self::Target {
2615        &self.snapshot
2616    }
2617}
2618
2619impl Deref for RemoteWorktree {
2620    type Target = Snapshot;
2621
2622    fn deref(&self) -> &Self::Target {
2623        &self.snapshot
2624    }
2625}
2626
2627impl fmt::Debug for LocalWorktree {
2628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2629        self.snapshot.fmt(f)
2630    }
2631}
2632
2633impl fmt::Debug for Snapshot {
2634    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2635        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2636        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2637
2638        impl<'a> fmt::Debug for EntriesByPath<'a> {
2639            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2640                f.debug_map()
2641                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2642                    .finish()
2643            }
2644        }
2645
2646        impl<'a> fmt::Debug for EntriesById<'a> {
2647            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2648                f.debug_list().entries(self.0.iter()).finish()
2649            }
2650        }
2651
2652        f.debug_struct("Snapshot")
2653            .field("id", &self.id)
2654            .field("root_name", &self.root_name)
2655            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2656            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2657            .finish()
2658    }
2659}
2660
2661#[derive(Clone, PartialEq)]
2662pub struct File {
2663    pub worktree: Model<Worktree>,
2664    pub path: Arc<Path>,
2665    pub mtime: SystemTime,
2666    pub(crate) entry_id: ProjectEntryId,
2667    pub(crate) is_local: bool,
2668    pub(crate) is_deleted: bool,
2669}
2670
2671impl language::File for File {
2672    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2673        if self.is_local {
2674            Some(self)
2675        } else {
2676            None
2677        }
2678    }
2679
2680    fn mtime(&self) -> SystemTime {
2681        self.mtime
2682    }
2683
2684    fn path(&self) -> &Arc<Path> {
2685        &self.path
2686    }
2687
2688    fn full_path(&self, cx: &AppContext) -> PathBuf {
2689        let mut full_path = PathBuf::new();
2690        let worktree = self.worktree.read(cx);
2691
2692        if worktree.is_visible() {
2693            full_path.push(worktree.root_name());
2694        } else {
2695            let path = worktree.abs_path();
2696
2697            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2698                full_path.push("~");
2699                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2700            } else {
2701                full_path.push(path)
2702            }
2703        }
2704
2705        if self.path.components().next().is_some() {
2706            full_path.push(&self.path);
2707        }
2708
2709        full_path
2710    }
2711
2712    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2713    /// of its worktree, then this method will return the name of the worktree itself.
2714    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2715        self.path
2716            .file_name()
2717            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2718    }
2719
2720    fn worktree_id(&self) -> usize {
2721        self.worktree.entity_id().as_u64() as usize
2722    }
2723
2724    fn is_deleted(&self) -> bool {
2725        self.is_deleted
2726    }
2727
2728    fn as_any(&self) -> &dyn Any {
2729        self
2730    }
2731
2732    fn to_proto(&self) -> rpc::proto::File {
2733        rpc::proto::File {
2734            worktree_id: self.worktree.entity_id().as_u64(),
2735            entry_id: self.entry_id.to_proto(),
2736            path: self.path.to_string_lossy().into(),
2737            mtime: Some(self.mtime.into()),
2738            is_deleted: self.is_deleted,
2739        }
2740    }
2741}
2742
2743impl language::LocalFile for File {
2744    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2745        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2746        if self.path.as_ref() == Path::new("") {
2747            worktree_path.to_path_buf()
2748        } else {
2749            worktree_path.join(&self.path)
2750        }
2751    }
2752
2753    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2754        let worktree = self.worktree.read(cx).as_local().unwrap();
2755        let abs_path = worktree.absolutize(&self.path);
2756        let fs = worktree.fs.clone();
2757        cx.background_executor()
2758            .spawn(async move { fs.load(&abs_path).await })
2759    }
2760
2761    fn buffer_reloaded(
2762        &self,
2763        buffer_id: u64,
2764        version: &clock::Global,
2765        fingerprint: RopeFingerprint,
2766        line_ending: LineEnding,
2767        mtime: SystemTime,
2768        cx: &mut AppContext,
2769    ) {
2770        let worktree = self.worktree.read(cx).as_local().unwrap();
2771        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2772            worktree
2773                .client
2774                .send(proto::BufferReloaded {
2775                    project_id,
2776                    buffer_id,
2777                    version: serialize_version(version),
2778                    mtime: Some(mtime.into()),
2779                    fingerprint: serialize_fingerprint(fingerprint),
2780                    line_ending: serialize_line_ending(line_ending) as i32,
2781                })
2782                .log_err();
2783        }
2784    }
2785}
2786
2787impl File {
2788    pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
2789        Arc::new(Self {
2790            worktree,
2791            path: entry.path.clone(),
2792            mtime: entry.mtime,
2793            entry_id: entry.id,
2794            is_local: true,
2795            is_deleted: false,
2796        })
2797    }
2798
2799    pub fn from_proto(
2800        proto: rpc::proto::File,
2801        worktree: Model<Worktree>,
2802        cx: &AppContext,
2803    ) -> Result<Self> {
2804        let worktree_id = worktree
2805            .read(cx)
2806            .as_remote()
2807            .ok_or_else(|| anyhow!("not remote"))?
2808            .id();
2809
2810        if worktree_id.to_proto() != proto.worktree_id {
2811            return Err(anyhow!("worktree id does not match file"));
2812        }
2813
2814        Ok(Self {
2815            worktree,
2816            path: Path::new(&proto.path).into(),
2817            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2818            entry_id: ProjectEntryId::from_proto(proto.entry_id),
2819            is_local: false,
2820            is_deleted: proto.is_deleted,
2821        })
2822    }
2823
2824    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2825        file.and_then(|f| f.as_any().downcast_ref())
2826    }
2827
2828    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2829        self.worktree.read(cx).id()
2830    }
2831
2832    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2833        if self.is_deleted {
2834            None
2835        } else {
2836            Some(self.entry_id)
2837        }
2838    }
2839}
2840
2841#[derive(Clone, Debug, PartialEq, Eq)]
2842pub struct Entry {
2843    pub id: ProjectEntryId,
2844    pub kind: EntryKind,
2845    pub path: Arc<Path>,
2846    pub inode: u64,
2847    pub mtime: SystemTime,
2848    pub is_symlink: bool,
2849
2850    /// Whether this entry is ignored by Git.
2851    ///
2852    /// We only scan ignored entries once the directory is expanded and
2853    /// exclude them from searches.
2854    pub is_ignored: bool,
2855
2856    /// Whether this entry's canonical path is outside of the worktree.
2857    /// This means the entry is only accessible from the worktree root via a
2858    /// symlink.
2859    ///
2860    /// We only scan entries outside of the worktree once the symlinked
2861    /// directory is expanded. External entries are treated like gitignored
2862    /// entries in that they are not included in searches.
2863    pub is_external: bool,
2864    pub git_status: Option<GitFileStatus>,
2865}
2866
2867#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2868pub enum EntryKind {
2869    UnloadedDir,
2870    PendingDir,
2871    Dir,
2872    File(CharBag),
2873}
2874
2875#[derive(Clone, Copy, Debug, PartialEq)]
2876pub enum PathChange {
2877    /// A filesystem entry was was created.
2878    Added,
2879    /// A filesystem entry was removed.
2880    Removed,
2881    /// A filesystem entry was updated.
2882    Updated,
2883    /// A filesystem entry was either updated or added. We don't know
2884    /// whether or not it already existed, because the path had not
2885    /// been loaded before the event.
2886    AddedOrUpdated,
2887    /// A filesystem entry was found during the initial scan of the worktree.
2888    Loaded,
2889}
2890
2891pub struct GitRepositoryChange {
2892    /// The previous state of the repository, if it already existed.
2893    pub old_repository: Option<RepositoryEntry>,
2894}
2895
2896pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2897pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2898
2899impl Entry {
2900    fn new(
2901        path: Arc<Path>,
2902        metadata: &fs::Metadata,
2903        next_entry_id: &AtomicUsize,
2904        root_char_bag: CharBag,
2905    ) -> Self {
2906        Self {
2907            id: ProjectEntryId::new(next_entry_id),
2908            kind: if metadata.is_dir {
2909                EntryKind::PendingDir
2910            } else {
2911                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2912            },
2913            path,
2914            inode: metadata.inode,
2915            mtime: metadata.mtime,
2916            is_symlink: metadata.is_symlink,
2917            is_ignored: false,
2918            is_external: false,
2919            git_status: None,
2920        }
2921    }
2922
2923    pub fn is_dir(&self) -> bool {
2924        self.kind.is_dir()
2925    }
2926
2927    pub fn is_file(&self) -> bool {
2928        self.kind.is_file()
2929    }
2930
2931    pub fn git_status(&self) -> Option<GitFileStatus> {
2932        self.git_status
2933    }
2934}
2935
2936impl EntryKind {
2937    pub fn is_dir(&self) -> bool {
2938        matches!(
2939            self,
2940            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
2941        )
2942    }
2943
2944    pub fn is_unloaded(&self) -> bool {
2945        matches!(self, EntryKind::UnloadedDir)
2946    }
2947
2948    pub fn is_file(&self) -> bool {
2949        matches!(self, EntryKind::File(_))
2950    }
2951}
2952
2953impl sum_tree::Item for Entry {
2954    type Summary = EntrySummary;
2955
2956    fn summary(&self) -> Self::Summary {
2957        let non_ignored_count = if self.is_ignored || self.is_external {
2958            0
2959        } else {
2960            1
2961        };
2962        let file_count;
2963        let non_ignored_file_count;
2964        if self.is_file() {
2965            file_count = 1;
2966            non_ignored_file_count = non_ignored_count;
2967        } else {
2968            file_count = 0;
2969            non_ignored_file_count = 0;
2970        }
2971
2972        let mut statuses = GitStatuses::default();
2973        match self.git_status {
2974            Some(status) => match status {
2975                GitFileStatus::Added => statuses.added = 1,
2976                GitFileStatus::Modified => statuses.modified = 1,
2977                GitFileStatus::Conflict => statuses.conflict = 1,
2978            },
2979            None => {}
2980        }
2981
2982        EntrySummary {
2983            max_path: self.path.clone(),
2984            count: 1,
2985            non_ignored_count,
2986            file_count,
2987            non_ignored_file_count,
2988            statuses,
2989        }
2990    }
2991}
2992
2993impl sum_tree::KeyedItem for Entry {
2994    type Key = PathKey;
2995
2996    fn key(&self) -> Self::Key {
2997        PathKey(self.path.clone())
2998    }
2999}
3000
3001#[derive(Clone, Debug)]
3002pub struct EntrySummary {
3003    max_path: Arc<Path>,
3004    count: usize,
3005    non_ignored_count: usize,
3006    file_count: usize,
3007    non_ignored_file_count: usize,
3008    statuses: GitStatuses,
3009}
3010
3011impl Default for EntrySummary {
3012    fn default() -> Self {
3013        Self {
3014            max_path: Arc::from(Path::new("")),
3015            count: 0,
3016            non_ignored_count: 0,
3017            file_count: 0,
3018            non_ignored_file_count: 0,
3019            statuses: Default::default(),
3020        }
3021    }
3022}
3023
3024impl sum_tree::Summary for EntrySummary {
3025    type Context = ();
3026
3027    fn add_summary(&mut self, rhs: &Self, _: &()) {
3028        self.max_path = rhs.max_path.clone();
3029        self.count += rhs.count;
3030        self.non_ignored_count += rhs.non_ignored_count;
3031        self.file_count += rhs.file_count;
3032        self.non_ignored_file_count += rhs.non_ignored_file_count;
3033        self.statuses += rhs.statuses;
3034    }
3035}
3036
3037#[derive(Clone, Debug)]
3038struct PathEntry {
3039    id: ProjectEntryId,
3040    path: Arc<Path>,
3041    is_ignored: bool,
3042    scan_id: usize,
3043}
3044
3045impl sum_tree::Item for PathEntry {
3046    type Summary = PathEntrySummary;
3047
3048    fn summary(&self) -> Self::Summary {
3049        PathEntrySummary { max_id: self.id }
3050    }
3051}
3052
3053impl sum_tree::KeyedItem for PathEntry {
3054    type Key = ProjectEntryId;
3055
3056    fn key(&self) -> Self::Key {
3057        self.id
3058    }
3059}
3060
3061#[derive(Clone, Debug, Default)]
3062struct PathEntrySummary {
3063    max_id: ProjectEntryId,
3064}
3065
3066impl sum_tree::Summary for PathEntrySummary {
3067    type Context = ();
3068
3069    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3070        self.max_id = summary.max_id;
3071    }
3072}
3073
3074impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3075    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3076        *self = summary.max_id;
3077    }
3078}
3079
3080#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3081pub struct PathKey(Arc<Path>);
3082
3083impl Default for PathKey {
3084    fn default() -> Self {
3085        Self(Path::new("").into())
3086    }
3087}
3088
3089impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3090    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3091        self.0 = summary.max_path.clone();
3092    }
3093}
3094
3095struct BackgroundScanner {
3096    state: Mutex<BackgroundScannerState>,
3097    fs: Arc<dyn Fs>,
3098    status_updates_tx: UnboundedSender<ScanState>,
3099    executor: BackgroundExecutor,
3100    scan_requests_rx: channel::Receiver<ScanRequest>,
3101    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3102    next_entry_id: Arc<AtomicUsize>,
3103    phase: BackgroundScannerPhase,
3104}
3105
3106#[derive(PartialEq)]
3107enum BackgroundScannerPhase {
3108    InitialScan,
3109    EventsReceivedDuringInitialScan,
3110    Events,
3111}
3112
3113impl BackgroundScanner {
3114    fn new(
3115        snapshot: LocalSnapshot,
3116        next_entry_id: Arc<AtomicUsize>,
3117        fs: Arc<dyn Fs>,
3118        status_updates_tx: UnboundedSender<ScanState>,
3119        executor: BackgroundExecutor,
3120        scan_requests_rx: channel::Receiver<ScanRequest>,
3121        path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3122    ) -> Self {
3123        Self {
3124            fs,
3125            status_updates_tx,
3126            executor,
3127            scan_requests_rx,
3128            path_prefixes_to_scan_rx,
3129            next_entry_id,
3130            state: Mutex::new(BackgroundScannerState {
3131                prev_snapshot: snapshot.snapshot.clone(),
3132                snapshot,
3133                scanned_dirs: Default::default(),
3134                path_prefixes_to_scan: Default::default(),
3135                paths_to_scan: Default::default(),
3136                removed_entry_ids: Default::default(),
3137                changed_paths: Default::default(),
3138            }),
3139            phase: BackgroundScannerPhase::InitialScan,
3140        }
3141    }
3142
3143    async fn run(
3144        &mut self,
3145        mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
3146    ) {
3147        use futures::FutureExt as _;
3148
3149        // Populate ignores above the root.
3150        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3151        for ancestor in root_abs_path.ancestors().skip(1) {
3152            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3153            {
3154                self.state
3155                    .lock()
3156                    .snapshot
3157                    .ignores_by_parent_abs_path
3158                    .insert(ancestor.into(), (ignore.into(), false));
3159            }
3160        }
3161
3162        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3163        {
3164            let mut state = self.state.lock();
3165            state.snapshot.scan_id += 1;
3166            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3167                let ignore_stack = state
3168                    .snapshot
3169                    .ignore_stack_for_abs_path(&root_abs_path, true);
3170                if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3171                    root_entry.is_ignored = true;
3172                    state.insert_entry(root_entry.clone(), self.fs.as_ref());
3173                }
3174                state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3175            }
3176        };
3177
3178        // Perform an initial scan of the directory.
3179        drop(scan_job_tx);
3180        self.scan_dirs(true, scan_job_rx).await;
3181        {
3182            let mut state = self.state.lock();
3183            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3184        }
3185
3186        self.send_status_update(false, None);
3187
3188        // Process any any FS events that occurred while performing the initial scan.
3189        // For these events, update events cannot be as precise, because we didn't
3190        // have the previous state loaded yet.
3191        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3192        if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3193            let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3194            while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3195                paths.extend(more_events.into_iter().map(|e| e.path));
3196            }
3197            self.process_events(paths).await;
3198        }
3199
3200        // Continue processing events until the worktree is dropped.
3201        self.phase = BackgroundScannerPhase::Events;
3202        loop {
3203            select_biased! {
3204                // Process any path refresh requests from the worktree. Prioritize
3205                // these before handling changes reported by the filesystem.
3206                request = self.scan_requests_rx.recv().fuse() => {
3207                    let Ok(request) = request else { break };
3208                    if !self.process_scan_request(request, false).await {
3209                        return;
3210                    }
3211                }
3212
3213                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3214                    let Ok(path_prefix) = path_prefix else { break };
3215                    log::trace!("adding path prefix {:?}", path_prefix);
3216
3217                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3218                    if did_scan {
3219                        let abs_path =
3220                        {
3221                            let mut state = self.state.lock();
3222                            state.path_prefixes_to_scan.insert(path_prefix.clone());
3223                            state.snapshot.abs_path.join(&path_prefix)
3224                        };
3225
3226                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3227                            self.process_events(vec![abs_path]).await;
3228                        }
3229                    }
3230                }
3231
3232                events = fs_events_rx.next().fuse() => {
3233                    let Some(events) = events else { break };
3234                    let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3235                    while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3236                        paths.extend(more_events.into_iter().map(|e| e.path));
3237                    }
3238                    self.process_events(paths.clone()).await;
3239                }
3240            }
3241        }
3242    }
3243
3244    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3245        log::debug!("rescanning paths {:?}", request.relative_paths);
3246
3247        request.relative_paths.sort_unstable();
3248        self.forcibly_load_paths(&request.relative_paths).await;
3249
3250        let root_path = self.state.lock().snapshot.abs_path.clone();
3251        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3252            Ok(path) => path,
3253            Err(err) => {
3254                log::error!("failed to canonicalize root path: {}", err);
3255                return false;
3256            }
3257        };
3258        let abs_paths = request
3259            .relative_paths
3260            .iter()
3261            .map(|path| {
3262                if path.file_name().is_some() {
3263                    root_canonical_path.join(path)
3264                } else {
3265                    root_canonical_path.clone()
3266                }
3267            })
3268            .collect::<Vec<_>>();
3269
3270        self.reload_entries_for_paths(
3271            root_path,
3272            root_canonical_path,
3273            &request.relative_paths,
3274            abs_paths,
3275            None,
3276        )
3277        .await;
3278        self.send_status_update(scanning, Some(request.done))
3279    }
3280
3281    async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3282        let root_path = self.state.lock().snapshot.abs_path.clone();
3283        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3284            Ok(path) => path,
3285            Err(err) => {
3286                log::error!("failed to canonicalize root path: {}", err);
3287                return;
3288            }
3289        };
3290
3291        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3292        let mut dot_git_paths_to_reload = HashSet::default();
3293        abs_paths.sort_unstable();
3294        abs_paths.dedup_by(|a, b| a.starts_with(&b));
3295        abs_paths.retain(|abs_path| {
3296            let snapshot = &self.state.lock().snapshot;
3297            {
3298                let mut is_git_related = false;
3299                if let Some(dot_git_dir) = abs_path
3300                    .ancestors()
3301                    .find(|ancestor| ancestor.file_name() == Some(&*DOT_GIT))
3302                {
3303                    let dot_git_path = dot_git_dir
3304                        .strip_prefix(&root_canonical_path)
3305                        .ok()
3306                        .map(|path| path.to_path_buf())
3307                        .unwrap_or_else(|| dot_git_dir.to_path_buf());
3308                    dot_git_paths_to_reload.insert(dot_git_path.to_path_buf());
3309                    is_git_related = true;
3310                }
3311
3312                let relative_path: Arc<Path> =
3313                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3314                        path.into()
3315                    } else {
3316                        log::error!(
3317                        "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3318                    );
3319                        return false;
3320                    };
3321
3322                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3323                    snapshot
3324                        .entry_for_path(parent)
3325                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
3326                });
3327                if !parent_dir_is_loaded {
3328                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3329                    return false;
3330                }
3331
3332                // FS events may come for files which parent directory is excluded, need to check ignore those.
3333                let mut path_to_test = abs_path.clone();
3334                let mut excluded_file_event = snapshot.is_path_excluded(abs_path)
3335                    || snapshot.is_path_excluded(&relative_path);
3336                while !excluded_file_event && path_to_test.pop() {
3337                    if snapshot.is_path_excluded(&path_to_test) {
3338                        excluded_file_event = true;
3339                    }
3340                }
3341                if excluded_file_event {
3342                    if !is_git_related {
3343                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
3344                    }
3345                    return false;
3346                }
3347
3348                relative_paths.push(relative_path);
3349                true
3350            }
3351        });
3352
3353        if dot_git_paths_to_reload.is_empty() && relative_paths.is_empty() {
3354            return;
3355        }
3356
3357        if !relative_paths.is_empty() {
3358            log::debug!("received fs events {:?}", relative_paths);
3359
3360            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3361            self.reload_entries_for_paths(
3362                root_path,
3363                root_canonical_path,
3364                &relative_paths,
3365                abs_paths,
3366                Some(scan_job_tx.clone()),
3367            )
3368            .await;
3369            drop(scan_job_tx);
3370            self.scan_dirs(false, scan_job_rx).await;
3371
3372            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3373            self.update_ignore_statuses(scan_job_tx).await;
3374            self.scan_dirs(false, scan_job_rx).await;
3375        }
3376
3377        {
3378            let mut state = self.state.lock();
3379            if !dot_git_paths_to_reload.is_empty() {
3380                if relative_paths.is_empty() {
3381                    state.snapshot.scan_id += 1;
3382                }
3383                log::debug!("reloading repositories: {dot_git_paths_to_reload:?}");
3384                state.reload_repositories(&dot_git_paths_to_reload, self.fs.as_ref());
3385            }
3386            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3387            for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3388                state.scanned_dirs.remove(&entry_id);
3389            }
3390        }
3391
3392        self.send_status_update(false, None);
3393    }
3394
3395    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3396        let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3397        {
3398            let mut state = self.state.lock();
3399            let root_path = state.snapshot.abs_path.clone();
3400            for path in paths {
3401                for ancestor in path.ancestors() {
3402                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3403                        if entry.kind == EntryKind::UnloadedDir {
3404                            let abs_path = root_path.join(ancestor);
3405                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3406                            state.paths_to_scan.insert(path.clone());
3407                            break;
3408                        }
3409                    }
3410                }
3411            }
3412            drop(scan_job_tx);
3413        }
3414        while let Some(job) = scan_job_rx.next().await {
3415            self.scan_dir(&job).await.log_err();
3416        }
3417
3418        mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3419    }
3420
3421    async fn scan_dirs(
3422        &self,
3423        enable_progress_updates: bool,
3424        scan_jobs_rx: channel::Receiver<ScanJob>,
3425    ) {
3426        use futures::FutureExt as _;
3427
3428        if self
3429            .status_updates_tx
3430            .unbounded_send(ScanState::Started)
3431            .is_err()
3432        {
3433            return;
3434        }
3435
3436        let progress_update_count = AtomicUsize::new(0);
3437        self.executor
3438            .scoped(|scope| {
3439                for _ in 0..self.executor.num_cpus() {
3440                    scope.spawn(async {
3441                        let mut last_progress_update_count = 0;
3442                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3443                        futures::pin_mut!(progress_update_timer);
3444
3445                        loop {
3446                            select_biased! {
3447                                // Process any path refresh requests before moving on to process
3448                                // the scan queue, so that user operations are prioritized.
3449                                request = self.scan_requests_rx.recv().fuse() => {
3450                                    let Ok(request) = request else { break };
3451                                    if !self.process_scan_request(request, true).await {
3452                                        return;
3453                                    }
3454                                }
3455
3456                                // Send periodic progress updates to the worktree. Use an atomic counter
3457                                // to ensure that only one of the workers sends a progress update after
3458                                // the update interval elapses.
3459                                _ = progress_update_timer => {
3460                                    match progress_update_count.compare_exchange(
3461                                        last_progress_update_count,
3462                                        last_progress_update_count + 1,
3463                                        SeqCst,
3464                                        SeqCst
3465                                    ) {
3466                                        Ok(_) => {
3467                                            last_progress_update_count += 1;
3468                                            self.send_status_update(true, None);
3469                                        }
3470                                        Err(count) => {
3471                                            last_progress_update_count = count;
3472                                        }
3473                                    }
3474                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3475                                }
3476
3477                                // Recursively load directories from the file system.
3478                                job = scan_jobs_rx.recv().fuse() => {
3479                                    let Ok(job) = job else { break };
3480                                    if let Err(err) = self.scan_dir(&job).await {
3481                                        if job.path.as_ref() != Path::new("") {
3482                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3483                                        }
3484                                    }
3485                                }
3486                            }
3487                        }
3488                    })
3489                }
3490            })
3491            .await;
3492    }
3493
3494    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3495        let mut state = self.state.lock();
3496        if state.changed_paths.is_empty() && scanning {
3497            return true;
3498        }
3499
3500        let new_snapshot = state.snapshot.clone();
3501        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3502        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3503        state.changed_paths.clear();
3504
3505        self.status_updates_tx
3506            .unbounded_send(ScanState::Updated {
3507                snapshot: new_snapshot,
3508                changes,
3509                scanning,
3510                barrier,
3511            })
3512            .is_ok()
3513    }
3514
3515    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3516        let root_abs_path;
3517        let mut ignore_stack;
3518        let mut new_ignore;
3519        let root_char_bag;
3520        let next_entry_id;
3521        {
3522            let state = self.state.lock();
3523            let snapshot = &state.snapshot;
3524            root_abs_path = snapshot.abs_path().clone();
3525            if snapshot.is_path_excluded(&job.abs_path) {
3526                log::error!("skipping excluded directory {:?}", job.path);
3527                return Ok(());
3528            }
3529            log::debug!("scanning directory {:?}", job.path);
3530            ignore_stack = job.ignore_stack.clone();
3531            new_ignore = None;
3532            root_char_bag = snapshot.root_char_bag;
3533            next_entry_id = self.next_entry_id.clone();
3534            drop(state);
3535        }
3536
3537        let mut dotgit_path = None;
3538        let mut root_canonical_path = None;
3539        let mut new_entries: Vec<Entry> = Vec::new();
3540        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3541        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3542        while let Some(child_abs_path) = child_paths.next().await {
3543            let child_abs_path: Arc<Path> = match child_abs_path {
3544                Ok(child_abs_path) => child_abs_path.into(),
3545                Err(error) => {
3546                    log::error!("error processing entry {:?}", error);
3547                    continue;
3548                }
3549            };
3550            let child_name = child_abs_path.file_name().unwrap();
3551            let child_path: Arc<Path> = job.path.join(child_name).into();
3552            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3553            if child_name == *GITIGNORE {
3554                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3555                    Ok(ignore) => {
3556                        let ignore = Arc::new(ignore);
3557                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3558                        new_ignore = Some(ignore);
3559                    }
3560                    Err(error) => {
3561                        log::error!(
3562                            "error loading .gitignore file {:?} - {:?}",
3563                            child_name,
3564                            error
3565                        );
3566                    }
3567                }
3568
3569                // Update ignore status of any child entries we've already processed to reflect the
3570                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3571                // there should rarely be too numerous. Update the ignore stack associated with any
3572                // new jobs as well.
3573                let mut new_jobs = new_jobs.iter_mut();
3574                for entry in &mut new_entries {
3575                    let entry_abs_path = root_abs_path.join(&entry.path);
3576                    entry.is_ignored =
3577                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3578
3579                    if entry.is_dir() {
3580                        if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3581                            job.ignore_stack = if entry.is_ignored {
3582                                IgnoreStack::all()
3583                            } else {
3584                                ignore_stack.clone()
3585                            };
3586                        }
3587                    }
3588                }
3589            }
3590            // If we find a .git, we'll need to load the repository.
3591            else if child_name == *DOT_GIT {
3592                dotgit_path = Some(child_path.clone());
3593            }
3594
3595            {
3596                let mut state = self.state.lock();
3597                if state.snapshot.is_path_excluded(&child_abs_path) {
3598                    let relative_path = job.path.join(child_name);
3599                    log::debug!("skipping excluded child entry {relative_path:?}");
3600                    state.remove_path(&relative_path);
3601                    continue;
3602                }
3603                drop(state);
3604            }
3605
3606            let child_metadata = match self.fs.metadata(&child_abs_path).await {
3607                Ok(Some(metadata)) => metadata,
3608                Ok(None) => continue,
3609                Err(err) => {
3610                    log::error!("error processing {child_abs_path:?}: {err:?}");
3611                    continue;
3612                }
3613            };
3614
3615            let mut child_entry = Entry::new(
3616                child_path.clone(),
3617                &child_metadata,
3618                &next_entry_id,
3619                root_char_bag,
3620            );
3621
3622            if job.is_external {
3623                child_entry.is_external = true;
3624            } else if child_metadata.is_symlink {
3625                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3626                    Ok(path) => path,
3627                    Err(err) => {
3628                        log::error!(
3629                            "error reading target of symlink {:?}: {:?}",
3630                            child_abs_path,
3631                            err
3632                        );
3633                        continue;
3634                    }
3635                };
3636
3637                // lazily canonicalize the root path in order to determine if
3638                // symlinks point outside of the worktree.
3639                let root_canonical_path = match &root_canonical_path {
3640                    Some(path) => path,
3641                    None => match self.fs.canonicalize(&root_abs_path).await {
3642                        Ok(path) => root_canonical_path.insert(path),
3643                        Err(err) => {
3644                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3645                            continue;
3646                        }
3647                    },
3648                };
3649
3650                if !canonical_path.starts_with(root_canonical_path) {
3651                    child_entry.is_external = true;
3652                }
3653            }
3654
3655            if child_entry.is_dir() {
3656                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3657
3658                // Avoid recursing until crash in the case of a recursive symlink
3659                if !job.ancestor_inodes.contains(&child_entry.inode) {
3660                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3661                    ancestor_inodes.insert(child_entry.inode);
3662
3663                    new_jobs.push(Some(ScanJob {
3664                        abs_path: child_abs_path,
3665                        path: child_path,
3666                        is_external: child_entry.is_external,
3667                        ignore_stack: if child_entry.is_ignored {
3668                            IgnoreStack::all()
3669                        } else {
3670                            ignore_stack.clone()
3671                        },
3672                        ancestor_inodes,
3673                        scan_queue: job.scan_queue.clone(),
3674                        containing_repository: job.containing_repository.clone(),
3675                    }));
3676                } else {
3677                    new_jobs.push(None);
3678                }
3679            } else {
3680                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3681                if !child_entry.is_ignored {
3682                    if let Some((repository_dir, repository, staged_statuses)) =
3683                        &job.containing_repository
3684                    {
3685                        if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3686                            let repo_path = RepoPath(repo_path.into());
3687                            child_entry.git_status = combine_git_statuses(
3688                                staged_statuses.get(&repo_path).copied(),
3689                                repository
3690                                    .lock()
3691                                    .unstaged_status(&repo_path, child_entry.mtime),
3692                            );
3693                        }
3694                    }
3695                }
3696            }
3697
3698            new_entries.push(child_entry);
3699        }
3700
3701        let mut state = self.state.lock();
3702
3703        // Identify any subdirectories that should not be scanned.
3704        let mut job_ix = 0;
3705        for entry in &mut new_entries {
3706            state.reuse_entry_id(entry);
3707            if entry.is_dir() {
3708                if state.should_scan_directory(&entry) {
3709                    job_ix += 1;
3710                } else {
3711                    log::debug!("defer scanning directory {:?}", entry.path);
3712                    entry.kind = EntryKind::UnloadedDir;
3713                    new_jobs.remove(job_ix);
3714                }
3715            }
3716        }
3717
3718        state.populate_dir(&job.path, new_entries, new_ignore);
3719
3720        let repository =
3721            dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3722
3723        for new_job in new_jobs {
3724            if let Some(mut new_job) = new_job {
3725                if let Some(containing_repository) = &repository {
3726                    new_job.containing_repository = Some(containing_repository.clone());
3727                }
3728
3729                job.scan_queue
3730                    .try_send(new_job)
3731                    .expect("channel is unbounded");
3732            }
3733        }
3734
3735        Ok(())
3736    }
3737
3738    async fn reload_entries_for_paths(
3739        &self,
3740        root_abs_path: Arc<Path>,
3741        root_canonical_path: PathBuf,
3742        relative_paths: &[Arc<Path>],
3743        abs_paths: Vec<PathBuf>,
3744        scan_queue_tx: Option<Sender<ScanJob>>,
3745    ) {
3746        let metadata = futures::future::join_all(
3747            abs_paths
3748                .iter()
3749                .map(|abs_path| async move {
3750                    let metadata = self.fs.metadata(&abs_path).await?;
3751                    if let Some(metadata) = metadata {
3752                        let canonical_path = self.fs.canonicalize(&abs_path).await?;
3753                        anyhow::Ok(Some((metadata, canonical_path)))
3754                    } else {
3755                        Ok(None)
3756                    }
3757                })
3758                .collect::<Vec<_>>(),
3759        )
3760        .await;
3761
3762        let mut state = self.state.lock();
3763        let snapshot = &mut state.snapshot;
3764        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3765        let doing_recursive_update = scan_queue_tx.is_some();
3766        snapshot.scan_id += 1;
3767        if is_idle && !doing_recursive_update {
3768            snapshot.completed_scan_id = snapshot.scan_id;
3769        }
3770
3771        // Remove any entries for paths that no longer exist or are being recursively
3772        // refreshed. Do this before adding any new entries, so that renames can be
3773        // detected regardless of the order of the paths.
3774        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3775            if matches!(metadata, Ok(None)) || doing_recursive_update {
3776                log::trace!("remove path {:?}", path);
3777                state.remove_path(path);
3778            }
3779        }
3780
3781        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3782            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3783            match metadata {
3784                Ok(Some((metadata, canonical_path))) => {
3785                    let ignore_stack = state
3786                        .snapshot
3787                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3788
3789                    let mut fs_entry = Entry::new(
3790                        path.clone(),
3791                        metadata,
3792                        self.next_entry_id.as_ref(),
3793                        state.snapshot.root_char_bag,
3794                    );
3795                    let is_dir = fs_entry.is_dir();
3796                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3797                    fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3798
3799                    if !is_dir && !fs_entry.is_ignored {
3800                        if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(&path) {
3801                            if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
3802                                let repo_path = RepoPath(repo_path.into());
3803                                let repo = repo.repo_ptr.lock();
3804                                fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
3805                            }
3806                        }
3807                    }
3808
3809                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3810                        if state.should_scan_directory(&fs_entry) {
3811                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3812                        } else {
3813                            fs_entry.kind = EntryKind::UnloadedDir;
3814                        }
3815                    }
3816
3817                    state.insert_entry(fs_entry, self.fs.as_ref());
3818                }
3819                Ok(None) => {
3820                    self.remove_repo_path(&path, &mut state.snapshot);
3821                }
3822                Err(err) => {
3823                    // TODO - create a special 'error' entry in the entries tree to mark this
3824                    log::error!("error reading file {abs_path:?} on event: {err:#}");
3825                }
3826            }
3827        }
3828
3829        util::extend_sorted(
3830            &mut state.changed_paths,
3831            relative_paths.iter().cloned(),
3832            usize::MAX,
3833            Ord::cmp,
3834        );
3835    }
3836
3837    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3838        if !path
3839            .components()
3840            .any(|component| component.as_os_str() == *DOT_GIT)
3841        {
3842            if let Some(repository) = snapshot.repository_for_work_directory(path) {
3843                let entry = repository.work_directory.0;
3844                snapshot.git_repositories.remove(&entry);
3845                snapshot
3846                    .snapshot
3847                    .repository_entries
3848                    .remove(&RepositoryWorkDirectory(path.into()));
3849                return Some(());
3850            }
3851        }
3852
3853        // TODO statuses
3854        // Track when a .git is removed and iterate over the file system there
3855
3856        Some(())
3857    }
3858
3859    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3860        use futures::FutureExt as _;
3861
3862        let mut snapshot = self.state.lock().snapshot.clone();
3863        let mut ignores_to_update = Vec::new();
3864        let mut ignores_to_delete = Vec::new();
3865        let abs_path = snapshot.abs_path.clone();
3866        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3867            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3868                if *needs_update {
3869                    *needs_update = false;
3870                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3871                        ignores_to_update.push(parent_abs_path.clone());
3872                    }
3873                }
3874
3875                let ignore_path = parent_path.join(&*GITIGNORE);
3876                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3877                    ignores_to_delete.push(parent_abs_path.clone());
3878                }
3879            }
3880        }
3881
3882        for parent_abs_path in ignores_to_delete {
3883            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3884            self.state
3885                .lock()
3886                .snapshot
3887                .ignores_by_parent_abs_path
3888                .remove(&parent_abs_path);
3889        }
3890
3891        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3892        ignores_to_update.sort_unstable();
3893        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3894        while let Some(parent_abs_path) = ignores_to_update.next() {
3895            while ignores_to_update
3896                .peek()
3897                .map_or(false, |p| p.starts_with(&parent_abs_path))
3898            {
3899                ignores_to_update.next().unwrap();
3900            }
3901
3902            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3903            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3904                abs_path: parent_abs_path,
3905                ignore_stack,
3906                ignore_queue: ignore_queue_tx.clone(),
3907                scan_queue: scan_job_tx.clone(),
3908            }))
3909            .unwrap();
3910        }
3911        drop(ignore_queue_tx);
3912
3913        self.executor
3914            .scoped(|scope| {
3915                for _ in 0..self.executor.num_cpus() {
3916                    scope.spawn(async {
3917                        loop {
3918                            select_biased! {
3919                                // Process any path refresh requests before moving on to process
3920                                // the queue of ignore statuses.
3921                                request = self.scan_requests_rx.recv().fuse() => {
3922                                    let Ok(request) = request else { break };
3923                                    if !self.process_scan_request(request, true).await {
3924                                        return;
3925                                    }
3926                                }
3927
3928                                // Recursively process directories whose ignores have changed.
3929                                job = ignore_queue_rx.recv().fuse() => {
3930                                    let Ok(job) = job else { break };
3931                                    self.update_ignore_status(job, &snapshot).await;
3932                                }
3933                            }
3934                        }
3935                    });
3936                }
3937            })
3938            .await;
3939    }
3940
3941    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3942        log::trace!("update ignore status {:?}", job.abs_path);
3943
3944        let mut ignore_stack = job.ignore_stack;
3945        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3946            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3947        }
3948
3949        let mut entries_by_id_edits = Vec::new();
3950        let mut entries_by_path_edits = Vec::new();
3951        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3952        for mut entry in snapshot.child_entries(path).cloned() {
3953            let was_ignored = entry.is_ignored;
3954            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
3955            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3956            if entry.is_dir() {
3957                let child_ignore_stack = if entry.is_ignored {
3958                    IgnoreStack::all()
3959                } else {
3960                    ignore_stack.clone()
3961                };
3962
3963                // Scan any directories that were previously ignored and weren't previously scanned.
3964                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
3965                    let state = self.state.lock();
3966                    if state.should_scan_directory(&entry) {
3967                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
3968                    }
3969                }
3970
3971                job.ignore_queue
3972                    .send(UpdateIgnoreStatusJob {
3973                        abs_path: abs_path.clone(),
3974                        ignore_stack: child_ignore_stack,
3975                        ignore_queue: job.ignore_queue.clone(),
3976                        scan_queue: job.scan_queue.clone(),
3977                    })
3978                    .await
3979                    .unwrap();
3980            }
3981
3982            if entry.is_ignored != was_ignored {
3983                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3984                path_entry.scan_id = snapshot.scan_id;
3985                path_entry.is_ignored = entry.is_ignored;
3986                entries_by_id_edits.push(Edit::Insert(path_entry));
3987                entries_by_path_edits.push(Edit::Insert(entry));
3988            }
3989        }
3990
3991        let state = &mut self.state.lock();
3992        for edit in &entries_by_path_edits {
3993            if let Edit::Insert(entry) = edit {
3994                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
3995                    state.changed_paths.insert(ix, entry.path.clone());
3996                }
3997            }
3998        }
3999
4000        state
4001            .snapshot
4002            .entries_by_path
4003            .edit(entries_by_path_edits, &());
4004        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4005    }
4006
4007    fn build_change_set(
4008        &self,
4009        old_snapshot: &Snapshot,
4010        new_snapshot: &Snapshot,
4011        event_paths: &[Arc<Path>],
4012    ) -> UpdatedEntriesSet {
4013        use BackgroundScannerPhase::*;
4014        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4015
4016        // Identify which paths have changed. Use the known set of changed
4017        // parent paths to optimize the search.
4018        let mut changes = Vec::new();
4019        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4020        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4021        let mut last_newly_loaded_dir_path = None;
4022        old_paths.next(&());
4023        new_paths.next(&());
4024        for path in event_paths {
4025            let path = PathKey(path.clone());
4026            if old_paths.item().map_or(false, |e| e.path < path.0) {
4027                old_paths.seek_forward(&path, Bias::Left, &());
4028            }
4029            if new_paths.item().map_or(false, |e| e.path < path.0) {
4030                new_paths.seek_forward(&path, Bias::Left, &());
4031            }
4032            loop {
4033                match (old_paths.item(), new_paths.item()) {
4034                    (Some(old_entry), Some(new_entry)) => {
4035                        if old_entry.path > path.0
4036                            && new_entry.path > path.0
4037                            && !old_entry.path.starts_with(&path.0)
4038                            && !new_entry.path.starts_with(&path.0)
4039                        {
4040                            break;
4041                        }
4042
4043                        match Ord::cmp(&old_entry.path, &new_entry.path) {
4044                            Ordering::Less => {
4045                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4046                                old_paths.next(&());
4047                            }
4048                            Ordering::Equal => {
4049                                if self.phase == EventsReceivedDuringInitialScan {
4050                                    if old_entry.id != new_entry.id {
4051                                        changes.push((
4052                                            old_entry.path.clone(),
4053                                            old_entry.id,
4054                                            Removed,
4055                                        ));
4056                                    }
4057                                    // If the worktree was not fully initialized when this event was generated,
4058                                    // we can't know whether this entry was added during the scan or whether
4059                                    // it was merely updated.
4060                                    changes.push((
4061                                        new_entry.path.clone(),
4062                                        new_entry.id,
4063                                        AddedOrUpdated,
4064                                    ));
4065                                } else if old_entry.id != new_entry.id {
4066                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4067                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
4068                                } else if old_entry != new_entry {
4069                                    if old_entry.kind.is_unloaded() {
4070                                        last_newly_loaded_dir_path = Some(&new_entry.path);
4071                                        changes.push((
4072                                            new_entry.path.clone(),
4073                                            new_entry.id,
4074                                            Loaded,
4075                                        ));
4076                                    } else {
4077                                        changes.push((
4078                                            new_entry.path.clone(),
4079                                            new_entry.id,
4080                                            Updated,
4081                                        ));
4082                                    }
4083                                }
4084                                old_paths.next(&());
4085                                new_paths.next(&());
4086                            }
4087                            Ordering::Greater => {
4088                                let is_newly_loaded = self.phase == InitialScan
4089                                    || last_newly_loaded_dir_path
4090                                        .as_ref()
4091                                        .map_or(false, |dir| new_entry.path.starts_with(&dir));
4092                                changes.push((
4093                                    new_entry.path.clone(),
4094                                    new_entry.id,
4095                                    if is_newly_loaded { Loaded } else { Added },
4096                                ));
4097                                new_paths.next(&());
4098                            }
4099                        }
4100                    }
4101                    (Some(old_entry), None) => {
4102                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
4103                        old_paths.next(&());
4104                    }
4105                    (None, Some(new_entry)) => {
4106                        let is_newly_loaded = self.phase == InitialScan
4107                            || last_newly_loaded_dir_path
4108                                .as_ref()
4109                                .map_or(false, |dir| new_entry.path.starts_with(&dir));
4110                        changes.push((
4111                            new_entry.path.clone(),
4112                            new_entry.id,
4113                            if is_newly_loaded { Loaded } else { Added },
4114                        ));
4115                        new_paths.next(&());
4116                    }
4117                    (None, None) => break,
4118                }
4119            }
4120        }
4121
4122        changes.into()
4123    }
4124
4125    async fn progress_timer(&self, running: bool) {
4126        if !running {
4127            return futures::future::pending().await;
4128        }
4129
4130        #[cfg(any(test, feature = "test-support"))]
4131        if self.fs.is_fake() {
4132            return self.executor.simulate_random_delay().await;
4133        }
4134
4135        smol::Timer::after(Duration::from_millis(100)).await;
4136    }
4137}
4138
4139fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4140    let mut result = root_char_bag;
4141    result.extend(
4142        path.to_string_lossy()
4143            .chars()
4144            .map(|c| c.to_ascii_lowercase()),
4145    );
4146    result
4147}
4148
4149struct ScanJob {
4150    abs_path: Arc<Path>,
4151    path: Arc<Path>,
4152    ignore_stack: Arc<IgnoreStack>,
4153    scan_queue: Sender<ScanJob>,
4154    ancestor_inodes: TreeSet<u64>,
4155    is_external: bool,
4156    containing_repository: Option<(
4157        RepositoryWorkDirectory,
4158        Arc<Mutex<dyn GitRepository>>,
4159        TreeMap<RepoPath, GitFileStatus>,
4160    )>,
4161}
4162
4163struct UpdateIgnoreStatusJob {
4164    abs_path: Arc<Path>,
4165    ignore_stack: Arc<IgnoreStack>,
4166    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4167    scan_queue: Sender<ScanJob>,
4168}
4169
4170pub trait WorktreeModelHandle {
4171    #[cfg(any(test, feature = "test-support"))]
4172    fn flush_fs_events<'a>(
4173        &self,
4174        cx: &'a mut gpui::TestAppContext,
4175    ) -> futures::future::LocalBoxFuture<'a, ()>;
4176}
4177
4178impl WorktreeModelHandle for Model<Worktree> {
4179    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4180    // occurred before the worktree was constructed. These events can cause the worktree to perform
4181    // extra directory scans, and emit extra scan-state notifications.
4182    //
4183    // This function mutates the worktree's directory and waits for those mutations to be picked up,
4184    // to ensure that all redundant FS events have already been processed.
4185    #[cfg(any(test, feature = "test-support"))]
4186    fn flush_fs_events<'a>(
4187        &self,
4188        cx: &'a mut gpui::TestAppContext,
4189    ) -> futures::future::LocalBoxFuture<'a, ()> {
4190        let file_name = "fs-event-sentinel";
4191
4192        let tree = self.clone();
4193        let (fs, root_path) = self.update(cx, |tree, _| {
4194            let tree = tree.as_local().unwrap();
4195            (tree.fs.clone(), tree.abs_path().clone())
4196        });
4197
4198        async move {
4199            fs.create_file(&root_path.join(file_name), Default::default())
4200                .await
4201                .unwrap();
4202
4203            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4204                .await;
4205
4206            fs.remove_file(&root_path.join(file_name), Default::default())
4207                .await
4208                .unwrap();
4209            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4210                .await;
4211
4212            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4213                .await;
4214        }
4215        .boxed_local()
4216    }
4217}
4218
4219#[derive(Clone, Debug)]
4220struct TraversalProgress<'a> {
4221    max_path: &'a Path,
4222    count: usize,
4223    non_ignored_count: usize,
4224    file_count: usize,
4225    non_ignored_file_count: usize,
4226}
4227
4228impl<'a> TraversalProgress<'a> {
4229    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4230        match (include_ignored, include_dirs) {
4231            (true, true) => self.count,
4232            (true, false) => self.file_count,
4233            (false, true) => self.non_ignored_count,
4234            (false, false) => self.non_ignored_file_count,
4235        }
4236    }
4237}
4238
4239impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4240    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4241        self.max_path = summary.max_path.as_ref();
4242        self.count += summary.count;
4243        self.non_ignored_count += summary.non_ignored_count;
4244        self.file_count += summary.file_count;
4245        self.non_ignored_file_count += summary.non_ignored_file_count;
4246    }
4247}
4248
4249impl<'a> Default for TraversalProgress<'a> {
4250    fn default() -> Self {
4251        Self {
4252            max_path: Path::new(""),
4253            count: 0,
4254            non_ignored_count: 0,
4255            file_count: 0,
4256            non_ignored_file_count: 0,
4257        }
4258    }
4259}
4260
4261#[derive(Clone, Debug, Default, Copy)]
4262struct GitStatuses {
4263    added: usize,
4264    modified: usize,
4265    conflict: usize,
4266}
4267
4268impl AddAssign for GitStatuses {
4269    fn add_assign(&mut self, rhs: Self) {
4270        self.added += rhs.added;
4271        self.modified += rhs.modified;
4272        self.conflict += rhs.conflict;
4273    }
4274}
4275
4276impl Sub for GitStatuses {
4277    type Output = GitStatuses;
4278
4279    fn sub(self, rhs: Self) -> Self::Output {
4280        GitStatuses {
4281            added: self.added - rhs.added,
4282            modified: self.modified - rhs.modified,
4283            conflict: self.conflict - rhs.conflict,
4284        }
4285    }
4286}
4287
4288impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4289    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4290        *self += summary.statuses
4291    }
4292}
4293
4294pub struct Traversal<'a> {
4295    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4296    include_ignored: bool,
4297    include_dirs: bool,
4298}
4299
4300impl<'a> Traversal<'a> {
4301    pub fn advance(&mut self) -> bool {
4302        self.cursor.seek_forward(
4303            &TraversalTarget::Count {
4304                count: self.end_offset() + 1,
4305                include_dirs: self.include_dirs,
4306                include_ignored: self.include_ignored,
4307            },
4308            Bias::Left,
4309            &(),
4310        )
4311    }
4312
4313    pub fn advance_to_sibling(&mut self) -> bool {
4314        while let Some(entry) = self.cursor.item() {
4315            self.cursor.seek_forward(
4316                &TraversalTarget::PathSuccessor(&entry.path),
4317                Bias::Left,
4318                &(),
4319            );
4320            if let Some(entry) = self.cursor.item() {
4321                if (self.include_dirs || !entry.is_dir())
4322                    && (self.include_ignored || !entry.is_ignored)
4323                {
4324                    return true;
4325                }
4326            }
4327        }
4328        false
4329    }
4330
4331    pub fn entry(&self) -> Option<&'a Entry> {
4332        self.cursor.item()
4333    }
4334
4335    pub fn start_offset(&self) -> usize {
4336        self.cursor
4337            .start()
4338            .count(self.include_dirs, self.include_ignored)
4339    }
4340
4341    pub fn end_offset(&self) -> usize {
4342        self.cursor
4343            .end(&())
4344            .count(self.include_dirs, self.include_ignored)
4345    }
4346}
4347
4348impl<'a> Iterator for Traversal<'a> {
4349    type Item = &'a Entry;
4350
4351    fn next(&mut self) -> Option<Self::Item> {
4352        if let Some(item) = self.entry() {
4353            self.advance();
4354            Some(item)
4355        } else {
4356            None
4357        }
4358    }
4359}
4360
4361#[derive(Debug)]
4362enum TraversalTarget<'a> {
4363    Path(&'a Path),
4364    PathSuccessor(&'a Path),
4365    Count {
4366        count: usize,
4367        include_ignored: bool,
4368        include_dirs: bool,
4369    },
4370}
4371
4372impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4373    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4374        match self {
4375            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4376            TraversalTarget::PathSuccessor(path) => {
4377                if !cursor_location.max_path.starts_with(path) {
4378                    Ordering::Equal
4379                } else {
4380                    Ordering::Greater
4381                }
4382            }
4383            TraversalTarget::Count {
4384                count,
4385                include_dirs,
4386                include_ignored,
4387            } => Ord::cmp(
4388                count,
4389                &cursor_location.count(*include_dirs, *include_ignored),
4390            ),
4391        }
4392    }
4393}
4394
4395impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4396    for TraversalTarget<'b>
4397{
4398    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4399        self.cmp(&cursor_location.0, &())
4400    }
4401}
4402
4403struct ChildEntriesIter<'a> {
4404    parent_path: &'a Path,
4405    traversal: Traversal<'a>,
4406}
4407
4408impl<'a> Iterator for ChildEntriesIter<'a> {
4409    type Item = &'a Entry;
4410
4411    fn next(&mut self) -> Option<Self::Item> {
4412        if let Some(item) = self.traversal.entry() {
4413            if item.path.starts_with(&self.parent_path) {
4414                self.traversal.advance_to_sibling();
4415                return Some(item);
4416            }
4417        }
4418        None
4419    }
4420}
4421
4422pub struct DescendentEntriesIter<'a> {
4423    parent_path: &'a Path,
4424    traversal: Traversal<'a>,
4425}
4426
4427impl<'a> Iterator for DescendentEntriesIter<'a> {
4428    type Item = &'a Entry;
4429
4430    fn next(&mut self) -> Option<Self::Item> {
4431        if let Some(item) = self.traversal.entry() {
4432            if item.path.starts_with(&self.parent_path) {
4433                self.traversal.advance();
4434                return Some(item);
4435            }
4436        }
4437        None
4438    }
4439}
4440
4441impl<'a> From<&'a Entry> for proto::Entry {
4442    fn from(entry: &'a Entry) -> Self {
4443        Self {
4444            id: entry.id.to_proto(),
4445            is_dir: entry.is_dir(),
4446            path: entry.path.to_string_lossy().into(),
4447            inode: entry.inode,
4448            mtime: Some(entry.mtime.into()),
4449            is_symlink: entry.is_symlink,
4450            is_ignored: entry.is_ignored,
4451            is_external: entry.is_external,
4452            git_status: entry.git_status.map(git_status_to_proto),
4453        }
4454    }
4455}
4456
4457impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4458    type Error = anyhow::Error;
4459
4460    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4461        if let Some(mtime) = entry.mtime {
4462            let kind = if entry.is_dir {
4463                EntryKind::Dir
4464            } else {
4465                let mut char_bag = *root_char_bag;
4466                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4467                EntryKind::File(char_bag)
4468            };
4469            let path: Arc<Path> = PathBuf::from(entry.path).into();
4470            Ok(Entry {
4471                id: ProjectEntryId::from_proto(entry.id),
4472                kind,
4473                path,
4474                inode: entry.inode,
4475                mtime: mtime.into(),
4476                is_symlink: entry.is_symlink,
4477                is_ignored: entry.is_ignored,
4478                is_external: entry.is_external,
4479                git_status: git_status_from_proto(entry.git_status),
4480            })
4481        } else {
4482            Err(anyhow!(
4483                "missing mtime in remote worktree entry {:?}",
4484                entry.path
4485            ))
4486        }
4487    }
4488}
4489
4490fn combine_git_statuses(
4491    staged: Option<GitFileStatus>,
4492    unstaged: Option<GitFileStatus>,
4493) -> Option<GitFileStatus> {
4494    if let Some(staged) = staged {
4495        if let Some(unstaged) = unstaged {
4496            if unstaged != staged {
4497                Some(GitFileStatus::Modified)
4498            } else {
4499                Some(staged)
4500            }
4501        } else {
4502            Some(staged)
4503        }
4504    } else {
4505        unstaged
4506    }
4507}
4508
4509fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4510    git_status.and_then(|status| {
4511        proto::GitStatus::from_i32(status).map(|status| match status {
4512            proto::GitStatus::Added => GitFileStatus::Added,
4513            proto::GitStatus::Modified => GitFileStatus::Modified,
4514            proto::GitStatus::Conflict => GitFileStatus::Conflict,
4515        })
4516    })
4517}
4518
4519fn git_status_to_proto(status: GitFileStatus) -> i32 {
4520    match status {
4521        GitFileStatus::Added => proto::GitStatus::Added as i32,
4522        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4523        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4524    }
4525}