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