worktree.rs

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