worktree.rs

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