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 write_file(
 690        &self,
 691        path: impl Into<Arc<Path>>,
 692        text: Rope,
 693        cx: &mut ModelContext<Worktree>,
 694    ) -> Task<Result<Entry>> {
 695        let path = path.into();
 696        let abs_path = self.absolutize(&path);
 697        let save = cx.background().spawn({
 698            let fs = self.fs.clone();
 699            let abs_path = abs_path.clone();
 700            async move { fs.save(&abs_path, &text).await }
 701        });
 702
 703        cx.spawn(|this, mut cx| async move {
 704            save.await?;
 705            let entry = this
 706                .update(&mut cx, |this, _| {
 707                    this.as_local_mut()
 708                        .unwrap()
 709                        .refresh_entry(path, abs_path, None)
 710                })
 711                .await?;
 712            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 713            Ok(entry)
 714        })
 715    }
 716
 717    pub fn rename_entry(
 718        &self,
 719        entry_id: ProjectEntryId,
 720        new_path: impl Into<Arc<Path>>,
 721        cx: &mut ModelContext<Worktree>,
 722    ) -> Option<Task<Result<Entry>>> {
 723        let old_path = self.entry_for_id(entry_id)?.path.clone();
 724        let new_path = new_path.into();
 725        let abs_old_path = self.absolutize(&old_path);
 726        let abs_new_path = self.absolutize(&new_path);
 727        let rename = cx.background().spawn({
 728            let fs = self.fs.clone();
 729            let abs_new_path = abs_new_path.clone();
 730            async move {
 731                fs.rename(&abs_old_path, &abs_new_path, Default::default())
 732                    .await
 733            }
 734        });
 735
 736        Some(cx.spawn(|this, mut cx| async move {
 737            rename.await?;
 738            let entry = this
 739                .update(&mut cx, |this, _| {
 740                    this.as_local_mut().unwrap().refresh_entry(
 741                        new_path.clone(),
 742                        abs_new_path,
 743                        Some(old_path),
 744                    )
 745                })
 746                .await?;
 747            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 748            Ok(entry)
 749        }))
 750    }
 751
 752    fn refresh_entry(
 753        &self,
 754        path: Arc<Path>,
 755        abs_path: PathBuf,
 756        old_path: Option<Arc<Path>>,
 757    ) -> impl Future<Output = Result<Entry>> {
 758        let root_char_bag;
 759        let next_entry_id;
 760        let fs = self.fs.clone();
 761        let shared_snapshots_tx = self.share.as_ref().map(|share| share.snapshots_tx.clone());
 762        let snapshot = self.background_snapshot.clone();
 763        {
 764            let snapshot = snapshot.lock();
 765            root_char_bag = snapshot.root_char_bag;
 766            next_entry_id = snapshot.next_entry_id.clone();
 767        }
 768        async move {
 769            let entry = Entry::new(
 770                path,
 771                &fs.metadata(&abs_path)
 772                    .await?
 773                    .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
 774                &next_entry_id,
 775                root_char_bag,
 776            );
 777            let mut snapshot = snapshot.lock();
 778            if let Some(old_path) = old_path {
 779                snapshot.remove_path(&old_path);
 780            }
 781            let entry = snapshot.insert_entry(entry, fs.as_ref());
 782            if let Some(tx) = shared_snapshots_tx {
 783                tx.send(snapshot.clone()).await.ok();
 784            }
 785            Ok(entry)
 786        }
 787    }
 788
 789    pub fn register(
 790        &mut self,
 791        project_id: u64,
 792        cx: &mut ModelContext<Worktree>,
 793    ) -> Task<anyhow::Result<()>> {
 794        if self.registration != Registration::None {
 795            return Task::ready(Ok(()));
 796        }
 797
 798        self.registration = Registration::Pending;
 799        let client = self.client.clone();
 800        let register_message = proto::RegisterWorktree {
 801            project_id,
 802            worktree_id: self.id().to_proto(),
 803            root_name: self.root_name().to_string(),
 804            authorized_logins: self.authorized_logins(),
 805            visible: self.visible,
 806        };
 807        let request = client.request(register_message);
 808        cx.spawn(|this, mut cx| async move {
 809            let response = request.await;
 810            this.update(&mut cx, |this, _| {
 811                let worktree = this.as_local_mut().unwrap();
 812                match response {
 813                    Ok(_) => {
 814                        if worktree.registration == Registration::Pending {
 815                            worktree.registration = Registration::Done { project_id };
 816                        }
 817                        Ok(())
 818                    }
 819                    Err(error) => {
 820                        worktree.registration = Registration::None;
 821                        Err(error)
 822                    }
 823                }
 824            })
 825        })
 826    }
 827
 828    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 829        let register = self.register(project_id, cx);
 830        let (share_tx, share_rx) = oneshot::channel();
 831        let (snapshots_to_send_tx, snapshots_to_send_rx) =
 832            smol::channel::unbounded::<LocalSnapshot>();
 833        if self.share.is_some() {
 834            let _ = share_tx.send(Ok(()));
 835        } else {
 836            let rpc = self.client.clone();
 837            let worktree_id = cx.model_id() as u64;
 838            let maintain_remote_snapshot = cx.background().spawn({
 839                let rpc = rpc.clone();
 840                let diagnostic_summaries = self.diagnostic_summaries.clone();
 841                async move {
 842                    let mut prev_snapshot = match snapshots_to_send_rx.recv().await {
 843                        Ok(snapshot) => {
 844                            if let Err(error) = rpc
 845                                .request(proto::UpdateWorktree {
 846                                    project_id,
 847                                    worktree_id,
 848                                    root_name: snapshot.root_name().to_string(),
 849                                    updated_entries: snapshot
 850                                        .entries_by_path
 851                                        .iter()
 852                                        .filter(|e| !e.is_ignored)
 853                                        .map(Into::into)
 854                                        .collect(),
 855                                    removed_entries: Default::default(),
 856                                })
 857                                .await
 858                            {
 859                                let _ = share_tx.send(Err(error));
 860                                return Err(anyhow!("failed to send initial update worktree"));
 861                            } else {
 862                                let _ = share_tx.send(Ok(()));
 863                                snapshot
 864                            }
 865                        }
 866                        Err(error) => {
 867                            let _ = share_tx.send(Err(error.into()));
 868                            return Err(anyhow!("failed to send initial update worktree"));
 869                        }
 870                    };
 871
 872                    for (path, summary) in diagnostic_summaries.iter() {
 873                        rpc.send(proto::UpdateDiagnosticSummary {
 874                            project_id,
 875                            worktree_id,
 876                            summary: Some(summary.to_proto(&path.0)),
 877                        })?;
 878                    }
 879
 880                    while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
 881                        let message =
 882                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, false);
 883                        rpc.request(message).await?;
 884                        prev_snapshot = snapshot;
 885                    }
 886
 887                    Ok::<_, anyhow::Error>(())
 888                }
 889                .log_err()
 890            });
 891            self.share = Some(ShareState {
 892                project_id,
 893                snapshots_tx: snapshots_to_send_tx.clone(),
 894                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
 895            });
 896        }
 897
 898        cx.spawn_weak(|this, cx| async move {
 899            register.await?;
 900            if let Some(this) = this.upgrade(&cx) {
 901                this.read_with(&cx, |this, _| {
 902                    let this = this.as_local().unwrap();
 903                    let _ = snapshots_to_send_tx.try_send(this.snapshot());
 904                });
 905            }
 906            share_rx
 907                .await
 908                .unwrap_or_else(|_| Err(anyhow!("share ended")))
 909        })
 910    }
 911
 912    pub fn unregister(&mut self) {
 913        self.unshare();
 914        self.registration = Registration::None;
 915    }
 916
 917    pub fn unshare(&mut self) {
 918        self.share.take();
 919    }
 920
 921    pub fn is_shared(&self) -> bool {
 922        self.share.is_some()
 923    }
 924}
 925
 926impl RemoteWorktree {
 927    fn snapshot(&self) -> Snapshot {
 928        self.snapshot.clone()
 929    }
 930
 931    pub fn update_from_remote(
 932        &mut self,
 933        envelope: TypedEnvelope<proto::UpdateWorktree>,
 934    ) -> Result<()> {
 935        self.updates_tx
 936            .unbounded_send(BackgroundUpdate::Update(envelope.payload))
 937            .expect("consumer runs to completion");
 938        Ok(())
 939    }
 940
 941    pub fn finish_pending_remote_updates(&self) -> impl Future<Output = ()> {
 942        let (tx, mut rx) = barrier::channel();
 943        self.updates_tx
 944            .unbounded_send(BackgroundUpdate::Barrier(tx))
 945            .expect("consumer runs to completion");
 946        async move {
 947            rx.recv().await;
 948        }
 949    }
 950
 951    pub fn update_diagnostic_summary(
 952        &mut self,
 953        path: Arc<Path>,
 954        summary: &proto::DiagnosticSummary,
 955    ) {
 956        let summary = DiagnosticSummary {
 957            error_count: summary.error_count as usize,
 958            warning_count: summary.warning_count as usize,
 959        };
 960        if summary.is_empty() {
 961            self.diagnostic_summaries.remove(&PathKey(path.clone()));
 962        } else {
 963            self.diagnostic_summaries
 964                .insert(PathKey(path.clone()), summary);
 965        }
 966    }
 967
 968    pub fn insert_entry(
 969        &self,
 970        entry: proto::Entry,
 971        cx: &mut ModelContext<Worktree>,
 972    ) -> Task<Result<Entry>> {
 973        cx.spawn(|this, mut cx| async move {
 974            this.update(&mut cx, |worktree, _| {
 975                worktree
 976                    .as_remote_mut()
 977                    .unwrap()
 978                    .finish_pending_remote_updates()
 979            })
 980            .await;
 981            this.update(&mut cx, |worktree, _| {
 982                let worktree = worktree.as_remote_mut().unwrap();
 983                let mut snapshot = worktree.background_snapshot.lock();
 984                let entry = snapshot.insert_entry(entry);
 985                worktree.snapshot = snapshot.clone();
 986                entry
 987            })
 988        })
 989    }
 990}
 991
 992impl Snapshot {
 993    pub fn id(&self) -> WorktreeId {
 994        self.id
 995    }
 996
 997    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
 998        self.entries_by_id.get(&entry_id, &()).is_some()
 999    }
