worktree.rs

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