worktree.rs

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