worktree.rs

   1use crate::ProjectEntryId;
   2
   3use super::{
   4    fs::{self, Fs},
   5    ignore::IgnoreStack,
   6    DiagnosticSummary,
   7};
   8use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   9use anyhow::{anyhow, Context, Result};
  10use client::{proto, Client, TypedEnvelope};
  11use clock::ReplicaId;
  12use collections::HashMap;
  13use futures::{
  14    channel::{
  15        mpsc::{self, UnboundedSender},
  16        oneshot,
  17    },
  18    Stream, StreamExt,
  19};
  20use fuzzy::CharBag;
  21use gpui::{
  22    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  23    Task,
  24};
  25use language::{
  26    proto::{deserialize_version, serialize_version},
  27    Buffer, DiagnosticEntry, PointUtf16, Rope,
  28};
  29use lazy_static::lazy_static;
  30use parking_lot::Mutex;
  31use postage::{
  32    barrier,
  33    prelude::{Sink as _, Stream as _},
  34    watch,
  35};
  36use serde::Deserialize;
  37use smol::channel::{self, Sender};
  38use std::{
  39    any::Any,
  40    cmp::{self, Ordering},
  41    convert::TryFrom,
  42    ffi::{OsStr, OsString},
  43    fmt,
  44    future::Future,
  45    ops::{Deref, DerefMut},
  46    os::unix::prelude::{OsStrExt, OsStringExt},
  47    path::{Path, PathBuf},
  48    sync::{atomic::AtomicUsize, Arc},
  49    time::{Duration, SystemTime},
  50};
  51use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap};
  52use util::{ResultExt, TryFutureExt};
  53
  54lazy_static! {
  55    static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
  56}
  57
  58#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  59pub struct WorktreeId(usize);
  60
  61pub enum Worktree {
  62    Local(LocalWorktree),
  63    Remote(RemoteWorktree),
  64}
  65
  66pub struct LocalWorktree {
  67    snapshot: LocalSnapshot,
  68    config: WorktreeConfig,
  69    background_snapshot: Arc<Mutex<LocalSnapshot>>,
  70    last_scan_state_rx: watch::Receiver<ScanState>,
  71    _background_scanner_task: Option<Task<()>>,
  72    poll_task: Option<Task<()>>,
  73    registration: Registration,
  74    share: Option<ShareState>,
  75    diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
  76    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  77    client: Arc<Client>,
  78    fs: Arc<dyn Fs>,
  79    visible: bool,
  80}
  81
  82pub struct RemoteWorktree {
  83    pub snapshot: Snapshot,
  84    pub(crate) background_snapshot: Arc<Mutex<Snapshot>>,
  85    project_id: u64,
  86    client: Arc<Client>,
  87    updates_tx: UnboundedSender<BackgroundUpdate>,
  88    replica_id: ReplicaId,
  89    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  90    visible: bool,
  91}
  92
  93enum BackgroundUpdate {
  94    Update(proto::UpdateWorktree),
  95    Barrier(barrier::Sender),
  96}
  97
  98#[derive(Clone)]
  99pub struct Snapshot {
 100    id: WorktreeId,
 101    root_name: String,
 102    root_char_bag: CharBag,
 103    entries_by_path: SumTree<Entry>,
 104    entries_by_id: SumTree<PathEntry>,
 105}
 106
 107#[derive(Clone)]
 108pub struct LocalSnapshot {
 109    abs_path: Arc<Path>,
 110    scan_id: usize,
 111    ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 112    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 113    next_entry_id: Arc<AtomicUsize>,
 114    snapshot: Snapshot,
 115}
 116
 117impl Deref for LocalSnapshot {
 118    type Target = Snapshot;
 119
 120    fn deref(&self) -> &Self::Target {
 121        &self.snapshot
 122    }
 123}
 124
 125impl DerefMut for LocalSnapshot {
 126    fn deref_mut(&mut self) -> &mut Self::Target {
 127        &mut self.snapshot
 128    }
 129}
 130
 131#[derive(Clone, Debug)]
 132enum ScanState {
 133    Idle,
 134    Scanning,
 135    Err(Arc<anyhow::Error>),
 136}
 137
 138#[derive(Debug, Eq, PartialEq)]
 139enum Registration {
 140    None,
 141    Pending,
 142    Done { project_id: u64 },
 143}
 144
 145struct ShareState {
 146    project_id: u64,
 147    snapshots_tx: Sender<LocalSnapshot>,
 148    _maintain_remote_snapshot: Option<Task<Option<()>>>,
 149}
 150
 151#[derive(Default, Deserialize)]
 152struct WorktreeConfig {
 153    collaborators: Vec<String>,
 154}
 155
 156pub enum Event {
 157    UpdatedEntries,
 158}
 159
 160impl Entity for Worktree {
 161    type Event = Event;
 162
 163    fn release(&mut self, _: &mut MutableAppContext) {
 164        if let Some(worktree) = self.as_local_mut() {
 165            if let Registration::Done { project_id } = worktree.registration {
 166                let client = worktree.client.clone();
 167                let unregister_message = proto::UnregisterWorktree {
 168                    project_id,
 169                    worktree_id: worktree.id().to_proto(),
 170                };
 171                client.send(unregister_message).log_err();
 172            }
 173        }
 174    }
 175}
 176
 177impl Worktree {
 178    pub async fn local(
 179        client: Arc<Client>,
 180        path: impl Into<Arc<Path>>,
 181        visible: bool,
 182        fs: Arc<dyn Fs>,
 183        next_entry_id: Arc<AtomicUsize>,
 184        cx: &mut AsyncAppContext,
 185    ) -> Result<ModelHandle<Self>> {
 186        let (tree, scan_states_tx) =
 187            LocalWorktree::new(client, path, visible, fs.clone(), next_entry_id, cx).await?;
 188        tree.update(cx, |tree, cx| {
 189            let tree = tree.as_local_mut().unwrap();
 190            let abs_path = tree.abs_path().clone();
 191            let background_snapshot = tree.background_snapshot.clone();
 192            let background = cx.background().clone();
 193            tree._background_scanner_task = Some(cx.background().spawn(async move {
 194                let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 195                let scanner =
 196                    BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
 197                scanner.run(events).await;
 198            }));
 199        });
 200        Ok(tree)
 201    }
 202
 203    pub fn remote(
 204        project_remote_id: u64,
 205        replica_id: ReplicaId,
 206        worktree: proto::Worktree,
 207        client: Arc<Client>,
 208        cx: &mut MutableAppContext,
 209    ) -> (ModelHandle<Self>, Task<()>) {
 210        let remote_id = worktree.id;
 211        let root_char_bag: CharBag = worktree
 212            .root_name
 213            .chars()
 214            .map(|c| c.to_ascii_lowercase())
 215            .collect();
 216        let root_name = worktree.root_name.clone();
 217        let visible = worktree.visible;
 218        let snapshot = Snapshot {
 219            id: WorktreeId(remote_id as usize),
 220            root_name,
 221            root_char_bag,
 222            entries_by_path: Default::default(),
 223            entries_by_id: Default::default(),
 224        };
 225
 226        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 227        let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 228        let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 229        let worktree_handle = cx.add_model(|_: &mut ModelContext<Worktree>| {
 230            Worktree::Remote(RemoteWorktree {
 231                project_id: project_remote_id,
 232                replica_id,
 233                snapshot: snapshot.clone(),
 234                background_snapshot: background_snapshot.clone(),
 235                updates_tx,
 236                client: client.clone(),
 237                diagnostic_summaries: TreeMap::from_ordered_entries(
 238                    worktree.diagnostic_summaries.into_iter().map(|summary| {
 239                        (
 240                            PathKey(PathBuf::from(summary.path).into()),
 241                            DiagnosticSummary {
 242                                error_count: summary.error_count as usize,
 243                                warning_count: summary.warning_count as usize,
 244                            },
 245                        )
 246                    }),
 247                ),
 248                visible,
 249            })
 250        });
 251
 252        let deserialize_task = cx.spawn({
 253            let worktree_handle = worktree_handle.clone();
 254            |cx| async move {
 255                let (entries_by_path, entries_by_id) = cx
 256                    .background()
 257                    .spawn(async move {
 258                        let mut entries_by_path_edits = Vec::new();
 259                        let mut entries_by_id_edits = Vec::new();
 260                        for entry in worktree.entries {
 261                            match Entry::try_from((&root_char_bag, entry)) {
 262                                Ok(entry) => {
 263                                    entries_by_id_edits.push(Edit::Insert(PathEntry {
 264                                        id: entry.id,
 265                                        path: entry.path.clone(),
 266                                        is_ignored: entry.is_ignored,
 267                                        scan_id: 0,
 268                                    }));
 269                                    entries_by_path_edits.push(Edit::Insert(entry));
 270                                }
 271                                Err(err) => log::warn!("error for remote worktree entry {:?}", err),
 272                            }
 273                        }
 274
 275                        let mut entries_by_path = SumTree::new();
 276                        let mut entries_by_id = SumTree::new();
 277                        entries_by_path.edit(entries_by_path_edits, &());
 278                        entries_by_id.edit(entries_by_id_edits, &());
 279
 280                        (entries_by_path, entries_by_id)
 281                    })
 282                    .await;
 283
 284                {
 285                    let mut snapshot = background_snapshot.lock();
 286                    snapshot.entries_by_path = entries_by_path;
 287                    snapshot.entries_by_id = entries_by_id;
 288                    snapshot_updated_tx.send(()).await.ok();
 289                }
 290
 291                cx.background()
 292                    .spawn(async move {
 293                        while let Some(update) = updates_rx.next().await {
 294                            if let BackgroundUpdate::Update(update) = update {
 295                                if let Err(error) =
 296                                    background_snapshot.lock().apply_remote_update(update)
 297                                {
 298                                    log::error!("error applying worktree update: {}", error);
 299                                }
 300                                snapshot_updated_tx.send(()).await.ok();
 301                            }
 302                        }
 303                    })
 304                    .detach();
 305
 306                cx.spawn(|mut cx| {
 307                    let this = worktree_handle.downgrade();
 308                    async move {
 309                        while let Some(_) = snapshot_updated_rx.recv().await {
 310                            if let Some(this) = this.upgrade(&cx) {
 311                                this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 312                            } else {
 313                                break;
 314                            }
 315                        }
 316                    }
 317                })
 318                .detach();
 319            }
 320        });
 321        (worktree_handle, deserialize_task)
 322    }
 323
 324    pub fn as_local(&self) -> Option<&LocalWorktree> {
 325        if let Worktree::Local(worktree) = self {
 326            Some(worktree)
 327        } else {
 328            None
 329        }
 330    }
 331
 332    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 333        if let Worktree::Remote(worktree) = self {
 334            Some(worktree)
 335        } else {
 336            None
 337        }
 338    }
 339
 340    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 341        if let Worktree::Local(worktree) = self {
 342            Some(worktree)
 343        } else {
 344            None
 345        }
 346    }
 347
 348    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 349        if let Worktree::Remote(worktree) = self {
 350            Some(worktree)
 351        } else {
 352            None
 353        }
 354    }
 355
 356    pub fn is_local(&self) -> bool {
 357        matches!(self, Worktree::Local(_))
 358    }
 359
 360    pub fn is_remote(&self) -> bool {
 361        !self.is_local()
 362    }
 363
 364    pub fn snapshot(&self) -> Snapshot {
 365        match self {
 366            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 367            Worktree::Remote(worktree) => worktree.snapshot(),
 368        }
 369    }
 370
 371    pub fn is_visible(&self) -> bool {
 372        match self {
 373            Worktree::Local(worktree) => worktree.visible,
 374            Worktree::Remote(worktree) => worktree.visible,
 375        }
 376    }
 377
 378    pub fn replica_id(&self) -> ReplicaId {
 379        match self {
 380            Worktree::Local(_) => 0,
 381            Worktree::Remote(worktree) => worktree.replica_id,
 382        }
 383    }
 384
 385    pub fn diagnostic_summaries<'a>(
 386        &'a self,
 387    ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + 'a {
 388        match self {
 389            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 390            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 391        }
 392        .iter()
 393        .map(|(path, summary)| (path.0.clone(), summary.clone()))
 394    }
 395
 396    fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
 397        match self {
 398            Self::Local(worktree) => {
 399                let is_fake_fs = worktree.fs.is_fake();
 400                worktree.snapshot = worktree.background_snapshot.lock().clone();
 401                if worktree.is_scanning() {
 402                    if worktree.poll_task.is_none() {
 403                        worktree.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
 404                            if is_fake_fs {
 405                                #[cfg(any(test, feature = "test-support"))]
 406                                cx.background().simulate_random_delay().await;
 407                            } else {
 408                                smol::Timer::after(Duration::from_millis(100)).await;
 409                            }
 410                            if let Some(this) = this.upgrade(&cx) {
 411                                this.update(&mut cx, |this, cx| {
 412                                    this.as_local_mut().unwrap().poll_task = None;
 413                                    this.poll_snapshot(cx);
 414                                });
 415                            }
 416                        }));
 417                    }
 418                } else {
 419                    worktree.poll_task.take();
 420                    cx.emit(Event::UpdatedEntries);
 421                }
 422            }
 423            Self::Remote(worktree) => {
 424                worktree.snapshot = worktree.background_snapshot.lock().clone();
 425                cx.emit(Event::UpdatedEntries);
 426            }
 427        };
 428
 429        cx.notify();
 430    }
 431}
 432
 433impl LocalWorktree {
 434    async fn new(
 435        client: Arc<Client>,
 436        path: impl Into<Arc<Path>>,
 437        visible: bool,
 438        fs: Arc<dyn Fs>,
 439        next_entry_id: Arc<AtomicUsize>,
 440        cx: &mut AsyncAppContext,
 441    ) -> Result<(ModelHandle<Worktree>, UnboundedSender<ScanState>)> {
 442        let abs_path = path.into();
 443        let path: Arc<Path> = Arc::from(Path::new(""));
 444
 445        // After determining whether the root entry is a file or a directory, populate the
 446        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 447        let root_name = abs_path
 448            .file_name()
 449            .map_or(String::new(), |f| f.to_string_lossy().to_string());
 450        let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
 451        let metadata = fs
 452            .metadata(&abs_path)
 453            .await
 454            .context("failed to stat worktree path")?;
 455
 456        let mut config = WorktreeConfig::default();
 457        if let Ok(zed_toml) = fs.load(&abs_path.join(".zed.toml")).await {
 458            if let Ok(parsed) = toml::from_str(&zed_toml) {
 459                config = parsed;
 460            }
 461        }
 462
 463        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 464        let (mut last_scan_state_tx, last_scan_state_rx) = watch::channel_with(ScanState::Scanning);
 465        let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 466            let mut snapshot = LocalSnapshot {
 467                abs_path,
 468                scan_id: 0,
 469                ignores: Default::default(),
 470                removed_entry_ids: Default::default(),
 471                next_entry_id,
 472                snapshot: Snapshot {
 473                    id: WorktreeId::from_usize(cx.model_id()),
 474                    root_name: root_name.clone(),
 475                    root_char_bag,
 476                    entries_by_path: Default::default(),
 477                    entries_by_id: Default::default(),
 478                },
 479            };
 480            if let Some(metadata) = metadata {
 481                let entry = Entry::new(
 482                    path.into(),
 483                    &metadata,
 484                    &snapshot.next_entry_id,
 485                    snapshot.root_char_bag,
 486                );
 487                snapshot.insert_entry(entry, fs.as_ref());
 488            }
 489
 490            let tree = Self {
 491                snapshot: snapshot.clone(),
 492                config,
 493                background_snapshot: Arc::new(Mutex::new(snapshot)),
 494                last_scan_state_rx,
 495                _background_scanner_task: None,
 496                registration: Registration::None,
 497                share: None,
 498                poll_task: None,
 499                diagnostics: Default::default(),
 500                diagnostic_summaries: Default::default(),
 501                client,
 502                fs,
 503                visible,
 504            };
 505
 506            cx.spawn_weak(|this, mut cx| async move {
 507                while let Some(scan_state) = scan_states_rx.next().await {
 508                    if let Some(handle) = this.upgrade(&cx) {
 509                        let to_send = handle.update(&mut cx, |this, cx| {
 510                            last_scan_state_tx.blocking_send(scan_state).ok();
 511                            this.poll_snapshot(cx);
 512                            let tree = this.as_local_mut().unwrap();
 513                            if !tree.is_scanning() {
 514                                if let Some(share) = tree.share.as_ref() {
 515                                    return Some((tree.snapshot(), share.snapshots_tx.clone()));
 516                                }
 517                            }
 518                            None
 519                        });
 520
 521                        if let Some((snapshot, snapshots_to_send_tx)) = to_send {
 522                            if let Err(err) = snapshots_to_send_tx.send(snapshot).await {
 523                                log::error!("error submitting snapshot to send {}", err);
 524                            }
 525                        }
 526                    } else {
 527                        break;
 528                    }
 529                }
 530            })
 531            .detach();
 532
 533            Worktree::Local(tree)
 534        });
 535
 536        Ok((tree, scan_states_tx))
 537    }
 538
 539    pub fn contains_abs_path(&self, path: &Path) -> bool {
 540        path.starts_with(&self.abs_path)
 541    }
 542
 543    fn absolutize(&self, path: &Path) -> PathBuf {
 544        if path.file_name().is_some() {
 545            self.abs_path.join(path)
 546        } else {
 547            self.abs_path.to_path_buf()
 548        }
 549    }
 550
 551    pub fn authorized_logins(&self) -> Vec<String> {
 552        self.config.collaborators.clone()
 553    }
 554
 555    pub(crate) fn load_buffer(
 556        &mut self,
 557        path: &Path,
 558        cx: &mut ModelContext<Worktree>,
 559    ) -> Task<Result<ModelHandle<Buffer>>> {
 560        let path = Arc::from(path);
 561        cx.spawn(move |this, mut cx| async move {
 562            let (file, contents) = this
 563                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 564                .await?;
 565            Ok(cx.add_model(|cx| Buffer::from_file(0, contents, Box::new(file), cx)))
 566        })
 567    }
 568
 569    pub fn diagnostics_for_path(&self, path: &Path) -> Option<Vec<DiagnosticEntry<PointUtf16>>> {
 570        self.diagnostics.get(path).cloned()
 571    }
 572
 573    pub fn update_diagnostics(
 574        &mut self,
 575        worktree_path: Arc<Path>,
 576        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
 577        _: &mut ModelContext<Worktree>,
 578    ) -> Result<bool> {
 579        self.diagnostics.remove(&worktree_path);
 580        let old_summary = self
 581            .diagnostic_summaries
 582            .remove(&PathKey(worktree_path.clone()))
 583            .unwrap_or_default();
 584        let new_summary = DiagnosticSummary::new(&diagnostics);
 585        if !new_summary.is_empty() {
 586            self.diagnostic_summaries
 587                .insert(PathKey(worktree_path.clone()), new_summary);
 588            self.diagnostics.insert(worktree_path.clone(), diagnostics);
 589        }
 590
 591        let updated = !old_summary.is_empty() || !new_summary.is_empty();
 592        if updated {
 593            if let Some(share) = self.share.as_ref() {
 594                self.client
 595                    .send(proto::UpdateDiagnosticSummary {
 596                        project_id: share.project_id,
 597                        worktree_id: self.id().to_proto(),
 598                        summary: Some(proto::DiagnosticSummary {
 599                            path: worktree_path.to_string_lossy().to_string(),
 600                            error_count: new_summary.error_count as u32,
 601                            warning_count: new_summary.warning_count as u32,
 602                        }),
 603                    })
 604                    .log_err();
 605            }
 606        }
 607
 608        Ok(updated)
 609    }
 610
 611    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 612        let mut scan_state_rx = self.last_scan_state_rx.clone();
 613        async move {
 614            let mut scan_state = Some(scan_state_rx.borrow().clone());
 615            while let Some(ScanState::Scanning) = scan_state {
 616                scan_state = scan_state_rx.recv().await;
 617            }
 618        }
 619    }
 620
 621    fn is_scanning(&self) -> bool {
 622        if let ScanState::Scanning = *self.last_scan_state_rx.borrow() {
 623            true
 624        } else {
 625            false
 626        }
 627    }
 628
 629    pub fn snapshot(&self) -> LocalSnapshot {
 630        self.snapshot.clone()
 631    }
 632
 633    fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
 634        let handle = cx.handle();
 635        let path = Arc::from(path);
 636        let abs_path = self.absolutize(&path);
 637        let fs = self.fs.clone();
 638        cx.spawn(|this, mut cx| async move {
 639            let text = fs.load(&abs_path).await?;
 640            // Eagerly populate the snapshot with an updated entry for the loaded file
 641            let entry = this
 642                .update(&mut cx, |this, _| {
 643                    this.as_local().unwrap().refresh_entry(path, abs_path, None)
 644                })
 645                .await?;
 646            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 647            Ok((
 648                File {
 649                    entry_id: Some(entry.id),
 650                    worktree: handle,
 651                    path: entry.path,
 652                    mtime: entry.mtime,
 653                    is_local: true,
 654                },
 655                text,
 656            ))
 657        })
 658    }
 659
 660    pub fn save_buffer_as(
 661        &self,
 662        buffer_handle: ModelHandle<Buffer>,
 663        path: impl Into<Arc<Path>>,
 664        cx: &mut ModelContext<Worktree>,
 665    ) -> Task<Result<()>> {
 666        let buffer = buffer_handle.read(cx);
 667        let text = buffer.as_rope().clone();
 668        let version = buffer.version();
 669        let save = self.write_file(path, text, cx);
 670        let handle = cx.handle();
 671        cx.as_mut().spawn(|mut cx| async move {
 672            let entry = save.await?;
 673            let file = File {
 674                entry_id: Some(entry.id),
 675                worktree: handle,
 676                path: entry.path,
 677                mtime: entry.mtime,
 678                is_local: true,
 679            };
 680
 681            buffer_handle.update(&mut cx, |buffer, cx| {
 682                buffer.did_save(version, file.mtime, Some(Box::new(file)), cx);
 683            });
 684
 685            Ok(())
 686        })
 687    }
 688
 689    pub fn create_entry(
 690        &self,
 691        path: impl Into<Arc<Path>>,
 692        is_dir: bool,
 693        cx: &mut ModelContext<Worktree>,
 694    ) -> Task<Result<Entry>> {
 695        self.write_entry_internal(
 696            path,
 697            if is_dir {
 698                None
 699            } else {
 700                Some(Default::default())
 701            },
 702            cx,
 703        )
 704    }
 705
 706    pub fn write_file(
 707        &self,
 708        path: impl Into<Arc<Path>>,
 709        text: Rope,
 710        cx: &mut ModelContext<Worktree>,
 711    ) -> Task<Result<Entry>> {
 712        self.write_entry_internal(path, Some(text), cx)
 713    }
 714
 715    pub fn rename_entry(
 716        &self,
 717        entry_id: ProjectEntryId,
 718        new_path: impl Into<Arc<Path>>,
 719        cx: &mut ModelContext<Worktree>,
 720    ) -> Option<Task<Result<Entry>>> {
 721        let old_path = self.entry_for_id(entry_id)?.path.clone();
 722        let new_path = new_path.into();
 723        let abs_old_path = self.absolutize(&old_path);
 724        let abs_new_path = self.absolutize(&new_path);
 725        let rename = cx.background().spawn({
 726            let fs = self.fs.clone();
 727            let abs_new_path = abs_new_path.clone();
 728            async move {
 729                fs.rename(&abs_old_path, &abs_new_path, Default::default())
 730                    .await
 731            }
 732        });
 733
 734        Some(cx.spawn(|this, mut cx| async move {
 735            rename.await?;
 736            let entry = this
 737                .update(&mut cx, |this, _| {
 738                    this.as_local_mut().unwrap().refresh_entry(
 739                        new_path.clone(),
 740                        abs_new_path,
 741                        Some(old_path),
 742                    )
 743                })
 744                .await?;
 745            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 746            Ok(entry)
 747        }))
 748    }
 749
 750    fn write_entry_internal(
 751        &self,
 752        path: impl Into<Arc<Path>>,
 753        text_if_file: Option<Rope>,
 754        cx: &mut ModelContext<Worktree>,
 755    ) -> Task<Result<Entry>> {
 756        let path = path.into();
 757        let abs_path = self.absolutize(&path);
 758        let write = cx.background().spawn({
 759            let fs = self.fs.clone();
 760            let abs_path = abs_path.clone();
 761            async move {
 762                if let Some(text) = text_if_file {
 763                    fs.save(&abs_path, &text).await
 764                } else {
 765                    fs.create_dir(&abs_path).await
 766                }
 767            }
 768        });
 769
 770        cx.spawn(|this, mut cx| async move {
 771            write.await?;
 772            let entry = this
 773                .update(&mut cx, |this, _| {
 774                    this.as_local_mut()
 775                        .unwrap()
 776                        .refresh_entry(path, abs_path, None)
 777                })
 778                .await?;
 779            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 780            Ok(entry)
 781        })
 782    }
 783
 784    fn refresh_entry(
 785        &self,
 786        path: Arc<Path>,
 787        abs_path: PathBuf,
 788        old_path: Option<Arc<Path>>,
 789    ) -> impl Future<Output = Result<Entry>> {
 790        let root_char_bag;
 791        let next_entry_id;
 792        let fs = self.fs.clone();
 793        let shared_snapshots_tx = self.share.as_ref().map(|share| share.snapshots_tx.clone());
 794        let snapshot = self.background_snapshot.clone();
 795        {
 796            let snapshot = snapshot.lock();
 797            root_char_bag = snapshot.root_char_bag;
 798            next_entry_id = snapshot.next_entry_id.clone();
 799        }
 800        async move {
 801            let entry = Entry::new(
 802                path,
 803                &fs.metadata(&abs_path)
 804                    .await?
 805                    .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
 806                &next_entry_id,
 807                root_char_bag,
 808            );
 809            let mut snapshot = snapshot.lock();
 810            if let Some(old_path) = old_path {
 811                snapshot.remove_path(&old_path);
 812            }
 813            let entry = snapshot.insert_entry(entry, fs.as_ref());
 814            if let Some(tx) = shared_snapshots_tx {
 815                tx.send(snapshot.clone()).await.ok();
 816            }
 817            Ok(entry)
 818        }
 819    }
 820
 821    pub fn register(
 822        &mut self,
 823        project_id: u64,
 824        cx: &mut ModelContext<Worktree>,
 825    ) -> Task<anyhow::Result<()>> {
 826        if self.registration != Registration::None {
 827            return Task::ready(Ok(()));
 828        }
 829
 830        self.registration = Registration::Pending;
 831        let client = self.client.clone();
 832        let register_message = proto::RegisterWorktree {
 833            project_id,
 834            worktree_id: self.id().to_proto(),
 835            root_name: self.root_name().to_string(),
 836            authorized_logins: self.authorized_logins(),
 837            visible: self.visible,
 838        };
 839        let request = client.request(register_message);
 840        cx.spawn(|this, mut cx| async move {
 841            let response = request.await;
 842            this.update(&mut cx, |this, _| {
 843                let worktree = this.as_local_mut().unwrap();
 844                match response {
 845                    Ok(_) => {
 846                        if worktree.registration == Registration::Pending {
 847                            worktree.registration = Registration::Done { project_id };
 848                        }
 849                        Ok(())
 850                    }
 851                    Err(error) => {
 852                        worktree.registration = Registration::None;
 853                        Err(error)
 854                    }
 855                }
 856            })
 857        })
 858    }
 859
 860    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 861        let register = self.register(project_id, cx);
 862        let (share_tx, share_rx) = oneshot::channel();
 863        let (snapshots_to_send_tx, snapshots_to_send_rx) =
 864            smol::channel::unbounded::<LocalSnapshot>();
 865        if self.share.is_some() {
 866            let _ = share_tx.send(Ok(()));
 867        } else {
 868            let rpc = self.client.clone();
 869            let worktree_id = cx.model_id() as u64;
 870            let maintain_remote_snapshot = cx.background().spawn({
 871                let rpc = rpc.clone();
 872                let diagnostic_summaries = self.diagnostic_summaries.clone();
 873                async move {
 874                    let mut prev_snapshot = match snapshots_to_send_rx.recv().await {
 875                        Ok(snapshot) => {
 876                            if let Err(error) = rpc
 877                                .request(proto::UpdateWorktree {
 878                                    project_id,
 879                                    worktree_id,
 880                                    root_name: snapshot.root_name().to_string(),
 881                                    updated_entries: snapshot
 882                                        .entries_by_path
 883                                        .iter()
 884                                        .filter(|e| !e.is_ignored)
 885                                        .map(Into::into)
 886                                        .collect(),
 887                                    removed_entries: Default::default(),
 888                                })
 889                                .await
 890                            {
 891                                let _ = share_tx.send(Err(error));
 892                                return Err(anyhow!("failed to send initial update worktree"));
 893                            } else {
 894                                let _ = share_tx.send(Ok(()));
 895                                snapshot
 896                            }
 897                        }
 898                        Err(error) => {
 899                            let _ = share_tx.send(Err(error.into()));
 900                            return Err(anyhow!("failed to send initial update worktree"));
 901                        }
 902                    };
 903
 904                    for (path, summary) in diagnostic_summaries.iter() {
 905                        rpc.send(proto::UpdateDiagnosticSummary {
 906                            project_id,
 907                            worktree_id,
 908                            summary: Some(summary.to_proto(&path.0)),
 909                        })?;
 910                    }
 911
 912                    while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
 913                        let message =
 914                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, false);
 915                        rpc.request(message).await?;
 916                        prev_snapshot = snapshot;
 917                    }
 918
 919                    Ok::<_, anyhow::Error>(())
 920                }
 921                .log_err()
 922            });
 923            self.share = Some(ShareState {
 924                project_id,
 925                snapshots_tx: snapshots_to_send_tx.clone(),
 926                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
 927            });
 928        }
 929
 930        cx.spawn_weak(|this, cx| async move {
 931            register.await?;
 932            if let Some(this) = this.upgrade(&cx) {
 933                this.read_with(&cx, |this, _| {
 934                    let this = this.as_local().unwrap();
 935                    let _ = snapshots_to_send_tx.try_send(this.snapshot());
 936                });
 937            }
 938            share_rx
 939                .await
 940                .unwrap_or_else(|_| Err(anyhow!("share ended")))
 941        })
 942    }
 943
 944    pub fn unregister(&mut self) {
 945        self.unshare();
 946        self.registration = Registration::None;
 947    }
 948
 949    pub fn unshare(&mut self) {
 950        self.share.take();
 951    }
 952
 953    pub fn is_shared(&self) -> bool {
 954        self.share.is_some()
 955    }
 956}
 957
 958impl RemoteWorktree {
 959    fn snapshot(&self) -> Snapshot {
 960        self.snapshot.clone()
 961    }
 962
 963    pub fn update_from_remote(
 964        &mut self,
 965        envelope: TypedEnvelope<proto::UpdateWorktree>,
 966    ) -> Result<()> {
 967        self.updates_tx
 968            .unbounded_send(BackgroundUpdate::Update(envelope.payload))
 969            .expect("consumer runs to completion");
 970        Ok(())
 971    }
 972
 973    pub fn finish_pending_remote_updates(&self) -> impl Future<Output = ()> {
 974        let (tx, mut rx) = barrier::channel();
 975        self.updates_tx
 976            .unbounded_send(BackgroundUpdate::Barrier(tx))
 977            .expect("consumer runs to completion");
 978        async move {
 979            rx.recv().await;
 980        }
 981    }
 982
 983    pub fn update_diagnostic_summary(
 984        &mut self,
 985        path: Arc<Path>,
 986        summary: &proto::DiagnosticSummary,
 987    ) {
 988        let summary = DiagnosticSummary {
 989            error_count: summary.error_count as usize,
 990            warning_count: summary.warning_count as usize,
 991        };
 992        if summary.is_empty() {
 993            self.diagnostic_summaries.remove(&PathKey(path.clone()));
 994        } else {
 995            self.diagnostic_summaries
 996                .insert(PathKey(path.clone()), summary);
 997        }
 998    }
 999
1000    pub fn insert_entry(
1001        &self,
1002        entry: proto::Entry,
1003        cx: &mut ModelContext<Worktree>,
1004    ) -> Task<Result<Entry>> {
1005        cx.spawn(|this, mut cx| async move {
1006            this.update(&mut cx, |worktree, _| {
1007                worktree
1008                    .as_remote_mut()
1009                    .unwrap()
1010                    .finish_pending_remote_updates()
1011            })
1012            .await;
1013            this.update(&mut cx, |worktree, _| {
1014                let worktree = worktree.as_remote_mut().unwrap();
1015                let mut snapshot = worktree.background_snapshot.lock();
1016                let entry = snapshot.insert_entry(entry);
1017                worktree.snapshot = snapshot.clone();
1018                entry
1019            })
1020        })
1021    }
1022}
1023
1024impl Snapshot {
1025    pub fn id(&self) -> WorktreeId {
1026        self.id
1027    }
1028
1029    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1030        self.entries_by_id.get(&entry_id, &()).is_some()
1031    }
1032
1033    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1034        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1035        let old_entry = self.entries_by_id.insert_or_replace(
1036            PathEntry {
1037                id: entry.id,
1038                path: entry.path.clone(),
1039                is_ignored: entry.is_ignored,
1040                scan_id: 0,
1041            },
1042            &(),
1043        );
1044        if let Some(old_entry) = old_entry {
1045            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1046        }
1047        self.entries_by_path.insert_or_replace(entry.clone(), &());
1048        Ok(entry)
1049    }
1050
1051    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1052        let mut entries_by_path_edits = Vec::new();
1053        let mut entries_by_id_edits = Vec::new();
1054        for entry_id in update.removed_entries {
1055            let entry = self
1056                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1057                .ok_or_else(|| anyhow!("unknown entry"))?;
1058            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1059            entries_by_id_edits.push(Edit::Remove(entry.id));
1060        }
1061
1062        for entry in update.updated_entries {
1063            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1064            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1065                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1066            }
1067            entries_by_id_edits.push(Edit::Insert(PathEntry {
1068                id: entry.id,
1069                path: entry.path.clone(),
1070                is_ignored: entry.is_ignored,
1071                scan_id: 0,
1072            }));
1073            entries_by_path_edits.push(Edit::Insert(entry));
1074        }
1075
1076        self.entries_by_path.edit(entries_by_path_edits, &());
1077        self.entries_by_id.edit(entries_by_id_edits, &());
1078
1079        Ok(())
1080    }
1081
1082    pub fn file_count(&self) -> usize {
1083        self.entries_by_path.summary().file_count
1084    }
1085
1086    pub fn visible_file_count(&self) -> usize {
1087        self.entries_by_path.summary().visible_file_count
1088    }
1089
1090    fn traverse_from_offset(
1091        &self,
1092        include_dirs: bool,
1093        include_ignored: bool,
1094        start_offset: usize,
1095    ) -> Traversal {
1096        let mut cursor = self.entries_by_path.cursor();
1097        cursor.seek(
1098            &TraversalTarget::Count {
1099                count: start_offset,
1100                include_dirs,
1101                include_ignored,
1102            },
1103            Bias::Right,
1104            &(),
1105        );
1106        Traversal {
1107            cursor,
1108            include_dirs,
1109            include_ignored,
1110        }
1111    }
1112
1113    fn traverse_from_path(
1114        &self,
1115        include_dirs: bool,
1116        include_ignored: bool,
1117        path: &Path,
1118    ) -> Traversal {
1119        let mut cursor = self.entries_by_path.cursor();
1120        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1121        Traversal {
1122            cursor,
1123            include_dirs,
1124            include_ignored,
1125        }
1126    }
1127
1128    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1129        self.traverse_from_offset(false, include_ignored, start)
1130    }
1131
1132    pub fn entries(&self, include_ignored: bool) -> Traversal {
1133        self.traverse_from_offset(true, include_ignored, 0)
1134    }
1135
1136    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1137        let empty_path = Path::new("");
1138        self.entries_by_path
1139            .cursor::<()>()
1140            .filter(move |entry| entry.path.as_ref() != empty_path)
1141            .map(|entry| &entry.path)
1142    }
1143
1144    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1145        let mut cursor = self.entries_by_path.cursor();
1146        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1147        let traversal = Traversal {
1148            cursor,
1149            include_dirs: true,
1150            include_ignored: true,
1151        };
1152        ChildEntriesIter {
1153            traversal,
1154            parent_path,
1155        }
1156    }
1157
1158    pub fn root_entry(&self) -> Option<&Entry> {
1159        self.entry_for_path("")
1160    }
1161
1162    pub fn root_name(&self) -> &str {
1163        &self.root_name
1164    }
1165
1166    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1167        let path = path.as_ref();
1168        self.traverse_from_path(true, true, path)
1169            .entry()
1170            .and_then(|entry| {
1171                if entry.path.as_ref() == path {
1172                    Some(entry)
1173                } else {
1174                    None
1175                }
1176            })
1177    }
1178
1179    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1180        let entry = self.entries_by_id.get(&id, &())?;
1181        self.entry_for_path(&entry.path)
1182    }
1183
1184    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1185        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1186    }
1187}
1188
1189impl LocalSnapshot {
1190    pub fn abs_path(&self) -> &Arc<Path> {
1191        &self.abs_path
1192    }
1193
1194    #[cfg(test)]
1195    pub(crate) fn to_proto(
1196        &self,
1197        diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1198        visible: bool,
1199    ) -> proto::Worktree {
1200        let root_name = self.root_name.clone();
1201        proto::Worktree {
1202            id: self.id.0 as u64,
1203            root_name,
1204            entries: self
1205                .entries_by_path
1206                .iter()
1207                .filter(|e| !e.is_ignored)
1208                .map(Into::into)
1209                .collect(),
1210            diagnostic_summaries: diagnostic_summaries
1211                .iter()
1212                .map(|(path, summary)| summary.to_proto(&path.0))
1213                .collect(),
1214            visible,
1215        }
1216    }
1217
1218    pub(crate) fn build_update(
1219        &self,
1220        other: &Self,
1221        project_id: u64,
1222        worktree_id: u64,
1223        include_ignored: bool,
1224    ) -> proto::UpdateWorktree {
1225        let mut updated_entries = Vec::new();
1226        let mut removed_entries = Vec::new();
1227        let mut self_entries = self
1228            .entries_by_id
1229            .cursor::<()>()
1230            .filter(|e| include_ignored || !e.is_ignored)
1231            .peekable();
1232        let mut other_entries = other
1233            .entries_by_id
1234            .cursor::<()>()
1235            .filter(|e| include_ignored || !e.is_ignored)
1236            .peekable();
1237        loop {
1238            match (self_entries.peek(), other_entries.peek()) {
1239                (Some(self_entry), Some(other_entry)) => {
1240                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1241                        Ordering::Less => {
1242                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1243                            updated_entries.push(entry);
1244                            self_entries.next();
1245                        }
1246                        Ordering::Equal => {
1247                            if self_entry.scan_id != other_entry.scan_id {
1248                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1249                                updated_entries.push(entry);
1250                            }
1251
1252                            self_entries.next();
1253                            other_entries.next();
1254                        }
1255                        Ordering::Greater => {
1256                            removed_entries.push(other_entry.id.to_proto());
1257                            other_entries.next();
1258                        }
1259                    }
1260                }
1261                (Some(self_entry), None) => {
1262                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1263                    updated_entries.push(entry);
1264                    self_entries.next();
1265                }
1266                (None, Some(other_entry)) => {
1267                    removed_entries.push(other_entry.id.to_proto());
1268                    other_entries.next();
1269                }
1270                (None, None) => break,
1271            }
1272        }
1273
1274        proto::UpdateWorktree {
1275            project_id,
1276            worktree_id,
1277            root_name: self.root_name().to_string(),
1278            updated_entries,
1279            removed_entries,
1280        }
1281    }
1282
1283    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1284        if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1285            let abs_path = self.abs_path.join(&entry.path);
1286            match build_gitignore(&abs_path, fs) {
1287                Ok(ignore) => {
1288                    let ignore_dir_path = entry.path.parent().unwrap();
1289                    self.ignores
1290                        .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1291                }
1292                Err(error) => {
1293                    log::error!(
1294                        "error loading .gitignore file {:?} - {:?}",
1295                        &entry.path,
1296                        error
1297                    );
1298                }
1299            }
1300        }
1301
1302        self.reuse_entry_id(&mut entry);
1303        self.entries_by_path.insert_or_replace(entry.clone(), &());
1304        let scan_id = self.scan_id;
1305        self.entries_by_id.insert_or_replace(
1306            PathEntry {
1307                id: entry.id,
1308                path: entry.path.clone(),
1309                is_ignored: entry.is_ignored,
1310                scan_id,
1311            },
1312            &(),
1313        );
1314        entry
1315    }
1316
1317    fn populate_dir(
1318        &mut self,
1319        parent_path: Arc<Path>,
1320        entries: impl IntoIterator<Item = Entry>,
1321        ignore: Option<Arc<Gitignore>>,
1322    ) {
1323        let mut parent_entry = self
1324            .entries_by_path
1325            .get(&PathKey(parent_path.clone()), &())
1326            .unwrap()
1327            .clone();
1328        if let Some(ignore) = ignore {
1329            self.ignores.insert(parent_path, (ignore, self.scan_id));
1330        }
1331        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1332            parent_entry.kind = EntryKind::Dir;
1333        } else {
1334            unreachable!();
1335        }
1336
1337        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1338        let mut entries_by_id_edits = Vec::new();
1339
1340        for mut entry in entries {
1341            self.reuse_entry_id(&mut entry);
1342            entries_by_id_edits.push(Edit::Insert(PathEntry {
1343                id: entry.id,
1344                path: entry.path.clone(),
1345                is_ignored: entry.is_ignored,
1346                scan_id: self.scan_id,
1347            }));
1348            entries_by_path_edits.push(Edit::Insert(entry));
1349        }
1350
1351        self.entries_by_path.edit(entries_by_path_edits, &());
1352        self.entries_by_id.edit(entries_by_id_edits, &());
1353    }
1354
1355    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1356        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1357            entry.id = removed_entry_id;
1358        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1359            entry.id = existing_entry.id;
1360        }
1361    }
1362
1363    fn remove_path(&mut self, path: &Path) {
1364        let mut new_entries;
1365        let removed_entries;
1366        {
1367            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1368            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1369            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1370            new_entries.push_tree(cursor.suffix(&()), &());
1371        }
1372        self.entries_by_path = new_entries;
1373
1374        let mut entries_by_id_edits = Vec::new();
1375        for entry in removed_entries.cursor::<()>() {
1376            let removed_entry_id = self
1377                .removed_entry_ids
1378                .entry(entry.inode)
1379                .or_insert(entry.id);
1380            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1381            entries_by_id_edits.push(Edit::Remove(entry.id));
1382        }
1383        self.entries_by_id.edit(entries_by_id_edits, &());
1384
1385        if path.file_name() == Some(&GITIGNORE) {
1386            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1387                *scan_id = self.scan_id;
1388            }
1389        }
1390    }
1391
1392    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1393        let mut new_ignores = Vec::new();
1394        for ancestor in path.ancestors().skip(1) {
1395            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1396                new_ignores.push((ancestor, Some(ignore.clone())));
1397            } else {
1398                new_ignores.push((ancestor, None));
1399            }
1400        }
1401
1402        let mut ignore_stack = IgnoreStack::none();
1403        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1404            if ignore_stack.is_path_ignored(&parent_path, true) {
1405                ignore_stack = IgnoreStack::all();
1406                break;
1407            } else if let Some(ignore) = ignore {
1408                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1409            }
1410        }
1411
1412        if ignore_stack.is_path_ignored(path, is_dir) {
1413            ignore_stack = IgnoreStack::all();
1414        }
1415
1416        ignore_stack
1417    }
1418}
1419
1420fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1421    let contents = smol::block_on(fs.load(&abs_path))?;
1422    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1423    let mut builder = GitignoreBuilder::new(parent);
1424    for line in contents.lines() {
1425        builder.add_line(Some(abs_path.into()), line)?;
1426    }
1427    Ok(builder.build()?)
1428}
1429
1430impl WorktreeId {
1431    pub fn from_usize(handle_id: usize) -> Self {
1432        Self(handle_id)
1433    }
1434
1435    pub(crate) fn from_proto(id: u64) -> Self {
1436        Self(id as usize)
1437    }
1438
1439    pub fn to_proto(&self) -> u64 {
1440        self.0 as u64
1441    }
1442
1443    pub fn to_usize(&self) -> usize {
1444        self.0
1445    }
1446}
1447
1448impl fmt::Display for WorktreeId {
1449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1450        self.0.fmt(f)
1451    }
1452}
1453
1454impl Deref for Worktree {
1455    type Target = Snapshot;
1456
1457    fn deref(&self) -> &Self::Target {
1458        match self {
1459            Worktree::Local(worktree) => &worktree.snapshot,
1460            Worktree::Remote(worktree) => &worktree.snapshot,
1461        }
1462    }
1463}
1464
1465impl Deref for LocalWorktree {
1466    type Target = LocalSnapshot;
1467
1468    fn deref(&self) -> &Self::Target {
1469        &self.snapshot
1470    }
1471}
1472
1473impl Deref for RemoteWorktree {
1474    type Target = Snapshot;
1475
1476    fn deref(&self) -> &Self::Target {
1477        &self.snapshot
1478    }
1479}
1480
1481impl fmt::Debug for LocalWorktree {
1482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1483        self.snapshot.fmt(f)
1484    }
1485}
1486
1487impl fmt::Debug for Snapshot {
1488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1489        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1490        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1491
1492        impl<'a> fmt::Debug for EntriesByPath<'a> {
1493            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494                f.debug_map()
1495                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1496                    .finish()
1497            }
1498        }
1499
1500        impl<'a> fmt::Debug for EntriesById<'a> {
1501            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1502                f.debug_list().entries(self.0.iter()).finish()
1503            }
1504        }
1505
1506        f.debug_struct("Snapshot")
1507            .field("id", &self.id)
1508            .field("root_name", &self.root_name)
1509            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1510            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1511            .finish()
1512    }
1513}
1514
1515#[derive(Clone, PartialEq)]
1516pub struct File {
1517    pub worktree: ModelHandle<Worktree>,
1518    pub path: Arc<Path>,
1519    pub mtime: SystemTime,
1520    pub(crate) entry_id: Option<ProjectEntryId>,
1521    pub(crate) is_local: bool,
1522}
1523
1524impl language::File for File {
1525    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1526        if self.is_local {
1527            Some(self)
1528        } else {
1529            None
1530        }
1531    }
1532
1533    fn mtime(&self) -> SystemTime {
1534        self.mtime
1535    }
1536
1537    fn path(&self) -> &Arc<Path> {
1538        &self.path
1539    }
1540
1541    fn full_path(&self, cx: &AppContext) -> PathBuf {
1542        let mut full_path = PathBuf::new();
1543        full_path.push(self.worktree.read(cx).root_name());
1544        if self.path.components().next().is_some() {
1545            full_path.push(&self.path);
1546        }
1547        full_path
1548    }
1549
1550    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1551    /// of its worktree, then this method will return the name of the worktree itself.
1552    fn file_name(&self, cx: &AppContext) -> OsString {
1553        self.path
1554            .file_name()
1555            .map(|name| name.into())
1556            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1557    }
1558
1559    fn is_deleted(&self) -> bool {
1560        self.entry_id.is_none()
1561    }
1562
1563    fn save(
1564        &self,
1565        buffer_id: u64,
1566        text: Rope,
1567        version: clock::Global,
1568        cx: &mut MutableAppContext,
1569    ) -> Task<Result<(clock::Global, SystemTime)>> {
1570        self.worktree.update(cx, |worktree, cx| match worktree {
1571            Worktree::Local(worktree) => {
1572                let rpc = worktree.client.clone();
1573                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1574                let save = worktree.write_file(self.path.clone(), text, cx);
1575                cx.background().spawn(async move {
1576                    let entry = save.await?;
1577                    if let Some(project_id) = project_id {
1578                        rpc.send(proto::BufferSaved {
1579                            project_id,
1580                            buffer_id,
1581                            version: serialize_version(&version),
1582                            mtime: Some(entry.mtime.into()),
1583                        })?;
1584                    }
1585                    Ok((version, entry.mtime))
1586                })
1587            }
1588            Worktree::Remote(worktree) => {
1589                let rpc = worktree.client.clone();
1590                let project_id = worktree.project_id;
1591                cx.foreground().spawn(async move {
1592                    let response = rpc
1593                        .request(proto::SaveBuffer {
1594                            project_id,
1595                            buffer_id,
1596                            version: serialize_version(&version),
1597                        })
1598                        .await?;
1599                    let version = deserialize_version(response.version);
1600                    let mtime = response
1601                        .mtime
1602                        .ok_or_else(|| anyhow!("missing mtime"))?
1603                        .into();
1604                    Ok((version, mtime))
1605                })
1606            }
1607        })
1608    }
1609
1610    fn as_any(&self) -> &dyn Any {
1611        self
1612    }
1613
1614    fn to_proto(&self) -> rpc::proto::File {
1615        rpc::proto::File {
1616            worktree_id: self.worktree.id() as u64,
1617            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1618            path: self.path.to_string_lossy().into(),
1619            mtime: Some(self.mtime.into()),
1620        }
1621    }
1622}
1623
1624impl language::LocalFile for File {
1625    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1626        self.worktree
1627            .read(cx)
1628            .as_local()
1629            .unwrap()
1630            .abs_path
1631            .join(&self.path)
1632    }
1633
1634    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1635        let worktree = self.worktree.read(cx).as_local().unwrap();
1636        let abs_path = worktree.absolutize(&self.path);
1637        let fs = worktree.fs.clone();
1638        cx.background()
1639            .spawn(async move { fs.load(&abs_path).await })
1640    }
1641
1642    fn buffer_reloaded(
1643        &self,
1644        buffer_id: u64,
1645        version: &clock::Global,
1646        mtime: SystemTime,
1647        cx: &mut MutableAppContext,
1648    ) {
1649        let worktree = self.worktree.read(cx).as_local().unwrap();
1650        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1651            worktree
1652                .client
1653                .send(proto::BufferReloaded {
1654                    project_id,
1655                    buffer_id,
1656                    version: serialize_version(&version),
1657                    mtime: Some(mtime.into()),
1658                })
1659                .log_err();
1660        }
1661    }
1662}
1663
1664impl File {
1665    pub fn from_proto(
1666        proto: rpc::proto::File,
1667        worktree: ModelHandle<Worktree>,
1668        cx: &AppContext,
1669    ) -> Result<Self> {
1670        let worktree_id = worktree
1671            .read(cx)
1672            .as_remote()
1673            .ok_or_else(|| anyhow!("not remote"))?
1674            .id();
1675
1676        if worktree_id.to_proto() != proto.worktree_id {
1677            return Err(anyhow!("worktree id does not match file"));
1678        }
1679
1680        Ok(Self {
1681            worktree,
1682            path: Path::new(&proto.path).into(),
1683            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1684            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1685            is_local: false,
1686        })
1687    }
1688
1689    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1690        file.and_then(|f| f.as_any().downcast_ref())
1691    }
1692
1693    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1694        self.worktree.read(cx).id()
1695    }
1696
1697    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1698        self.entry_id
1699    }
1700}
1701
1702#[derive(Clone, Debug, PartialEq, Eq)]
1703pub struct Entry {
1704    pub id: ProjectEntryId,
1705    pub kind: EntryKind,
1706    pub path: Arc<Path>,
1707    pub inode: u64,
1708    pub mtime: SystemTime,
1709    pub is_symlink: bool,
1710    pub is_ignored: bool,
1711}
1712
1713#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1714pub enum EntryKind {
1715    PendingDir,
1716    Dir,
1717    File(CharBag),
1718}
1719
1720impl Entry {
1721    fn new(
1722        path: Arc<Path>,
1723        metadata: &fs::Metadata,
1724        next_entry_id: &AtomicUsize,
1725        root_char_bag: CharBag,
1726    ) -> Self {
1727        Self {
1728            id: ProjectEntryId::new(next_entry_id),
1729            kind: if metadata.is_dir {
1730                EntryKind::PendingDir
1731            } else {
1732                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1733            },
1734            path,
1735            inode: metadata.inode,
1736            mtime: metadata.mtime,
1737            is_symlink: metadata.is_symlink,
1738            is_ignored: false,
1739        }
1740    }
1741
1742    pub fn is_dir(&self) -> bool {
1743        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1744    }
1745
1746    pub fn is_file(&self) -> bool {
1747        matches!(self.kind, EntryKind::File(_))
1748    }
1749}
1750
1751impl sum_tree::Item for Entry {
1752    type Summary = EntrySummary;
1753
1754    fn summary(&self) -> Self::Summary {
1755        let visible_count = if self.is_ignored { 0 } else { 1 };
1756        let file_count;
1757        let visible_file_count;
1758        if self.is_file() {
1759            file_count = 1;
1760            visible_file_count = visible_count;
1761        } else {
1762            file_count = 0;
1763            visible_file_count = 0;
1764        }
1765
1766        EntrySummary {
1767            max_path: self.path.clone(),
1768            count: 1,
1769            visible_count,
1770            file_count,
1771            visible_file_count,
1772        }
1773    }
1774}
1775
1776impl sum_tree::KeyedItem for Entry {
1777    type Key = PathKey;
1778
1779    fn key(&self) -> Self::Key {
1780        PathKey(self.path.clone())
1781    }
1782}
1783
1784#[derive(Clone, Debug)]
1785pub struct EntrySummary {
1786    max_path: Arc<Path>,
1787    count: usize,
1788    visible_count: usize,
1789    file_count: usize,
1790    visible_file_count: usize,
1791}
1792
1793impl Default for EntrySummary {
1794    fn default() -> Self {
1795        Self {
1796            max_path: Arc::from(Path::new("")),
1797            count: 0,
1798            visible_count: 0,
1799            file_count: 0,
1800            visible_file_count: 0,
1801        }
1802    }
1803}
1804
1805impl sum_tree::Summary for EntrySummary {
1806    type Context = ();
1807
1808    fn add_summary(&mut self, rhs: &Self, _: &()) {
1809        self.max_path = rhs.max_path.clone();
1810        self.visible_count += rhs.visible_count;
1811        self.file_count += rhs.file_count;
1812        self.visible_file_count += rhs.visible_file_count;
1813    }
1814}
1815
1816#[derive(Clone, Debug)]
1817struct PathEntry {
1818    id: ProjectEntryId,
1819    path: Arc<Path>,
1820    is_ignored: bool,
1821    scan_id: usize,
1822}
1823
1824impl sum_tree::Item for PathEntry {
1825    type Summary = PathEntrySummary;
1826
1827    fn summary(&self) -> Self::Summary {
1828        PathEntrySummary { max_id: self.id }
1829    }
1830}
1831
1832impl sum_tree::KeyedItem for PathEntry {
1833    type Key = ProjectEntryId;
1834
1835    fn key(&self) -> Self::Key {
1836        self.id
1837    }
1838}
1839
1840#[derive(Clone, Debug, Default)]
1841struct PathEntrySummary {
1842    max_id: ProjectEntryId,
1843}
1844
1845impl sum_tree::Summary for PathEntrySummary {
1846    type Context = ();
1847
1848    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1849        self.max_id = summary.max_id;
1850    }
1851}
1852
1853impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
1854    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1855        *self = summary.max_id;
1856    }
1857}
1858
1859#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1860pub struct PathKey(Arc<Path>);
1861
1862impl Default for PathKey {
1863    fn default() -> Self {
1864        Self(Path::new("").into())
1865    }
1866}
1867
1868impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1869    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1870        self.0 = summary.max_path.clone();
1871    }
1872}
1873
1874struct BackgroundScanner {
1875    fs: Arc<dyn Fs>,
1876    snapshot: Arc<Mutex<LocalSnapshot>>,
1877    notify: UnboundedSender<ScanState>,
1878    executor: Arc<executor::Background>,
1879}
1880
1881impl BackgroundScanner {
1882    fn new(
1883        snapshot: Arc<Mutex<LocalSnapshot>>,
1884        notify: UnboundedSender<ScanState>,
1885        fs: Arc<dyn Fs>,
1886        executor: Arc<executor::Background>,
1887    ) -> Self {
1888        Self {
1889            fs,
1890            snapshot,
1891            notify,
1892            executor,
1893        }
1894    }
1895
1896    fn abs_path(&self) -> Arc<Path> {
1897        self.snapshot.lock().abs_path.clone()
1898    }
1899
1900    fn snapshot(&self) -> LocalSnapshot {
1901        self.snapshot.lock().clone()
1902    }
1903
1904    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1905        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1906            return;
1907        }
1908
1909        if let Err(err) = self.scan_dirs().await {
1910            if self
1911                .notify
1912                .unbounded_send(ScanState::Err(Arc::new(err)))
1913                .is_err()
1914            {
1915                return;
1916            }
1917        }
1918
1919        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1920            return;
1921        }
1922
1923        futures::pin_mut!(events_rx);
1924        while let Some(events) = events_rx.next().await {
1925            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1926                break;
1927            }
1928
1929            if !self.process_events(events).await {
1930                break;
1931            }
1932
1933            if self.notify.unbounded_send(ScanState::Idle).is_err() {
1934                break;
1935            }
1936        }
1937    }
1938
1939    async fn scan_dirs(&mut self) -> Result<()> {
1940        let root_char_bag;
1941        let next_entry_id;
1942        let is_dir;
1943        {
1944            let snapshot = self.snapshot.lock();
1945            root_char_bag = snapshot.root_char_bag;
1946            next_entry_id = snapshot.next_entry_id.clone();
1947            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1948        };
1949
1950        if is_dir {
1951            let path: Arc<Path> = Arc::from(Path::new(""));
1952            let abs_path = self.abs_path();
1953            let (tx, rx) = channel::unbounded();
1954            self.executor
1955                .block(tx.send(ScanJob {
1956                    abs_path: abs_path.to_path_buf(),
1957                    path,
1958                    ignore_stack: IgnoreStack::none(),
1959                    scan_queue: tx.clone(),
1960                }))
1961                .unwrap();
1962            drop(tx);
1963
1964            self.executor
1965                .scoped(|scope| {
1966                    for _ in 0..self.executor.num_cpus() {
1967                        scope.spawn(async {
1968                            while let Ok(job) = rx.recv().await {
1969                                if let Err(err) = self
1970                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1971                                    .await
1972                                {
1973                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
1974                                }
1975                            }
1976                        });
1977                    }
1978                })
1979                .await;
1980        }
1981
1982        Ok(())
1983    }
1984
1985    async fn scan_dir(
1986        &self,
1987        root_char_bag: CharBag,
1988        next_entry_id: Arc<AtomicUsize>,
1989        job: &ScanJob,
1990    ) -> Result<()> {
1991        let mut new_entries: Vec<Entry> = Vec::new();
1992        let mut new_jobs: Vec<ScanJob> = Vec::new();
1993        let mut ignore_stack = job.ignore_stack.clone();
1994        let mut new_ignore = None;
1995
1996        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1997        while let Some(child_abs_path) = child_paths.next().await {
1998            let child_abs_path = match child_abs_path {
1999                Ok(child_abs_path) => child_abs_path,
2000                Err(error) => {
2001                    log::error!("error processing entry {:?}", error);
2002                    continue;
2003                }
2004            };
2005            let child_name = child_abs_path.file_name().unwrap();
2006            let child_path: Arc<Path> = job.path.join(child_name).into();
2007            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
2008                Some(metadata) => metadata,
2009                None => continue,
2010            };
2011
2012            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2013            if child_name == *GITIGNORE {
2014                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2015                    Ok(ignore) => {
2016                        let ignore = Arc::new(ignore);
2017                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2018                        new_ignore = Some(ignore);
2019                    }
2020                    Err(error) => {
2021                        log::error!(
2022                            "error loading .gitignore file {:?} - {:?}",
2023                            child_name,
2024                            error
2025                        );
2026                    }
2027                }
2028
2029                // Update ignore status of any child entries we've already processed to reflect the
2030                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2031                // there should rarely be too numerous. Update the ignore stack associated with any
2032                // new jobs as well.
2033                let mut new_jobs = new_jobs.iter_mut();
2034                for entry in &mut new_entries {
2035                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2036                    if entry.is_dir() {
2037                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2038                            IgnoreStack::all()
2039                        } else {
2040                            ignore_stack.clone()
2041                        };
2042                    }
2043                }
2044            }
2045
2046            let mut child_entry = Entry::new(
2047                child_path.clone(),
2048                &child_metadata,
2049                &next_entry_id,
2050                root_char_bag,
2051            );
2052
2053            if child_metadata.is_dir {
2054                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2055                child_entry.is_ignored = is_ignored;
2056                new_entries.push(child_entry);
2057                new_jobs.push(ScanJob {
2058                    abs_path: child_abs_path,
2059                    path: child_path,
2060                    ignore_stack: if is_ignored {
2061                        IgnoreStack::all()
2062                    } else {
2063                        ignore_stack.clone()
2064                    },
2065                    scan_queue: job.scan_queue.clone(),
2066                });
2067            } else {
2068                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2069                new_entries.push(child_entry);
2070            };
2071        }
2072
2073        self.snapshot
2074            .lock()
2075            .populate_dir(job.path.clone(), new_entries, new_ignore);
2076        for new_job in new_jobs {
2077            job.scan_queue.send(new_job).await.unwrap();
2078        }
2079
2080        Ok(())
2081    }
2082
2083    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2084        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2085        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2086
2087        let root_char_bag;
2088        let root_abs_path;
2089        let next_entry_id;
2090        {
2091            let mut snapshot = self.snapshot.lock();
2092            snapshot.scan_id += 1;
2093            root_char_bag = snapshot.root_char_bag;
2094            root_abs_path = snapshot.abs_path.clone();
2095            next_entry_id = snapshot.next_entry_id.clone();
2096        }
2097
2098        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2099            abs_path
2100        } else {
2101            return false;
2102        };
2103        let metadata = futures::future::join_all(
2104            events
2105                .iter()
2106                .map(|event| self.fs.metadata(&event.path))
2107                .collect::<Vec<_>>(),
2108        )
2109        .await;
2110
2111        // Hold the snapshot lock while clearing and re-inserting the root entries
2112        // for each event. This way, the snapshot is not observable to the foreground
2113        // thread while this operation is in-progress.
2114        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2115        {
2116            let mut snapshot = self.snapshot.lock();
2117            for event in &events {
2118                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2119                    snapshot.remove_path(&path);
2120                }
2121            }
2122
2123            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2124                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2125                    Ok(path) => Arc::from(path.to_path_buf()),
2126                    Err(_) => {
2127                        log::error!(
2128                            "unexpected event {:?} for root path {:?}",
2129                            event.path,
2130                            root_abs_path
2131                        );
2132                        continue;
2133                    }
2134                };
2135
2136                match metadata {
2137                    Ok(Some(metadata)) => {
2138                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2139                        let mut fs_entry = Entry::new(
2140                            path.clone(),
2141                            &metadata,
2142                            snapshot.next_entry_id.as_ref(),
2143                            snapshot.root_char_bag,
2144                        );
2145                        fs_entry.is_ignored = ignore_stack.is_all();
2146                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2147                        if metadata.is_dir {
2148                            self.executor
2149                                .block(scan_queue_tx.send(ScanJob {
2150                                    abs_path: event.path,
2151                                    path,
2152                                    ignore_stack,
2153                                    scan_queue: scan_queue_tx.clone(),
2154                                }))
2155                                .unwrap();
2156                        }
2157                    }
2158                    Ok(None) => {}
2159                    Err(err) => {
2160                        // TODO - create a special 'error' entry in the entries tree to mark this
2161                        log::error!("error reading file on event {:?}", err);
2162                    }
2163                }
2164            }
2165            drop(scan_queue_tx);
2166        }
2167
2168        // Scan any directories that were created as part of this event batch.
2169        self.executor
2170            .scoped(|scope| {
2171                for _ in 0..self.executor.num_cpus() {
2172                    scope.spawn(async {
2173                        while let Ok(job) = scan_queue_rx.recv().await {
2174                            if let Err(err) = self
2175                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2176                                .await
2177                            {
2178                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2179                            }
2180                        }
2181                    });
2182                }
2183            })
2184            .await;
2185
2186        // Attempt to detect renames only over a single batch of file-system events.
2187        self.snapshot.lock().removed_entry_ids.clear();
2188
2189        self.update_ignore_statuses().await;
2190        true
2191    }
2192
2193    async fn update_ignore_statuses(&self) {
2194        let mut snapshot = self.snapshot();
2195
2196        let mut ignores_to_update = Vec::new();
2197        let mut ignores_to_delete = Vec::new();
2198        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2199            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2200                ignores_to_update.push(parent_path.clone());
2201            }
2202
2203            let ignore_path = parent_path.join(&*GITIGNORE);
2204            if snapshot.entry_for_path(ignore_path).is_none() {
2205                ignores_to_delete.push(parent_path.clone());
2206            }
2207        }
2208
2209        for parent_path in ignores_to_delete {
2210            snapshot.ignores.remove(&parent_path);
2211            self.snapshot.lock().ignores.remove(&parent_path);
2212        }
2213
2214        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2215        ignores_to_update.sort_unstable();
2216        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2217        while let Some(parent_path) = ignores_to_update.next() {
2218            while ignores_to_update
2219                .peek()
2220                .map_or(false, |p| p.starts_with(&parent_path))
2221            {
2222                ignores_to_update.next().unwrap();
2223            }
2224
2225            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2226            ignore_queue_tx
2227                .send(UpdateIgnoreStatusJob {
2228                    path: parent_path,
2229                    ignore_stack,
2230                    ignore_queue: ignore_queue_tx.clone(),
2231                })
2232                .await
2233                .unwrap();
2234        }
2235        drop(ignore_queue_tx);
2236
2237        self.executor
2238            .scoped(|scope| {
2239                for _ in 0..self.executor.num_cpus() {
2240                    scope.spawn(async {
2241                        while let Ok(job) = ignore_queue_rx.recv().await {
2242                            self.update_ignore_status(job, &snapshot).await;
2243                        }
2244                    });
2245                }
2246            })
2247            .await;
2248    }
2249
2250    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2251        let mut ignore_stack = job.ignore_stack;
2252        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2253            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2254        }
2255
2256        let mut entries_by_id_edits = Vec::new();
2257        let mut entries_by_path_edits = Vec::new();
2258        for mut entry in snapshot.child_entries(&job.path).cloned() {
2259            let was_ignored = entry.is_ignored;
2260            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2261            if entry.is_dir() {
2262                let child_ignore_stack = if entry.is_ignored {
2263                    IgnoreStack::all()
2264                } else {
2265                    ignore_stack.clone()
2266                };
2267                job.ignore_queue
2268                    .send(UpdateIgnoreStatusJob {
2269                        path: entry.path.clone(),
2270                        ignore_stack: child_ignore_stack,
2271                        ignore_queue: job.ignore_queue.clone(),
2272                    })
2273                    .await
2274                    .unwrap();
2275            }
2276
2277            if entry.is_ignored != was_ignored {
2278                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2279                path_entry.scan_id = snapshot.scan_id;
2280                path_entry.is_ignored = entry.is_ignored;
2281                entries_by_id_edits.push(Edit::Insert(path_entry));
2282                entries_by_path_edits.push(Edit::Insert(entry));
2283            }
2284        }
2285
2286        let mut snapshot = self.snapshot.lock();
2287        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2288        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2289    }
2290}
2291
2292fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2293    let mut result = root_char_bag;
2294    result.extend(
2295        path.to_string_lossy()
2296            .chars()
2297            .map(|c| c.to_ascii_lowercase()),
2298    );
2299    result
2300}
2301
2302struct ScanJob {
2303    abs_path: PathBuf,
2304    path: Arc<Path>,
2305    ignore_stack: Arc<IgnoreStack>,
2306    scan_queue: Sender<ScanJob>,
2307}
2308
2309struct UpdateIgnoreStatusJob {
2310    path: Arc<Path>,
2311    ignore_stack: Arc<IgnoreStack>,
2312    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2313}
2314
2315pub trait WorktreeHandle {
2316    #[cfg(any(test, feature = "test-support"))]
2317    fn flush_fs_events<'a>(
2318        &self,
2319        cx: &'a gpui::TestAppContext,
2320    ) -> futures::future::LocalBoxFuture<'a, ()>;
2321}
2322
2323impl WorktreeHandle for ModelHandle<Worktree> {
2324    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2325    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2326    // extra directory scans, and emit extra scan-state notifications.
2327    //
2328    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2329    // to ensure that all redundant FS events have already been processed.
2330    #[cfg(any(test, feature = "test-support"))]
2331    fn flush_fs_events<'a>(
2332        &self,
2333        cx: &'a gpui::TestAppContext,
2334    ) -> futures::future::LocalBoxFuture<'a, ()> {
2335        use smol::future::FutureExt;
2336
2337        let filename = "fs-event-sentinel";
2338        let tree = self.clone();
2339        let (fs, root_path) = self.read_with(cx, |tree, _| {
2340            let tree = tree.as_local().unwrap();
2341            (tree.fs.clone(), tree.abs_path().clone())
2342        });
2343
2344        async move {
2345            fs.create_file(&root_path.join(filename), Default::default())
2346                .await
2347                .unwrap();
2348            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2349                .await;
2350
2351            fs.remove_file(&root_path.join(filename), Default::default())
2352                .await
2353                .unwrap();
2354            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2355                .await;
2356
2357            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2358                .await;
2359        }
2360        .boxed_local()
2361    }
2362}
2363
2364#[derive(Clone, Debug)]
2365struct TraversalProgress<'a> {
2366    max_path: &'a Path,
2367    count: usize,
2368    visible_count: usize,
2369    file_count: usize,
2370    visible_file_count: usize,
2371}
2372
2373impl<'a> TraversalProgress<'a> {
2374    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2375        match (include_ignored, include_dirs) {
2376            (true, true) => self.count,
2377            (true, false) => self.file_count,
2378            (false, true) => self.visible_count,
2379            (false, false) => self.visible_file_count,
2380        }
2381    }
2382}
2383
2384impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2385    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2386        self.max_path = summary.max_path.as_ref();
2387        self.count += summary.count;
2388        self.visible_count += summary.visible_count;
2389        self.file_count += summary.file_count;
2390        self.visible_file_count += summary.visible_file_count;
2391    }
2392}
2393
2394impl<'a> Default for TraversalProgress<'a> {
2395    fn default() -> Self {
2396        Self {
2397            max_path: Path::new(""),
2398            count: 0,
2399            visible_count: 0,
2400            file_count: 0,
2401            visible_file_count: 0,
2402        }
2403    }
2404}
2405
2406pub struct Traversal<'a> {
2407    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2408    include_ignored: bool,
2409    include_dirs: bool,
2410}
2411
2412impl<'a> Traversal<'a> {
2413    pub fn advance(&mut self) -> bool {
2414        self.advance_to_offset(self.offset() + 1)
2415    }
2416
2417    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2418        self.cursor.seek_forward(
2419            &TraversalTarget::Count {
2420                count: offset,
2421                include_dirs: self.include_dirs,
2422                include_ignored: self.include_ignored,
2423            },
2424            Bias::Right,
2425            &(),
2426        )
2427    }
2428
2429    pub fn advance_to_sibling(&mut self) -> bool {
2430        while let Some(entry) = self.cursor.item() {
2431            self.cursor.seek_forward(
2432                &TraversalTarget::PathSuccessor(&entry.path),
2433                Bias::Left,
2434                &(),
2435            );
2436            if let Some(entry) = self.cursor.item() {
2437                if (self.include_dirs || !entry.is_dir())
2438                    && (self.include_ignored || !entry.is_ignored)
2439                {
2440                    return true;
2441                }
2442            }
2443        }
2444        false
2445    }
2446
2447    pub fn entry(&self) -> Option<&'a Entry> {
2448        self.cursor.item()
2449    }
2450
2451    pub fn offset(&self) -> usize {
2452        self.cursor
2453            .start()
2454            .count(self.include_dirs, self.include_ignored)
2455    }
2456}
2457
2458impl<'a> Iterator for Traversal<'a> {
2459    type Item = &'a Entry;
2460
2461    fn next(&mut self) -> Option<Self::Item> {
2462        if let Some(item) = self.entry() {
2463            self.advance();
2464            Some(item)
2465        } else {
2466            None
2467        }
2468    }
2469}
2470
2471#[derive(Debug)]
2472enum TraversalTarget<'a> {
2473    Path(&'a Path),
2474    PathSuccessor(&'a Path),
2475    Count {
2476        count: usize,
2477        include_ignored: bool,
2478        include_dirs: bool,
2479    },
2480}
2481
2482impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2483    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2484        match self {
2485            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2486            TraversalTarget::PathSuccessor(path) => {
2487                if !cursor_location.max_path.starts_with(path) {
2488                    Ordering::Equal
2489                } else {
2490                    Ordering::Greater
2491                }
2492            }
2493            TraversalTarget::Count {
2494                count,
2495                include_dirs,
2496                include_ignored,
2497            } => Ord::cmp(
2498                count,
2499                &cursor_location.count(*include_dirs, *include_ignored),
2500            ),
2501        }
2502    }
2503}
2504
2505struct ChildEntriesIter<'a> {
2506    parent_path: &'a Path,
2507    traversal: Traversal<'a>,
2508}
2509
2510impl<'a> Iterator for ChildEntriesIter<'a> {
2511    type Item = &'a Entry;
2512
2513    fn next(&mut self) -> Option<Self::Item> {
2514        if let Some(item) = self.traversal.entry() {
2515            if item.path.starts_with(&self.parent_path) {
2516                self.traversal.advance_to_sibling();
2517                return Some(item);
2518            }
2519        }
2520        None
2521    }
2522}
2523
2524impl<'a> From<&'a Entry> for proto::Entry {
2525    fn from(entry: &'a Entry) -> Self {
2526        Self {
2527            id: entry.id.to_proto(),
2528            is_dir: entry.is_dir(),
2529            path: entry.path.as_os_str().as_bytes().to_vec(),
2530            inode: entry.inode,
2531            mtime: Some(entry.mtime.into()),
2532            is_symlink: entry.is_symlink,
2533            is_ignored: entry.is_ignored,
2534        }
2535    }
2536}
2537
2538impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2539    type Error = anyhow::Error;
2540
2541    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2542        if let Some(mtime) = entry.mtime {
2543            let kind = if entry.is_dir {
2544                EntryKind::Dir
2545            } else {
2546                let mut char_bag = root_char_bag.clone();
2547                char_bag.extend(
2548                    String::from_utf8_lossy(&entry.path)
2549                        .chars()
2550                        .map(|c| c.to_ascii_lowercase()),
2551                );
2552                EntryKind::File(char_bag)
2553            };
2554            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2555            Ok(Entry {
2556                id: ProjectEntryId::from_proto(entry.id),
2557                kind,
2558                path: path.clone(),
2559                inode: entry.inode,
2560                mtime: mtime.into(),
2561                is_symlink: entry.is_symlink,
2562                is_ignored: entry.is_ignored,
2563            })
2564        } else {
2565            Err(anyhow!(
2566                "missing mtime in remote worktree entry {:?}",
2567                entry.path
2568            ))
2569        }
2570    }
2571}
2572
2573#[cfg(test)]
2574mod tests {
2575    use super::*;
2576    use crate::fs::FakeFs;
2577    use anyhow::Result;
2578    use client::test::FakeHttpClient;
2579    use fs::RealFs;
2580    use rand::prelude::*;
2581    use serde_json::json;
2582    use std::{
2583        env,
2584        fmt::Write,
2585        time::{SystemTime, UNIX_EPOCH},
2586    };
2587    use util::test::temp_tree;
2588
2589    #[gpui::test]
2590    async fn test_traversal(cx: &mut gpui::TestAppContext) {
2591        let fs = FakeFs::new(cx.background());
2592        fs.insert_tree(
2593            "/root",
2594            json!({
2595               ".gitignore": "a/b\n",
2596               "a": {
2597                   "b": "",
2598                   "c": "",
2599               }
2600            }),
2601        )
2602        .await;
2603
2604        let http_client = FakeHttpClient::with_404_response();
2605        let client = Client::new(http_client);
2606
2607        let tree = Worktree::local(
2608            client,
2609            Arc::from(Path::new("/root")),
2610            true,
2611            fs,
2612            Default::default(),
2613            &mut cx.to_async(),
2614        )
2615        .await
2616        .unwrap();
2617        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2618            .await;
2619
2620        tree.read_with(cx, |tree, _| {
2621            assert_eq!(
2622                tree.entries(false)
2623                    .map(|entry| entry.path.as_ref())
2624                    .collect::<Vec<_>>(),
2625                vec![
2626                    Path::new(""),
2627                    Path::new(".gitignore"),
2628                    Path::new("a"),
2629                    Path::new("a/c"),
2630                ]
2631            );
2632        })
2633    }
2634
2635    #[gpui::test]
2636    async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2637        let dir = temp_tree(json!({
2638            ".git": {},
2639            ".gitignore": "ignored-dir\n",
2640            "tracked-dir": {
2641                "tracked-file1": "tracked contents",
2642            },
2643            "ignored-dir": {
2644                "ignored-file1": "ignored contents",
2645            }
2646        }));
2647
2648        let http_client = FakeHttpClient::with_404_response();
2649        let client = Client::new(http_client.clone());
2650
2651        let tree = Worktree::local(
2652            client,
2653            dir.path(),
2654            true,
2655            Arc::new(RealFs),
2656            Default::default(),
2657            &mut cx.to_async(),
2658        )
2659        .await
2660        .unwrap();
2661        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2662            .await;
2663        tree.flush_fs_events(&cx).await;
2664        cx.read(|cx| {
2665            let tree = tree.read(cx);
2666            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2667            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2668            assert_eq!(tracked.is_ignored, false);
2669            assert_eq!(ignored.is_ignored, true);
2670        });
2671
2672        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2673        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2674        tree.flush_fs_events(&cx).await;
2675        cx.read(|cx| {
2676            let tree = tree.read(cx);
2677            let dot_git = tree.entry_for_path(".git").unwrap();
2678            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2679            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2680            assert_eq!(tracked.is_ignored, false);
2681            assert_eq!(ignored.is_ignored, true);
2682            assert_eq!(dot_git.is_ignored, true);
2683        });
2684    }
2685
2686    #[gpui::test(iterations = 100)]
2687    fn test_random(mut rng: StdRng) {
2688        let operations = env::var("OPERATIONS")
2689            .map(|o| o.parse().unwrap())
2690            .unwrap_or(40);
2691        let initial_entries = env::var("INITIAL_ENTRIES")
2692            .map(|o| o.parse().unwrap())
2693            .unwrap_or(20);
2694
2695        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2696        for _ in 0..initial_entries {
2697            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2698        }
2699        log::info!("Generated initial tree");
2700
2701        let (notify_tx, _notify_rx) = mpsc::unbounded();
2702        let fs = Arc::new(RealFs);
2703        let next_entry_id = Arc::new(AtomicUsize::new(0));
2704        let mut initial_snapshot = LocalSnapshot {
2705            abs_path: root_dir.path().into(),
2706            scan_id: 0,
2707            removed_entry_ids: Default::default(),
2708            ignores: Default::default(),
2709            next_entry_id: next_entry_id.clone(),
2710            snapshot: Snapshot {
2711                id: WorktreeId::from_usize(0),
2712                entries_by_path: Default::default(),
2713                entries_by_id: Default::default(),
2714                root_name: Default::default(),
2715                root_char_bag: Default::default(),
2716            },
2717        };
2718        initial_snapshot.insert_entry(
2719            Entry::new(
2720                Path::new("").into(),
2721                &smol::block_on(fs.metadata(root_dir.path()))
2722                    .unwrap()
2723                    .unwrap(),
2724                &next_entry_id,
2725                Default::default(),
2726            ),
2727            fs.as_ref(),
2728        );
2729        let mut scanner = BackgroundScanner::new(
2730            Arc::new(Mutex::new(initial_snapshot.clone())),
2731            notify_tx,
2732            fs.clone(),
2733            Arc::new(gpui::executor::Background::new()),
2734        );
2735        smol::block_on(scanner.scan_dirs()).unwrap();
2736        scanner.snapshot().check_invariants();
2737
2738        let mut events = Vec::new();
2739        let mut snapshots = Vec::new();
2740        let mut mutations_len = operations;
2741        while mutations_len > 1 {
2742            if !events.is_empty() && rng.gen_bool(0.4) {
2743                let len = rng.gen_range(0..=events.len());
2744                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2745                log::info!("Delivering events: {:#?}", to_deliver);
2746                smol::block_on(scanner.process_events(to_deliver));
2747                scanner.snapshot().check_invariants();
2748            } else {
2749                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2750                mutations_len -= 1;
2751            }
2752
2753            if rng.gen_bool(0.2) {
2754                snapshots.push(scanner.snapshot());
2755            }
2756        }
2757        log::info!("Quiescing: {:#?}", events);
2758        smol::block_on(scanner.process_events(events));
2759        scanner.snapshot().check_invariants();
2760
2761        let (notify_tx, _notify_rx) = mpsc::unbounded();
2762        let mut new_scanner = BackgroundScanner::new(
2763            Arc::new(Mutex::new(initial_snapshot)),
2764            notify_tx,
2765            scanner.fs.clone(),
2766            scanner.executor.clone(),
2767        );
2768        smol::block_on(new_scanner.scan_dirs()).unwrap();
2769        assert_eq!(
2770            scanner.snapshot().to_vec(true),
2771            new_scanner.snapshot().to_vec(true)
2772        );
2773
2774        for mut prev_snapshot in snapshots {
2775            let include_ignored = rng.gen::<bool>();
2776            if !include_ignored {
2777                let mut entries_by_path_edits = Vec::new();
2778                let mut entries_by_id_edits = Vec::new();
2779                for entry in prev_snapshot
2780                    .entries_by_id
2781                    .cursor::<()>()
2782                    .filter(|e| e.is_ignored)
2783                {
2784                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2785                    entries_by_id_edits.push(Edit::Remove(entry.id));
2786                }
2787
2788                prev_snapshot
2789                    .entries_by_path
2790                    .edit(entries_by_path_edits, &());
2791                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2792            }
2793
2794            let update = scanner
2795                .snapshot()
2796                .build_update(&prev_snapshot, 0, 0, include_ignored);
2797            prev_snapshot.apply_remote_update(update).unwrap();
2798            assert_eq!(
2799                prev_snapshot.to_vec(true),
2800                scanner.snapshot().to_vec(include_ignored)
2801            );
2802        }
2803    }
2804
2805    fn randomly_mutate_tree(
2806        root_path: &Path,
2807        insertion_probability: f64,
2808        rng: &mut impl Rng,
2809    ) -> Result<Vec<fsevent::Event>> {
2810        let root_path = root_path.canonicalize().unwrap();
2811        let (dirs, files) = read_dir_recursive(root_path.clone());
2812
2813        let mut events = Vec::new();
2814        let mut record_event = |path: PathBuf| {
2815            events.push(fsevent::Event {
2816                event_id: SystemTime::now()
2817                    .duration_since(UNIX_EPOCH)
2818                    .unwrap()
2819                    .as_secs(),
2820                flags: fsevent::StreamFlags::empty(),
2821                path,
2822            });
2823        };
2824
2825        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2826            let path = dirs.choose(rng).unwrap();
2827            let new_path = path.join(gen_name(rng));
2828
2829            if rng.gen() {
2830                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2831                std::fs::create_dir(&new_path)?;
2832            } else {
2833                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2834                std::fs::write(&new_path, "")?;
2835            }
2836            record_event(new_path);
2837        } else if rng.gen_bool(0.05) {
2838            let ignore_dir_path = dirs.choose(rng).unwrap();
2839            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2840
2841            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2842            let files_to_ignore = {
2843                let len = rng.gen_range(0..=subfiles.len());
2844                subfiles.choose_multiple(rng, len)
2845            };
2846            let dirs_to_ignore = {
2847                let len = rng.gen_range(0..subdirs.len());
2848                subdirs.choose_multiple(rng, len)
2849            };
2850
2851            let mut ignore_contents = String::new();
2852            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2853                write!(
2854                    ignore_contents,
2855                    "{}\n",
2856                    path_to_ignore
2857                        .strip_prefix(&ignore_dir_path)?
2858                        .to_str()
2859                        .unwrap()
2860                )
2861                .unwrap();
2862            }
2863            log::info!(
2864                "Creating {:?} with contents:\n{}",
2865                ignore_path.strip_prefix(&root_path)?,
2866                ignore_contents
2867            );
2868            std::fs::write(&ignore_path, ignore_contents).unwrap();
2869            record_event(ignore_path);
2870        } else {
2871            let old_path = {
2872                let file_path = files.choose(rng);
2873                let dir_path = dirs[1..].choose(rng);
2874                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2875            };
2876
2877            let is_rename = rng.gen();
2878            if is_rename {
2879                let new_path_parent = dirs
2880                    .iter()
2881                    .filter(|d| !d.starts_with(old_path))
2882                    .choose(rng)
2883                    .unwrap();
2884
2885                let overwrite_existing_dir =
2886                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2887                let new_path = if overwrite_existing_dir {
2888                    std::fs::remove_dir_all(&new_path_parent).ok();
2889                    new_path_parent.to_path_buf()
2890                } else {
2891                    new_path_parent.join(gen_name(rng))
2892                };
2893
2894                log::info!(
2895                    "Renaming {:?} to {}{:?}",
2896                    old_path.strip_prefix(&root_path)?,
2897                    if overwrite_existing_dir {
2898                        "overwrite "
2899                    } else {
2900                        ""
2901                    },
2902                    new_path.strip_prefix(&root_path)?
2903                );
2904                std::fs::rename(&old_path, &new_path)?;
2905                record_event(old_path.clone());
2906                record_event(new_path);
2907            } else if old_path.is_dir() {
2908                let (dirs, files) = read_dir_recursive(old_path.clone());
2909
2910                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2911                std::fs::remove_dir_all(&old_path).unwrap();
2912                for file in files {
2913                    record_event(file);
2914                }
2915                for dir in dirs {
2916                    record_event(dir);
2917                }
2918            } else {
2919                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2920                std::fs::remove_file(old_path).unwrap();
2921                record_event(old_path.clone());
2922            }
2923        }
2924
2925        Ok(events)
2926    }
2927
2928    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2929        let child_entries = std::fs::read_dir(&path).unwrap();
2930        let mut dirs = vec![path];
2931        let mut files = Vec::new();
2932        for child_entry in child_entries {
2933            let child_path = child_entry.unwrap().path();
2934            if child_path.is_dir() {
2935                let (child_dirs, child_files) = read_dir_recursive(child_path);
2936                dirs.extend(child_dirs);
2937                files.extend(child_files);
2938            } else {
2939                files.push(child_path);
2940            }
2941        }
2942        (dirs, files)
2943    }
2944
2945    fn gen_name(rng: &mut impl Rng) -> String {
2946        (0..6)
2947            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2948            .map(char::from)
2949            .collect()
2950    }
2951
2952    impl LocalSnapshot {
2953        fn check_invariants(&self) {
2954            let mut files = self.files(true, 0);
2955            let mut visible_files = self.files(false, 0);
2956            for entry in self.entries_by_path.cursor::<()>() {
2957                if entry.is_file() {
2958                    assert_eq!(files.next().unwrap().inode, entry.inode);
2959                    if !entry.is_ignored {
2960                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2961                    }
2962                }
2963            }
2964            assert!(files.next().is_none());
2965            assert!(visible_files.next().is_none());
2966
2967            let mut bfs_paths = Vec::new();
2968            let mut stack = vec![Path::new("")];
2969            while let Some(path) = stack.pop() {
2970                bfs_paths.push(path);
2971                let ix = stack.len();
2972                for child_entry in self.child_entries(path) {
2973                    stack.insert(ix, &child_entry.path);
2974                }
2975            }
2976
2977            let dfs_paths = self
2978                .entries_by_path
2979                .cursor::<()>()
2980                .map(|e| e.path.as_ref())
2981                .collect::<Vec<_>>();
2982            assert_eq!(bfs_paths, dfs_paths);
2983
2984            for (ignore_parent_path, _) in &self.ignores {
2985                assert!(self.entry_for_path(ignore_parent_path).is_some());
2986                assert!(self
2987                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2988                    .is_some());
2989            }
2990        }
2991
2992        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2993            let mut paths = Vec::new();
2994            for entry in self.entries_by_path.cursor::<()>() {
2995                if include_ignored || !entry.is_ignored {
2996                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2997                }
2998            }
2999            paths.sort_by(|a, b| a.0.cmp(&b.0));
3000            paths
3001        }
3002    }
3003}