worktree.rs

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