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