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        if self.path.components().next().is_some() {
1358            full_path.push(&self.path);
1359        }
1360        full_path
1361    }
1362
1363    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1364    /// of its worktree, then this method will return the name of the worktree itself.
1365    fn file_name(&self, cx: &AppContext) -> OsString {
1366        self.path
1367            .file_name()
1368            .map(|name| name.into())
1369            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1370    }
1371
1372    fn is_deleted(&self) -> bool {
1373        self.entry_id.is_none()
1374    }
1375
1376    fn save(
1377        &self,
1378        buffer_id: u64,
1379        text: Rope,
1380        version: clock::Global,
1381        cx: &mut MutableAppContext,
1382    ) -> Task<Result<(clock::Global, SystemTime)>> {
1383        self.worktree.update(cx, |worktree, cx| match worktree {
1384            Worktree::Local(worktree) => {
1385                let rpc = worktree.client.clone();
1386                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1387                let save = worktree.save(self.path.clone(), text, cx);
1388                cx.background().spawn(async move {
1389                    let entry = save.await?;
1390                    if let Some(project_id) = project_id {
1391                        rpc.send(proto::BufferSaved {
1392                            project_id,
1393                            buffer_id,
1394                            version: (&version).into(),
1395                            mtime: Some(entry.mtime.into()),
1396                        })?;
1397                    }
1398                    Ok((version, entry.mtime))
1399                })
1400            }
1401            Worktree::Remote(worktree) => {
1402                let rpc = worktree.client.clone();
1403                let project_id = worktree.project_id;
1404                cx.foreground().spawn(async move {
1405                    let response = rpc
1406                        .request(proto::SaveBuffer {
1407                            project_id,
1408                            buffer_id,
1409                            version: (&version).into(),
1410                        })
1411                        .await?;
1412                    let version = response.version.try_into()?;
1413                    let mtime = response
1414                        .mtime
1415                        .ok_or_else(|| anyhow!("missing mtime"))?
1416                        .into();
1417                    Ok((version, mtime))
1418                })
1419            }
1420        })
1421    }
1422
1423    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext) {
1424        self.worktree.update(cx, |worktree, cx| {
1425            worktree.send_buffer_update(buffer_id, operation, cx);
1426        });
1427    }
1428
1429    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext) {
1430        self.worktree.update(cx, |worktree, _| {
1431            if let Worktree::Remote(worktree) = worktree {
1432                worktree
1433                    .client
1434                    .send(proto::CloseBuffer {
1435                        project_id: worktree.project_id,
1436                        buffer_id,
1437                    })
1438                    .log_err();
1439            }
1440        });
1441    }
1442
1443    fn as_any(&self) -> &dyn Any {
1444        self
1445    }
1446
1447    fn to_proto(&self) -> rpc::proto::File {
1448        rpc::proto::File {
1449            worktree_id: self.worktree.id() as u64,
1450            entry_id: self.entry_id.map(|entry_id| entry_id as u64),
1451            path: self.path.to_string_lossy().into(),
1452            mtime: Some(self.mtime.into()),
1453        }
1454    }
1455}
1456
1457impl language::LocalFile for File {
1458    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1459        self.worktree
1460            .read(cx)
1461            .as_local()
1462            .unwrap()
1463            .abs_path
1464            .join(&self.path)
1465    }
1466
1467    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1468        let worktree = self.worktree.read(cx).as_local().unwrap();
1469        let abs_path = worktree.absolutize(&self.path);
1470        let fs = worktree.fs.clone();
1471        cx.background()
1472            .spawn(async move { fs.load(&abs_path).await })
1473    }
1474
1475    fn buffer_reloaded(
1476        &self,
1477        buffer_id: u64,
1478        version: &clock::Global,
1479        mtime: SystemTime,
1480        cx: &mut MutableAppContext,
1481    ) {
1482        let worktree = self.worktree.read(cx).as_local().unwrap();
1483        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1484            worktree
1485                .client
1486                .send(proto::BufferReloaded {
1487                    project_id,
1488                    buffer_id,
1489                    version: version.into(),
1490                    mtime: Some(mtime.into()),
1491                })
1492                .log_err();
1493        }
1494    }
1495}
1496
1497impl File {
1498    pub fn from_proto(
1499        proto: rpc::proto::File,
1500        worktree: ModelHandle<Worktree>,
1501        cx: &AppContext,
1502    ) -> Result<Self> {
1503        let worktree_id = worktree
1504            .read(cx)
1505            .as_remote()
1506            .ok_or_else(|| anyhow!("not remote"))?
1507            .id();
1508
1509        if worktree_id.to_proto() != proto.worktree_id {
1510            return Err(anyhow!("worktree id does not match file"));
1511        }
1512
1513        Ok(Self {
1514            worktree,
1515            path: Path::new(&proto.path).into(),
1516            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1517            entry_id: proto.entry_id.map(|entry_id| entry_id as usize),
1518            is_local: false,
1519        })
1520    }
1521
1522    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1523        file.and_then(|f| f.as_any().downcast_ref())
1524    }
1525
1526    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1527        self.worktree.read(cx).id()
1528    }
1529}
1530
1531#[derive(Clone, Debug)]
1532pub struct Entry {
1533    pub id: usize,
1534    pub kind: EntryKind,
1535    pub path: Arc<Path>,
1536    pub inode: u64,
1537    pub mtime: SystemTime,
1538    pub is_symlink: bool,
1539    pub is_ignored: bool,
1540}
1541
1542#[derive(Clone, Debug)]
1543pub enum EntryKind {
1544    PendingDir,
1545    Dir,
1546    File(CharBag),
1547}
1548
1549impl Entry {
1550    fn new(
1551        path: Arc<Path>,
1552        metadata: &fs::Metadata,
1553        next_entry_id: &AtomicUsize,
1554        root_char_bag: CharBag,
1555    ) -> Self {
1556        Self {
1557            id: next_entry_id.fetch_add(1, SeqCst),
1558            kind: if metadata.is_dir {
1559                EntryKind::PendingDir
1560            } else {
1561                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1562            },
1563            path,
1564            inode: metadata.inode,
1565            mtime: metadata.mtime,
1566            is_symlink: metadata.is_symlink,
1567            is_ignored: false,
1568        }
1569    }
1570
1571    pub fn is_dir(&self) -> bool {
1572        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1573    }
1574
1575    pub fn is_file(&self) -> bool {
1576        matches!(self.kind, EntryKind::File(_))
1577    }
1578}
1579
1580impl sum_tree::Item for Entry {
1581    type Summary = EntrySummary;
1582
1583    fn summary(&self) -> Self::Summary {
1584        let visible_count = if self.is_ignored { 0 } else { 1 };
1585        let file_count;
1586        let visible_file_count;
1587        if self.is_file() {
1588            file_count = 1;
1589            visible_file_count = visible_count;
1590        } else {
1591            file_count = 0;
1592            visible_file_count = 0;
1593        }
1594
1595        EntrySummary {
1596            max_path: self.path.clone(),
1597            count: 1,
1598            visible_count,
1599            file_count,
1600            visible_file_count,
1601        }
1602    }
1603}
1604
1605impl sum_tree::KeyedItem for Entry {
1606    type Key = PathKey;
1607
1608    fn key(&self) -> Self::Key {
1609        PathKey(self.path.clone())
1610    }
1611}
1612
1613#[derive(Clone, Debug)]
1614pub struct EntrySummary {
1615    max_path: Arc<Path>,
1616    count: usize,
1617    visible_count: usize,
1618    file_count: usize,
1619    visible_file_count: usize,
1620}
1621
1622impl Default for EntrySummary {
1623    fn default() -> Self {
1624        Self {
1625            max_path: Arc::from(Path::new("")),
1626            count: 0,
1627            visible_count: 0,
1628            file_count: 0,
1629            visible_file_count: 0,
1630        }
1631    }
1632}
1633
1634impl sum_tree::Summary for EntrySummary {
1635    type Context = ();
1636
1637    fn add_summary(&mut self, rhs: &Self, _: &()) {
1638        self.max_path = rhs.max_path.clone();
1639        self.visible_count += rhs.visible_count;
1640        self.file_count += rhs.file_count;
1641        self.visible_file_count += rhs.visible_file_count;
1642    }
1643}
1644
1645#[derive(Clone, Debug)]
1646struct PathEntry {
1647    id: usize,
1648    path: Arc<Path>,
1649    is_ignored: bool,
1650    scan_id: usize,
1651}
1652
1653impl sum_tree::Item for PathEntry {
1654    type Summary = PathEntrySummary;
1655
1656    fn summary(&self) -> Self::Summary {
1657        PathEntrySummary { max_id: self.id }
1658    }
1659}
1660
1661impl sum_tree::KeyedItem for PathEntry {
1662    type Key = usize;
1663
1664    fn key(&self) -> Self::Key {
1665        self.id
1666    }
1667}
1668
1669#[derive(Clone, Debug, Default)]
1670struct PathEntrySummary {
1671    max_id: usize,
1672}
1673
1674impl sum_tree::Summary for PathEntrySummary {
1675    type Context = ();
1676
1677    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1678        self.max_id = summary.max_id;
1679    }
1680}
1681
1682impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for usize {
1683    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1684        *self = summary.max_id;
1685    }
1686}
1687
1688#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1689pub struct PathKey(Arc<Path>);
1690
1691impl Default for PathKey {
1692    fn default() -> Self {
1693        Self(Path::new("").into())
1694    }
1695}
1696
1697impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1698    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1699        self.0 = summary.max_path.clone();
1700    }
1701}
1702
1703struct BackgroundScanner {
1704    fs: Arc<dyn Fs>,
1705    snapshot: Arc<Mutex<LocalSnapshot>>,
1706    notify: UnboundedSender<ScanState>,
1707    executor: Arc<executor::Background>,
1708}
1709
1710impl BackgroundScanner {
1711    fn new(
1712        snapshot: Arc<Mutex<LocalSnapshot>>,
1713        notify: UnboundedSender<ScanState>,
1714        fs: Arc<dyn Fs>,
1715        executor: Arc<executor::Background>,
1716    ) -> Self {
1717        Self {
1718            fs,
1719            snapshot,
1720            notify,
1721            executor,
1722        }
1723    }
1724
1725    fn abs_path(&self) -> Arc<Path> {
1726        self.snapshot.lock().abs_path.clone()
1727    }
1728
1729    fn snapshot(&self) -> LocalSnapshot {
1730        self.snapshot.lock().clone()
1731    }
1732
1733    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1734        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1735            return;
1736        }
1737
1738        if let Err(err) = self.scan_dirs().await {
1739            if self
1740                .notify
1741                .unbounded_send(ScanState::Err(Arc::new(err)))
1742                .is_err()
1743            {
1744                return;
1745            }
1746        }
1747
1748        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1749            return;
1750        }
1751
1752        futures::pin_mut!(events_rx);
1753        while let Some(events) = events_rx.next().await {
1754            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1755                break;
1756            }
1757
1758            if !self.process_events(events).await {
1759                break;
1760            }
1761
1762            if self.notify.unbounded_send(ScanState::Idle).is_err() {
1763                break;
1764            }
1765        }
1766    }
1767
1768    async fn scan_dirs(&mut self) -> Result<()> {
1769        let root_char_bag;
1770        let next_entry_id;
1771        let is_dir;
1772        {
1773            let snapshot = self.snapshot.lock();
1774            root_char_bag = snapshot.root_char_bag;
1775            next_entry_id = snapshot.next_entry_id.clone();
1776            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1777        };
1778
1779        if is_dir {
1780            let path: Arc<Path> = Arc::from(Path::new(""));
1781            let abs_path = self.abs_path();
1782            let (tx, rx) = channel::unbounded();
1783            tx.send(ScanJob {
1784                abs_path: abs_path.to_path_buf(),
1785                path,
1786                ignore_stack: IgnoreStack::none(),
1787                scan_queue: tx.clone(),
1788            })
1789            .await
1790            .unwrap();
1791            drop(tx);
1792
1793            self.executor
1794                .scoped(|scope| {
1795                    for _ in 0..self.executor.num_cpus() {
1796                        scope.spawn(async {
1797                            while let Ok(job) = rx.recv().await {
1798                                if let Err(err) = self
1799                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1800                                    .await
1801                                {
1802                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
1803                                }
1804                            }
1805                        });
1806                    }
1807                })
1808                .await;
1809        }
1810
1811        Ok(())
1812    }
1813
1814    async fn scan_dir(
1815        &self,
1816        root_char_bag: CharBag,
1817        next_entry_id: Arc<AtomicUsize>,
1818        job: &ScanJob,
1819    ) -> Result<()> {
1820        let mut new_entries: Vec<Entry> = Vec::new();
1821        let mut new_jobs: Vec<ScanJob> = Vec::new();
1822        let mut ignore_stack = job.ignore_stack.clone();
1823        let mut new_ignore = None;
1824
1825        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1826        while let Some(child_abs_path) = child_paths.next().await {
1827            let child_abs_path = match child_abs_path {
1828                Ok(child_abs_path) => child_abs_path,
1829                Err(error) => {
1830                    log::error!("error processing entry {:?}", error);
1831                    continue;
1832                }
1833            };
1834            let child_name = child_abs_path.file_name().unwrap();
1835            let child_path: Arc<Path> = job.path.join(child_name).into();
1836            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
1837                Some(metadata) => metadata,
1838                None => continue,
1839            };
1840
1841            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
1842            if child_name == *GITIGNORE {
1843                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
1844                    Ok(ignore) => {
1845                        let ignore = Arc::new(ignore);
1846                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
1847                        new_ignore = Some(ignore);
1848                    }
1849                    Err(error) => {
1850                        log::error!(
1851                            "error loading .gitignore file {:?} - {:?}",
1852                            child_name,
1853                            error
1854                        );
1855                    }
1856                }
1857
1858                // Update ignore status of any child entries we've already processed to reflect the
1859                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
1860                // there should rarely be too numerous. Update the ignore stack associated with any
1861                // new jobs as well.
1862                let mut new_jobs = new_jobs.iter_mut();
1863                for entry in &mut new_entries {
1864                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
1865                    if entry.is_dir() {
1866                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
1867                            IgnoreStack::all()
1868                        } else {
1869                            ignore_stack.clone()
1870                        };
1871                    }
1872                }
1873            }
1874
1875            let mut child_entry = Entry::new(
1876                child_path.clone(),
1877                &child_metadata,
1878                &next_entry_id,
1879                root_char_bag,
1880            );
1881
1882            if child_metadata.is_dir {
1883                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
1884                child_entry.is_ignored = is_ignored;
1885                new_entries.push(child_entry);
1886                new_jobs.push(ScanJob {
1887                    abs_path: child_abs_path,
1888                    path: child_path,
1889                    ignore_stack: if is_ignored {
1890                        IgnoreStack::all()
1891                    } else {
1892                        ignore_stack.clone()
1893                    },
1894                    scan_queue: job.scan_queue.clone(),
1895                });
1896            } else {
1897                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
1898                new_entries.push(child_entry);
1899            };
1900        }
1901
1902        self.snapshot
1903            .lock()
1904            .populate_dir(job.path.clone(), new_entries, new_ignore);
1905        for new_job in new_jobs {
1906            job.scan_queue.send(new_job).await.unwrap();
1907        }
1908
1909        Ok(())
1910    }
1911
1912    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
1913        let mut snapshot = self.snapshot();
1914        snapshot.scan_id += 1;
1915
1916        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
1917            abs_path
1918        } else {
1919            return false;
1920        };
1921        let root_char_bag = snapshot.root_char_bag;
1922        let next_entry_id = snapshot.next_entry_id.clone();
1923
1924        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
1925        events.dedup_by(|a, b| a.path.starts_with(&b.path));
1926
1927        for event in &events {
1928            match event.path.strip_prefix(&root_abs_path) {
1929                Ok(path) => snapshot.remove_path(&path),
1930                Err(_) => {
1931                    log::error!(
1932                        "unexpected event {:?} for root path {:?}",
1933                        event.path,
1934                        root_abs_path
1935                    );
1936                    continue;
1937                }
1938            }
1939        }
1940
1941        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
1942        for event in events {
1943            let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
1944                Ok(path) => Arc::from(path.to_path_buf()),
1945                Err(_) => {
1946                    log::error!(
1947                        "unexpected event {:?} for root path {:?}",
1948                        event.path,
1949                        root_abs_path
1950                    );
1951                    continue;
1952                }
1953            };
1954
1955            match self.fs.metadata(&event.path).await {
1956                Ok(Some(metadata)) => {
1957                    let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
1958                    let mut fs_entry = Entry::new(
1959                        path.clone(),
1960                        &metadata,
1961                        snapshot.next_entry_id.as_ref(),
1962                        snapshot.root_char_bag,
1963                    );
1964                    fs_entry.is_ignored = ignore_stack.is_all();
1965                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
1966                    if metadata.is_dir {
1967                        scan_queue_tx
1968                            .send(ScanJob {
1969                                abs_path: event.path,
1970                                path,
1971                                ignore_stack,
1972                                scan_queue: scan_queue_tx.clone(),
1973                            })
1974                            .await
1975                            .unwrap();
1976                    }
1977                }
1978                Ok(None) => {}
1979                Err(err) => {
1980                    // TODO - create a special 'error' entry in the entries tree to mark this
1981                    log::error!("error reading file on event {:?}", err);
1982                }
1983            }
1984        }
1985
1986        *self.snapshot.lock() = snapshot;
1987
1988        // Scan any directories that were created as part of this event batch.
1989        drop(scan_queue_tx);
1990        self.executor
1991            .scoped(|scope| {
1992                for _ in 0..self.executor.num_cpus() {
1993                    scope.spawn(async {
1994                        while let Ok(job) = scan_queue_rx.recv().await {
1995                            if let Err(err) = self
1996                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1997                                .await
1998                            {
1999                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2000                            }
2001                        }
2002                    });
2003                }
2004            })
2005            .await;
2006
2007        // Attempt to detect renames only over a single batch of file-system events.
2008        self.snapshot.lock().removed_entry_ids.clear();
2009
2010        self.update_ignore_statuses().await;
2011        true
2012    }
2013
2014    async fn update_ignore_statuses(&self) {
2015        let mut snapshot = self.snapshot();
2016
2017        let mut ignores_to_update = Vec::new();
2018        let mut ignores_to_delete = Vec::new();
2019        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2020            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2021                ignores_to_update.push(parent_path.clone());
2022            }
2023
2024            let ignore_path = parent_path.join(&*GITIGNORE);
2025            if snapshot.entry_for_path(ignore_path).is_none() {
2026                ignores_to_delete.push(parent_path.clone());
2027            }
2028        }
2029
2030        for parent_path in ignores_to_delete {
2031            snapshot.ignores.remove(&parent_path);
2032            self.snapshot.lock().ignores.remove(&parent_path);
2033        }
2034
2035        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2036        ignores_to_update.sort_unstable();
2037        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2038        while let Some(parent_path) = ignores_to_update.next() {
2039            while ignores_to_update
2040                .peek()
2041                .map_or(false, |p| p.starts_with(&parent_path))
2042            {
2043                ignores_to_update.next().unwrap();
2044            }
2045
2046            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2047            ignore_queue_tx
2048                .send(UpdateIgnoreStatusJob {
2049                    path: parent_path,
2050                    ignore_stack,
2051                    ignore_queue: ignore_queue_tx.clone(),
2052                })
2053                .await
2054                .unwrap();
2055        }
2056        drop(ignore_queue_tx);
2057
2058        self.executor
2059            .scoped(|scope| {
2060                for _ in 0..self.executor.num_cpus() {
2061                    scope.spawn(async {
2062                        while let Ok(job) = ignore_queue_rx.recv().await {
2063                            self.update_ignore_status(job, &snapshot).await;
2064                        }
2065                    });
2066                }
2067            })
2068            .await;
2069    }
2070
2071    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2072        let mut ignore_stack = job.ignore_stack;
2073        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2074            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2075        }
2076
2077        let mut entries_by_id_edits = Vec::new();
2078        let mut entries_by_path_edits = Vec::new();
2079        for mut entry in snapshot.child_entries(&job.path).cloned() {
2080            let was_ignored = entry.is_ignored;
2081            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2082            if entry.is_dir() {
2083                let child_ignore_stack = if entry.is_ignored {
2084                    IgnoreStack::all()
2085                } else {
2086                    ignore_stack.clone()
2087                };
2088                job.ignore_queue
2089                    .send(UpdateIgnoreStatusJob {
2090                        path: entry.path.clone(),
2091                        ignore_stack: child_ignore_stack,
2092                        ignore_queue: job.ignore_queue.clone(),
2093                    })
2094                    .await
2095                    .unwrap();
2096            }
2097
2098            if entry.is_ignored != was_ignored {
2099                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2100                path_entry.scan_id = snapshot.scan_id;
2101                path_entry.is_ignored = entry.is_ignored;
2102                entries_by_id_edits.push(Edit::Insert(path_entry));
2103                entries_by_path_edits.push(Edit::Insert(entry));
2104            }
2105        }
2106
2107        let mut snapshot = self.snapshot.lock();
2108        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2109        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2110    }
2111}
2112
2113async fn refresh_entry(
2114    fs: &dyn Fs,
2115    snapshot: &Mutex<LocalSnapshot>,
2116    path: Arc<Path>,
2117    abs_path: &Path,
2118) -> Result<Entry> {
2119    let root_char_bag;
2120    let next_entry_id;
2121    {
2122        let snapshot = snapshot.lock();
2123        root_char_bag = snapshot.root_char_bag;
2124        next_entry_id = snapshot.next_entry_id.clone();
2125    }
2126    let entry = Entry::new(
2127        path,
2128        &fs.metadata(abs_path)
2129            .await?
2130            .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2131        &next_entry_id,
2132        root_char_bag,
2133    );
2134    Ok(snapshot.lock().insert_entry(entry, fs))
2135}
2136
2137fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2138    let mut result = root_char_bag;
2139    result.extend(
2140        path.to_string_lossy()
2141            .chars()
2142            .map(|c| c.to_ascii_lowercase()),
2143    );
2144    result
2145}
2146
2147struct ScanJob {
2148    abs_path: PathBuf,
2149    path: Arc<Path>,
2150    ignore_stack: Arc<IgnoreStack>,
2151    scan_queue: Sender<ScanJob>,
2152}
2153
2154struct UpdateIgnoreStatusJob {
2155    path: Arc<Path>,
2156    ignore_stack: Arc<IgnoreStack>,
2157    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2158}
2159
2160pub trait WorktreeHandle {
2161    #[cfg(any(test, feature = "test-support"))]
2162    fn flush_fs_events<'a>(
2163        &self,
2164        cx: &'a gpui::TestAppContext,
2165    ) -> futures::future::LocalBoxFuture<'a, ()>;
2166}
2167
2168impl WorktreeHandle for ModelHandle<Worktree> {
2169    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2170    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2171    // extra directory scans, and emit extra scan-state notifications.
2172    //
2173    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2174    // to ensure that all redundant FS events have already been processed.
2175    #[cfg(any(test, feature = "test-support"))]
2176    fn flush_fs_events<'a>(
2177        &self,
2178        cx: &'a gpui::TestAppContext,
2179    ) -> futures::future::LocalBoxFuture<'a, ()> {
2180        use smol::future::FutureExt;
2181
2182        let filename = "fs-event-sentinel";
2183        let tree = self.clone();
2184        let (fs, root_path) = self.read_with(cx, |tree, _| {
2185            let tree = tree.as_local().unwrap();
2186            (tree.fs.clone(), tree.abs_path().clone())
2187        });
2188
2189        async move {
2190            fs.create_file(&root_path.join(filename), Default::default())
2191                .await
2192                .unwrap();
2193            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2194                .await;
2195
2196            fs.remove_file(&root_path.join(filename), Default::default())
2197                .await
2198                .unwrap();
2199            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2200                .await;
2201
2202            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2203                .await;
2204        }
2205        .boxed_local()
2206    }
2207}
2208
2209#[derive(Clone, Debug)]
2210struct TraversalProgress<'a> {
2211    max_path: &'a Path,
2212    count: usize,
2213    visible_count: usize,
2214    file_count: usize,
2215    visible_file_count: usize,
2216}
2217
2218impl<'a> TraversalProgress<'a> {
2219    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2220        match (include_ignored, include_dirs) {
2221            (true, true) => self.count,
2222            (true, false) => self.file_count,
2223            (false, true) => self.visible_count,
2224            (false, false) => self.visible_file_count,
2225        }
2226    }
2227}
2228
2229impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2230    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2231        self.max_path = summary.max_path.as_ref();
2232        self.count += summary.count;
2233        self.visible_count += summary.visible_count;
2234        self.file_count += summary.file_count;
2235        self.visible_file_count += summary.visible_file_count;
2236    }
2237}
2238
2239impl<'a> Default for TraversalProgress<'a> {
2240    fn default() -> Self {
2241        Self {
2242            max_path: Path::new(""),
2243            count: 0,
2244            visible_count: 0,
2245            file_count: 0,
2246            visible_file_count: 0,
2247        }
2248    }
2249}
2250
2251pub struct Traversal<'a> {
2252    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2253    include_ignored: bool,
2254    include_dirs: bool,
2255}
2256
2257impl<'a> Traversal<'a> {
2258    pub fn advance(&mut self) -> bool {
2259        self.advance_to_offset(self.offset() + 1)
2260    }
2261
2262    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2263        self.cursor.seek_forward(
2264            &TraversalTarget::Count {
2265                count: offset,
2266                include_dirs: self.include_dirs,
2267                include_ignored: self.include_ignored,
2268            },
2269            Bias::Right,
2270            &(),
2271        )
2272    }
2273
2274    pub fn advance_to_sibling(&mut self) -> bool {
2275        while let Some(entry) = self.cursor.item() {
2276            self.cursor.seek_forward(
2277                &TraversalTarget::PathSuccessor(&entry.path),
2278                Bias::Left,
2279                &(),
2280            );
2281            if let Some(entry) = self.cursor.item() {
2282                if (self.include_dirs || !entry.is_dir())
2283                    && (self.include_ignored || !entry.is_ignored)
2284                {
2285                    return true;
2286                }
2287            }
2288        }
2289        false
2290    }
2291
2292    pub fn entry(&self) -> Option<&'a Entry> {
2293        self.cursor.item()
2294    }
2295
2296    pub fn offset(&self) -> usize {
2297        self.cursor
2298            .start()
2299            .count(self.include_dirs, self.include_ignored)
2300    }
2301}
2302
2303impl<'a> Iterator for Traversal<'a> {
2304    type Item = &'a Entry;
2305
2306    fn next(&mut self) -> Option<Self::Item> {
2307        if let Some(item) = self.entry() {
2308            self.advance();
2309            Some(item)
2310        } else {
2311            None
2312        }
2313    }
2314}
2315
2316#[derive(Debug)]
2317enum TraversalTarget<'a> {
2318    Path(&'a Path),
2319    PathSuccessor(&'a Path),
2320    Count {
2321        count: usize,
2322        include_ignored: bool,
2323        include_dirs: bool,
2324    },
2325}
2326
2327impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2328    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2329        match self {
2330            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2331            TraversalTarget::PathSuccessor(path) => {
2332                if !cursor_location.max_path.starts_with(path) {
2333                    Ordering::Equal
2334                } else {
2335                    Ordering::Greater
2336                }
2337            }
2338            TraversalTarget::Count {
2339                count,
2340                include_dirs,
2341                include_ignored,
2342            } => Ord::cmp(
2343                count,
2344                &cursor_location.count(*include_dirs, *include_ignored),
2345            ),
2346        }
2347    }
2348}
2349
2350struct ChildEntriesIter<'a> {
2351    parent_path: &'a Path,
2352    traversal: Traversal<'a>,
2353}
2354
2355impl<'a> Iterator for ChildEntriesIter<'a> {
2356    type Item = &'a Entry;
2357
2358    fn next(&mut self) -> Option<Self::Item> {
2359        if let Some(item) = self.traversal.entry() {
2360            if item.path.starts_with(&self.parent_path) {
2361                self.traversal.advance_to_sibling();
2362                return Some(item);
2363            }
2364        }
2365        None
2366    }
2367}
2368
2369impl<'a> From<&'a Entry> for proto::Entry {
2370    fn from(entry: &'a Entry) -> Self {
2371        Self {
2372            id: entry.id as u64,
2373            is_dir: entry.is_dir(),
2374            path: entry.path.to_string_lossy().to_string(),
2375            inode: entry.inode,
2376            mtime: Some(entry.mtime.into()),
2377            is_symlink: entry.is_symlink,
2378            is_ignored: entry.is_ignored,
2379        }
2380    }
2381}
2382
2383impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2384    type Error = anyhow::Error;
2385
2386    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2387        if let Some(mtime) = entry.mtime {
2388            let kind = if entry.is_dir {
2389                EntryKind::Dir
2390            } else {
2391                let mut char_bag = root_char_bag.clone();
2392                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2393                EntryKind::File(char_bag)
2394            };
2395            let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2396            Ok(Entry {
2397                id: entry.id as usize,
2398                kind,
2399                path: path.clone(),
2400                inode: entry.inode,
2401                mtime: mtime.into(),
2402                is_symlink: entry.is_symlink,
2403                is_ignored: entry.is_ignored,
2404            })
2405        } else {
2406            Err(anyhow!(
2407                "missing mtime in remote worktree entry {:?}",
2408                entry.path
2409            ))
2410        }
2411    }
2412}
2413
2414#[cfg(test)]
2415mod tests {
2416    use super::*;
2417    use crate::fs::FakeFs;
2418    use anyhow::Result;
2419    use client::test::FakeHttpClient;
2420    use fs::RealFs;
2421    use rand::prelude::*;
2422    use serde_json::json;
2423    use std::{
2424        env,
2425        fmt::Write,
2426        time::{SystemTime, UNIX_EPOCH},
2427    };
2428    use util::test::temp_tree;
2429
2430    #[gpui::test]
2431    async fn test_traversal(cx: gpui::TestAppContext) {
2432        let fs = FakeFs::new(cx.background());
2433        fs.insert_tree(
2434            "/root",
2435            json!({
2436               ".gitignore": "a/b\n",
2437               "a": {
2438                   "b": "",
2439                   "c": "",
2440               }
2441            }),
2442        )
2443        .await;
2444
2445        let http_client = FakeHttpClient::with_404_response();
2446        let client = Client::new(http_client);
2447
2448        let tree = Worktree::local(
2449            client,
2450            Arc::from(Path::new("/root")),
2451            false,
2452            Arc::new(fs),
2453            &mut cx.to_async(),
2454        )
2455        .await
2456        .unwrap();
2457        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2458            .await;
2459
2460        tree.read_with(&cx, |tree, _| {
2461            assert_eq!(
2462                tree.entries(false)
2463                    .map(|entry| entry.path.as_ref())
2464                    .collect::<Vec<_>>(),
2465                vec![
2466                    Path::new(""),
2467                    Path::new(".gitignore"),
2468                    Path::new("a"),
2469                    Path::new("a/c"),
2470                ]
2471            );
2472        })
2473    }
2474
2475    #[gpui::test]
2476    async fn test_rescan_with_gitignore(cx: gpui::TestAppContext) {
2477        let dir = temp_tree(json!({
2478            ".git": {},
2479            ".gitignore": "ignored-dir\n",
2480            "tracked-dir": {
2481                "tracked-file1": "tracked contents",
2482            },
2483            "ignored-dir": {
2484                "ignored-file1": "ignored contents",
2485            }
2486        }));
2487
2488        let http_client = FakeHttpClient::with_404_response();
2489        let client = Client::new(http_client.clone());
2490
2491        let tree = Worktree::local(
2492            client,
2493            dir.path(),
2494            false,
2495            Arc::new(RealFs),
2496            &mut cx.to_async(),
2497        )
2498        .await
2499        .unwrap();
2500        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2501            .await;
2502        tree.flush_fs_events(&cx).await;
2503        cx.read(|cx| {
2504            let tree = tree.read(cx);
2505            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2506            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2507            assert_eq!(tracked.is_ignored, false);
2508            assert_eq!(ignored.is_ignored, true);
2509        });
2510
2511        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2512        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2513        tree.flush_fs_events(&cx).await;
2514        cx.read(|cx| {
2515            let tree = tree.read(cx);
2516            let dot_git = tree.entry_for_path(".git").unwrap();
2517            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2518            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2519            assert_eq!(tracked.is_ignored, false);
2520            assert_eq!(ignored.is_ignored, true);
2521            assert_eq!(dot_git.is_ignored, true);
2522        });
2523    }
2524
2525    #[gpui::test(iterations = 100)]
2526    fn test_random(mut rng: StdRng) {
2527        let operations = env::var("OPERATIONS")
2528            .map(|o| o.parse().unwrap())
2529            .unwrap_or(40);
2530        let initial_entries = env::var("INITIAL_ENTRIES")
2531            .map(|o| o.parse().unwrap())
2532            .unwrap_or(20);
2533
2534        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2535        for _ in 0..initial_entries {
2536            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2537        }
2538        log::info!("Generated initial tree");
2539
2540        let (notify_tx, _notify_rx) = mpsc::unbounded();
2541        let fs = Arc::new(RealFs);
2542        let next_entry_id = Arc::new(AtomicUsize::new(0));
2543        let mut initial_snapshot = LocalSnapshot {
2544            abs_path: root_dir.path().into(),
2545            scan_id: 0,
2546            removed_entry_ids: Default::default(),
2547            ignores: Default::default(),
2548            next_entry_id: next_entry_id.clone(),
2549            snapshot: Snapshot {
2550                id: WorktreeId::from_usize(0),
2551                entries_by_path: Default::default(),
2552                entries_by_id: Default::default(),
2553                root_name: Default::default(),
2554                root_char_bag: Default::default(),
2555            },
2556        };
2557        initial_snapshot.insert_entry(
2558            Entry::new(
2559                Path::new("").into(),
2560                &smol::block_on(fs.metadata(root_dir.path()))
2561                    .unwrap()
2562                    .unwrap(),
2563                &next_entry_id,
2564                Default::default(),
2565            ),
2566            fs.as_ref(),
2567        );
2568        let mut scanner = BackgroundScanner::new(
2569            Arc::new(Mutex::new(initial_snapshot.clone())),
2570            notify_tx,
2571            fs.clone(),
2572            Arc::new(gpui::executor::Background::new()),
2573        );
2574        smol::block_on(scanner.scan_dirs()).unwrap();
2575        scanner.snapshot().check_invariants();
2576
2577        let mut events = Vec::new();
2578        let mut snapshots = Vec::new();
2579        let mut mutations_len = operations;
2580        while mutations_len > 1 {
2581            if !events.is_empty() && rng.gen_bool(0.4) {
2582                let len = rng.gen_range(0..=events.len());
2583                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2584                log::info!("Delivering events: {:#?}", to_deliver);
2585                smol::block_on(scanner.process_events(to_deliver));
2586                scanner.snapshot().check_invariants();
2587            } else {
2588                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2589                mutations_len -= 1;
2590            }
2591
2592            if rng.gen_bool(0.2) {
2593                snapshots.push(scanner.snapshot());
2594            }
2595        }
2596        log::info!("Quiescing: {:#?}", events);
2597        smol::block_on(scanner.process_events(events));
2598        scanner.snapshot().check_invariants();
2599
2600        let (notify_tx, _notify_rx) = mpsc::unbounded();
2601        let mut new_scanner = BackgroundScanner::new(
2602            Arc::new(Mutex::new(initial_snapshot)),
2603            notify_tx,
2604            scanner.fs.clone(),
2605            scanner.executor.clone(),
2606        );
2607        smol::block_on(new_scanner.scan_dirs()).unwrap();
2608        assert_eq!(
2609            scanner.snapshot().to_vec(true),
2610            new_scanner.snapshot().to_vec(true)
2611        );
2612
2613        let mut update_id = 0;
2614        for mut prev_snapshot in snapshots {
2615            let include_ignored = rng.gen::<bool>();
2616            if !include_ignored {
2617                let mut entries_by_path_edits = Vec::new();
2618                let mut entries_by_id_edits = Vec::new();
2619                for entry in prev_snapshot
2620                    .entries_by_id
2621                    .cursor::<()>()
2622                    .filter(|e| e.is_ignored)
2623                {
2624                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2625                    entries_by_id_edits.push(Edit::Remove(entry.id));
2626                }
2627
2628                prev_snapshot
2629                    .entries_by_path
2630                    .edit(entries_by_path_edits, &());
2631                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2632            }
2633
2634            let update = scanner.snapshot().build_update(
2635                &prev_snapshot,
2636                0,
2637                0,
2638                post_inc(&mut update_id),
2639                include_ignored,
2640            );
2641            prev_snapshot.apply_remote_update(update).unwrap();
2642            assert_eq!(
2643                prev_snapshot.to_vec(true),
2644                scanner.snapshot().to_vec(include_ignored)
2645            );
2646        }
2647    }
2648
2649    fn randomly_mutate_tree(
2650        root_path: &Path,
2651        insertion_probability: f64,
2652        rng: &mut impl Rng,
2653    ) -> Result<Vec<fsevent::Event>> {
2654        let root_path = root_path.canonicalize().unwrap();
2655        let (dirs, files) = read_dir_recursive(root_path.clone());
2656
2657        let mut events = Vec::new();
2658        let mut record_event = |path: PathBuf| {
2659            events.push(fsevent::Event {
2660                event_id: SystemTime::now()
2661                    .duration_since(UNIX_EPOCH)
2662                    .unwrap()
2663                    .as_secs(),
2664                flags: fsevent::StreamFlags::empty(),
2665                path,
2666            });
2667        };
2668
2669        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2670            let path = dirs.choose(rng).unwrap();
2671            let new_path = path.join(gen_name(rng));
2672
2673            if rng.gen() {
2674                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2675                std::fs::create_dir(&new_path)?;
2676            } else {
2677                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2678                std::fs::write(&new_path, "")?;
2679            }
2680            record_event(new_path);
2681        } else if rng.gen_bool(0.05) {
2682            let ignore_dir_path = dirs.choose(rng).unwrap();
2683            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2684
2685            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2686            let files_to_ignore = {
2687                let len = rng.gen_range(0..=subfiles.len());
2688                subfiles.choose_multiple(rng, len)
2689            };
2690            let dirs_to_ignore = {
2691                let len = rng.gen_range(0..subdirs.len());
2692                subdirs.choose_multiple(rng, len)
2693            };
2694
2695            let mut ignore_contents = String::new();
2696            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2697                write!(
2698                    ignore_contents,
2699                    "{}\n",
2700                    path_to_ignore
2701                        .strip_prefix(&ignore_dir_path)?
2702                        .to_str()
2703                        .unwrap()
2704                )
2705                .unwrap();
2706            }
2707            log::info!(
2708                "Creating {:?} with contents:\n{}",
2709                ignore_path.strip_prefix(&root_path)?,
2710                ignore_contents
2711            );
2712            std::fs::write(&ignore_path, ignore_contents).unwrap();
2713            record_event(ignore_path);
2714        } else {
2715            let old_path = {
2716                let file_path = files.choose(rng);
2717                let dir_path = dirs[1..].choose(rng);
2718                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2719            };
2720
2721            let is_rename = rng.gen();
2722            if is_rename {
2723                let new_path_parent = dirs
2724                    .iter()
2725                    .filter(|d| !d.starts_with(old_path))
2726                    .choose(rng)
2727                    .unwrap();
2728
2729                let overwrite_existing_dir =
2730                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2731                let new_path = if overwrite_existing_dir {
2732                    std::fs::remove_dir_all(&new_path_parent).ok();
2733                    new_path_parent.to_path_buf()
2734                } else {
2735                    new_path_parent.join(gen_name(rng))
2736                };
2737
2738                log::info!(
2739                    "Renaming {:?} to {}{:?}",
2740                    old_path.strip_prefix(&root_path)?,
2741                    if overwrite_existing_dir {
2742                        "overwrite "
2743                    } else {
2744                        ""
2745                    },
2746                    new_path.strip_prefix(&root_path)?
2747                );
2748                std::fs::rename(&old_path, &new_path)?;
2749                record_event(old_path.clone());
2750                record_event(new_path);
2751            } else if old_path.is_dir() {
2752                let (dirs, files) = read_dir_recursive(old_path.clone());
2753
2754                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2755                std::fs::remove_dir_all(&old_path).unwrap();
2756                for file in files {
2757                    record_event(file);
2758                }
2759                for dir in dirs {
2760                    record_event(dir);
2761                }
2762            } else {
2763                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2764                std::fs::remove_file(old_path).unwrap();
2765                record_event(old_path.clone());
2766            }
2767        }
2768
2769        Ok(events)
2770    }
2771
2772    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2773        let child_entries = std::fs::read_dir(&path).unwrap();
2774        let mut dirs = vec![path];
2775        let mut files = Vec::new();
2776        for child_entry in child_entries {
2777            let child_path = child_entry.unwrap().path();
2778            if child_path.is_dir() {
2779                let (child_dirs, child_files) = read_dir_recursive(child_path);
2780                dirs.extend(child_dirs);
2781                files.extend(child_files);
2782            } else {
2783                files.push(child_path);
2784            }
2785        }
2786        (dirs, files)
2787    }
2788
2789    fn gen_name(rng: &mut impl Rng) -> String {
2790        (0..6)
2791            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2792            .map(char::from)
2793            .collect()
2794    }
2795
2796    impl LocalSnapshot {
2797        fn check_invariants(&self) {
2798            let mut files = self.files(true, 0);
2799            let mut visible_files = self.files(false, 0);
2800            for entry in self.entries_by_path.cursor::<()>() {
2801                if entry.is_file() {
2802                    assert_eq!(files.next().unwrap().inode, entry.inode);
2803                    if !entry.is_ignored {
2804                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2805                    }
2806                }
2807            }
2808            assert!(files.next().is_none());
2809            assert!(visible_files.next().is_none());
2810
2811            let mut bfs_paths = Vec::new();
2812            let mut stack = vec![Path::new("")];
2813            while let Some(path) = stack.pop() {
2814                bfs_paths.push(path);
2815                let ix = stack.len();
2816                for child_entry in self.child_entries(path) {
2817                    stack.insert(ix, &child_entry.path);
2818                }
2819            }
2820
2821            let dfs_paths = self
2822                .entries_by_path
2823                .cursor::<()>()
2824                .map(|e| e.path.as_ref())
2825                .collect::<Vec<_>>();
2826            assert_eq!(bfs_paths, dfs_paths);
2827
2828            for (ignore_parent_path, _) in &self.ignores {
2829                assert!(self.entry_for_path(ignore_parent_path).is_some());
2830                assert!(self
2831                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2832                    .is_some());
2833            }
2834        }
2835
2836        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2837            let mut paths = Vec::new();
2838            for entry in self.entries_by_path.cursor::<()>() {
2839                if include_ignored || !entry.is_ignored {
2840                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2841                }
2842            }
2843            paths.sort_by(|a, b| a.0.cmp(&b.0));
2844            paths
2845        }
2846    }
2847}