worktree.rs

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