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