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