1000
1001    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1002        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1003        let old_entry = self.entries_by_id.insert_or_replace(
1004            PathEntry {
1005                id: entry.id,
1006                path: entry.path.clone(),
1007                is_ignored: entry.is_ignored,
1008                scan_id: 0,
1009            },
1010            &(),
1011        );
1012        if let Some(old_entry) = old_entry {
1013            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1014        }
1015        self.entries_by_path.insert_or_replace(entry.clone(), &());
1016        Ok(entry)
1017    }
1018
1019    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1020        let mut entries_by_path_edits = Vec::new();
1021        let mut entries_by_id_edits = Vec::new();
1022        for entry_id in update.removed_entries {
1023            let entry = self
1024                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1025                .ok_or_else(|| anyhow!("unknown entry"))?;
1026            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1027            entries_by_id_edits.push(Edit::Remove(entry.id));
1028        }
1029
1030        for entry in update.updated_entries {
1031            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1032            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1033                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1034            }
1035            entries_by_id_edits.push(Edit::Insert(PathEntry {
1036                id: entry.id,
1037                path: entry.path.clone(),
1038                is_ignored: entry.is_ignored,
1039                scan_id: 0,
1040            }));
1041            entries_by_path_edits.push(Edit::Insert(entry));
1042        }
1043
1044        self.entries_by_path.edit(entries_by_path_edits, &());
1045        self.entries_by_id.edit(entries_by_id_edits, &());
1046
1047        Ok(())
1048    }
1049
1050    pub fn file_count(&self) -> usize {
1051        self.entries_by_path.summary().file_count
1052    }
1053
1054    pub fn visible_file_count(&self) -> usize {
1055        self.entries_by_path.summary().visible_file_count
1056    }
1057
1058    fn traverse_from_offset(
1059        &self,
1060        include_dirs: bool,
1061        include_ignored: bool,
1062        start_offset: usize,
1063    ) -> Traversal {
1064        let mut cursor = self.entries_by_path.cursor();
1065        cursor.seek(
1066            &TraversalTarget::Count {
1067                count: start_offset,
1068                include_dirs,
1069                include_ignored,
1070            },
1071            Bias::Right,
1072            &(),
1073        );
1074        Traversal {
1075            cursor,
1076            include_dirs,
1077            include_ignored,
1078        }
1079    }
1080
1081    fn traverse_from_path(
1082        &self,
1083        include_dirs: bool,
1084        include_ignored: bool,
1085        path: &Path,
1086    ) -> Traversal {
1087        let mut cursor = self.entries_by_path.cursor();
1088        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1089        Traversal {
1090            cursor,
1091            include_dirs,
1092            include_ignored,
1093        }
1094    }
1095
1096    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1097        self.traverse_from_offset(false, include_ignored, start)
1098    }
1099
1100    pub fn entries(&self, include_ignored: bool) -> Traversal {
1101        self.traverse_from_offset(true, include_ignored, 0)
1102    }
1103
1104    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1105        let empty_path = Path::new("");
1106        self.entries_by_path
1107            .cursor::<()>()
1108            .filter(move |entry| entry.path.as_ref() != empty_path)
1109            .map(|entry| &entry.path)
1110    }
1111
1112    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1113        let mut cursor = self.entries_by_path.cursor();
1114        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1115        let traversal = Traversal {
1116            cursor,
1117            include_dirs: true,
1118            include_ignored: true,
1119        };
1120        ChildEntriesIter {
1121            traversal,
1122            parent_path,
1123        }
1124    }
1125
1126    pub fn root_entry(&self) -> Option<&Entry> {
1127        self.entry_for_path("")
1128    }
1129
1130    pub fn root_name(&self) -> &str {
1131        &self.root_name
1132    }
1133
1134    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1135        let path = path.as_ref();
1136        self.traverse_from_path(true, true, path)
1137            .entry()
1138            .and_then(|entry| {
1139                if entry.path.as_ref() == path {
1140                    Some(entry)
1141                } else {
1142                    None
1143                }
1144            })
1145    }
1146
1147    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1148        let entry = self.entries_by_id.get(&id, &())?;
1149        self.entry_for_path(&entry.path)
1150    }
1151
1152    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1153        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1154    }
1155}
1156
1157impl LocalSnapshot {
1158    pub fn abs_path(&self) -> &Arc<Path> {
1159        &self.abs_path
1160    }
1161
1162    #[cfg(test)]
1163    pub(crate) fn to_proto(
1164        &self,
1165        diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1166        visible: bool,
1167    ) -> proto::Worktree {
1168        let root_name = self.root_name.clone();
1169        proto::Worktree {
1170            id: self.id.0 as u64,
1171            root_name,
1172            entries: self
1173                .entries_by_path
1174                .iter()
1175                .filter(|e| !e.is_ignored)
1176                .map(Into::into)
1177                .collect(),
1178            diagnostic_summaries: diagnostic_summaries
1179                .iter()
1180                .map(|(path, summary)| summary.to_proto(&path.0))
1181                .collect(),
1182            visible,
1183        }
1184    }
1185
1186    pub(crate) fn build_update(
1187        &self,
1188        other: &Self,
1189        project_id: u64,
1190        worktree_id: u64,
1191        include_ignored: bool,
1192    ) -> proto::UpdateWorktree {
1193        let mut updated_entries = Vec::new();
1194        let mut removed_entries = Vec::new();
1195        let mut self_entries = self
1196            .entries_by_id
1197            .cursor::<()>()
1198            .filter(|e| include_ignored || !e.is_ignored)
1199            .peekable();
1200        let mut other_entries = other
1201            .entries_by_id
1202            .cursor::<()>()
1203            .filter(|e| include_ignored || !e.is_ignored)
1204            .peekable();
1205        loop {
1206            match (self_entries.peek(), other_entries.peek()) {
1207                (Some(self_entry), Some(other_entry)) => {
1208                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1209                        Ordering::Less => {
1210                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1211                            updated_entries.push(entry);
1212                            self_entries.next();
1213                        }
1214                        Ordering::Equal => {
1215                            if self_entry.scan_id != other_entry.scan_id {
1216                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1217                                updated_entries.push(entry);
1218                            }
1219
1220                            self_entries.next();
1221                            other_entries.next();
1222                        }
1223                        Ordering::Greater => {
1224                            removed_entries.push(other_entry.id.to_proto());
1225                            other_entries.next();
1226                        }
1227                    }
1228                }
1229                (Some(self_entry), None) => {
1230                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1231                    updated_entries.push(entry);
1232                    self_entries.next();
1233                }
1234                (None, Some(other_entry)) => {
1235                    removed_entries.push(other_entry.id.to_proto());
1236                    other_entries.next();
1237                }
1238                (None, None) => break,
1239            }
1240        }
1241
1242        proto::UpdateWorktree {
1243            project_id,
1244            worktree_id,
1245            root_name: self.root_name().to_string(),
1246            updated_entries,
1247            removed_entries,
1248        }
1249    }
1250
1251    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1252        if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1253            let abs_path = self.abs_path.join(&entry.path);
1254            match build_gitignore(&abs_path, fs) {
1255                Ok(ignore) => {
1256                    let ignore_dir_path = entry.path.parent().unwrap();
1257                    self.ignores
1258                        .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1259                }
1260                Err(error) => {
1261                    log::error!(
1262                        "error loading .gitignore file {:?} - {:?}",
1263                        &entry.path,
1264                        error
1265                    );
1266                }
1267            }
1268        }
1269
1270        self.reuse_entry_id(&mut entry);
1271        self.entries_by_path.insert_or_replace(entry.clone(), &());
1272        let scan_id = self.scan_id;
1273        self.entries_by_id.insert_or_replace(
1274            PathEntry {
1275                id: entry.id,
1276                path: entry.path.clone(),
1277                is_ignored: entry.is_ignored,
1278                scan_id,
1279            },
1280            &(),
1281        );
1282        entry
1283    }
1284
1285    fn populate_dir(
1286        &mut self,
1287        parent_path: Arc<Path>,
1288        entries: impl IntoIterator<Item = Entry>,
1289        ignore: Option<Arc<Gitignore>>,
1290    ) {
1291        let mut parent_entry = self
1292            .entries_by_path
1293            .get(&PathKey(parent_path.clone()), &())
1294            .unwrap()
1295            .clone();
1296        if let Some(ignore) = ignore {
1297            self.ignores.insert(parent_path, (ignore, self.scan_id));
1298        }
1299        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1300            parent_entry.kind = EntryKind::Dir;
1301        } else {
1302            unreachable!();
1303        }
1304
1305        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1306        let mut entries_by_id_edits = Vec::new();
1307
1308        for mut entry in entries {
1309            self.reuse_entry_id(&mut entry);
1310            entries_by_id_edits.push(Edit::Insert(PathEntry {
1311                id: entry.id,
1312                path: entry.path.clone(),
1313                is_ignored: entry.is_ignored,
1314                scan_id: self.scan_id,
1315            }));
1316            entries_by_path_edits.push(Edit::Insert(entry));
1317        }
1318
1319        self.entries_by_path.edit(entries_by_path_edits, &());
1320        self.entries_by_id.edit(entries_by_id_edits, &());
1321    }
1322
1323    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1324        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1325            entry.id = removed_entry_id;
1326        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1327            entry.id = existing_entry.id;
1328        }
1329    }
1330
1331    fn remove_path(&mut self, path: &Path) {
1332        let mut new_entries;
1333        let removed_entries;
1334        {
1335            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1336            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1337            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1338            new_entries.push_tree(cursor.suffix(&()), &());
1339        }
1340        self.entries_by_path = new_entries;
1341
1342        let mut entries_by_id_edits = Vec::new();
1343        for entry in removed_entries.cursor::<()>() {
1344            let removed_entry_id = self
1345                .removed_entry_ids
1346                .entry(entry.inode)
1347                .or_insert(entry.id);
1348            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1349            entries_by_id_edits.push(Edit::Remove(entry.id));
1350        }
1351        self.entries_by_id.edit(entries_by_id_edits, &());
1352
1353        if path.file_name() == Some(&GITIGNORE) {
1354            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1355                *scan_id = self.scan_id;
1356            }
1357        }
1358    }
1359
1360    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1361        let mut new_ignores = Vec::new();
1362        for ancestor in path.ancestors().skip(1) {
1363            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1364                new_ignores.push((ancestor, Some(ignore.clone())));
1365            } else {
1366                new_ignores.push((ancestor, None));
1367            }
1368        }
1369
1370        let mut ignore_stack = IgnoreStack::none();
1371        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1372            if ignore_stack.is_path_ignored(&parent_path, true) {
1373                ignore_stack = IgnoreStack::all();
1374                break;
1375            } else if let Some(ignore) = ignore {
1376                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1377            }
1378        }
1379
1380        if ignore_stack.is_path_ignored(path, is_dir) {
1381            ignore_stack = IgnoreStack::all();
1382        }
1383
1384        ignore_stack
1385    }
1386}
1387
1388fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1389    let contents = smol::block_on(fs.load(&abs_path))?;
1390    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1391    let mut builder = GitignoreBuilder::new(parent);
1392    for line in contents.lines() {
1393        builder.add_line(Some(abs_path.into()), line)?;
1394    }
1395    Ok(builder.build()?)
1396}
1397
1398impl WorktreeId {
1399    pub fn from_usize(handle_id: usize) -> Self {
1400        Self(handle_id)
1401    }
1402
1403    pub(crate) fn from_proto(id: u64) -> Self {
1404        Self(id as usize)
1405    }
1406
1407    pub fn to_proto(&self) -> u64 {
1408        self.0 as u64
1409    }
1410
1411    pub fn to_usize(&self) -> usize {
1412        self.0
1413    }
1414}
1415
1416impl fmt::Display for WorktreeId {
1417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418        self.0.fmt(f)
1419    }
1420}
1421
1422impl Deref for Worktree {
1423    type Target = Snapshot;
1424
1425    fn deref(&self) -> &Self::Target {
1426        match self {
1427            Worktree::Local(worktree) => &worktree.snapshot,
1428            Worktree::Remote(worktree) => &worktree.snapshot,
1429        }
1430    }
1431}
1432
1433impl Deref for LocalWorktree {
1434    type Target = LocalSnapshot;
1435
1436    fn deref(&self) -> &Self::Target {
1437        &self.snapshot
1438    }
1439}
1440
1441impl Deref for RemoteWorktree {
1442    type Target = Snapshot;
1443
1444    fn deref(&self) -> &Self::Target {
1445        &self.snapshot
1446    }
1447}
1448
1449impl fmt::Debug for LocalWorktree {
1450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1451        self.snapshot.fmt(f)
1452    }
1453}
1454
1455impl fmt::Debug for Snapshot {
1456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1457        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1458        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1459
1460        impl<'a> fmt::Debug for EntriesByPath<'a> {
1461            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1462                f.debug_map()
1463                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1464                    .finish()
1465            }
1466        }
1467
1468        impl<'a> fmt::Debug for EntriesById<'a> {
1469            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1470                f.debug_list().entries(self.0.iter()).finish()
1471            }
1472        }
1473
1474        f.debug_struct("Snapshot")
1475            .field("id", &self.id)
1476            .field("root_name", &self.root_name)
1477            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1478            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1479            .finish()
1480    }
1481}
1482
1483#[derive(Clone, PartialEq)]
1484pub struct File {
1485    pub worktree: ModelHandle<Worktree>,
1486    pub path: Arc<Path>,
1487    pub mtime: SystemTime,
1488    pub(crate) entry_id: Option<ProjectEntryId>,
1489    pub(crate) is_local: bool,
1490}
1491
1492impl language::File for File {
1493    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1494        if self.is_local {
1495            Some(self)
1496        } else {
1497            None
1498        }
1499    }
1500
1501    fn mtime(&self) -> SystemTime {
1502        self.mtime
1503    }
1504
1505    fn path(&self) -> &Arc<Path> {
1506        &self.path
1507    }
1508
1509    fn full_path(&self, cx: &AppContext) -> PathBuf {
1510        let mut full_path = PathBuf::new();
1511        full_path.push(self.worktree.read(cx).root_name());
1512        if self.path.components().next().is_some() {
1513            full_path.push(&self.path);
1514        }
1515        full_path
1516    }
1517
1518    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1519    /// of its worktree, then this method will return the name of the worktree itself.
1520    fn file_name(&self, cx: &AppContext) -> OsString {
1521        self.path
1522            .file_name()
1523            .map(|name| name.into())
1524            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1525    }
1526
1527    fn is_deleted(&self) -> bool {
1528        self.entry_id.is_none()
1529    }
1530
1531    fn save(
1532        &self,
1533        buffer_id: u64,
1534        text: Rope,
1535        version: clock::Global,
1536        cx: &mut MutableAppContext,
1537    ) -> Task<Result<(clock::Global, SystemTime)>> {
1538        self.worktree.update(cx, |worktree, cx| match worktree {
1539            Worktree::Local(worktree) => {
1540                let rpc = worktree.client.clone();
1541                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1542                let save = worktree.write_file(self.path.clone(), text, cx);
1543                cx.background().spawn(async move {
1544                    let entry = save.await?;
1545                    if let Some(project_id) = project_id {
1546                        rpc.send(proto::BufferSaved {
1547                            project_id,
1548                            buffer_id,
1549                            version: serialize_version(&version),
1550                            mtime: Some(entry.mtime.into()),
1551                        })?;
1552                    }
1553                    Ok((version, entry.mtime))
1554                })
1555            }
1556            Worktree::Remote(worktree) => {
1557                let rpc = worktree.client.clone();
1558                let project_id = worktree.project_id;
1559                cx.foreground().spawn(async move {
1560                    let response = rpc
1561                        .request(proto::SaveBuffer {
1562                            project_id,
1563                            buffer_id,
1564                            version: serialize_version(&version),
1565                        })
1566                        .await?;
1567                    let version = deserialize_version(response.version);
1568                    let mtime = response
1569                        .mtime
1570                        .ok_or_else(|| anyhow!("missing mtime"))?
1571                        .into();
1572                    Ok((version, mtime))
1573                })
1574            }
1575        })
1576    }
1577
1578    fn as_any(&self) -> &dyn Any {
1579        self
1580    }
1581
1582    fn to_proto(&self) -> rpc::proto::File {
1583        rpc::proto::File {
1584            worktree_id: self.worktree.id() as u64,
1585            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1586            path: self.path.to_string_lossy().into(),
1587            mtime: Some(self.mtime.into()),
1588        }
1589    }
1590}
1591
1592impl language::LocalFile for File {
1593    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1594        self.worktree
1595            .read(cx)
1596            .as_local()
1597            .unwrap()
1598            .abs_path
1599            .join(&self.path)
1600    }
1601
1602    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1603        let worktree = self.worktree.read(cx).as_local().unwrap();
1604        let abs_path = worktree.absolutize(&self.path);
1605        let fs = worktree.fs.clone();
1606        cx.background()
1607            .spawn(async move { fs.load(&abs_path).await })
1608    }
1609
1610    fn buffer_reloaded(
1611        &self,
1612        buffer_id: u64,
1613        version: &clock::Global,
1614        mtime: SystemTime,
1615        cx: &mut MutableAppContext,
1616    ) {
1617        let worktree = self.worktree.read(cx).as_local().unwrap();
1618        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1619            worktree
1620                .client
1621                .send(proto::BufferReloaded {
1622                    project_id,
1623                    buffer_id,
1624                    version: serialize_version(&version),
1625                    mtime: Some(mtime.into()),
1626                })
1627                .log_err();
1628        }
1629    }
1630}
1631
1632impl File {
1633    pub fn from_proto(
1634        proto: rpc::proto::File,
1635        worktree: ModelHandle<Worktree>,
1636        cx: &AppContext,
1637    ) -> Result<Self> {
1638        let worktree_id = worktree
1639            .read(cx)
1640            .as_remote()
1641            .ok_or_else(|| anyhow!("not remote"))?
1642            .id();
1643
1644        if worktree_id.to_proto() != proto.worktree_id {
1645            return Err(anyhow!("worktree id does not match file"));
1646        }
1647
1648        Ok(Self {
1649            worktree,
1650            path: Path::new(&proto.path).into(),
1651            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1652            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1653            is_local: false,
1654        })
1655    }
1656
1657    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1658        file.and_then(|f| f.as_any().downcast_ref())
1659    }
1660
1661    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1662        self.worktree.read(cx).id()
1663    }
1664
1665    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1666        self.entry_id
1667    }
1668}
1669
1670#[derive(Clone, Debug, PartialEq, Eq)]
1671pub struct Entry {
1672    pub id: ProjectEntryId,
1673    pub kind: EntryKind,
1674    pub path: Arc<Path>,
1675    pub inode: u64,
1676    pub mtime: SystemTime,
1677    pub is_symlink: bool,
1678    pub is_ignored: bool,
1679}
1680
1681#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1682pub enum EntryKind {
1683    PendingDir,
1684    Dir,
1685    File(CharBag),
1686}
1687
1688impl Entry {
1689    fn new(
1690        path: Arc<Path>,
1691        metadata: &fs::Metadata,
1692        next_entry_id: &AtomicUsize,
1693        root_char_bag: CharBag,
1694    ) -> Self {
1695        Self {
1696            id: ProjectEntryId::new(next_entry_id),
1697            kind: if metadata.is_dir {
1698                EntryKind::PendingDir
1699            } else {
1700                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1701            },
1702            path,
1703            inode: metadata.inode,
1704            mtime: metadata.mtime,
1705            is_symlink: metadata.is_symlink,
1706            is_ignored: false,
1707        }
1708    }
1709
1710    pub fn is_dir(&self) -> bool {
1711        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1712    }
1713
1714    pub fn is_file(&self) -> bool {
1715        matches!(self.kind, EntryKind::File(_))
1716    }
1717}
1718
1719impl sum_tree::Item for Entry {
1720    type Summary = EntrySummary;
1721
1722    fn summary(&self) -> Self::Summary {
1723        let visible_count = if self.is_ignored { 0 } else { 1 };
1724        let file_count;
1725        let visible_file_count;
1726        if self.is_file() {
1727            file_count = 1;
1728            visible_file_count = visible_count;
1729        } else {
1730            file_count = 0;
1731            visible_file_count = 0;
1732        }
1733
1734        EntrySummary {
1735            max_path: self.path.clone(),
1736            count: 1,
1737            visible_count,
1738            file_count,
1739            visible_file_count,
1740        }
1741    }
1742}
1743
1744impl sum_tree::KeyedItem for Entry {
1745    type Key = PathKey;
1746
1747    fn key(&self) -> Self::Key {
1748        PathKey(self.path.clone())
1749    }
1750}
1751
1752#[derive(Clone, Debug)]
1753pub struct EntrySummary {
1754    max_path: Arc<Path>,
1755    count: usize,
1756    visible_count: usize,
1757    file_count: usize,
1758    visible_file_count: usize,
1759}
1760
1761impl Default for EntrySummary {
1762    fn default() -> Self {
1763        Self {
1764            max_path: Arc::from(Path::new("")),
1765            count: 0,
1766            visible_count: 0,
1767            file_count: 0,
1768            visible_file_count: 0,
1769        }
1770    }
1771}
1772
1773impl sum_tree::Summary for EntrySummary {
1774    type Context = ();
1775
1776    fn add_summary(&mut self, rhs: &Self, _: &()) {
1777        self.max_path = rhs.max_path.clone();
1778        self.visible_count += rhs.visible_count;
1779        self.file_count += rhs.file_count;
1780        self.visible_file_count += rhs.visible_file_count;
1781    }
1782}
1783
1784#[derive(Clone, Debug)]
1785struct PathEntry {
1786    id: ProjectEntryId,
1787    path: Arc<Path>,
1788    is_ignored: bool,
1789    scan_id: usize,
1790}
1791
1792impl sum_tree::Item for PathEntry {
1793    type Summary = PathEntrySummary;
1794
1795    fn summary(&self) -> Self::Summary {
1796        PathEntrySummary { max_id: self.id }
1797    }
1798}
1799
1800impl sum_tree::KeyedItem for PathEntry {
1801    type Key = ProjectEntryId;
1802
1803    fn key(&self) -> Self::Key {
1804        self.id
1805    }
1806}
1807
1808#[derive(Clone, Debug, Default)]
1809struct PathEntrySummary {
1810    max_id: ProjectEntryId,
1811}
1812
1813impl sum_tree::Summary for PathEntrySummary {
1814    type Context = ();
1815
1816    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1817        self.max_id = summary.max_id;
1818    }
1819}
1820
1821impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
1822    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1823        *self = summary.max_id;
1824    }
1825}
1826
1827#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1828pub struct PathKey(Arc<Path>);
1829
1830impl Default for PathKey {
1831    fn default() -> Self {
1832        Self(Path::new("").into())
1833    }
1834}
1835
1836impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1837    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1838        self.0 = summary.max_path.clone();
1839    }
1840}
1841
1842struct BackgroundScanner {
1843    fs: Arc<dyn Fs>,
1844    snapshot: Arc<Mutex<LocalSnapshot>>,
1845    notify: UnboundedSender<ScanState>,
1846    executor: Arc<executor::Background>,
1847}
1848
1849impl BackgroundScanner {
1850    fn new(
1851        snapshot: Arc<Mutex<LocalSnapshot>>,
1852        notify: UnboundedSender<ScanState>,
1853        fs: Arc<dyn Fs>,
1854        executor: Arc<executor::Background>,
1855    ) -> Self {
1856        Self {
1857            fs,
1858            snapshot,
1859            notify,
1860            executor,
1861        }
1862    }
1863
1864    fn abs_path(&self) -> Arc<Path> {
1865        self.snapshot.lock().abs_path.clone()
1866    }
1867
1868    fn snapshot(&self) -> LocalSnapshot {
1869        self.snapshot.lock().clone()
1870    }
1871
1872    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1873        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1874            return;
1875        }
1876
1877        if let Err(err) = self.scan_dirs().await {
1878            if self
1879                .notify
1880                .unbounded_send(ScanState::Err(Arc::new(err)))
1881                .is_err()
1882            {
1883                return;
1884            }
1885        }
1886
1887        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1888            return;
1889        }
1890
1891        futures::pin_mut!(events_rx);
1892        while let Some(events) = events_rx.next().await {
1893            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1894                break;
1895            }
1896
1897            if !self.process_events(events).await {
1898                break;
1899            }
1900
1901            if self.notify.unbounded_send(ScanState::Idle).is_err() {
1902                break;
1903            }
1904        }
1905    }
1906
1907    async fn scan_dirs(&mut self) -> Result<()> {
1908        let root_char_bag;
1909        let next_entry_id;
1910        let is_dir;
1911        {
1912            let snapshot = self.snapshot.lock();
1913            root_char_bag = snapshot.root_char_bag;
1914            next_entry_id = snapshot.next_entry_id.clone();
1915            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1916        };
1917
1918        if is_dir {
1919            let path: Arc<Path> = Arc::from(Path::new(""));
1920            let abs_path = self.abs_path();
1921            let (tx, rx) = channel::unbounded();
1922            self.executor
1923                .block(tx.send(ScanJob {
1924                    abs_path: abs_path.to_path_buf(),
1925                    path,
1926                    ignore_stack: IgnoreStack::none(),
1927                    scan_queue: tx.clone(),
1928                }))
1929                .unwrap();
1930            drop(tx);
1931
1932            self.executor
1933                .scoped(|scope| {
1934                    for _ in 0..self.executor.num_cpus() {
1935                        scope.spawn(async {
1936                            while let Ok(job) = rx.recv().await {
1937                                if let Err(err) = self
1938                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1939                                    .await
1940                                {
1941                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
1942                                }
1943                            }
1944                        });
1945                    }
1946                })
1947                .await;
1948        }
1949
1950        Ok(())
1951    }
1952
1953    async fn scan_dir(
1954        &self,
1955        root_char_bag: CharBag,
1956        next_entry_id: Arc<AtomicUsize>,
1957        job: &ScanJob,
1958    ) -> Result<()> {
1959        let mut new_entries: Vec<Entry> = Vec::new();
1960        let mut new_jobs: Vec<ScanJob> = Vec::new();
1961        let mut ignore_stack = job.ignore_stack.clone();
1962        let mut new_ignore = None;
1963
1964        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1965        while let Some(child_abs_path) = child_paths.next().await {
1966            let child_abs_path = match child_abs_path {
1967                Ok(child_abs_path) => child_abs_path,
1968                Err(error) => {
1969                    log::error!("error processing entry {:?}", error);
1970                    continue;
1971                }
1972            };
1973            let child_name = child_abs_path.file_name().unwrap();
1974            let child_path: Arc<Path> = job.path.join(child_name).into();
1975            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
1976                Some(metadata) => metadata,
1977                None => continue,
1978            };
1979
1980            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
1981            if child_name == *GITIGNORE {
1982                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
1983                    Ok(ignore) => {
1984                        let ignore = Arc::new(ignore);
1985                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
1986                        new_ignore = Some(ignore);
1987                    }
1988                    Err(error) => {
1989                        log::error!(
1990                            "error loading .gitignore file {:?} - {:?}",
1991                            child_name,
1992                            error
1993                        );
1994                    }
1995                }
1996
1997                // Update ignore status of any child entries we've already processed to reflect the
1998                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
1999                // there should rarely be too numerous. Update the ignore stack associated with any
2000                // new jobs as well.
2001                let mut new_jobs = new_jobs.iter_mut();
2002                for entry in &mut new_entries {
2003                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2004                    if entry.is_dir() {
2005                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2006                            IgnoreStack::all()
2007                        } else {
2008                            ignore_stack.clone()
2009                        };
2010                    }
2011                }
2012            }
2013
2014            let mut child_entry = Entry::new(
2015                child_path.clone(),
2016                &child_metadata,
2017                &next_entry_id,
2018                root_char_bag,
2019            );
2020
2021            if child_metadata.is_dir {
2022                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2023                child_entry.is_ignored = is_ignored;
2024                new_entries.push(child_entry);
2025                new_jobs.push(ScanJob {
2026                    abs_path: child_abs_path,
2027                    path: child_path,
2028                    ignore_stack: if is_ignored {
2029                        IgnoreStack::all()
2030                    } else {
2031                        ignore_stack.clone()
2032                    },
2033                    scan_queue: job.scan_queue.clone(),
2034                });
2035            } else {
2036                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2037                new_entries.push(child_entry);
2038            };
2039        }
2040
2041        self.snapshot
2042            .lock()
2043            .populate_dir(job.path.clone(), new_entries, new_ignore);
2044        for new_job in new_jobs {
2045            job.scan_queue.send(new_job).await.unwrap();
2046        }
2047
2048        Ok(())
2049    }
2050
2051    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2052        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2053        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2054
2055        let root_char_bag;
2056        let root_abs_path;
2057        let next_entry_id;
2058        {
2059            let mut snapshot = self.snapshot.lock();
2060            snapshot.scan_id += 1;
2061            root_char_bag = snapshot.root_char_bag;
2062            root_abs_path = snapshot.abs_path.clone();
2063            next_entry_id = snapshot.next_entry_id.clone();
2064        }
2065
2066        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2067            abs_path
2068        } else {
2069            return false;
2070        };
2071        let metadata = futures::future::join_all(
2072            events
2073                .iter()
2074                .map(|event| self.fs.metadata(&event.path))
2075                .collect::<Vec<_>>(),
2076        )
2077        .await;
2078
2079        // Hold the snapshot lock while clearing and re-inserting the root entries
2080        // for each event. This way, the snapshot is not observable to the foreground
2081        // thread while this operation is in-progress.
2082        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2083        {
2084            let mut snapshot = self.snapshot.lock();
2085            for event in &events {
2086                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2087                    snapshot.remove_path(&path);
2088                }
2089            }
2090
2091            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2092                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2093                    Ok(path) => Arc::from(path.to_path_buf()),
2094                    Err(_) => {
2095                        log::error!(
2096                            "unexpected event {:?} for root path {:?}",
2097                            event.path,
2098                            root_abs_path
2099                        );
2100                        continue;
2101                    }
2102                };
2103
2104                match metadata {
2105                    Ok(Some(metadata)) => {
2106                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2107                        let mut fs_entry = Entry::new(
2108                            path.clone(),
2109                            &metadata,
2110                            snapshot.next_entry_id.as_ref(),
2111                            snapshot.root_char_bag,
2112                        );
2113                        fs_entry.is_ignored = ignore_stack.is_all();
2114                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2115                        if metadata.is_dir {
2116                            self.executor
2117                                .block(scan_queue_tx.send(ScanJob {
2118                                    abs_path: event.path,
2119                                    path,
2120                                    ignore_stack,
2121                                    scan_queue: scan_queue_tx.clone(),
2122                                }))
2123                                .unwrap();
2124                        }
2125                    }
2126                    Ok(None) => {}
2127                    Err(err) => {
2128                        // TODO - create a special 'error' entry in the entries tree to mark this
2129                        log::error!("error reading file on event {:?}", err);
2130                    }
2131                }
2132            }
2133            drop(scan_queue_tx);
2134        }
2135
2136        // Scan any directories that were created as part of this event batch.
2137        self.executor
2138            .scoped(|scope| {
2139                for _ in 0..self.executor.num_cpus() {
2140                    scope.spawn(async {
2141                        while let Ok(job) = scan_queue_rx.recv().await {
2142                            if let Err(err) = self
2143                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2144                                .await
2145                            {
2146                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2147                            }
2148                        }
2149                    });
2150                }
2151            })
2152            .await;
2153
2154        // Attempt to detect renames only over a single batch of file-system events.
2155        self.snapshot.lock().removed_entry_ids.clear();
2156
2157        self.update_ignore_statuses().await;
2158        true
2159    }
2160
2161    async fn update_ignore_statuses(&self) {
2162        let mut snapshot = self.snapshot();
2163
2164        let mut ignores_to_update = Vec::new();
2165        let mut ignores_to_delete = Vec::new();
2166        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2167            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2168                ignores_to_update.push(parent_path.clone());
2169            }
2170
2171            let ignore_path = parent_path.join(&*GITIGNORE);
2172            if snapshot.entry_for_path(ignore_path).is_none() {
2173                ignores_to_delete.push(parent_path.clone());
2174            }
2175        }
2176
2177        for parent_path in ignores_to_delete {
2178            snapshot.ignores.remove(&parent_path);
2179            self.snapshot.lock().ignores.remove(&parent_path);
2180        }
2181
2182        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2183        ignores_to_update.sort_unstable();
2184        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2185        while let Some(parent_path) = ignores_to_update.next() {
2186            while ignores_to_update
2187                .peek()
2188                .map_or(false, |p| p.starts_with(&parent_path))
2189            {
2190                ignores_to_update.next().unwrap();
2191            }
2192
2193            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2194            ignore_queue_tx
2195                .send(UpdateIgnoreStatusJob {
2196                    path: parent_path,
2197                    ignore_stack,
2198                    ignore_queue: ignore_queue_tx.clone(),
2199                })
2200                .await
2201                .unwrap();
2202        }
2203        drop(ignore_queue_tx);
2204
2205        self.executor
2206            .scoped(|scope| {
2207                for _ in 0..self.executor.num_cpus() {
2208                    scope.spawn(async {
2209                        while let Ok(job) = ignore_queue_rx.recv().await {
2210                            self.update_ignore_status(job, &snapshot).await;
2211                        }
2212                    });
2213                }
2214            })
2215            .await;
2216    }
2217
2218    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2219        let mut ignore_stack = job.ignore_stack;
2220        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2221            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2222        }
2223
2224        let mut entries_by_id_edits = Vec::new();
2225        let mut entries_by_path_edits = Vec::new();
2226        for mut entry in snapshot.child_entries(&job.path).cloned() {
2227            let was_ignored = entry.is_ignored;
2228            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2229            if entry.is_dir() {
2230                let child_ignore_stack = if entry.is_ignored {
2231                    IgnoreStack::all()
2232                } else {
2233                    ignore_stack.clone()
2234                };
2235                job.ignore_queue
2236                    .send(UpdateIgnoreStatusJob {
2237                        path: entry.path.clone(),
2238                        ignore_stack: child_ignore_stack,
2239                        ignore_queue: job.ignore_queue.clone(),
2240                    })
2241                    .await
2242                    .unwrap();
2243            }
2244
2245            if entry.is_ignored != was_ignored {
2246                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2247                path_entry.scan_id = snapshot.scan_id;
2248                path_entry.is_ignored = entry.is_ignored;
2249                entries_by_id_edits.push(Edit::Insert(path_entry));
2250                entries_by_path_edits.push(Edit::Insert(entry));
2251            }
2252        }
2253
2254        let mut snapshot = self.snapshot.lock();
2255        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2256        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2257    }
2258}
2259
2260fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2261    let mut result = root_char_bag;
2262    result.extend(
2263        path.to_string_lossy()
2264            .chars()
2265            .map(|c| c.to_ascii_lowercase()),
2266    );
2267    result
2268}
2269
2270struct ScanJob {
2271    abs_path: PathBuf,
2272    path: Arc<Path>,
2273    ignore_stack: Arc<IgnoreStack>,
2274    scan_queue: Sender<ScanJob>,
2275}
2276
2277struct UpdateIgnoreStatusJob {
2278    path: Arc<Path>,
2279    ignore_stack: Arc<IgnoreStack>,
2280    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2281}
2282
2283pub trait WorktreeHandle {
2284    #[cfg(any(test, feature = "test-support"))]
2285    fn flush_fs_events<'a>(
2286        &self,
2287        cx: &'a gpui::TestAppContext,
2288    ) -> futures::future::LocalBoxFuture<'a, ()>;
2289}
2290
2291impl WorktreeHandle for ModelHandle<Worktree> {
2292    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2293    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2294    // extra directory scans, and emit extra scan-state notifications.
2295    //
2296    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2297    // to ensure that all redundant FS events have already been processed.
2298    #[cfg(any(test, feature = "test-support"))]
2299    fn flush_fs_events<'a>(
2300        &self,
2301        cx: &'a gpui::TestAppContext,
2302    ) -> futures::future::LocalBoxFuture<'a, ()> {
2303        use smol::future::FutureExt;
2304
2305        let filename = "fs-event-sentinel";
2306        let tree = self.clone();
2307        let (fs, root_path) = self.read_with(cx, |tree, _| {
2308            let tree = tree.as_local().unwrap();
2309            (tree.fs.clone(), tree.abs_path().clone())
2310        });
2311
2312        async move {
2313            fs.create_file(&root_path.join(filename), Default::default())
2314                .await
2315                .unwrap();
2316            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2317                .await;
2318
2319            fs.remove_file(&root_path.join(filename), Default::default())
2320                .await
2321                .unwrap();
2322            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2323                .await;
2324
2325            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2326                .await;
2327        }
2328        .boxed_local()
2329    }
2330}
2331
2332#[derive(Clone, Debug)]
2333struct TraversalProgress<'a> {
2334    max_path: &'a Path,
2335    count: usize,
2336    visible_count: usize,
2337    file_count: usize,
2338    visible_file_count: usize,
2339}
2340
2341impl<'a> TraversalProgress<'a> {
2342    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2343        match (include_ignored, include_dirs) {
2344            (true, true) => self.count,
2345            (true, false) => self.file_count,
2346            (false, true) => self.visible_count,
2347            (false, false) => self.visible_file_count,
2348        }
2349    }
2350}
2351
2352impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2353    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2354        self.max_path = summary.max_path.as_ref();
2355        self.count += summary.count;
2356        self.visible_count += summary.visible_count;
2357        self.file_count += summary.file_count;
2358        self.visible_file_count += summary.visible_file_count;
2359    }
2360}
2361
2362impl<'a> Default for TraversalProgress<'a> {
2363    fn default() -> Self {
2364        Self {
2365            max_path: Path::new(""),
2366            count: 0,
2367            visible_count: 0,
2368            file_count: 0,
2369            visible_file_count: 0,
2370        }
2371    }
2372}
2373
2374pub struct Traversal<'a> {
2375    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2376    include_ignored: bool,
2377    include_dirs: bool,
2378}
2379
2380impl<'a> Traversal<'a> {
2381    pub fn advance(&mut self) -> bool {
2382        self.advance_to_offset(self.offset() + 1)
2383    }
2384
2385    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2386        self.cursor.seek_forward(
2387            &TraversalTarget::Count {
2388                count: offset,
2389                include_dirs: self.include_dirs,
2390                include_ignored: self.include_ignored,
2391            },
2392            Bias::Right,
2393            &(),
2394        )
2395    }
2396
2397    pub fn advance_to_sibling(&mut self) -> bool {
2398        while let Some(entry) = self.cursor.item() {
2399            self.cursor.seek_forward(
2400                &TraversalTarget::PathSuccessor(&entry.path),
2401                Bias::Left,
2402                &(),
2403            );
2404            if let Some(entry) = self.cursor.item() {
2405                if (self.include_dirs || !entry.is_dir())
2406                    && (self.include_ignored || !entry.is_ignored)
2407                {
2408                    return true;
2409                }
2410            }
2411        }
2412        false
2413    }
2414
2415    pub fn entry(&self) -> Option<&'a Entry> {
2416        self.cursor.item()
2417    }
2418
2419    pub fn offset(&self) -> usize {
2420        self.cursor
2421            .start()
2422            .count(self.include_dirs, self.include_ignored)
2423    }
2424}
2425
2426impl<'a> Iterator for Traversal<'a> {
2427    type Item = &'a Entry;
2428
2429    fn next(&mut self) -> Option<Self::Item> {
2430        if let Some(item) = self.entry() {
2431            self.advance();
2432            Some(item)
2433        } else {
2434            None
2435        }
2436    }
2437}
2438
2439#[derive(Debug)]
2440enum TraversalTarget<'a> {
2441    Path(&'a Path),
2442    PathSuccessor(&'a Path),
2443    Count {
2444        count: usize,
2445        include_ignored: bool,
2446        include_dirs: bool,
2447    },
2448}
2449
2450impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2451    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2452        match self {
2453            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2454            TraversalTarget::PathSuccessor(path) => {
2455                if !cursor_location.max_path.starts_with(path) {
2456                    Ordering::Equal
2457                } else {
2458                    Ordering::Greater
2459                }
2460            }
2461            TraversalTarget::Count {
2462                count,
2463                include_dirs,
2464                include_ignored,
2465            } => Ord::cmp(
2466                count,
2467                &cursor_location.count(*include_dirs, *include_ignored),
2468            ),
2469        }
2470    }
2471}
2472
2473struct ChildEntriesIter<'a> {
2474    parent_path: &'a Path,
2475    traversal: Traversal<'a>,
2476}
2477
2478impl<'a> Iterator for ChildEntriesIter<'a> {
2479    type Item = &'a Entry;
2480
2481    fn next(&mut self) -> Option<Self::Item> {
2482        if let Some(item) = self.traversal.entry() {
2483            if item.path.starts_with(&self.parent_path) {
2484                self.traversal.advance_to_sibling();
2485                return Some(item);
2486            }
2487        }
2488        None
2489    }
2490}
2491
2492impl<'a> From<&'a Entry> for proto::Entry {
2493    fn from(entry: &'a Entry) -> Self {
2494        Self {
2495            id: entry.id.to_proto(),
2496            is_dir: entry.is_dir(),
2497            path: entry.path.as_os_str().as_bytes().to_vec(),
2498            inode: entry.inode,
2499            mtime: Some(entry.mtime.into()),
2500            is_symlink: entry.is_symlink,
2501            is_ignored: entry.is_ignored,
2502        }
2503    }
2504}
2505
2506impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2507    type Error = anyhow::Error;
2508
2509    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2510        if let Some(mtime) = entry.mtime {
2511            let kind = if entry.is_dir {
2512                EntryKind::Dir
2513            } else {
2514                let mut char_bag = root_char_bag.clone();
2515                char_bag.extend(
2516                    String::from_utf8_lossy(&entry.path)
2517                        .chars()
2518                        .map(|c| c.to_ascii_lowercase()),
2519                );
2520                EntryKind::File(char_bag)
2521            };
2522            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2523            Ok(Entry {
2524                id: ProjectEntryId::from_proto(entry.id),
2525                kind,
2526                path: path.clone(),
2527                inode: entry.inode,
2528                mtime: mtime.into(),
2529                is_symlink: entry.is_symlink,
2530                is_ignored: entry.is_ignored,
2531            })
2532        } else {
2533            Err(anyhow!(
2534                "missing mtime in remote worktree entry {:?}",
2535                entry.path
2536            ))
2537        }
2538    }
2539}
2540
2541#[cfg(test)]
2542mod tests {
2543    use super::*;
2544    use crate::fs::FakeFs;
2545    use anyhow::Result;
2546    use client::test::FakeHttpClient;
2547    use fs::RealFs;
2548    use rand::prelude::*;
2549    use serde_json::json;
2550    use std::{
2551        env,
2552        fmt::Write,
2553        time::{SystemTime, UNIX_EPOCH},
2554    };
2555    use util::test::temp_tree;
2556
2557    #[gpui::test]
2558    async fn test_traversal(cx: &mut gpui::TestAppContext) {
2559        let fs = FakeFs::new(cx.background());
2560        fs.insert_tree(
2561            "/root",
2562            json!({
2563               ".gitignore": "a/b\n",
2564               "a": {
2565                   "b": "",
2566                   "c": "",
2567               }
2568            }),
2569        )
2570        .await;
2571
2572        let http_client = FakeHttpClient::with_404_response();
2573        let client = Client::new(http_client);
2574
2575        let tree = Worktree::local(
2576            client,
2577            Arc::from(Path::new("/root")),
2578            true,
2579            fs,
2580            Default::default(),
2581            &mut cx.to_async(),
2582        )
2583        .await
2584        .unwrap();
2585        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2586            .await;
2587
2588        tree.read_with(cx, |tree, _| {
2589            assert_eq!(
2590                tree.entries(false)
2591                    .map(|entry| entry.path.as_ref())
2592                    .collect::<Vec<_>>(),
2593                vec![
2594                    Path::new(""),
2595                    Path::new(".gitignore"),
2596                    Path::new("a"),
2597                    Path::new("a/c"),
2598                ]
2599            );
2600        })
2601    }
2602
2603    #[gpui::test]
2604    async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2605        let dir = temp_tree(json!({
2606            ".git": {},
2607            ".gitignore": "ignored-dir\n",
2608            "tracked-dir": {
2609                "tracked-file1": "tracked contents",
2610            },
2611            "ignored-dir": {
2612                "ignored-file1": "ignored contents",
2613            }
2614        }));
2615
2616        let http_client = FakeHttpClient::with_404_response();
2617        let client = Client::new(http_client.clone());
2618
2619        let tree = Worktree::local(
2620            client,
2621            dir.path(),
2622            true,
2623            Arc::new(RealFs),
2624            Default::default(),
2625            &mut cx.to_async(),
2626        )
2627        .await
2628        .unwrap();
2629        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2630            .await;
2631        tree.flush_fs_events(&cx).await;
2632        cx.read(|cx| {
2633            let tree = tree.read(cx);
2634            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2635            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2636            assert_eq!(tracked.is_ignored, false);
2637            assert_eq!(ignored.is_ignored, true);
2638        });
2639
2640        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2641        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2642        tree.flush_fs_events(&cx).await;
2643        cx.read(|cx| {
2644            let tree = tree.read(cx);
2645            let dot_git = tree.entry_for_path(".git").unwrap();
2646            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2647            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2648            assert_eq!(tracked.is_ignored, false);
2649            assert_eq!(ignored.is_ignored, true);
2650            assert_eq!(dot_git.is_ignored, true);
2651        });
2652    }
2653
2654    #[gpui::test(iterations = 100)]
2655    fn test_random(mut rng: StdRng) {
2656        let operations = env::var("OPERATIONS")
2657            .map(|o| o.parse().unwrap())
2658            .unwrap_or(40);
2659        let initial_entries = env::var("INITIAL_ENTRIES")
2660            .map(|o| o.parse().unwrap())
2661            .unwrap_or(20);
2662
2663        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2664        for _ in 0..initial_entries {
2665            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2666        }
2667        log::info!("Generated initial tree");
2668
2669        let (notify_tx, _notify_rx) = mpsc::unbounded();
2670        let fs = Arc::new(RealFs);
2671        let next_entry_id = Arc::new(AtomicUsize::new(0));
2672        let mut initial_snapshot = LocalSnapshot {
2673            abs_path: root_dir.path().into(),
2674            scan_id: 0,
2675            removed_entry_ids: Default::default(),
2676            ignores: Default::default(),
2677            next_entry_id: next_entry_id.clone(),
2678            snapshot: Snapshot {
2679                id: WorktreeId::from_usize(0),
2680                entries_by_path: Default::default(),
2681                entries_by_id: Default::default(),
2682                root_name: Default::default(),
2683                root_char_bag: Default::default(),
2684            },
2685        };
2686        initial_snapshot.insert_entry(
2687            Entry::new(
2688                Path::new("").into(),
2689                &smol::block_on(fs.metadata(root_dir.path()))
2690                    .unwrap()
2691                    .unwrap(),
2692                &next_entry_id,
2693                Default::default(),
2694            ),
2695            fs.as_ref(),
2696        );
2697        let mut scanner = BackgroundScanner::new(
2698            Arc::new(Mutex::new(initial_snapshot.clone())),
2699            notify_tx,
2700            fs.clone(),
2701            Arc::new(gpui::executor::Background::new()),
2702        );
2703        smol::block_on(scanner.scan_dirs()).unwrap();
2704        scanner.snapshot().check_invariants();
2705
2706        let mut events = Vec::new();
2707        let mut snapshots = Vec::new();
2708        let mut mutations_len = operations;
2709        while mutations_len > 1 {
2710            if !events.is_empty() && rng.gen_bool(0.4) {
2711                let len = rng.gen_range(0..=events.len());
2712                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2713                log::info!("Delivering events: {:#?}", to_deliver);
2714                smol::block_on(scanner.process_events(to_deliver));
2715                scanner.snapshot().check_invariants();
2716            } else {
2717                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2718                mutations_len -= 1;
2719            }
2720
2721            if rng.gen_bool(0.2) {
2722                snapshots.push(scanner.snapshot());
2723            }
2724        }
2725        log::info!("Quiescing: {:#?}", events);
2726        smol::block_on(scanner.process_events(events));
2727        scanner.snapshot().check_invariants();
2728
2729        let (notify_tx, _notify_rx) = mpsc::unbounded();
2730        let mut new_scanner = BackgroundScanner::new(
2731            Arc::new(Mutex::new(initial_snapshot)),
2732            notify_tx,
2733            scanner.fs.clone(),
2734            scanner.executor.clone(),
2735        );
2736        smol::block_on(new_scanner.scan_dirs()).unwrap();
2737        assert_eq!(
2738            scanner.snapshot().to_vec(true),
2739            new_scanner.snapshot().to_vec(true)
2740        );
2741
2742        for mut prev_snapshot in snapshots {
2743            let include_ignored = rng.gen::<bool>();
2744            if !include_ignored {
2745                let mut entries_by_path_edits = Vec::new();
2746                let mut entries_by_id_edits = Vec::new();
2747                for entry in prev_snapshot
2748                    .entries_by_id
2749                    .cursor::<()>()
2750                    .filter(|e| e.is_ignored)
2751                {
2752                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2753                    entries_by_id_edits.push(Edit::Remove(entry.id));
2754                }
2755
2756                prev_snapshot
2757                    .entries_by_path
2758                    .edit(entries_by_path_edits, &());
2759                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2760            }
2761
2762            let update = scanner
2763                .snapshot()
2764                .build_update(&prev_snapshot, 0, 0, include_ignored);
2765            prev_snapshot.apply_remote_update(update).unwrap();
2766            assert_eq!(
2767                prev_snapshot.to_vec(true),
2768                scanner.snapshot().to_vec(include_ignored)
2769            );
2770        }
2771    }
2772
2773    fn randomly_mutate_tree(
2774        root_path: &Path,
2775        insertion_probability: f64,
2776        rng: &mut impl Rng,
2777    ) -> Result<Vec<fsevent::Event>> {
2778        let root_path = root_path.canonicalize().unwrap();
2779        let (dirs, files) = read_dir_recursive(root_path.clone());
2780
2781        let mut events = Vec::new();
2782        let mut record_event = |path: PathBuf| {
2783            events.push(fsevent::Event {
2784                event_id: SystemTime::now()
2785                    .duration_since(UNIX_EPOCH)
2786                    .unwrap()
2787                    .as_secs(),
2788                flags: fsevent::StreamFlags::empty(),
2789                path,
2790            });
2791        };
2792
2793        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2794            let path = dirs.choose(rng).unwrap();
2795            let new_path = path.join(gen_name(rng));
2796
2797            if rng.gen() {
2798                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2799                std::fs::create_dir(&new_path)?;
2800            } else {
2801                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2802                std::fs::write(&new_path, "")?;
2803            }
2804            record_event(new_path);
2805        } else if rng.gen_bool(0.05) {
2806            let ignore_dir_path = dirs.choose(rng).unwrap();
2807            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2808
2809            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2810            let files_to_ignore = {
2811                let len = rng.gen_range(0..=subfiles.len());
2812                subfiles.choose_multiple(rng, len)
2813            };
2814            let dirs_to_ignore = {
2815                let len = rng.gen_range(0..subdirs.len());
2816                subdirs.choose_multiple(rng, len)
2817            };
2818
2819            let mut ignore_contents = String::new();
2820            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2821                write!(
2822                    ignore_contents,
2823                    "{}\n",
2824                    path_to_ignore
2825                        .strip_prefix(&ignore_dir_path)?
2826                        .to_str()
2827                        .unwrap()
2828                )
2829                .unwrap();
2830            }
2831            log::info!(
2832                "Creating {:?} with contents:\n{}",
2833                ignore_path.strip_prefix(&root_path)?,
2834                ignore_contents
2835            );
2836            std::fs::write(&ignore_path, ignore_contents).unwrap();
2837            record_event(ignore_path);
2838        } else {
2839            let old_path = {
2840                let file_path = files.choose(rng);
2841                let dir_path = dirs[1..].choose(rng);
2842                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2843            };
2844
2845            let is_rename = rng.gen();
2846            if is_rename {
2847                let new_path_parent = dirs
2848                    .iter()
2849                    .filter(|d| !d.starts_with(old_path))
2850                    .choose(rng)
2851                    .unwrap();
2852
2853                let overwrite_existing_dir =
2854                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2855                let new_path = if overwrite_existing_dir {
2856                    std::fs::remove_dir_all(&new_path_parent).ok();
2857                    new_path_parent.to_path_buf()
2858                } else {
2859                    new_path_parent.join(gen_name(rng))
2860                };
2861
2862                log::info!(
2863                    "Renaming {:?} to {}{:?}",
2864                    old_path.strip_prefix(&root_path)?,
2865                    if overwrite_existing_dir {
2866                        "overwrite "
2867                    } else {
2868                        ""
2869                    },
2870                    new_path.strip_prefix(&root_path)?
2871                );
2872                std::fs::rename(&old_path, &new_path)?;
2873                record_event(old_path.clone());
2874                record_event(new_path);
2875            } else if old_path.is_dir() {
2876                let (dirs, files) = read_dir_recursive(old_path.clone());
2877
2878                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2879                std::fs::remove_dir_all(&old_path).unwrap();
2880                for file in files {
2881                    record_event(file);
2882                }
2883                for dir in dirs {
2884                    record_event(dir);
2885                }
2886            } else {
2887                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2888                std::fs::remove_file(old_path).unwrap();
2889                record_event(old_path.clone());
2890            }
2891        }
2892
2893        Ok(events)
2894    }
2895
2896    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2897        let child_entries = std::fs::read_dir(&path).unwrap();
2898        let mut dirs = vec![path];
2899        let mut files = Vec::new();
2900        for child_entry in child_entries {
2901            let child_path = child_entry.unwrap().path();
2902            if child_path.is_dir() {
2903                let (child_dirs, child_files) = read_dir_recursive(child_path);
2904                dirs.extend(child_dirs);
2905                files.extend(child_files);
2906            } else {
2907                files.push(child_path);
2908            }
2909        }
2910        (dirs, files)
2911    }
2912
2913    fn gen_name(rng: &mut impl Rng) -> String {
2914        (0..6)
2915            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2916            .map(char::from)
2917            .collect()
2918    }
2919
2920    impl LocalSnapshot {
2921        fn check_invariants(&self) {
2922            let mut files = self.files(true, 0);
2923            let mut visible_files = self.files(false, 0);
2924            for entry in self.entries_by_path.cursor::<()>() {
2925                if entry.is_file() {
2926                    assert_eq!(files.next().unwrap().inode, entry.inode);
2927                    if !entry.is_ignored {
2928                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2929                    }
2930                }
2931            }
2932            assert!(files.next().is_none());
2933            assert!(visible_files.next().is_none());
2934
2935            let mut bfs_paths = Vec::new();
2936            let mut stack = vec![Path::new("")];
2937            while let Some(path) = stack.pop() {
2938                bfs_paths.push(path);
2939                let ix = stack.len();
2940                for child_entry in self.child_entries(path) {
2941                    stack.insert(ix, &child_entry.path);
2942                }
2943            }
2944
2945            let dfs_paths = self
2946                .entries_by_path
2947                .cursor::<()>()
2948                .map(|e| e.path.as_ref())
2949                .collect::<Vec<_>>();
2950            assert_eq!(bfs_paths, dfs_paths);
2951
2952            for (ignore_parent_path, _) in &self.ignores {
2953                assert!(self.entry_for_path(ignore_parent_path).is_some());
2954                assert!(self
2955                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2956                    .is_some());
2957            }
2958        }
2959
2960        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2961            let mut paths = Vec::new();
2962            for entry in self.entries_by_path.cursor::<()>() {
2963                if include_ignored || !entry.is_ignored {
2964                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2965                }
2966            }
2967            paths.sort_by(|a, b| a.0.cmp(&b.0));
2968            paths
2969        }
2970    }
2971}