worktree.rs

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