1use crate::{
2 copy_recursive, ignore::IgnoreStack, project_settings::ProjectSettings, DiagnosticSummary,
3 ProjectEntryId, RemoveOptions,
4};
5use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
6use anyhow::{anyhow, Context as _, Result};
7use client::{proto, Client};
8use clock::ReplicaId;
9use collections::{HashMap, HashSet, VecDeque};
10use fs::{
11 repository::{GitFileStatus, GitRepository, RepoPath},
12 Fs,
13};
14use futures::{
15 channel::{
16 mpsc::{self, UnboundedSender},
17 oneshot,
18 },
19 select_biased,
20 task::Poll,
21 FutureExt as _, Stream, StreamExt,
22};
23use fuzzy::CharBag;
24use git::{DOT_GIT, GITIGNORE};
25use gpui::{
26 AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, Model, ModelContext,
27 Task,
28};
29use itertools::Itertools;
30use language::{
31 proto::{
32 deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
33 serialize_version,
34 },
35 Buffer, DiagnosticEntry, File as _, LineEnding, PointUtf16, Rope, RopeFingerprint, Unclipped,
36};
37use lsp::LanguageServerId;
38use parking_lot::Mutex;
39use postage::{
40 barrier,
41 prelude::{Sink as _, Stream as _},
42 watch,
43};
44use settings::{Settings, SettingsStore};
45use smol::channel::{self, Sender};
46use std::{
47 any::Any,
48 cmp::{self, Ordering},
49 convert::TryFrom,
50 ffi::OsStr,
51 fmt,
52 future::Future,
53 mem,
54 ops::{AddAssign, Deref, DerefMut, Sub},
55 path::{Path, PathBuf},
56 pin::Pin,
57 sync::{
58 atomic::{AtomicUsize, Ordering::SeqCst},
59 Arc,
60 },
61 time::{Duration, SystemTime},
62};
63use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
64use util::{
65 paths::{PathMatcher, HOME},
66 ResultExt,
67};
68
69#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
70pub struct WorktreeId(usize);
71
72pub enum Worktree {
73 Local(LocalWorktree),
74 Remote(RemoteWorktree),
75}
76
77pub struct LocalWorktree {
78 snapshot: LocalSnapshot,
79 scan_requests_tx: channel::Sender<ScanRequest>,
80 path_prefixes_to_scan_tx: channel::Sender<Arc<Path>>,
81 is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
82 _background_scanner_tasks: Vec<Task<()>>,
83 share: Option<ShareState>,
84 diagnostics: HashMap<
85 Arc<Path>,
86 Vec<(
87 LanguageServerId,
88 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
89 )>,
90 >,
91 diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
92 client: Arc<Client>,
93 fs: Arc<dyn Fs>,
94 visible: bool,
95}
96
97struct ScanRequest {
98 relative_paths: Vec<Arc<Path>>,
99 done: barrier::Sender,
100}
101
102pub struct RemoteWorktree {
103 snapshot: Snapshot,
104 background_snapshot: Arc<Mutex<Snapshot>>,
105 project_id: u64,
106 client: Arc<Client>,
107 updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
108 snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
109 replica_id: ReplicaId,
110 diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
111 visible: bool,
112 disconnected: bool,
113}
114
115#[derive(Clone)]
116pub struct Snapshot {
117 id: WorktreeId,
118 abs_path: Arc<Path>,
119 root_name: String,
120 root_char_bag: CharBag,
121 entries_by_path: SumTree<Entry>,
122 entries_by_id: SumTree<PathEntry>,
123 repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
124
125 /// A number that increases every time the worktree begins scanning
126 /// a set of paths from the filesystem. This scanning could be caused
127 /// by some operation performed on the worktree, such as reading or
128 /// writing a file, or by an event reported by the filesystem.
129 scan_id: usize,
130
131 /// The latest scan id that has completed, and whose preceding scans
132 /// have all completed. The current `scan_id` could be more than one
133 /// greater than the `completed_scan_id` if operations are performed
134 /// on the worktree while it is processing a file-system event.
135 completed_scan_id: usize,
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct RepositoryEntry {
140 pub(crate) work_directory: WorkDirectoryEntry,
141 pub(crate) branch: Option<Arc<str>>,
142}
143
144impl RepositoryEntry {
145 pub fn branch(&self) -> Option<Arc<str>> {
146 self.branch.clone()
147 }
148
149 pub fn work_directory_id(&self) -> ProjectEntryId {
150 *self.work_directory
151 }
152
153 pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
154 snapshot
155 .entry_for_id(self.work_directory_id())
156 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
157 }
158
159 pub fn build_update(&self, _: &Self) -> proto::RepositoryEntry {
160 proto::RepositoryEntry {
161 work_directory_id: self.work_directory_id().to_proto(),
162 branch: self.branch.as_ref().map(|str| str.to_string()),
163 }
164 }
165}
166
167impl From<&RepositoryEntry> for proto::RepositoryEntry {
168 fn from(value: &RepositoryEntry) -> Self {
169 proto::RepositoryEntry {
170 work_directory_id: value.work_directory.to_proto(),
171 branch: value.branch.as_ref().map(|str| str.to_string()),
172 }
173 }
174}
175
176/// This path corresponds to the 'content path' (the folder that contains the .git)
177#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
178pub struct RepositoryWorkDirectory(pub(crate) Arc<Path>);
179
180impl Default for RepositoryWorkDirectory {
181 fn default() -> Self {
182 RepositoryWorkDirectory(Arc::from(Path::new("")))
183 }
184}
185
186impl AsRef<Path> for RepositoryWorkDirectory {
187 fn as_ref(&self) -> &Path {
188 self.0.as_ref()
189 }
190}
191
192#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
193pub struct WorkDirectoryEntry(ProjectEntryId);
194
195impl WorkDirectoryEntry {
196 pub(crate) fn relativize(&self, worktree: &Snapshot, path: &Path) -> Option<RepoPath> {
197 worktree.entry_for_id(self.0).and_then(|entry| {
198 path.strip_prefix(&entry.path)
199 .ok()
200 .map(move |path| path.into())
201 })
202 }
203}
204
205impl Deref for WorkDirectoryEntry {
206 type Target = ProjectEntryId;
207
208 fn deref(&self) -> &Self::Target {
209 &self.0
210 }
211}
212
213impl<'a> From<ProjectEntryId> for WorkDirectoryEntry {
214 fn from(value: ProjectEntryId) -> Self {
215 WorkDirectoryEntry(value)
216 }
217}
218
219#[derive(Debug, Clone)]
220pub struct LocalSnapshot {
221 snapshot: Snapshot,
222 /// All of the gitignore files in the worktree, indexed by their relative path.
223 /// The boolean indicates whether the gitignore needs to be updated.
224 ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
225 /// All of the git repositories in the worktree, indexed by the project entry
226 /// id of their parent directory.
227 git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
228 file_scan_exclusions: Vec<PathMatcher>,
229}
230
231struct BackgroundScannerState {
232 snapshot: LocalSnapshot,
233 scanned_dirs: HashSet<ProjectEntryId>,
234 path_prefixes_to_scan: HashSet<Arc<Path>>,
235 paths_to_scan: HashSet<Arc<Path>>,
236 /// The ids of all of the entries that were removed from the snapshot
237 /// as part of the current update. These entry ids may be re-used
238 /// if the same inode is discovered at a new path, or if the given
239 /// path is re-created after being deleted.
240 removed_entry_ids: HashMap<u64, ProjectEntryId>,
241 changed_paths: Vec<Arc<Path>>,
242 prev_snapshot: Snapshot,
243}
244
245#[derive(Debug, Clone)]
246pub struct LocalRepositoryEntry {
247 pub(crate) git_dir_scan_id: usize,
248 pub(crate) repo_ptr: Arc<Mutex<dyn GitRepository>>,
249 /// Path to the actual .git folder.
250 /// Note: if .git is a file, this points to the folder indicated by the .git file
251 pub(crate) git_dir_path: Arc<Path>,
252}
253
254impl Deref for LocalSnapshot {
255 type Target = Snapshot;
256
257 fn deref(&self) -> &Self::Target {
258 &self.snapshot
259 }
260}
261
262impl DerefMut for LocalSnapshot {
263 fn deref_mut(&mut self) -> &mut Self::Target {
264 &mut self.snapshot
265 }
266}
267
268enum ScanState {
269 Started,
270 Updated {
271 snapshot: LocalSnapshot,
272 changes: UpdatedEntriesSet,
273 barrier: Option<barrier::Sender>,
274 scanning: bool,
275 },
276}
277
278struct ShareState {
279 project_id: u64,
280 snapshots_tx:
281 mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>,
282 resume_updates: watch::Sender<()>,
283 _maintain_remote_snapshot: Task<Option<()>>,
284}
285
286#[derive(Clone)]
287pub enum Event {
288 UpdatedEntries(UpdatedEntriesSet),
289 UpdatedGitRepositories(UpdatedGitRepositoriesSet),
290}
291
292impl EventEmitter<Event> for Worktree {}
293
294impl Worktree {
295 pub async fn local(
296 client: Arc<Client>,
297 path: impl Into<Arc<Path>>,
298 visible: bool,
299 fs: Arc<dyn Fs>,
300 next_entry_id: Arc<AtomicUsize>,
301 cx: &mut AsyncAppContext,
302 ) -> Result<Model<Self>> {
303 // After determining whether the root entry is a file or a directory, populate the
304 // snapshot's "root name", which will be used for the purpose of fuzzy matching.
305 let abs_path = path.into();
306
307 let metadata = fs
308 .metadata(&abs_path)
309 .await
310 .context("failed to stat worktree path")?;
311
312 let closure_fs = Arc::clone(&fs);
313 let closure_next_entry_id = Arc::clone(&next_entry_id);
314 let closure_abs_path = abs_path.to_path_buf();
315 cx.new_model(move |cx: &mut ModelContext<Worktree>| {
316 cx.observe_global::<SettingsStore>(move |this, cx| {
317 if let Self::Local(this) = this {
318 let new_file_scan_exclusions =
319 file_scan_exclusions(ProjectSettings::get_global(cx));
320 if new_file_scan_exclusions != this.snapshot.file_scan_exclusions {
321 this.snapshot.file_scan_exclusions = new_file_scan_exclusions;
322 log::info!(
323 "Re-scanning directories, new scan exclude files: {:?}",
324 this.snapshot
325 .file_scan_exclusions
326 .iter()
327 .map(ToString::to_string)
328 .collect::<Vec<_>>()
329 );
330
331 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
332 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) =
333 channel::unbounded();
334 this.scan_requests_tx = scan_requests_tx;
335 this.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
336 this._background_scanner_tasks = start_background_scan_tasks(
337 &closure_abs_path,
338 this.snapshot(),
339 scan_requests_rx,
340 path_prefixes_to_scan_rx,
341 Arc::clone(&closure_next_entry_id),
342 Arc::clone(&closure_fs),
343 cx,
344 );
345 this.is_scanning = watch::channel_with(true);
346 }
347 }
348 })
349 .detach();
350
351 let root_name = abs_path
352 .file_name()
353 .map_or(String::new(), |f| f.to_string_lossy().to_string());
354
355 let mut snapshot = LocalSnapshot {
356 file_scan_exclusions: file_scan_exclusions(ProjectSettings::get_global(cx)),
357 ignores_by_parent_abs_path: Default::default(),
358 git_repositories: Default::default(),
359 snapshot: Snapshot {
360 id: WorktreeId::from_usize(cx.entity_id().as_u64() as usize),
361 abs_path: abs_path.to_path_buf().into(),
362 root_name: root_name.clone(),
363 root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
364 entries_by_path: Default::default(),
365 entries_by_id: Default::default(),
366 repository_entries: Default::default(),
367 scan_id: 1,
368 completed_scan_id: 0,
369 },
370 };
371
372 if let Some(metadata) = metadata {
373 snapshot.insert_entry(
374 Entry::new(
375 Arc::from(Path::new("")),
376 &metadata,
377 &next_entry_id,
378 snapshot.root_char_bag,
379 ),
380 fs.as_ref(),
381 );
382 }
383
384 let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
385 let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
386 let task_snapshot = snapshot.clone();
387 Worktree::Local(LocalWorktree {
388 snapshot,
389 is_scanning: watch::channel_with(true),
390 share: None,
391 scan_requests_tx,
392 path_prefixes_to_scan_tx,
393 _background_scanner_tasks: start_background_scan_tasks(
394 &abs_path,
395 task_snapshot,
396 scan_requests_rx,
397 path_prefixes_to_scan_rx,
398 Arc::clone(&next_entry_id),
399 Arc::clone(&fs),
400 cx,
401 ),
402 diagnostics: Default::default(),
403 diagnostic_summaries: Default::default(),
404 client,
405 fs,
406 visible,
407 })
408 })
409 }
410
411 pub fn remote(
412 project_remote_id: u64,
413 replica_id: ReplicaId,
414 worktree: proto::WorktreeMetadata,
415 client: Arc<Client>,
416 cx: &mut AppContext,
417 ) -> Model<Self> {
418 cx.new_model(|cx: &mut ModelContext<Self>| {
419 let snapshot = Snapshot {
420 id: WorktreeId(worktree.id as usize),
421 abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
422 root_name: worktree.root_name.clone(),
423 root_char_bag: worktree
424 .root_name
425 .chars()
426 .map(|c| c.to_ascii_lowercase())
427 .collect(),
428 entries_by_path: Default::default(),
429 entries_by_id: Default::default(),
430 repository_entries: Default::default(),
431 scan_id: 1,
432 completed_scan_id: 0,
433 };
434
435 let (updates_tx, mut updates_rx) = mpsc::unbounded();
436 let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
437 let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
438
439 cx.background_executor()
440 .spawn({
441 let background_snapshot = background_snapshot.clone();
442 async move {
443 while let Some(update) = updates_rx.next().await {
444 if let Err(error) =
445 background_snapshot.lock().apply_remote_update(update)
446 {
447 log::error!("error applying worktree update: {}", error);
448 }
449 snapshot_updated_tx.send(()).await.ok();
450 }
451 }
452 })
453 .detach();
454
455 cx.spawn(|this, mut cx| async move {
456 while (snapshot_updated_rx.recv().await).is_some() {
457 this.update(&mut cx, |this, cx| {
458 let this = this.as_remote_mut().unwrap();
459 this.snapshot = this.background_snapshot.lock().clone();
460 cx.emit(Event::UpdatedEntries(Arc::from([])));
461 cx.notify();
462 while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
463 if this.observed_snapshot(*scan_id) {
464 let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
465 let _ = tx.send(());
466 } else {
467 break;
468 }
469 }
470 })?;
471 }
472 anyhow::Ok(())
473 })
474 .detach();
475
476 Worktree::Remote(RemoteWorktree {
477 project_id: project_remote_id,
478 replica_id,
479 snapshot: snapshot.clone(),
480 background_snapshot,
481 updates_tx: Some(updates_tx),
482 snapshot_subscriptions: Default::default(),
483 client: client.clone(),
484 diagnostic_summaries: Default::default(),
485 visible: worktree.visible,
486 disconnected: false,
487 })
488 })
489 }
490
491 pub fn as_local(&self) -> Option<&LocalWorktree> {
492 if let Worktree::Local(worktree) = self {
493 Some(worktree)
494 } else {
495 None
496 }
497 }
498
499 pub fn as_remote(&self) -> Option<&RemoteWorktree> {
500 if let Worktree::Remote(worktree) = self {
501 Some(worktree)
502 } else {
503 None
504 }
505 }
506
507 pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
508 if let Worktree::Local(worktree) = self {
509 Some(worktree)
510 } else {
511 None
512 }
513 }
514
515 pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
516 if let Worktree::Remote(worktree) = self {
517 Some(worktree)
518 } else {
519 None
520 }
521 }
522
523 pub fn is_local(&self) -> bool {
524 matches!(self, Worktree::Local(_))
525 }
526
527 pub fn is_remote(&self) -> bool {
528 !self.is_local()
529 }
530
531 pub fn snapshot(&self) -> Snapshot {
532 match self {
533 Worktree::Local(worktree) => worktree.snapshot().snapshot,
534 Worktree::Remote(worktree) => worktree.snapshot(),
535 }
536 }
537
538 pub fn scan_id(&self) -> usize {
539 match self {
540 Worktree::Local(worktree) => worktree.snapshot.scan_id,
541 Worktree::Remote(worktree) => worktree.snapshot.scan_id,
542 }
543 }
544
545 pub fn completed_scan_id(&self) -> usize {
546 match self {
547 Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
548 Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
549 }
550 }
551
552 pub fn is_visible(&self) -> bool {
553 match self {
554 Worktree::Local(worktree) => worktree.visible,
555 Worktree::Remote(worktree) => worktree.visible,
556 }
557 }
558
559 pub fn replica_id(&self) -> ReplicaId {
560 match self {
561 Worktree::Local(_) => 0,
562 Worktree::Remote(worktree) => worktree.replica_id,
563 }
564 }
565
566 pub fn diagnostic_summaries(
567 &self,
568 ) -> impl Iterator<Item = (Arc<Path>, LanguageServerId, DiagnosticSummary)> + '_ {
569 match self {
570 Worktree::Local(worktree) => &worktree.diagnostic_summaries,
571 Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
572 }
573 .iter()
574 .flat_map(|(path, summaries)| {
575 summaries
576 .iter()
577 .map(move |(&server_id, &summary)| (path.clone(), server_id, summary))
578 })
579 }
580
581 pub fn abs_path(&self) -> Arc<Path> {
582 match self {
583 Worktree::Local(worktree) => worktree.abs_path.clone(),
584 Worktree::Remote(worktree) => worktree.abs_path.clone(),
585 }
586 }
587
588 pub fn root_file(&self, cx: &mut ModelContext<Self>) -> Option<Arc<File>> {
589 let entry = self.root_entry()?;
590 Some(File::for_entry(entry.clone(), cx.handle()))
591 }
592}
593
594fn start_background_scan_tasks(
595 abs_path: &Path,
596 snapshot: LocalSnapshot,
597 scan_requests_rx: channel::Receiver<ScanRequest>,
598 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
599 next_entry_id: Arc<AtomicUsize>,
600 fs: Arc<dyn Fs>,
601 cx: &mut ModelContext<'_, Worktree>,
602) -> Vec<Task<()>> {
603 let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
604 let background_scanner = cx.background_executor().spawn({
605 let abs_path = abs_path.to_path_buf();
606 let background = cx.background_executor().clone();
607 async move {
608 let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
609 BackgroundScanner::new(
610 snapshot,
611 next_entry_id,
612 fs,
613 scan_states_tx,
614 background,
615 scan_requests_rx,
616 path_prefixes_to_scan_rx,
617 )
618 .run(events)
619 .await;
620 }
621 });
622 let scan_state_updater = cx.spawn(|this, mut cx| async move {
623 while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
624 this.update(&mut cx, |this, cx| {
625 let this = this.as_local_mut().unwrap();
626 match state {
627 ScanState::Started => {
628 *this.is_scanning.0.borrow_mut() = true;
629 }
630 ScanState::Updated {
631 snapshot,
632 changes,
633 barrier,
634 scanning,
635 } => {
636 *this.is_scanning.0.borrow_mut() = scanning;
637 this.set_snapshot(snapshot, changes, cx);
638 drop(barrier);
639 }
640 }
641 cx.notify();
642 })
643 .ok();
644 }
645 });
646 vec![background_scanner, scan_state_updater]
647}
648
649fn file_scan_exclusions(project_settings: &ProjectSettings) -> Vec<PathMatcher> {
650 project_settings.file_scan_exclusions.as_deref().unwrap_or(&[]).iter()
651 .sorted()
652 .filter_map(|pattern| {
653 PathMatcher::new(pattern)
654 .map(Some)
655 .unwrap_or_else(|e| {
656 log::error!(
657 "Skipping pattern {pattern} in `file_scan_exclusions` project settings due to parsing error: {e:#}"
658 );
659 None
660 })
661 })
662 .collect()
663}
664
665impl LocalWorktree {
666 pub fn contains_abs_path(&self, path: &Path) -> bool {
667 path.starts_with(&self.abs_path)
668 }
669
670 pub(crate) fn load_buffer(
671 &mut self,
672 id: u64,
673 path: &Path,
674 cx: &mut ModelContext<Worktree>,
675 ) -> Task<Result<Model<Buffer>>> {
676 let path = Arc::from(path);
677 cx.spawn(move |this, mut cx| async move {
678 let (file, contents, diff_base) = this
679 .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))?
680 .await?;
681 let text_buffer = cx
682 .background_executor()
683 .spawn(async move { text::Buffer::new(0, id, contents) })
684 .await;
685 cx.new_model(|_| Buffer::build(text_buffer, diff_base, Some(Arc::new(file))))
686 })
687 }
688
689 pub fn diagnostics_for_path(
690 &self,
691 path: &Path,
692 ) -> Vec<(
693 LanguageServerId,
694 Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
695 )> {
696 self.diagnostics.get(path).cloned().unwrap_or_default()
697 }
698
699 pub fn clear_diagnostics_for_language_server(
700 &mut self,
701 server_id: LanguageServerId,
702 _: &mut ModelContext<Worktree>,
703 ) {
704 let worktree_id = self.id().to_proto();
705 self.diagnostic_summaries
706 .retain(|path, summaries_by_server_id| {
707 if summaries_by_server_id.remove(&server_id).is_some() {
708 if let Some(share) = self.share.as_ref() {
709 self.client
710 .send(proto::UpdateDiagnosticSummary {
711 project_id: share.project_id,
712 worktree_id,
713 summary: Some(proto::DiagnosticSummary {
714 path: path.to_string_lossy().to_string(),
715 language_server_id: server_id.0 as u64,
716 error_count: 0,
717 warning_count: 0,
718 }),
719 })
720 .log_err();
721 }
722 !summaries_by_server_id.is_empty()
723 } else {
724 true
725 }
726 });
727
728 self.diagnostics.retain(|_, diagnostics_by_server_id| {
729 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
730 diagnostics_by_server_id.remove(ix);
731 !diagnostics_by_server_id.is_empty()
732 } else {
733 true
734 }
735 });
736 }
737
738 pub fn update_diagnostics(
739 &mut self,
740 server_id: LanguageServerId,
741 worktree_path: Arc<Path>,
742 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
743 _: &mut ModelContext<Worktree>,
744 ) -> Result<bool> {
745 let summaries_by_server_id = self
746 .diagnostic_summaries
747 .entry(worktree_path.clone())
748 .or_default();
749
750 let old_summary = summaries_by_server_id
751 .remove(&server_id)
752 .unwrap_or_default();
753
754 let new_summary = DiagnosticSummary::new(&diagnostics);
755 if new_summary.is_empty() {
756 if let Some(diagnostics_by_server_id) = self.diagnostics.get_mut(&worktree_path) {
757 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
758 diagnostics_by_server_id.remove(ix);
759 }
760 if diagnostics_by_server_id.is_empty() {
761 self.diagnostics.remove(&worktree_path);
762 }
763 }
764 } else {
765 summaries_by_server_id.insert(server_id, new_summary);
766 let diagnostics_by_server_id =
767 self.diagnostics.entry(worktree_path.clone()).or_default();
768 match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
769 Ok(ix) => {
770 diagnostics_by_server_id[ix] = (server_id, diagnostics);
771 }
772 Err(ix) => {
773 diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
774 }
775 }
776 }
777
778 if !old_summary.is_empty() || !new_summary.is_empty() {
779 if let Some(share) = self.share.as_ref() {
780 self.client
781 .send(proto::UpdateDiagnosticSummary {
782 project_id: share.project_id,
783 worktree_id: self.id().to_proto(),
784 summary: Some(proto::DiagnosticSummary {
785 path: worktree_path.to_string_lossy().to_string(),
786 language_server_id: server_id.0 as u64,
787 error_count: new_summary.error_count as u32,
788 warning_count: new_summary.warning_count as u32,
789 }),
790 })
791 .log_err();
792 }
793 }
794
795 Ok(!old_summary.is_empty() || !new_summary.is_empty())
796 }
797
798 fn set_snapshot(
799 &mut self,
800 new_snapshot: LocalSnapshot,
801 entry_changes: UpdatedEntriesSet,
802 cx: &mut ModelContext<Worktree>,
803 ) {
804 let repo_changes = self.changed_repos(&self.snapshot, &new_snapshot);
805
806 self.snapshot = new_snapshot;
807
808 if let Some(share) = self.share.as_mut() {
809 share
810 .snapshots_tx
811 .unbounded_send((
812 self.snapshot.clone(),
813 entry_changes.clone(),
814 repo_changes.clone(),
815 ))
816 .ok();
817 }
818
819 if !entry_changes.is_empty() {
820 cx.emit(Event::UpdatedEntries(entry_changes));
821 }
822 if !repo_changes.is_empty() {
823 cx.emit(Event::UpdatedGitRepositories(repo_changes));
824 }
825 }
826
827 fn changed_repos(
828 &self,
829 old_snapshot: &LocalSnapshot,
830 new_snapshot: &LocalSnapshot,
831 ) -> UpdatedGitRepositoriesSet {
832 let mut changes = Vec::new();
833 let mut old_repos = old_snapshot.git_repositories.iter().peekable();
834 let mut new_repos = new_snapshot.git_repositories.iter().peekable();
835 loop {
836 match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
837 (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
838 match Ord::cmp(&new_entry_id, &old_entry_id) {
839 Ordering::Less => {
840 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
841 changes.push((
842 entry.path.clone(),
843 GitRepositoryChange {
844 old_repository: None,
845 },
846 ));
847 }
848 new_repos.next();
849 }
850 Ordering::Equal => {
851 if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id {
852 if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
853 let old_repo = old_snapshot
854 .repository_entries
855 .get(&RepositoryWorkDirectory(entry.path.clone()))
856 .cloned();
857 changes.push((
858 entry.path.clone(),
859 GitRepositoryChange {
860 old_repository: old_repo,
861 },
862 ));
863 }
864 }
865 new_repos.next();
866 old_repos.next();
867 }
868 Ordering::Greater => {
869 if let Some(entry) = old_snapshot.entry_for_id(old_entry_id) {
870 let old_repo = old_snapshot
871 .repository_entries
872 .get(&RepositoryWorkDirectory(entry.path.clone()))
873 .cloned();
874 changes.push((
875 entry.path.clone(),
876 GitRepositoryChange {
877 old_repository: old_repo,
878 },
879 ));
880 }
881 old_repos.next();
882 }
883 }
884 }
885 (Some((entry_id, _)), None) => {
886 if let Some(entry) = new_snapshot.entry_for_id(entry_id) {
887 changes.push((
888 entry.path.clone(),
889 GitRepositoryChange {
890 old_repository: None,
891 },
892 ));
893 }
894 new_repos.next();
895 }
896 (None, Some((entry_id, _))) => {
897 if let Some(entry) = old_snapshot.entry_for_id(entry_id) {
898 let old_repo = old_snapshot
899 .repository_entries
900 .get(&RepositoryWorkDirectory(entry.path.clone()))
901 .cloned();
902 changes.push((
903 entry.path.clone(),
904 GitRepositoryChange {
905 old_repository: old_repo,
906 },
907 ));
908 }
909 old_repos.next();
910 }
911 (None, None) => break,
912 }
913 }
914
915 fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
916 (value.0.clone(), value.1.clone())
917 }
918
919 changes.into()
920 }
921
922 pub fn scan_complete(&self) -> impl Future<Output = ()> {
923 let mut is_scanning_rx = self.is_scanning.1.clone();
924 async move {
925 let mut is_scanning = is_scanning_rx.borrow().clone();
926 while is_scanning {
927 if let Some(value) = is_scanning_rx.recv().await {
928 is_scanning = value;
929 } else {
930 break;
931 }
932 }
933 }
934 }
935
936 pub fn snapshot(&self) -> LocalSnapshot {
937 self.snapshot.clone()
938 }
939
940 pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
941 proto::WorktreeMetadata {
942 id: self.id().to_proto(),
943 root_name: self.root_name().to_string(),
944 visible: self.visible,
945 abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
946 }
947 }
948
949 fn load(
950 &self,
951 path: &Path,
952 cx: &mut ModelContext<Worktree>,
953 ) -> Task<Result<(File, String, Option<String>)>> {
954 let path = Arc::from(path);
955 let abs_path = self.absolutize(&path);
956 let fs = self.fs.clone();
957 let entry = self.refresh_entry(path.clone(), None, cx);
958
959 cx.spawn(|this, mut cx| async move {
960 let text = fs.load(&abs_path).await?;
961 let mut index_task = None;
962 let snapshot = this.update(&mut cx, |this, _| this.as_local().unwrap().snapshot())?;
963 if let Some(repo) = snapshot.repository_for_path(&path) {
964 let repo_path = repo.work_directory.relativize(&snapshot, &path).unwrap();
965 if let Some(repo) = snapshot.git_repositories.get(&*repo.work_directory) {
966 let repo = repo.repo_ptr.clone();
967 index_task = Some(
968 cx.background_executor()
969 .spawn(async move { repo.lock().load_index_text(&repo_path) }),
970 );
971 }
972 }
973
974 let diff_base = if let Some(index_task) = index_task {
975 index_task.await
976 } else {
977 None
978 };
979
980 let worktree = this
981 .upgrade()
982 .ok_or_else(|| anyhow!("worktree was dropped"))?;
983 match entry.await? {
984 Some(entry) => Ok((
985 File {
986 entry_id: Some(entry.id),
987 worktree,
988 path: entry.path,
989 mtime: entry.mtime,
990 is_local: true,
991 is_deleted: false,
992 },
993 text,
994 diff_base,
995 )),
996 None => {
997 let metadata = fs
998 .metadata(&abs_path)
999 .await
1000 .with_context(|| {
1001 format!("Loading metadata for excluded file {abs_path:?}")
1002 })?
1003 .with_context(|| {
1004 format!("Excluded file {abs_path:?} got removed during loading")
1005 })?;
1006 Ok((
1007 File {
1008 entry_id: None,
1009 worktree,
1010 path,
1011 mtime: metadata.mtime,
1012 is_local: true,
1013 is_deleted: false,
1014 },
1015 text,
1016 diff_base,
1017 ))
1018 }
1019 }
1020 })
1021 }
1022
1023 pub fn save_buffer(
1024 &self,
1025 buffer_handle: Model<Buffer>,
1026 path: Arc<Path>,
1027 has_changed_file: bool,
1028 cx: &mut ModelContext<Worktree>,
1029 ) -> Task<Result<()>> {
1030 let buffer = buffer_handle.read(cx);
1031
1032 let rpc = self.client.clone();
1033 let buffer_id = buffer.remote_id();
1034 let project_id = self.share.as_ref().map(|share| share.project_id);
1035
1036 let text = buffer.as_rope().clone();
1037 let fingerprint = text.fingerprint();
1038 let version = buffer.version();
1039 let save = self.write_file(path.as_ref(), text, buffer.line_ending(), cx);
1040 let fs = Arc::clone(&self.fs);
1041 let abs_path = self.absolutize(&path);
1042
1043 cx.spawn(move |this, mut cx| async move {
1044 let entry = save.await?;
1045 let this = this.upgrade().context("worktree dropped")?;
1046
1047 let (entry_id, mtime, path) = match entry {
1048 Some(entry) => (Some(entry.id), entry.mtime, entry.path),
1049 None => {
1050 let metadata = fs
1051 .metadata(&abs_path)
1052 .await
1053 .with_context(|| {
1054 format!(
1055 "Fetching metadata after saving the excluded buffer {abs_path:?}"
1056 )
1057 })?
1058 .with_context(|| {
1059 format!("Excluded buffer {path:?} got removed during saving")
1060 })?;
1061 (None, metadata.mtime, path)
1062 }
1063 };
1064
1065 if has_changed_file {
1066 let new_file = Arc::new(File {
1067 entry_id,
1068 worktree: this,
1069 path,
1070 mtime,
1071 is_local: true,
1072 is_deleted: false,
1073 });
1074
1075 if let Some(project_id) = project_id {
1076 rpc.send(proto::UpdateBufferFile {
1077 project_id,
1078 buffer_id,
1079 file: Some(new_file.to_proto()),
1080 })
1081 .log_err();
1082 }
1083
1084 buffer_handle.update(&mut cx, |buffer, cx| {
1085 if has_changed_file {
1086 buffer.file_updated(new_file, cx);
1087 }
1088 })?;
1089 }
1090
1091 if let Some(project_id) = project_id {
1092 rpc.send(proto::BufferSaved {
1093 project_id,
1094 buffer_id,
1095 version: serialize_version(&version),
1096 mtime: Some(mtime.into()),
1097 fingerprint: serialize_fingerprint(fingerprint),
1098 })?;
1099 }
1100
1101 buffer_handle.update(&mut cx, |buffer, cx| {
1102 buffer.did_save(version.clone(), fingerprint, mtime, cx);
1103 })?;
1104
1105 Ok(())
1106 })
1107 }
1108
1109 /// Find the lowest path in the worktree's datastructures that is an ancestor
1110 fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1111 let mut lowest_ancestor = None;
1112 for path in path.ancestors() {
1113 if self.entry_for_path(path).is_some() {
1114 lowest_ancestor = Some(path.to_path_buf());
1115 break;
1116 }
1117 }
1118
1119 lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1120 }
1121
1122 pub fn create_entry(
1123 &self,
1124 path: impl Into<Arc<Path>>,
1125 is_dir: bool,
1126 cx: &mut ModelContext<Worktree>,
1127 ) -> Task<Result<Option<Entry>>> {
1128 let path = path.into();
1129 let lowest_ancestor = self.lowest_ancestor(&path);
1130 let abs_path = self.absolutize(&path);
1131 let fs = self.fs.clone();
1132 let write = cx.background_executor().spawn(async move {
1133 if is_dir {
1134 fs.create_dir(&abs_path).await
1135 } else {
1136 fs.save(&abs_path, &Default::default(), Default::default())
1137 .await
1138 }
1139 });
1140
1141 cx.spawn(|this, mut cx| async move {
1142 write.await?;
1143 let (result, refreshes) = this.update(&mut cx, |this, cx| {
1144 let mut refreshes = Vec::new();
1145 let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1146 for refresh_path in refresh_paths.ancestors() {
1147 if refresh_path == Path::new("") {
1148 continue;
1149 }
1150 let refresh_full_path = lowest_ancestor.join(refresh_path);
1151
1152 refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1153 refresh_full_path.into(),
1154 None,
1155 cx,
1156 ));
1157 }
1158 (
1159 this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1160 refreshes,
1161 )
1162 })?;
1163 for refresh in refreshes {
1164 refresh.await.log_err();
1165 }
1166
1167 result.await
1168 })
1169 }
1170
1171 pub(crate) fn write_file(
1172 &self,
1173 path: impl Into<Arc<Path>>,
1174 text: Rope,
1175 line_ending: LineEnding,
1176 cx: &mut ModelContext<Worktree>,
1177 ) -> Task<Result<Option<Entry>>> {
1178 let path: Arc<Path> = path.into();
1179 let abs_path = self.absolutize(&path);
1180 let fs = self.fs.clone();
1181 let write = cx
1182 .background_executor()
1183 .spawn(async move { fs.save(&abs_path, &text, line_ending).await });
1184
1185 cx.spawn(|this, mut cx| async move {
1186 write.await?;
1187 this.update(&mut cx, |this, cx| {
1188 this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1189 })?
1190 .await
1191 })
1192 }
1193
1194 pub fn delete_entry(
1195 &self,
1196 entry_id: ProjectEntryId,
1197 cx: &mut ModelContext<Worktree>,
1198 ) -> Option<Task<Result<()>>> {
1199 let entry = self.entry_for_id(entry_id)?.clone();
1200 let abs_path = self.absolutize(&entry.path);
1201 let fs = self.fs.clone();
1202
1203 let delete = cx.background_executor().spawn(async move {
1204 if entry.is_file() {
1205 fs.remove_file(&abs_path, Default::default()).await?;
1206 } else {
1207 fs.remove_dir(
1208 &abs_path,
1209 RemoveOptions {
1210 recursive: true,
1211 ignore_if_not_exists: false,
1212 },
1213 )
1214 .await?;
1215 }
1216 anyhow::Ok(entry.path)
1217 });
1218
1219 Some(cx.spawn(|this, mut cx| async move {
1220 let path = delete.await?;
1221 this.update(&mut cx, |this, _| {
1222 this.as_local_mut()
1223 .unwrap()
1224 .refresh_entries_for_paths(vec![path])
1225 })?
1226 .recv()
1227 .await;
1228 Ok(())
1229 }))
1230 }
1231
1232 pub fn rename_entry(
1233 &self,
1234 entry_id: ProjectEntryId,
1235 new_path: impl Into<Arc<Path>>,
1236 cx: &mut ModelContext<Worktree>,
1237 ) -> Task<Result<Option<Entry>>> {
1238 let old_path = match self.entry_for_id(entry_id) {
1239 Some(entry) => entry.path.clone(),
1240 None => return Task::ready(Ok(None)),
1241 };
1242 let new_path = new_path.into();
1243 let abs_old_path = self.absolutize(&old_path);
1244 let abs_new_path = self.absolutize(&new_path);
1245 let fs = self.fs.clone();
1246 let rename = cx.background_executor().spawn(async move {
1247 fs.rename(&abs_old_path, &abs_new_path, Default::default())
1248 .await
1249 });
1250
1251 cx.spawn(|this, mut cx| async move {
1252 rename.await?;
1253 this.update(&mut cx, |this, cx| {
1254 this.as_local_mut()
1255 .unwrap()
1256 .refresh_entry(new_path.clone(), Some(old_path), cx)
1257 })?
1258 .await
1259 })
1260 }
1261
1262 pub fn copy_entry(
1263 &self,
1264 entry_id: ProjectEntryId,
1265 new_path: impl Into<Arc<Path>>,
1266 cx: &mut ModelContext<Worktree>,
1267 ) -> Task<Result<Option<Entry>>> {
1268 let old_path = match self.entry_for_id(entry_id) {
1269 Some(entry) => entry.path.clone(),
1270 None => return Task::ready(Ok(None)),
1271 };
1272 let new_path = new_path.into();
1273 let abs_old_path = self.absolutize(&old_path);
1274 let abs_new_path = self.absolutize(&new_path);
1275 let fs = self.fs.clone();
1276 let copy = cx.background_executor().spawn(async move {
1277 copy_recursive(
1278 fs.as_ref(),
1279 &abs_old_path,
1280 &abs_new_path,
1281 Default::default(),
1282 )
1283 .await
1284 });
1285
1286 cx.spawn(|this, mut cx| async move {
1287 copy.await?;
1288 this.update(&mut cx, |this, cx| {
1289 this.as_local_mut()
1290 .unwrap()
1291 .refresh_entry(new_path.clone(), None, cx)
1292 })?
1293 .await
1294 })
1295 }
1296
1297 pub fn expand_entry(
1298 &mut self,
1299 entry_id: ProjectEntryId,
1300 cx: &mut ModelContext<Worktree>,
1301 ) -> Option<Task<Result<()>>> {
1302 let path = self.entry_for_id(entry_id)?.path.clone();
1303 let mut refresh = self.refresh_entries_for_paths(vec![path]);
1304 Some(cx.background_executor().spawn(async move {
1305 refresh.next().await;
1306 Ok(())
1307 }))
1308 }
1309
1310 pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1311 let (tx, rx) = barrier::channel();
1312 self.scan_requests_tx
1313 .try_send(ScanRequest {
1314 relative_paths: paths,
1315 done: tx,
1316 })
1317 .ok();
1318 rx
1319 }
1320
1321 pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) {
1322 self.path_prefixes_to_scan_tx.try_send(path_prefix).ok();
1323 }
1324
1325 fn refresh_entry(
1326 &self,
1327 path: Arc<Path>,
1328 old_path: Option<Arc<Path>>,
1329 cx: &mut ModelContext<Worktree>,
1330 ) -> Task<Result<Option<Entry>>> {
1331 if self.is_path_excluded(path.to_path_buf()) {
1332 return Task::ready(Ok(None));
1333 }
1334 let paths = if let Some(old_path) = old_path.as_ref() {
1335 vec![old_path.clone(), path.clone()]
1336 } else {
1337 vec![path.clone()]
1338 };
1339 let mut refresh = self.refresh_entries_for_paths(paths);
1340 cx.spawn(move |this, mut cx| async move {
1341 refresh.recv().await;
1342 let new_entry = this.update(&mut cx, |this, _| {
1343 this.entry_for_path(path)
1344 .cloned()
1345 .ok_or_else(|| anyhow!("failed to read path after update"))
1346 })??;
1347 Ok(Some(new_entry))
1348 })
1349 }
1350
1351 pub fn observe_updates<F, Fut>(
1352 &mut self,
1353 project_id: u64,
1354 cx: &mut ModelContext<Worktree>,
1355 callback: F,
1356 ) -> oneshot::Receiver<()>
1357 where
1358 F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1359 Fut: Send + Future<Output = bool>,
1360 {
1361 #[cfg(any(test, feature = "test-support"))]
1362 const MAX_CHUNK_SIZE: usize = 2;
1363 #[cfg(not(any(test, feature = "test-support")))]
1364 const MAX_CHUNK_SIZE: usize = 256;
1365
1366 let (share_tx, share_rx) = oneshot::channel();
1367
1368 if let Some(share) = self.share.as_mut() {
1369 share_tx.send(()).ok();
1370 *share.resume_updates.borrow_mut() = ();
1371 return share_rx;
1372 }
1373
1374 let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1375 let (snapshots_tx, mut snapshots_rx) =
1376 mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>();
1377 snapshots_tx
1378 .unbounded_send((self.snapshot(), Arc::from([]), Arc::from([])))
1379 .ok();
1380
1381 let worktree_id = cx.entity_id().as_u64();
1382 let _maintain_remote_snapshot = cx.background_executor().spawn(async move {
1383 let mut is_first = true;
1384 while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
1385 let update;
1386 if is_first {
1387 update = snapshot.build_initial_update(project_id, worktree_id);
1388 is_first = false;
1389 } else {
1390 update =
1391 snapshot.build_update(project_id, worktree_id, entry_changes, repo_changes);
1392 }
1393
1394 for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1395 let _ = resume_updates_rx.try_recv();
1396 loop {
1397 let result = callback(update.clone());
1398 if result.await {
1399 break;
1400 } else {
1401 log::info!("waiting to resume updates");
1402 if resume_updates_rx.next().await.is_none() {
1403 return Some(());
1404 }
1405 }
1406 }
1407 }
1408 }
1409 share_tx.send(()).ok();
1410 Some(())
1411 });
1412
1413 self.share = Some(ShareState {
1414 project_id,
1415 snapshots_tx,
1416 resume_updates: resume_updates_tx,
1417 _maintain_remote_snapshot,
1418 });
1419 share_rx
1420 }
1421
1422 pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1423 let client = self.client.clone();
1424
1425 for (path, summaries) in &self.diagnostic_summaries {
1426 for (&server_id, summary) in summaries {
1427 if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1428 project_id,
1429 worktree_id: cx.entity_id().as_u64(),
1430 summary: Some(summary.to_proto(server_id, &path)),
1431 }) {
1432 return Task::ready(Err(e));
1433 }
1434 }
1435 }
1436
1437 let rx = self.observe_updates(project_id, cx, move |update| {
1438 client.request(update).map(|result| result.is_ok())
1439 });
1440 cx.background_executor()
1441 .spawn(async move { rx.await.map_err(|_| anyhow!("share ended")) })
1442 }
1443
1444 pub fn unshare(&mut self) {
1445 self.share.take();
1446 }
1447
1448 pub fn is_shared(&self) -> bool {
1449 self.share.is_some()
1450 }
1451}
1452
1453impl RemoteWorktree {
1454 fn snapshot(&self) -> Snapshot {
1455 self.snapshot.clone()
1456 }
1457
1458 pub fn disconnected_from_host(&mut self) {
1459 self.updates_tx.take();
1460 self.snapshot_subscriptions.clear();
1461 self.disconnected = true;
1462 }
1463
1464 pub fn save_buffer(
1465 &self,
1466 buffer_handle: Model<Buffer>,
1467 cx: &mut ModelContext<Worktree>,
1468 ) -> Task<Result<()>> {
1469 let buffer = buffer_handle.read(cx);
1470 let buffer_id = buffer.remote_id();
1471 let version = buffer.version();
1472 let rpc = self.client.clone();
1473 let project_id = self.project_id;
1474 cx.spawn(move |_, mut cx| async move {
1475 let response = rpc
1476 .request(proto::SaveBuffer {
1477 project_id,
1478 buffer_id,
1479 version: serialize_version(&version),
1480 })
1481 .await?;
1482 let version = deserialize_version(&response.version);
1483 let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1484 let mtime = response
1485 .mtime
1486 .ok_or_else(|| anyhow!("missing mtime"))?
1487 .into();
1488
1489 buffer_handle.update(&mut cx, |buffer, cx| {
1490 buffer.did_save(version.clone(), fingerprint, mtime, cx);
1491 })?;
1492
1493 Ok(())
1494 })
1495 }
1496
1497 pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1498 if let Some(updates_tx) = &self.updates_tx {
1499 updates_tx
1500 .unbounded_send(update)
1501 .expect("consumer runs to completion");
1502 }
1503 }
1504
1505 fn observed_snapshot(&self, scan_id: usize) -> bool {
1506 self.completed_scan_id >= scan_id
1507 }
1508
1509 pub(crate) fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1510 let (tx, rx) = oneshot::channel();
1511 if self.observed_snapshot(scan_id) {
1512 let _ = tx.send(());
1513 } else if self.disconnected {
1514 drop(tx);
1515 } else {
1516 match self
1517 .snapshot_subscriptions
1518 .binary_search_by_key(&scan_id, |probe| probe.0)
1519 {
1520 Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1521 }
1522 }
1523
1524 async move {
1525 rx.await?;
1526 Ok(())
1527 }
1528 }
1529
1530 pub fn update_diagnostic_summary(
1531 &mut self,
1532 path: Arc<Path>,
1533 summary: &proto::DiagnosticSummary,
1534 ) {
1535 let server_id = LanguageServerId(summary.language_server_id as usize);
1536 let summary = DiagnosticSummary {
1537 error_count: summary.error_count as usize,
1538 warning_count: summary.warning_count as usize,
1539 };
1540
1541 if summary.is_empty() {
1542 if let Some(summaries) = self.diagnostic_summaries.get_mut(&path) {
1543 summaries.remove(&server_id);
1544 if summaries.is_empty() {
1545 self.diagnostic_summaries.remove(&path);
1546 }
1547 }
1548 } else {
1549 self.diagnostic_summaries
1550 .entry(path)
1551 .or_default()
1552 .insert(server_id, summary);
1553 }
1554 }
1555
1556 pub fn insert_entry(
1557 &mut self,
1558 entry: proto::Entry,
1559 scan_id: usize,
1560 cx: &mut ModelContext<Worktree>,
1561 ) -> Task<Result<Entry>> {
1562 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1563 cx.spawn(|this, mut cx| async move {
1564 wait_for_snapshot.await?;
1565 this.update(&mut cx, |worktree, _| {
1566 let worktree = worktree.as_remote_mut().unwrap();
1567 let mut snapshot = worktree.background_snapshot.lock();
1568 let entry = snapshot.insert_entry(entry);
1569 worktree.snapshot = snapshot.clone();
1570 entry
1571 })?
1572 })
1573 }
1574
1575 pub(crate) fn delete_entry(
1576 &mut self,
1577 id: ProjectEntryId,
1578 scan_id: usize,
1579 cx: &mut ModelContext<Worktree>,
1580 ) -> Task<Result<()>> {
1581 let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1582 cx.spawn(move |this, mut cx| async move {
1583 wait_for_snapshot.await?;
1584 this.update(&mut cx, |worktree, _| {
1585 let worktree = worktree.as_remote_mut().unwrap();
1586 let mut snapshot = worktree.background_snapshot.lock();
1587 snapshot.delete_entry(id);
1588 worktree.snapshot = snapshot.clone();
1589 })?;
1590 Ok(())
1591 })
1592 }
1593}
1594
1595impl Snapshot {
1596 pub fn id(&self) -> WorktreeId {
1597 self.id
1598 }
1599
1600 pub fn abs_path(&self) -> &Arc<Path> {
1601 &self.abs_path
1602 }
1603
1604 pub fn absolutize(&self, path: &Path) -> PathBuf {
1605 if path.file_name().is_some() {
1606 self.abs_path.join(path)
1607 } else {
1608 self.abs_path.to_path_buf()
1609 }
1610 }
1611
1612 pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1613 self.entries_by_id.get(&entry_id, &()).is_some()
1614 }
1615
1616 fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1617 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1618 let old_entry = self.entries_by_id.insert_or_replace(
1619 PathEntry {
1620 id: entry.id,
1621 path: entry.path.clone(),
1622 is_ignored: entry.is_ignored,
1623 scan_id: 0,
1624 },
1625 &(),
1626 );
1627 if let Some(old_entry) = old_entry {
1628 self.entries_by_path.remove(&PathKey(old_entry.path), &());
1629 }
1630 self.entries_by_path.insert_or_replace(entry.clone(), &());
1631 Ok(entry)
1632 }
1633
1634 fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1635 let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1636 self.entries_by_path = {
1637 let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1638 let mut new_entries_by_path =
1639 cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1640 while let Some(entry) = cursor.item() {
1641 if entry.path.starts_with(&removed_entry.path) {
1642 self.entries_by_id.remove(&entry.id, &());
1643 cursor.next(&());
1644 } else {
1645 break;
1646 }
1647 }
1648 new_entries_by_path.append(cursor.suffix(&()), &());
1649 new_entries_by_path
1650 };
1651
1652 Some(removed_entry.path)
1653 }
1654
1655 #[cfg(any(test, feature = "test-support"))]
1656 pub fn status_for_file(&self, path: impl Into<PathBuf>) -> Option<GitFileStatus> {
1657 let path = path.into();
1658 self.entries_by_path
1659 .get(&PathKey(Arc::from(path)), &())
1660 .and_then(|entry| entry.git_status)
1661 }
1662
1663 pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1664 let mut entries_by_path_edits = Vec::new();
1665 let mut entries_by_id_edits = Vec::new();
1666
1667 for entry_id in update.removed_entries {
1668 let entry_id = ProjectEntryId::from_proto(entry_id);
1669 entries_by_id_edits.push(Edit::Remove(entry_id));
1670 if let Some(entry) = self.entry_for_id(entry_id) {
1671 entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1672 }
1673 }
1674
1675 for entry in update.updated_entries {
1676 let entry = Entry::try_from((&self.root_char_bag, entry))?;
1677 if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1678 entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1679 }
1680 if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
1681 if old_entry.id != entry.id {
1682 entries_by_id_edits.push(Edit::Remove(old_entry.id));
1683 }
1684 }
1685 entries_by_id_edits.push(Edit::Insert(PathEntry {
1686 id: entry.id,
1687 path: entry.path.clone(),
1688 is_ignored: entry.is_ignored,
1689 scan_id: 0,
1690 }));
1691 entries_by_path_edits.push(Edit::Insert(entry));
1692 }
1693
1694 self.entries_by_path.edit(entries_by_path_edits, &());
1695 self.entries_by_id.edit(entries_by_id_edits, &());
1696
1697 update.removed_repositories.sort_unstable();
1698 self.repository_entries.retain(|_, entry| {
1699 if let Ok(_) = update
1700 .removed_repositories
1701 .binary_search(&entry.work_directory.to_proto())
1702 {
1703 false
1704 } else {
1705 true
1706 }
1707 });
1708
1709 for repository in update.updated_repositories {
1710 let work_directory_entry: WorkDirectoryEntry =
1711 ProjectEntryId::from_proto(repository.work_directory_id).into();
1712
1713 if let Some(entry) = self.entry_for_id(*work_directory_entry) {
1714 let work_directory = RepositoryWorkDirectory(entry.path.clone());
1715 if self.repository_entries.get(&work_directory).is_some() {
1716 self.repository_entries.update(&work_directory, |repo| {
1717 repo.branch = repository.branch.map(Into::into);
1718 });
1719 } else {
1720 self.repository_entries.insert(
1721 work_directory,
1722 RepositoryEntry {
1723 work_directory: work_directory_entry,
1724 branch: repository.branch.map(Into::into),
1725 },
1726 )
1727 }
1728 } else {
1729 log::error!("no work directory entry for repository {:?}", repository)
1730 }
1731 }
1732
1733 self.scan_id = update.scan_id as usize;
1734 if update.is_last_update {
1735 self.completed_scan_id = update.scan_id as usize;
1736 }
1737
1738 Ok(())
1739 }
1740
1741 pub fn file_count(&self) -> usize {
1742 self.entries_by_path.summary().file_count
1743 }
1744
1745 pub fn visible_file_count(&self) -> usize {
1746 self.entries_by_path.summary().non_ignored_file_count
1747 }
1748
1749 fn traverse_from_offset(
1750 &self,
1751 include_dirs: bool,
1752 include_ignored: bool,
1753 start_offset: usize,
1754 ) -> Traversal {
1755 let mut cursor = self.entries_by_path.cursor();
1756 cursor.seek(
1757 &TraversalTarget::Count {
1758 count: start_offset,
1759 include_dirs,
1760 include_ignored,
1761 },
1762 Bias::Right,
1763 &(),
1764 );
1765 Traversal {
1766 cursor,
1767 include_dirs,
1768 include_ignored,
1769 }
1770 }
1771
1772 fn traverse_from_path(
1773 &self,
1774 include_dirs: bool,
1775 include_ignored: bool,
1776 path: &Path,
1777 ) -> Traversal {
1778 let mut cursor = self.entries_by_path.cursor();
1779 cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1780 Traversal {
1781 cursor,
1782 include_dirs,
1783 include_ignored,
1784 }
1785 }
1786
1787 pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1788 self.traverse_from_offset(false, include_ignored, start)
1789 }
1790
1791 pub fn entries(&self, include_ignored: bool) -> Traversal {
1792 self.traverse_from_offset(true, include_ignored, 0)
1793 }
1794
1795 pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
1796 self.repository_entries
1797 .iter()
1798 .map(|(path, entry)| (&path.0, entry))
1799 }
1800
1801 /// Get the repository whose work directory contains the given path.
1802 pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
1803 self.repository_entries
1804 .get(&RepositoryWorkDirectory(path.into()))
1805 .cloned()
1806 }
1807
1808 /// Get the repository whose work directory contains the given path.
1809 pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
1810 self.repository_and_work_directory_for_path(path)
1811 .map(|e| e.1)
1812 }
1813
1814 pub fn repository_and_work_directory_for_path(
1815 &self,
1816 path: &Path,
1817 ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
1818 self.repository_entries
1819 .iter()
1820 .filter(|(workdir_path, _)| path.starts_with(workdir_path))
1821 .last()
1822 .map(|(path, repo)| (path.clone(), repo.clone()))
1823 }
1824
1825 /// Given an ordered iterator of entries, returns an iterator of those entries,
1826 /// along with their containing git repository.
1827 pub fn entries_with_repositories<'a>(
1828 &'a self,
1829 entries: impl 'a + Iterator<Item = &'a Entry>,
1830 ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
1831 let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
1832 let mut repositories = self.repositories().peekable();
1833 entries.map(move |entry| {
1834 while let Some((repo_path, _)) = containing_repos.last() {
1835 if !entry.path.starts_with(repo_path) {
1836 containing_repos.pop();
1837 } else {
1838 break;
1839 }
1840 }
1841 while let Some((repo_path, _)) = repositories.peek() {
1842 if entry.path.starts_with(repo_path) {
1843 containing_repos.push(repositories.next().unwrap());
1844 } else {
1845 break;
1846 }
1847 }
1848 let repo = containing_repos.last().map(|(_, repo)| *repo);
1849 (entry, repo)
1850 })
1851 }
1852
1853 /// Update the `git_status` of the given entries such that files'
1854 /// statuses bubble up to their ancestor directories.
1855 pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
1856 let mut cursor = self
1857 .entries_by_path
1858 .cursor::<(TraversalProgress, GitStatuses)>();
1859 let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
1860
1861 let mut result_ix = 0;
1862 loop {
1863 let next_entry = result.get(result_ix);
1864 let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
1865
1866 let entry_to_finish = match (containing_entry, next_entry) {
1867 (Some(_), None) => entry_stack.pop(),
1868 (Some(containing_entry), Some(next_path)) => {
1869 if !next_path.path.starts_with(&containing_entry.path) {
1870 entry_stack.pop()
1871 } else {
1872 None
1873 }
1874 }
1875 (None, Some(_)) => None,
1876 (None, None) => break,
1877 };
1878
1879 if let Some((entry_ix, prev_statuses)) = entry_to_finish {
1880 cursor.seek_forward(
1881 &TraversalTarget::PathSuccessor(&result[entry_ix].path),
1882 Bias::Left,
1883 &(),
1884 );
1885
1886 let statuses = cursor.start().1 - prev_statuses;
1887
1888 result[entry_ix].git_status = if statuses.conflict > 0 {
1889 Some(GitFileStatus::Conflict)
1890 } else if statuses.modified > 0 {
1891 Some(GitFileStatus::Modified)
1892 } else if statuses.added > 0 {
1893 Some(GitFileStatus::Added)
1894 } else {
1895 None
1896 };
1897 } else {
1898 if result[result_ix].is_dir() {
1899 cursor.seek_forward(
1900 &TraversalTarget::Path(&result[result_ix].path),
1901 Bias::Left,
1902 &(),
1903 );
1904 entry_stack.push((result_ix, cursor.start().1));
1905 }
1906 result_ix += 1;
1907 }
1908 }
1909 }
1910
1911 pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1912 let empty_path = Path::new("");
1913 self.entries_by_path
1914 .cursor::<()>()
1915 .filter(move |entry| entry.path.as_ref() != empty_path)
1916 .map(|entry| &entry.path)
1917 }
1918
1919 fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1920 let mut cursor = self.entries_by_path.cursor();
1921 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1922 let traversal = Traversal {
1923 cursor,
1924 include_dirs: true,
1925 include_ignored: true,
1926 };
1927 ChildEntriesIter {
1928 traversal,
1929 parent_path,
1930 }
1931 }
1932
1933 pub fn descendent_entries<'a>(
1934 &'a self,
1935 include_dirs: bool,
1936 include_ignored: bool,
1937 parent_path: &'a Path,
1938 ) -> DescendentEntriesIter<'a> {
1939 let mut cursor = self.entries_by_path.cursor();
1940 cursor.seek(&TraversalTarget::Path(parent_path), Bias::Left, &());
1941 let mut traversal = Traversal {
1942 cursor,
1943 include_dirs,
1944 include_ignored,
1945 };
1946
1947 if traversal.end_offset() == traversal.start_offset() {
1948 traversal.advance();
1949 }
1950
1951 DescendentEntriesIter {
1952 traversal,
1953 parent_path,
1954 }
1955 }
1956
1957 pub fn root_entry(&self) -> Option<&Entry> {
1958 self.entry_for_path("")
1959 }
1960
1961 pub fn root_name(&self) -> &str {
1962 &self.root_name
1963 }
1964
1965 pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1966 self.repository_entries
1967 .get(&RepositoryWorkDirectory(Path::new("").into()))
1968 .map(|entry| entry.to_owned())
1969 }
1970
1971 pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1972 self.repository_entries.values()
1973 }
1974
1975 pub fn scan_id(&self) -> usize {
1976 self.scan_id
1977 }
1978
1979 pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1980 let path = path.as_ref();
1981 self.traverse_from_path(true, true, path)
1982 .entry()
1983 .and_then(|entry| {
1984 if entry.path.as_ref() == path {
1985 Some(entry)
1986 } else {
1987 None
1988 }
1989 })
1990 }
1991
1992 pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1993 let entry = self.entries_by_id.get(&id, &())?;
1994 self.entry_for_path(&entry.path)
1995 }
1996
1997 pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1998 self.entry_for_path(path.as_ref()).map(|e| e.inode)
1999 }
2000}
2001
2002impl LocalSnapshot {
2003 pub(crate) fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
2004 self.git_repositories.get(&repo.work_directory.0)
2005 }
2006
2007 pub(crate) fn local_repo_for_path(
2008 &self,
2009 path: &Path,
2010 ) -> Option<(RepositoryWorkDirectory, &LocalRepositoryEntry)> {
2011 let (path, repo) = self.repository_and_work_directory_for_path(path)?;
2012 Some((path, self.git_repositories.get(&repo.work_directory_id())?))
2013 }
2014
2015 fn build_update(
2016 &self,
2017 project_id: u64,
2018 worktree_id: u64,
2019 entry_changes: UpdatedEntriesSet,
2020 repo_changes: UpdatedGitRepositoriesSet,
2021 ) -> proto::UpdateWorktree {
2022 let mut updated_entries = Vec::new();
2023 let mut removed_entries = Vec::new();
2024 let mut updated_repositories = Vec::new();
2025 let mut removed_repositories = Vec::new();
2026
2027 for (_, entry_id, path_change) in entry_changes.iter() {
2028 if let PathChange::Removed = path_change {
2029 removed_entries.push(entry_id.0 as u64);
2030 } else if let Some(entry) = self.entry_for_id(*entry_id) {
2031 updated_entries.push(proto::Entry::from(entry));
2032 }
2033 }
2034
2035 for (work_dir_path, change) in repo_changes.iter() {
2036 let new_repo = self
2037 .repository_entries
2038 .get(&RepositoryWorkDirectory(work_dir_path.clone()));
2039 match (&change.old_repository, new_repo) {
2040 (Some(old_repo), Some(new_repo)) => {
2041 updated_repositories.push(new_repo.build_update(old_repo));
2042 }
2043 (None, Some(new_repo)) => {
2044 updated_repositories.push(proto::RepositoryEntry::from(new_repo));
2045 }
2046 (Some(old_repo), None) => {
2047 removed_repositories.push(old_repo.work_directory.0.to_proto());
2048 }
2049 _ => {}
2050 }
2051 }
2052
2053 removed_entries.sort_unstable();
2054 updated_entries.sort_unstable_by_key(|e| e.id);
2055 removed_repositories.sort_unstable();
2056 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2057
2058 // TODO - optimize, knowing that removed_entries are sorted.
2059 removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2060
2061 proto::UpdateWorktree {
2062 project_id,
2063 worktree_id,
2064 abs_path: self.abs_path().to_string_lossy().into(),
2065 root_name: self.root_name().to_string(),
2066 updated_entries,
2067 removed_entries,
2068 scan_id: self.scan_id as u64,
2069 is_last_update: self.completed_scan_id == self.scan_id,
2070 updated_repositories,
2071 removed_repositories,
2072 }
2073 }
2074
2075 fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2076 let mut updated_entries = self
2077 .entries_by_path
2078 .iter()
2079 .map(proto::Entry::from)
2080 .collect::<Vec<_>>();
2081 updated_entries.sort_unstable_by_key(|e| e.id);
2082
2083 let mut updated_repositories = self
2084 .repository_entries
2085 .values()
2086 .map(proto::RepositoryEntry::from)
2087 .collect::<Vec<_>>();
2088 updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2089
2090 proto::UpdateWorktree {
2091 project_id,
2092 worktree_id,
2093 abs_path: self.abs_path().to_string_lossy().into(),
2094 root_name: self.root_name().to_string(),
2095 updated_entries,
2096 removed_entries: Vec::new(),
2097 scan_id: self.scan_id as u64,
2098 is_last_update: self.completed_scan_id == self.scan_id,
2099 updated_repositories,
2100 removed_repositories: Vec::new(),
2101 }
2102 }
2103
2104 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2105 if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2106 let abs_path = self.abs_path.join(&entry.path);
2107 match smol::block_on(build_gitignore(&abs_path, fs)) {
2108 Ok(ignore) => {
2109 self.ignores_by_parent_abs_path
2110 .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2111 }
2112 Err(error) => {
2113 log::error!(
2114 "error loading .gitignore file {:?} - {:?}",
2115 &entry.path,
2116 error
2117 );
2118 }
2119 }
2120 }
2121
2122 if entry.kind == EntryKind::PendingDir {
2123 if let Some(existing_entry) =
2124 self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2125 {
2126 entry.kind = existing_entry.kind;
2127 }
2128 }
2129
2130 let scan_id = self.scan_id;
2131 let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2132 if let Some(removed) = removed {
2133 if removed.id != entry.id {
2134 self.entries_by_id.remove(&removed.id, &());
2135 }
2136 }
2137 self.entries_by_id.insert_or_replace(
2138 PathEntry {
2139 id: entry.id,
2140 path: entry.path.clone(),
2141 is_ignored: entry.is_ignored,
2142 scan_id,
2143 },
2144 &(),
2145 );
2146
2147 entry
2148 }
2149
2150 fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2151 let mut inodes = TreeSet::default();
2152 for ancestor in path.ancestors().skip(1) {
2153 if let Some(entry) = self.entry_for_path(ancestor) {
2154 inodes.insert(entry.inode);
2155 }
2156 }
2157 inodes
2158 }
2159
2160 fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2161 let mut new_ignores = Vec::new();
2162 for ancestor in abs_path.ancestors().skip(1) {
2163 if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2164 new_ignores.push((ancestor, Some(ignore.clone())));
2165 } else {
2166 new_ignores.push((ancestor, None));
2167 }
2168 }
2169
2170 let mut ignore_stack = IgnoreStack::none();
2171 for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2172 if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2173 ignore_stack = IgnoreStack::all();
2174 break;
2175 } else if let Some(ignore) = ignore {
2176 ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2177 }
2178 }
2179
2180 if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2181 ignore_stack = IgnoreStack::all();
2182 }
2183
2184 ignore_stack
2185 }
2186
2187 #[cfg(test)]
2188 pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2189 self.entries_by_path
2190 .cursor::<()>()
2191 .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2192 }
2193
2194 #[cfg(test)]
2195 pub fn check_invariants(&self, git_state: bool) {
2196 use pretty_assertions::assert_eq;
2197
2198 assert_eq!(
2199 self.entries_by_path
2200 .cursor::<()>()
2201 .map(|e| (&e.path, e.id))
2202 .collect::<Vec<_>>(),
2203 self.entries_by_id
2204 .cursor::<()>()
2205 .map(|e| (&e.path, e.id))
2206 .collect::<collections::BTreeSet<_>>()
2207 .into_iter()
2208 .collect::<Vec<_>>(),
2209 "entries_by_path and entries_by_id are inconsistent"
2210 );
2211
2212 let mut files = self.files(true, 0);
2213 let mut visible_files = self.files(false, 0);
2214 for entry in self.entries_by_path.cursor::<()>() {
2215 if entry.is_file() {
2216 assert_eq!(files.next().unwrap().inode, entry.inode);
2217 if !entry.is_ignored && !entry.is_external {
2218 assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2219 }
2220 }
2221 }
2222
2223 assert!(files.next().is_none());
2224 assert!(visible_files.next().is_none());
2225
2226 let mut bfs_paths = Vec::new();
2227 let mut stack = self
2228 .root_entry()
2229 .map(|e| e.path.as_ref())
2230 .into_iter()
2231 .collect::<Vec<_>>();
2232 while let Some(path) = stack.pop() {
2233 bfs_paths.push(path);
2234 let ix = stack.len();
2235 for child_entry in self.child_entries(path) {
2236 stack.insert(ix, &child_entry.path);
2237 }
2238 }
2239
2240 let dfs_paths_via_iter = self
2241 .entries_by_path
2242 .cursor::<()>()
2243 .map(|e| e.path.as_ref())
2244 .collect::<Vec<_>>();
2245 assert_eq!(bfs_paths, dfs_paths_via_iter);
2246
2247 let dfs_paths_via_traversal = self
2248 .entries(true)
2249 .map(|e| e.path.as_ref())
2250 .collect::<Vec<_>>();
2251 assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2252
2253 if git_state {
2254 for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2255 let ignore_parent_path =
2256 ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2257 assert!(self.entry_for_path(&ignore_parent_path).is_some());
2258 assert!(self
2259 .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2260 .is_some());
2261 }
2262 }
2263 }
2264
2265 #[cfg(test)]
2266 pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2267 let mut paths = Vec::new();
2268 for entry in self.entries_by_path.cursor::<()>() {
2269 if include_ignored || !entry.is_ignored {
2270 paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2271 }
2272 }
2273 paths.sort_by(|a, b| a.0.cmp(b.0));
2274 paths
2275 }
2276
2277 pub fn is_path_excluded(&self, mut path: PathBuf) -> bool {
2278 loop {
2279 if self
2280 .file_scan_exclusions
2281 .iter()
2282 .any(|exclude_matcher| exclude_matcher.is_match(&path))
2283 {
2284 return true;
2285 }
2286 if !path.pop() {
2287 return false;
2288 }
2289 }
2290 }
2291}
2292
2293impl BackgroundScannerState {
2294 fn should_scan_directory(&self, entry: &Entry) -> bool {
2295 (!entry.is_external && !entry.is_ignored)
2296 || entry.path.file_name() == Some(&*DOT_GIT)
2297 || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2298 || self
2299 .paths_to_scan
2300 .iter()
2301 .any(|p| p.starts_with(&entry.path))
2302 || self
2303 .path_prefixes_to_scan
2304 .iter()
2305 .any(|p| entry.path.starts_with(p))
2306 }
2307
2308 fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2309 let path = entry.path.clone();
2310 let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2311 let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2312 let mut containing_repository = None;
2313 if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2314 if let Some((workdir_path, repo)) = self.snapshot.local_repo_for_path(&path) {
2315 if let Ok(repo_path) = path.strip_prefix(&workdir_path.0) {
2316 containing_repository = Some((
2317 workdir_path,
2318 repo.repo_ptr.clone(),
2319 repo.repo_ptr.lock().staged_statuses(repo_path),
2320 ));
2321 }
2322 }
2323 }
2324 if !ancestor_inodes.contains(&entry.inode) {
2325 ancestor_inodes.insert(entry.inode);
2326 scan_job_tx
2327 .try_send(ScanJob {
2328 abs_path,
2329 path,
2330 ignore_stack,
2331 scan_queue: scan_job_tx.clone(),
2332 ancestor_inodes,
2333 is_external: entry.is_external,
2334 containing_repository,
2335 })
2336 .unwrap();
2337 }
2338 }
2339
2340 fn reuse_entry_id(&mut self, entry: &mut Entry) {
2341 if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2342 entry.id = removed_entry_id;
2343 } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2344 entry.id = existing_entry.id;
2345 }
2346 }
2347
2348 fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2349 self.reuse_entry_id(&mut entry);
2350 let entry = self.snapshot.insert_entry(entry, fs);
2351 if entry.path.file_name() == Some(&DOT_GIT) {
2352 self.build_git_repository(entry.path.clone(), fs);
2353 }
2354
2355 #[cfg(test)]
2356 self.snapshot.check_invariants(false);
2357
2358 entry
2359 }
2360
2361 fn populate_dir(
2362 &mut self,
2363 parent_path: &Arc<Path>,
2364 entries: impl IntoIterator<Item = Entry>,
2365 ignore: Option<Arc<Gitignore>>,
2366 ) {
2367 let mut parent_entry = if let Some(parent_entry) = self
2368 .snapshot
2369 .entries_by_path
2370 .get(&PathKey(parent_path.clone()), &())
2371 {
2372 parent_entry.clone()
2373 } else {
2374 log::warn!(
2375 "populating a directory {:?} that has been removed",
2376 parent_path
2377 );
2378 return;
2379 };
2380
2381 match parent_entry.kind {
2382 EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2383 EntryKind::Dir => {}
2384 _ => return,
2385 }
2386
2387 if let Some(ignore) = ignore {
2388 let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2389 self.snapshot
2390 .ignores_by_parent_abs_path
2391 .insert(abs_parent_path, (ignore, false));
2392 }
2393
2394 let parent_entry_id = parent_entry.id;
2395 self.scanned_dirs.insert(parent_entry_id);
2396 let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2397 let mut entries_by_id_edits = Vec::new();
2398
2399 for entry in entries {
2400 entries_by_id_edits.push(Edit::Insert(PathEntry {
2401 id: entry.id,
2402 path: entry.path.clone(),
2403 is_ignored: entry.is_ignored,
2404 scan_id: self.snapshot.scan_id,
2405 }));
2406 entries_by_path_edits.push(Edit::Insert(entry));
2407 }
2408
2409 self.snapshot
2410 .entries_by_path
2411 .edit(entries_by_path_edits, &());
2412 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2413
2414 if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2415 self.changed_paths.insert(ix, parent_path.clone());
2416 }
2417
2418 #[cfg(test)]
2419 self.snapshot.check_invariants(false);
2420 }
2421
2422 fn remove_path(&mut self, path: &Path) {
2423 let mut new_entries;
2424 let removed_entries;
2425 {
2426 let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2427 new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2428 removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2429 new_entries.append(cursor.suffix(&()), &());
2430 }
2431 self.snapshot.entries_by_path = new_entries;
2432
2433 let mut entries_by_id_edits = Vec::new();
2434 for entry in removed_entries.cursor::<()>() {
2435 let removed_entry_id = self
2436 .removed_entry_ids
2437 .entry(entry.inode)
2438 .or_insert(entry.id);
2439 *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2440 entries_by_id_edits.push(Edit::Remove(entry.id));
2441 }
2442 self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2443
2444 if path.file_name() == Some(&GITIGNORE) {
2445 let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2446 if let Some((_, needs_update)) = self
2447 .snapshot
2448 .ignores_by_parent_abs_path
2449 .get_mut(abs_parent_path.as_path())
2450 {
2451 *needs_update = true;
2452 }
2453 }
2454
2455 #[cfg(test)]
2456 self.snapshot.check_invariants(false);
2457 }
2458
2459 fn reload_repositories(&mut self, dot_git_dirs_to_reload: &HashSet<PathBuf>, fs: &dyn Fs) {
2460 let scan_id = self.snapshot.scan_id;
2461
2462 for dot_git_dir in dot_git_dirs_to_reload {
2463 // If there is already a repository for this .git directory, reload
2464 // the status for all of its files.
2465 let repository = self
2466 .snapshot
2467 .git_repositories
2468 .iter()
2469 .find_map(|(entry_id, repo)| {
2470 (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2471 });
2472 match repository {
2473 None => {
2474 self.build_git_repository(Arc::from(dot_git_dir.as_path()), fs);
2475 }
2476 Some((entry_id, repository)) => {
2477 if repository.git_dir_scan_id == scan_id {
2478 continue;
2479 }
2480 let Some(work_dir) = self
2481 .snapshot
2482 .entry_for_id(entry_id)
2483 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2484 else {
2485 continue;
2486 };
2487
2488 log::info!("reload git repository {dot_git_dir:?}");
2489 let repository = repository.repo_ptr.lock();
2490 let branch = repository.branch_name();
2491 repository.reload_index();
2492
2493 self.snapshot
2494 .git_repositories
2495 .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2496 self.snapshot
2497 .snapshot
2498 .repository_entries
2499 .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2500
2501 self.update_git_statuses(&work_dir, &*repository);
2502 }
2503 }
2504 }
2505
2506 // Remove any git repositories whose .git entry no longer exists.
2507 let snapshot = &mut self.snapshot;
2508 let mut ids_to_preserve = HashSet::default();
2509 for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
2510 let exists_in_snapshot = snapshot
2511 .entry_for_id(work_directory_id)
2512 .map_or(false, |entry| {
2513 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2514 });
2515 if exists_in_snapshot {
2516 ids_to_preserve.insert(work_directory_id);
2517 } else {
2518 let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
2519 let git_dir_excluded = snapshot.is_path_excluded(entry.git_dir_path.to_path_buf());
2520 if git_dir_excluded
2521 && !matches!(smol::block_on(fs.metadata(&git_dir_abs_path)), Ok(None))
2522 {
2523 ids_to_preserve.insert(work_directory_id);
2524 }
2525 }
2526 }
2527 snapshot
2528 .git_repositories
2529 .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
2530 snapshot
2531 .repository_entries
2532 .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
2533 }
2534
2535 fn build_git_repository(
2536 &mut self,
2537 dot_git_path: Arc<Path>,
2538 fs: &dyn Fs,
2539 ) -> Option<(
2540 RepositoryWorkDirectory,
2541 Arc<Mutex<dyn GitRepository>>,
2542 TreeMap<RepoPath, GitFileStatus>,
2543 )> {
2544 log::info!("build git repository {:?}", dot_git_path);
2545
2546 let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2547
2548 // Guard against repositories inside the repository metadata
2549 if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2550 return None;
2551 };
2552
2553 let work_dir_id = self
2554 .snapshot
2555 .entry_for_path(work_dir_path.clone())
2556 .map(|entry| entry.id)?;
2557
2558 if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2559 return None;
2560 }
2561
2562 let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2563 let repository = fs.open_repo(abs_path.as_path())?;
2564 let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2565
2566 let repo_lock = repository.lock();
2567 self.snapshot.repository_entries.insert(
2568 work_directory.clone(),
2569 RepositoryEntry {
2570 work_directory: work_dir_id.into(),
2571 branch: repo_lock.branch_name().map(Into::into),
2572 },
2573 );
2574
2575 let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2576 drop(repo_lock);
2577
2578 self.snapshot.git_repositories.insert(
2579 work_dir_id,
2580 LocalRepositoryEntry {
2581 git_dir_scan_id: 0,
2582 repo_ptr: repository.clone(),
2583 git_dir_path: dot_git_path.clone(),
2584 },
2585 );
2586
2587 Some((work_directory, repository, staged_statuses))
2588 }
2589
2590 fn update_git_statuses(
2591 &mut self,
2592 work_directory: &RepositoryWorkDirectory,
2593 repo: &dyn GitRepository,
2594 ) -> TreeMap<RepoPath, GitFileStatus> {
2595 let staged_statuses = repo.staged_statuses(Path::new(""));
2596
2597 let mut changes = vec![];
2598 let mut edits = vec![];
2599
2600 for mut entry in self
2601 .snapshot
2602 .descendent_entries(false, false, &work_directory.0)
2603 .cloned()
2604 {
2605 let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2606 continue;
2607 };
2608 let repo_path = RepoPath(repo_path.to_path_buf());
2609 let git_file_status = combine_git_statuses(
2610 staged_statuses.get(&repo_path).copied(),
2611 repo.unstaged_status(&repo_path, entry.mtime),
2612 );
2613 if entry.git_status != git_file_status {
2614 entry.git_status = git_file_status;
2615 changes.push(entry.path.clone());
2616 edits.push(Edit::Insert(entry));
2617 }
2618 }
2619
2620 self.snapshot.entries_by_path.edit(edits, &());
2621 util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2622 staged_statuses
2623 }
2624}
2625
2626async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2627 let contents = fs.load(abs_path).await?;
2628 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2629 let mut builder = GitignoreBuilder::new(parent);
2630 for line in contents.lines() {
2631 builder.add_line(Some(abs_path.into()), line)?;
2632 }
2633 Ok(builder.build()?)
2634}
2635
2636impl WorktreeId {
2637 pub fn from_usize(handle_id: usize) -> Self {
2638 Self(handle_id)
2639 }
2640
2641 pub(crate) fn from_proto(id: u64) -> Self {
2642 Self(id as usize)
2643 }
2644
2645 pub fn to_proto(&self) -> u64 {
2646 self.0 as u64
2647 }
2648
2649 pub fn to_usize(&self) -> usize {
2650 self.0
2651 }
2652}
2653
2654impl fmt::Display for WorktreeId {
2655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2656 self.0.fmt(f)
2657 }
2658}
2659
2660impl Deref for Worktree {
2661 type Target = Snapshot;
2662
2663 fn deref(&self) -> &Self::Target {
2664 match self {
2665 Worktree::Local(worktree) => &worktree.snapshot,
2666 Worktree::Remote(worktree) => &worktree.snapshot,
2667 }
2668 }
2669}
2670
2671impl Deref for LocalWorktree {
2672 type Target = LocalSnapshot;
2673
2674 fn deref(&self) -> &Self::Target {
2675 &self.snapshot
2676 }
2677}
2678
2679impl Deref for RemoteWorktree {
2680 type Target = Snapshot;
2681
2682 fn deref(&self) -> &Self::Target {
2683 &self.snapshot
2684 }
2685}
2686
2687impl fmt::Debug for LocalWorktree {
2688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2689 self.snapshot.fmt(f)
2690 }
2691}
2692
2693impl fmt::Debug for Snapshot {
2694 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2695 struct EntriesById<'a>(&'a SumTree<PathEntry>);
2696 struct EntriesByPath<'a>(&'a SumTree<Entry>);
2697
2698 impl<'a> fmt::Debug for EntriesByPath<'a> {
2699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2700 f.debug_map()
2701 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2702 .finish()
2703 }
2704 }
2705
2706 impl<'a> fmt::Debug for EntriesById<'a> {
2707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2708 f.debug_list().entries(self.0.iter()).finish()
2709 }
2710 }
2711
2712 f.debug_struct("Snapshot")
2713 .field("id", &self.id)
2714 .field("root_name", &self.root_name)
2715 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2716 .field("entries_by_id", &EntriesById(&self.entries_by_id))
2717 .finish()
2718 }
2719}
2720
2721#[derive(Clone, PartialEq)]
2722pub struct File {
2723 pub worktree: Model<Worktree>,
2724 pub path: Arc<Path>,
2725 pub mtime: SystemTime,
2726 pub(crate) entry_id: Option<ProjectEntryId>,
2727 pub(crate) is_local: bool,
2728 pub(crate) is_deleted: bool,
2729}
2730
2731impl language::File for File {
2732 fn as_local(&self) -> Option<&dyn language::LocalFile> {
2733 if self.is_local {
2734 Some(self)
2735 } else {
2736 None
2737 }
2738 }
2739
2740 fn mtime(&self) -> SystemTime {
2741 self.mtime
2742 }
2743
2744 fn path(&self) -> &Arc<Path> {
2745 &self.path
2746 }
2747
2748 fn full_path(&self, cx: &AppContext) -> PathBuf {
2749 let mut full_path = PathBuf::new();
2750 let worktree = self.worktree.read(cx);
2751
2752 if worktree.is_visible() {
2753 full_path.push(worktree.root_name());
2754 } else {
2755 let path = worktree.abs_path();
2756
2757 if worktree.is_local() && path.starts_with(HOME.as_path()) {
2758 full_path.push("~");
2759 full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2760 } else {
2761 full_path.push(path)
2762 }
2763 }
2764
2765 if self.path.components().next().is_some() {
2766 full_path.push(&self.path);
2767 }
2768
2769 full_path
2770 }
2771
2772 /// Returns the last component of this handle's absolute path. If this handle refers to the root
2773 /// of its worktree, then this method will return the name of the worktree itself.
2774 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2775 self.path
2776 .file_name()
2777 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2778 }
2779
2780 fn worktree_id(&self) -> usize {
2781 self.worktree.entity_id().as_u64() as usize
2782 }
2783
2784 fn is_deleted(&self) -> bool {
2785 self.is_deleted
2786 }
2787
2788 fn as_any(&self) -> &dyn Any {
2789 self
2790 }
2791
2792 fn to_proto(&self) -> rpc::proto::File {
2793 rpc::proto::File {
2794 worktree_id: self.worktree.entity_id().as_u64(),
2795 entry_id: self.entry_id.map(|id| id.to_proto()),
2796 path: self.path.to_string_lossy().into(),
2797 mtime: Some(self.mtime.into()),
2798 is_deleted: self.is_deleted,
2799 }
2800 }
2801}
2802
2803impl language::LocalFile for File {
2804 fn abs_path(&self, cx: &AppContext) -> PathBuf {
2805 let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2806 if self.path.as_ref() == Path::new("") {
2807 worktree_path.to_path_buf()
2808 } else {
2809 worktree_path.join(&self.path)
2810 }
2811 }
2812
2813 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2814 let worktree = self.worktree.read(cx).as_local().unwrap();
2815 let abs_path = worktree.absolutize(&self.path);
2816 let fs = worktree.fs.clone();
2817 cx.background_executor()
2818 .spawn(async move { fs.load(&abs_path).await })
2819 }
2820
2821 fn buffer_reloaded(
2822 &self,
2823 buffer_id: u64,
2824 version: &clock::Global,
2825 fingerprint: RopeFingerprint,
2826 line_ending: LineEnding,
2827 mtime: SystemTime,
2828 cx: &mut AppContext,
2829 ) {
2830 let worktree = self.worktree.read(cx).as_local().unwrap();
2831 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2832 worktree
2833 .client
2834 .send(proto::BufferReloaded {
2835 project_id,
2836 buffer_id,
2837 version: serialize_version(version),
2838 mtime: Some(mtime.into()),
2839 fingerprint: serialize_fingerprint(fingerprint),
2840 line_ending: serialize_line_ending(line_ending) as i32,
2841 })
2842 .log_err();
2843 }
2844 }
2845}
2846
2847impl File {
2848 pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
2849 Arc::new(Self {
2850 worktree,
2851 path: entry.path.clone(),
2852 mtime: entry.mtime,
2853 entry_id: Some(entry.id),
2854 is_local: true,
2855 is_deleted: false,
2856 })
2857 }
2858
2859 pub fn from_proto(
2860 proto: rpc::proto::File,
2861 worktree: Model<Worktree>,
2862 cx: &AppContext,
2863 ) -> Result<Self> {
2864 let worktree_id = worktree
2865 .read(cx)
2866 .as_remote()
2867 .ok_or_else(|| anyhow!("not remote"))?
2868 .id();
2869
2870 if worktree_id.to_proto() != proto.worktree_id {
2871 return Err(anyhow!("worktree id does not match file"));
2872 }
2873
2874 Ok(Self {
2875 worktree,
2876 path: Path::new(&proto.path).into(),
2877 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2878 entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
2879 is_local: false,
2880 is_deleted: proto.is_deleted,
2881 })
2882 }
2883
2884 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2885 file.and_then(|f| f.as_any().downcast_ref())
2886 }
2887
2888 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2889 self.worktree.read(cx).id()
2890 }
2891
2892 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2893 if self.is_deleted {
2894 None
2895 } else {
2896 self.entry_id
2897 }
2898 }
2899}
2900
2901#[derive(Clone, Debug, PartialEq, Eq)]
2902pub struct Entry {
2903 pub id: ProjectEntryId,
2904 pub kind: EntryKind,
2905 pub path: Arc<Path>,
2906 pub inode: u64,
2907 pub mtime: SystemTime,
2908 pub is_symlink: bool,
2909
2910 /// Whether this entry is ignored by Git.
2911 ///
2912 /// We only scan ignored entries once the directory is expanded and
2913 /// exclude them from searches.
2914 pub is_ignored: bool,
2915
2916 /// Whether this entry's canonical path is outside of the worktree.
2917 /// This means the entry is only accessible from the worktree root via a
2918 /// symlink.
2919 ///
2920 /// We only scan entries outside of the worktree once the symlinked
2921 /// directory is expanded. External entries are treated like gitignored
2922 /// entries in that they are not included in searches.
2923 pub is_external: bool,
2924 pub git_status: Option<GitFileStatus>,
2925}
2926
2927#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2928pub enum EntryKind {
2929 UnloadedDir,
2930 PendingDir,
2931 Dir,
2932 File(CharBag),
2933}
2934
2935#[derive(Clone, Copy, Debug, PartialEq)]
2936pub enum PathChange {
2937 /// A filesystem entry was was created.
2938 Added,
2939 /// A filesystem entry was removed.
2940 Removed,
2941 /// A filesystem entry was updated.
2942 Updated,
2943 /// A filesystem entry was either updated or added. We don't know
2944 /// whether or not it already existed, because the path had not
2945 /// been loaded before the event.
2946 AddedOrUpdated,
2947 /// A filesystem entry was found during the initial scan of the worktree.
2948 Loaded,
2949}
2950
2951pub struct GitRepositoryChange {
2952 /// The previous state of the repository, if it already existed.
2953 pub old_repository: Option<RepositoryEntry>,
2954}
2955
2956pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2957pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2958
2959impl Entry {
2960 fn new(
2961 path: Arc<Path>,
2962 metadata: &fs::Metadata,
2963 next_entry_id: &AtomicUsize,
2964 root_char_bag: CharBag,
2965 ) -> Self {
2966 Self {
2967 id: ProjectEntryId::new(next_entry_id),
2968 kind: if metadata.is_dir {
2969 EntryKind::PendingDir
2970 } else {
2971 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2972 },
2973 path,
2974 inode: metadata.inode,
2975 mtime: metadata.mtime,
2976 is_symlink: metadata.is_symlink,
2977 is_ignored: false,
2978 is_external: false,
2979 git_status: None,
2980 }
2981 }
2982
2983 pub fn is_dir(&self) -> bool {
2984 self.kind.is_dir()
2985 }
2986
2987 pub fn is_file(&self) -> bool {
2988 self.kind.is_file()
2989 }
2990
2991 pub fn git_status(&self) -> Option<GitFileStatus> {
2992 self.git_status
2993 }
2994}
2995
2996impl EntryKind {
2997 pub fn is_dir(&self) -> bool {
2998 matches!(
2999 self,
3000 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3001 )
3002 }
3003
3004 pub fn is_unloaded(&self) -> bool {
3005 matches!(self, EntryKind::UnloadedDir)
3006 }
3007
3008 pub fn is_file(&self) -> bool {
3009 matches!(self, EntryKind::File(_))
3010 }
3011}
3012
3013impl sum_tree::Item for Entry {
3014 type Summary = EntrySummary;
3015
3016 fn summary(&self) -> Self::Summary {
3017 let non_ignored_count = if self.is_ignored || self.is_external {
3018 0
3019 } else {
3020 1
3021 };
3022 let file_count;
3023 let non_ignored_file_count;
3024 if self.is_file() {
3025 file_count = 1;
3026 non_ignored_file_count = non_ignored_count;
3027 } else {
3028 file_count = 0;
3029 non_ignored_file_count = 0;
3030 }
3031
3032 let mut statuses = GitStatuses::default();
3033 match self.git_status {
3034 Some(status) => match status {
3035 GitFileStatus::Added => statuses.added = 1,
3036 GitFileStatus::Modified => statuses.modified = 1,
3037 GitFileStatus::Conflict => statuses.conflict = 1,
3038 },
3039 None => {}
3040 }
3041
3042 EntrySummary {
3043 max_path: self.path.clone(),
3044 count: 1,
3045 non_ignored_count,
3046 file_count,
3047 non_ignored_file_count,
3048 statuses,
3049 }
3050 }
3051}
3052
3053impl sum_tree::KeyedItem for Entry {
3054 type Key = PathKey;
3055
3056 fn key(&self) -> Self::Key {
3057 PathKey(self.path.clone())
3058 }
3059}
3060
3061#[derive(Clone, Debug)]
3062pub struct EntrySummary {
3063 max_path: Arc<Path>,
3064 count: usize,
3065 non_ignored_count: usize,
3066 file_count: usize,
3067 non_ignored_file_count: usize,
3068 statuses: GitStatuses,
3069}
3070
3071impl Default for EntrySummary {
3072 fn default() -> Self {
3073 Self {
3074 max_path: Arc::from(Path::new("")),
3075 count: 0,
3076 non_ignored_count: 0,
3077 file_count: 0,
3078 non_ignored_file_count: 0,
3079 statuses: Default::default(),
3080 }
3081 }
3082}
3083
3084impl sum_tree::Summary for EntrySummary {
3085 type Context = ();
3086
3087 fn add_summary(&mut self, rhs: &Self, _: &()) {
3088 self.max_path = rhs.max_path.clone();
3089 self.count += rhs.count;
3090 self.non_ignored_count += rhs.non_ignored_count;
3091 self.file_count += rhs.file_count;
3092 self.non_ignored_file_count += rhs.non_ignored_file_count;
3093 self.statuses += rhs.statuses;
3094 }
3095}
3096
3097#[derive(Clone, Debug)]
3098struct PathEntry {
3099 id: ProjectEntryId,
3100 path: Arc<Path>,
3101 is_ignored: bool,
3102 scan_id: usize,
3103}
3104
3105impl sum_tree::Item for PathEntry {
3106 type Summary = PathEntrySummary;
3107
3108 fn summary(&self) -> Self::Summary {
3109 PathEntrySummary { max_id: self.id }
3110 }
3111}
3112
3113impl sum_tree::KeyedItem for PathEntry {
3114 type Key = ProjectEntryId;
3115
3116 fn key(&self) -> Self::Key {
3117 self.id
3118 }
3119}
3120
3121#[derive(Clone, Debug, Default)]
3122struct PathEntrySummary {
3123 max_id: ProjectEntryId,
3124}
3125
3126impl sum_tree::Summary for PathEntrySummary {
3127 type Context = ();
3128
3129 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3130 self.max_id = summary.max_id;
3131 }
3132}
3133
3134impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3135 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3136 *self = summary.max_id;
3137 }
3138}
3139
3140#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3141pub struct PathKey(Arc<Path>);
3142
3143impl Default for PathKey {
3144 fn default() -> Self {
3145 Self(Path::new("").into())
3146 }
3147}
3148
3149impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3150 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3151 self.0 = summary.max_path.clone();
3152 }
3153}
3154
3155struct BackgroundScanner {
3156 state: Mutex<BackgroundScannerState>,
3157 fs: Arc<dyn Fs>,
3158 status_updates_tx: UnboundedSender<ScanState>,
3159 executor: BackgroundExecutor,
3160 scan_requests_rx: channel::Receiver<ScanRequest>,
3161 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3162 next_entry_id: Arc<AtomicUsize>,
3163 phase: BackgroundScannerPhase,
3164}
3165
3166#[derive(PartialEq)]
3167enum BackgroundScannerPhase {
3168 InitialScan,
3169 EventsReceivedDuringInitialScan,
3170 Events,
3171}
3172
3173impl BackgroundScanner {
3174 fn new(
3175 snapshot: LocalSnapshot,
3176 next_entry_id: Arc<AtomicUsize>,
3177 fs: Arc<dyn Fs>,
3178 status_updates_tx: UnboundedSender<ScanState>,
3179 executor: BackgroundExecutor,
3180 scan_requests_rx: channel::Receiver<ScanRequest>,
3181 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3182 ) -> Self {
3183 Self {
3184 fs,
3185 status_updates_tx,
3186 executor,
3187 scan_requests_rx,
3188 path_prefixes_to_scan_rx,
3189 next_entry_id,
3190 state: Mutex::new(BackgroundScannerState {
3191 prev_snapshot: snapshot.snapshot.clone(),
3192 snapshot,
3193 scanned_dirs: Default::default(),
3194 path_prefixes_to_scan: Default::default(),
3195 paths_to_scan: Default::default(),
3196 removed_entry_ids: Default::default(),
3197 changed_paths: Default::default(),
3198 }),
3199 phase: BackgroundScannerPhase::InitialScan,
3200 }
3201 }
3202
3203 async fn run(
3204 &mut self,
3205 mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
3206 ) {
3207 use futures::FutureExt as _;
3208
3209 // Populate ignores above the root.
3210 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3211 for ancestor in root_abs_path.ancestors().skip(1) {
3212 if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3213 {
3214 self.state
3215 .lock()
3216 .snapshot
3217 .ignores_by_parent_abs_path
3218 .insert(ancestor.into(), (ignore.into(), false));
3219 }
3220 }
3221
3222 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3223 {
3224 let mut state = self.state.lock();
3225 state.snapshot.scan_id += 1;
3226 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3227 let ignore_stack = state
3228 .snapshot
3229 .ignore_stack_for_abs_path(&root_abs_path, true);
3230 if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3231 root_entry.is_ignored = true;
3232 state.insert_entry(root_entry.clone(), self.fs.as_ref());
3233 }
3234 state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3235 }
3236 };
3237
3238 // Perform an initial scan of the directory.
3239 drop(scan_job_tx);
3240 self.scan_dirs(true, scan_job_rx).await;
3241 {
3242 let mut state = self.state.lock();
3243 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3244 }
3245
3246 self.send_status_update(false, None);
3247
3248 // Process any any FS events that occurred while performing the initial scan.
3249 // For these events, update events cannot be as precise, because we didn't
3250 // have the previous state loaded yet.
3251 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3252 if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3253 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3254 while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3255 paths.extend(more_events.into_iter().map(|e| e.path));
3256 }
3257 self.process_events(paths).await;
3258 }
3259
3260 // Continue processing events until the worktree is dropped.
3261 self.phase = BackgroundScannerPhase::Events;
3262 loop {
3263 select_biased! {
3264 // Process any path refresh requests from the worktree. Prioritize
3265 // these before handling changes reported by the filesystem.
3266 request = self.scan_requests_rx.recv().fuse() => {
3267 let Ok(request) = request else { break };
3268 if !self.process_scan_request(request, false).await {
3269 return;
3270 }
3271 }
3272
3273 path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3274 let Ok(path_prefix) = path_prefix else { break };
3275 log::trace!("adding path prefix {:?}", path_prefix);
3276
3277 let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3278 if did_scan {
3279 let abs_path =
3280 {
3281 let mut state = self.state.lock();
3282 state.path_prefixes_to_scan.insert(path_prefix.clone());
3283 state.snapshot.abs_path.join(&path_prefix)
3284 };
3285
3286 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3287 self.process_events(vec![abs_path]).await;
3288 }
3289 }
3290 }
3291
3292 events = fs_events_rx.next().fuse() => {
3293 let Some(events) = events else { break };
3294 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3295 while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3296 paths.extend(more_events.into_iter().map(|e| e.path));
3297 }
3298 self.process_events(paths.clone()).await;
3299 }
3300 }
3301 }
3302 }
3303
3304 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3305 log::debug!("rescanning paths {:?}", request.relative_paths);
3306
3307 request.relative_paths.sort_unstable();
3308 self.forcibly_load_paths(&request.relative_paths).await;
3309
3310 let root_path = self.state.lock().snapshot.abs_path.clone();
3311 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3312 Ok(path) => path,
3313 Err(err) => {
3314 log::error!("failed to canonicalize root path: {}", err);
3315 return false;
3316 }
3317 };
3318 let abs_paths = request
3319 .relative_paths
3320 .iter()
3321 .map(|path| {
3322 if path.file_name().is_some() {
3323 root_canonical_path.join(path)
3324 } else {
3325 root_canonical_path.clone()
3326 }
3327 })
3328 .collect::<Vec<_>>();
3329
3330 self.reload_entries_for_paths(
3331 root_path,
3332 root_canonical_path,
3333 &request.relative_paths,
3334 abs_paths,
3335 None,
3336 )
3337 .await;
3338 self.send_status_update(scanning, Some(request.done))
3339 }
3340
3341 async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3342 let root_path = self.state.lock().snapshot.abs_path.clone();
3343 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3344 Ok(path) => path,
3345 Err(err) => {
3346 log::error!("failed to canonicalize root path: {}", err);
3347 return;
3348 }
3349 };
3350
3351 let mut relative_paths = Vec::with_capacity(abs_paths.len());
3352 let mut dot_git_paths_to_reload = HashSet::default();
3353 abs_paths.sort_unstable();
3354 abs_paths.dedup_by(|a, b| a.starts_with(&b));
3355 abs_paths.retain(|abs_path| {
3356 let snapshot = &self.state.lock().snapshot;
3357 {
3358 let mut is_git_related = false;
3359 if let Some(dot_git_dir) = abs_path
3360 .ancestors()
3361 .find(|ancestor| ancestor.file_name() == Some(&*DOT_GIT))
3362 {
3363 let dot_git_path = dot_git_dir
3364 .strip_prefix(&root_canonical_path)
3365 .ok()
3366 .map(|path| path.to_path_buf())
3367 .unwrap_or_else(|| dot_git_dir.to_path_buf());
3368 dot_git_paths_to_reload.insert(dot_git_path.to_path_buf());
3369 is_git_related = true;
3370 }
3371
3372 let relative_path: Arc<Path> =
3373 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3374 path.into()
3375 } else {
3376 log::error!(
3377 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3378 );
3379 return false;
3380 };
3381
3382 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3383 snapshot
3384 .entry_for_path(parent)
3385 .map_or(false, |entry| entry.kind == EntryKind::Dir)
3386 });
3387 if !parent_dir_is_loaded {
3388 log::debug!("ignoring event {relative_path:?} within unloaded directory");
3389 return false;
3390 }
3391
3392 if snapshot.is_path_excluded(relative_path.to_path_buf()) {
3393 if !is_git_related {
3394 log::debug!("ignoring FS event for excluded path {relative_path:?}");
3395 }
3396 return false;
3397 }
3398
3399 relative_paths.push(relative_path);
3400 true
3401 }
3402 });
3403
3404 if dot_git_paths_to_reload.is_empty() && relative_paths.is_empty() {
3405 return;
3406 }
3407
3408 if !relative_paths.is_empty() {
3409 log::debug!("received fs events {:?}", relative_paths);
3410
3411 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3412 self.reload_entries_for_paths(
3413 root_path,
3414 root_canonical_path,
3415 &relative_paths,
3416 abs_paths,
3417 Some(scan_job_tx.clone()),
3418 )
3419 .await;
3420 drop(scan_job_tx);
3421 self.scan_dirs(false, scan_job_rx).await;
3422
3423 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3424 self.update_ignore_statuses(scan_job_tx).await;
3425 self.scan_dirs(false, scan_job_rx).await;
3426 }
3427
3428 {
3429 let mut state = self.state.lock();
3430 if !dot_git_paths_to_reload.is_empty() {
3431 if relative_paths.is_empty() {
3432 state.snapshot.scan_id += 1;
3433 }
3434 log::debug!("reloading repositories: {dot_git_paths_to_reload:?}");
3435 state.reload_repositories(&dot_git_paths_to_reload, self.fs.as_ref());
3436 }
3437 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3438 for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3439 state.scanned_dirs.remove(&entry_id);
3440 }
3441 }
3442
3443 self.send_status_update(false, None);
3444 }
3445
3446 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3447 let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3448 {
3449 let mut state = self.state.lock();
3450 let root_path = state.snapshot.abs_path.clone();
3451 for path in paths {
3452 for ancestor in path.ancestors() {
3453 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3454 if entry.kind == EntryKind::UnloadedDir {
3455 let abs_path = root_path.join(ancestor);
3456 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3457 state.paths_to_scan.insert(path.clone());
3458 break;
3459 }
3460 }
3461 }
3462 }
3463 drop(scan_job_tx);
3464 }
3465 while let Some(job) = scan_job_rx.next().await {
3466 self.scan_dir(&job).await.log_err();
3467 }
3468
3469 mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3470 }
3471
3472 async fn scan_dirs(
3473 &self,
3474 enable_progress_updates: bool,
3475 scan_jobs_rx: channel::Receiver<ScanJob>,
3476 ) {
3477 use futures::FutureExt as _;
3478
3479 if self
3480 .status_updates_tx
3481 .unbounded_send(ScanState::Started)
3482 .is_err()
3483 {
3484 return;
3485 }
3486
3487 let progress_update_count = AtomicUsize::new(0);
3488 self.executor
3489 .scoped(|scope| {
3490 for _ in 0..self.executor.num_cpus() {
3491 scope.spawn(async {
3492 let mut last_progress_update_count = 0;
3493 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3494 futures::pin_mut!(progress_update_timer);
3495
3496 loop {
3497 select_biased! {
3498 // Process any path refresh requests before moving on to process
3499 // the scan queue, so that user operations are prioritized.
3500 request = self.scan_requests_rx.recv().fuse() => {
3501 let Ok(request) = request else { break };
3502 if !self.process_scan_request(request, true).await {
3503 return;
3504 }
3505 }
3506
3507 // Send periodic progress updates to the worktree. Use an atomic counter
3508 // to ensure that only one of the workers sends a progress update after
3509 // the update interval elapses.
3510 _ = progress_update_timer => {
3511 match progress_update_count.compare_exchange(
3512 last_progress_update_count,
3513 last_progress_update_count + 1,
3514 SeqCst,
3515 SeqCst
3516 ) {
3517 Ok(_) => {
3518 last_progress_update_count += 1;
3519 self.send_status_update(true, None);
3520 }
3521 Err(count) => {
3522 last_progress_update_count = count;
3523 }
3524 }
3525 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3526 }
3527
3528 // Recursively load directories from the file system.
3529 job = scan_jobs_rx.recv().fuse() => {
3530 let Ok(job) = job else { break };
3531 if let Err(err) = self.scan_dir(&job).await {
3532 if job.path.as_ref() != Path::new("") {
3533 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3534 }
3535 }
3536 }
3537 }
3538 }
3539 })
3540 }
3541 })
3542 .await;
3543 }
3544
3545 fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3546 let mut state = self.state.lock();
3547 if state.changed_paths.is_empty() && scanning {
3548 return true;
3549 }
3550
3551 let new_snapshot = state.snapshot.clone();
3552 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3553 let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3554 state.changed_paths.clear();
3555
3556 self.status_updates_tx
3557 .unbounded_send(ScanState::Updated {
3558 snapshot: new_snapshot,
3559 changes,
3560 scanning,
3561 barrier,
3562 })
3563 .is_ok()
3564 }
3565
3566 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3567 let root_abs_path;
3568 let mut ignore_stack;
3569 let mut new_ignore;
3570 let root_char_bag;
3571 let next_entry_id;
3572 {
3573 let state = self.state.lock();
3574 let snapshot = &state.snapshot;
3575 root_abs_path = snapshot.abs_path().clone();
3576 if snapshot.is_path_excluded(job.path.to_path_buf()) {
3577 log::error!("skipping excluded directory {:?}", job.path);
3578 return Ok(());
3579 }
3580 log::debug!("scanning directory {:?}", job.path);
3581 ignore_stack = job.ignore_stack.clone();
3582 new_ignore = None;
3583 root_char_bag = snapshot.root_char_bag;
3584 next_entry_id = self.next_entry_id.clone();
3585 drop(state);
3586 }
3587
3588 let mut dotgit_path = None;
3589 let mut root_canonical_path = None;
3590 let mut new_entries: Vec<Entry> = Vec::new();
3591 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3592 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3593 while let Some(child_abs_path) = child_paths.next().await {
3594 let child_abs_path: Arc<Path> = match child_abs_path {
3595 Ok(child_abs_path) => child_abs_path.into(),
3596 Err(error) => {
3597 log::error!("error processing entry {:?}", error);
3598 continue;
3599 }
3600 };
3601 let child_name = child_abs_path.file_name().unwrap();
3602 let child_path: Arc<Path> = job.path.join(child_name).into();
3603 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3604 if child_name == *GITIGNORE {
3605 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3606 Ok(ignore) => {
3607 let ignore = Arc::new(ignore);
3608 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3609 new_ignore = Some(ignore);
3610 }
3611 Err(error) => {
3612 log::error!(
3613 "error loading .gitignore file {:?} - {:?}",
3614 child_name,
3615 error
3616 );
3617 }
3618 }
3619
3620 // Update ignore status of any child entries we've already processed to reflect the
3621 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3622 // there should rarely be too numerous. Update the ignore stack associated with any
3623 // new jobs as well.
3624 let mut new_jobs = new_jobs.iter_mut();
3625 for entry in &mut new_entries {
3626 let entry_abs_path = root_abs_path.join(&entry.path);
3627 entry.is_ignored =
3628 ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3629
3630 if entry.is_dir() {
3631 if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3632 job.ignore_stack = if entry.is_ignored {
3633 IgnoreStack::all()
3634 } else {
3635 ignore_stack.clone()
3636 };
3637 }
3638 }
3639 }
3640 }
3641 // If we find a .git, we'll need to load the repository.
3642 else if child_name == *DOT_GIT {
3643 dotgit_path = Some(child_path.clone());
3644 }
3645
3646 {
3647 let relative_path = job.path.join(child_name);
3648 let mut state = self.state.lock();
3649 if state.snapshot.is_path_excluded(relative_path.clone()) {
3650 log::debug!("skipping excluded child entry {relative_path:?}");
3651 state.remove_path(&relative_path);
3652 continue;
3653 }
3654 drop(state);
3655 }
3656
3657 let child_metadata = match self.fs.metadata(&child_abs_path).await {
3658 Ok(Some(metadata)) => metadata,
3659 Ok(None) => continue,
3660 Err(err) => {
3661 log::error!("error processing {child_abs_path:?}: {err:?}");
3662 continue;
3663 }
3664 };
3665
3666 let mut child_entry = Entry::new(
3667 child_path.clone(),
3668 &child_metadata,
3669 &next_entry_id,
3670 root_char_bag,
3671 );
3672
3673 if job.is_external {
3674 child_entry.is_external = true;
3675 } else if child_metadata.is_symlink {
3676 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3677 Ok(path) => path,
3678 Err(err) => {
3679 log::error!(
3680 "error reading target of symlink {:?}: {:?}",
3681 child_abs_path,
3682 err
3683 );
3684 continue;
3685 }
3686 };
3687
3688 // lazily canonicalize the root path in order to determine if
3689 // symlinks point outside of the worktree.
3690 let root_canonical_path = match &root_canonical_path {
3691 Some(path) => path,
3692 None => match self.fs.canonicalize(&root_abs_path).await {
3693 Ok(path) => root_canonical_path.insert(path),
3694 Err(err) => {
3695 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3696 continue;
3697 }
3698 },
3699 };
3700
3701 if !canonical_path.starts_with(root_canonical_path) {
3702 child_entry.is_external = true;
3703 }
3704 }
3705
3706 if child_entry.is_dir() {
3707 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3708
3709 // Avoid recursing until crash in the case of a recursive symlink
3710 if !job.ancestor_inodes.contains(&child_entry.inode) {
3711 let mut ancestor_inodes = job.ancestor_inodes.clone();
3712 ancestor_inodes.insert(child_entry.inode);
3713
3714 new_jobs.push(Some(ScanJob {
3715 abs_path: child_abs_path,
3716 path: child_path,
3717 is_external: child_entry.is_external,
3718 ignore_stack: if child_entry.is_ignored {
3719 IgnoreStack::all()
3720 } else {
3721 ignore_stack.clone()
3722 },
3723 ancestor_inodes,
3724 scan_queue: job.scan_queue.clone(),
3725 containing_repository: job.containing_repository.clone(),
3726 }));
3727 } else {
3728 new_jobs.push(None);
3729 }
3730 } else {
3731 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3732 if !child_entry.is_ignored {
3733 if let Some((repository_dir, repository, staged_statuses)) =
3734 &job.containing_repository
3735 {
3736 if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3737 let repo_path = RepoPath(repo_path.into());
3738 child_entry.git_status = combine_git_statuses(
3739 staged_statuses.get(&repo_path).copied(),
3740 repository
3741 .lock()
3742 .unstaged_status(&repo_path, child_entry.mtime),
3743 );
3744 }
3745 }
3746 }
3747 }
3748
3749 new_entries.push(child_entry);
3750 }
3751
3752 let mut state = self.state.lock();
3753
3754 // Identify any subdirectories that should not be scanned.
3755 let mut job_ix = 0;
3756 for entry in &mut new_entries {
3757 state.reuse_entry_id(entry);
3758 if entry.is_dir() {
3759 if state.should_scan_directory(&entry) {
3760 job_ix += 1;
3761 } else {
3762 log::debug!("defer scanning directory {:?}", entry.path);
3763 entry.kind = EntryKind::UnloadedDir;
3764 new_jobs.remove(job_ix);
3765 }
3766 }
3767 }
3768
3769 state.populate_dir(&job.path, new_entries, new_ignore);
3770
3771 let repository =
3772 dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3773
3774 for new_job in new_jobs {
3775 if let Some(mut new_job) = new_job {
3776 if let Some(containing_repository) = &repository {
3777 new_job.containing_repository = Some(containing_repository.clone());
3778 }
3779
3780 job.scan_queue
3781 .try_send(new_job)
3782 .expect("channel is unbounded");
3783 }
3784 }
3785
3786 Ok(())
3787 }
3788
3789 async fn reload_entries_for_paths(
3790 &self,
3791 root_abs_path: Arc<Path>,
3792 root_canonical_path: PathBuf,
3793 relative_paths: &[Arc<Path>],
3794 abs_paths: Vec<PathBuf>,
3795 scan_queue_tx: Option<Sender<ScanJob>>,
3796 ) {
3797 let metadata = futures::future::join_all(
3798 abs_paths
3799 .iter()
3800 .map(|abs_path| async move {
3801 let metadata = self.fs.metadata(&abs_path).await?;
3802 if let Some(metadata) = metadata {
3803 let canonical_path = self.fs.canonicalize(&abs_path).await?;
3804 anyhow::Ok(Some((metadata, canonical_path)))
3805 } else {
3806 Ok(None)
3807 }
3808 })
3809 .collect::<Vec<_>>(),
3810 )
3811 .await;
3812
3813 let mut state = self.state.lock();
3814 let snapshot = &mut state.snapshot;
3815 let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3816 let doing_recursive_update = scan_queue_tx.is_some();
3817 snapshot.scan_id += 1;
3818 if is_idle && !doing_recursive_update {
3819 snapshot.completed_scan_id = snapshot.scan_id;
3820 }
3821
3822 // Remove any entries for paths that no longer exist or are being recursively
3823 // refreshed. Do this before adding any new entries, so that renames can be
3824 // detected regardless of the order of the paths.
3825 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3826 if matches!(metadata, Ok(None)) || doing_recursive_update {
3827 log::trace!("remove path {:?}", path);
3828 state.remove_path(path);
3829 }
3830 }
3831
3832 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3833 let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3834 match metadata {
3835 Ok(Some((metadata, canonical_path))) => {
3836 let ignore_stack = state
3837 .snapshot
3838 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3839
3840 let mut fs_entry = Entry::new(
3841 path.clone(),
3842 metadata,
3843 self.next_entry_id.as_ref(),
3844 state.snapshot.root_char_bag,
3845 );
3846 let is_dir = fs_entry.is_dir();
3847 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3848 fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3849
3850 if !is_dir && !fs_entry.is_ignored {
3851 if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(&path) {
3852 if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
3853 let repo_path = RepoPath(repo_path.into());
3854 let repo = repo.repo_ptr.lock();
3855 fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
3856 }
3857 }
3858 }
3859
3860 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3861 if state.should_scan_directory(&fs_entry) {
3862 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3863 } else {
3864 fs_entry.kind = EntryKind::UnloadedDir;
3865 }
3866 }
3867
3868 state.insert_entry(fs_entry, self.fs.as_ref());
3869 }
3870 Ok(None) => {
3871 self.remove_repo_path(&path, &mut state.snapshot);
3872 }
3873 Err(err) => {
3874 // TODO - create a special 'error' entry in the entries tree to mark this
3875 log::error!("error reading file {abs_path:?} on event: {err:#}");
3876 }
3877 }
3878 }
3879
3880 util::extend_sorted(
3881 &mut state.changed_paths,
3882 relative_paths.iter().cloned(),
3883 usize::MAX,
3884 Ord::cmp,
3885 );
3886 }
3887
3888 fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3889 if !path
3890 .components()
3891 .any(|component| component.as_os_str() == *DOT_GIT)
3892 {
3893 if let Some(repository) = snapshot.repository_for_work_directory(path) {
3894 let entry = repository.work_directory.0;
3895 snapshot.git_repositories.remove(&entry);
3896 snapshot
3897 .snapshot
3898 .repository_entries
3899 .remove(&RepositoryWorkDirectory(path.into()));
3900 return Some(());
3901 }
3902 }
3903
3904 // TODO statuses
3905 // Track when a .git is removed and iterate over the file system there
3906
3907 Some(())
3908 }
3909
3910 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3911 use futures::FutureExt as _;
3912
3913 let mut snapshot = self.state.lock().snapshot.clone();
3914 let mut ignores_to_update = Vec::new();
3915 let mut ignores_to_delete = Vec::new();
3916 let abs_path = snapshot.abs_path.clone();
3917 for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3918 if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3919 if *needs_update {
3920 *needs_update = false;
3921 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3922 ignores_to_update.push(parent_abs_path.clone());
3923 }
3924 }
3925
3926 let ignore_path = parent_path.join(&*GITIGNORE);
3927 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3928 ignores_to_delete.push(parent_abs_path.clone());
3929 }
3930 }
3931 }
3932
3933 for parent_abs_path in ignores_to_delete {
3934 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3935 self.state
3936 .lock()
3937 .snapshot
3938 .ignores_by_parent_abs_path
3939 .remove(&parent_abs_path);
3940 }
3941
3942 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3943 ignores_to_update.sort_unstable();
3944 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3945 while let Some(parent_abs_path) = ignores_to_update.next() {
3946 while ignores_to_update
3947 .peek()
3948 .map_or(false, |p| p.starts_with(&parent_abs_path))
3949 {
3950 ignores_to_update.next().unwrap();
3951 }
3952
3953 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3954 smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3955 abs_path: parent_abs_path,
3956 ignore_stack,
3957 ignore_queue: ignore_queue_tx.clone(),
3958 scan_queue: scan_job_tx.clone(),
3959 }))
3960 .unwrap();
3961 }
3962 drop(ignore_queue_tx);
3963
3964 self.executor
3965 .scoped(|scope| {
3966 for _ in 0..self.executor.num_cpus() {
3967 scope.spawn(async {
3968 loop {
3969 select_biased! {
3970 // Process any path refresh requests before moving on to process
3971 // the queue of ignore statuses.
3972 request = self.scan_requests_rx.recv().fuse() => {
3973 let Ok(request) = request else { break };
3974 if !self.process_scan_request(request, true).await {
3975 return;
3976 }
3977 }
3978
3979 // Recursively process directories whose ignores have changed.
3980 job = ignore_queue_rx.recv().fuse() => {
3981 let Ok(job) = job else { break };
3982 self.update_ignore_status(job, &snapshot).await;
3983 }
3984 }
3985 }
3986 });
3987 }
3988 })
3989 .await;
3990 }
3991
3992 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3993 log::trace!("update ignore status {:?}", job.abs_path);
3994
3995 let mut ignore_stack = job.ignore_stack;
3996 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3997 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3998 }
3999
4000 let mut entries_by_id_edits = Vec::new();
4001 let mut entries_by_path_edits = Vec::new();
4002 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
4003 for mut entry in snapshot.child_entries(path).cloned() {
4004 let was_ignored = entry.is_ignored;
4005 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4006 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4007 if entry.is_dir() {
4008 let child_ignore_stack = if entry.is_ignored {
4009 IgnoreStack::all()
4010 } else {
4011 ignore_stack.clone()
4012 };
4013
4014 // Scan any directories that were previously ignored and weren't previously scanned.
4015 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4016 let state = self.state.lock();
4017 if state.should_scan_directory(&entry) {
4018 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4019 }
4020 }
4021
4022 job.ignore_queue
4023 .send(UpdateIgnoreStatusJob {
4024 abs_path: abs_path.clone(),
4025 ignore_stack: child_ignore_stack,
4026 ignore_queue: job.ignore_queue.clone(),
4027 scan_queue: job.scan_queue.clone(),
4028 })
4029 .await
4030 .unwrap();
4031 }
4032
4033 if entry.is_ignored != was_ignored {
4034 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4035 path_entry.scan_id = snapshot.scan_id;
4036 path_entry.is_ignored = entry.is_ignored;
4037 entries_by_id_edits.push(Edit::Insert(path_entry));
4038 entries_by_path_edits.push(Edit::Insert(entry));
4039 }
4040 }
4041
4042 let state = &mut self.state.lock();
4043 for edit in &entries_by_path_edits {
4044 if let Edit::Insert(entry) = edit {
4045 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4046 state.changed_paths.insert(ix, entry.path.clone());
4047 }
4048 }
4049 }
4050
4051 state
4052 .snapshot
4053 .entries_by_path
4054 .edit(entries_by_path_edits, &());
4055 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4056 }
4057
4058 fn build_change_set(
4059 &self,
4060 old_snapshot: &Snapshot,
4061 new_snapshot: &Snapshot,
4062 event_paths: &[Arc<Path>],
4063 ) -> UpdatedEntriesSet {
4064 use BackgroundScannerPhase::*;
4065 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4066
4067 // Identify which paths have changed. Use the known set of changed
4068 // parent paths to optimize the search.
4069 let mut changes = Vec::new();
4070 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4071 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4072 let mut last_newly_loaded_dir_path = None;
4073 old_paths.next(&());
4074 new_paths.next(&());
4075 for path in event_paths {
4076 let path = PathKey(path.clone());
4077 if old_paths.item().map_or(false, |e| e.path < path.0) {
4078 old_paths.seek_forward(&path, Bias::Left, &());
4079 }
4080 if new_paths.item().map_or(false, |e| e.path < path.0) {
4081 new_paths.seek_forward(&path, Bias::Left, &());
4082 }
4083 loop {
4084 match (old_paths.item(), new_paths.item()) {
4085 (Some(old_entry), Some(new_entry)) => {
4086 if old_entry.path > path.0
4087 && new_entry.path > path.0
4088 && !old_entry.path.starts_with(&path.0)
4089 && !new_entry.path.starts_with(&path.0)
4090 {
4091 break;
4092 }
4093
4094 match Ord::cmp(&old_entry.path, &new_entry.path) {
4095 Ordering::Less => {
4096 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4097 old_paths.next(&());
4098 }
4099 Ordering::Equal => {
4100 if self.phase == EventsReceivedDuringInitialScan {
4101 if old_entry.id != new_entry.id {
4102 changes.push((
4103 old_entry.path.clone(),
4104 old_entry.id,
4105 Removed,
4106 ));
4107 }
4108 // If the worktree was not fully initialized when this event was generated,
4109 // we can't know whether this entry was added during the scan or whether
4110 // it was merely updated.
4111 changes.push((
4112 new_entry.path.clone(),
4113 new_entry.id,
4114 AddedOrUpdated,
4115 ));
4116 } else if old_entry.id != new_entry.id {
4117 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4118 changes.push((new_entry.path.clone(), new_entry.id, Added));
4119 } else if old_entry != new_entry {
4120 if old_entry.kind.is_unloaded() {
4121 last_newly_loaded_dir_path = Some(&new_entry.path);
4122 changes.push((
4123 new_entry.path.clone(),
4124 new_entry.id,
4125 Loaded,
4126 ));
4127 } else {
4128 changes.push((
4129 new_entry.path.clone(),
4130 new_entry.id,
4131 Updated,
4132 ));
4133 }
4134 }
4135 old_paths.next(&());
4136 new_paths.next(&());
4137 }
4138 Ordering::Greater => {
4139 let is_newly_loaded = self.phase == InitialScan
4140 || last_newly_loaded_dir_path
4141 .as_ref()
4142 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4143 changes.push((
4144 new_entry.path.clone(),
4145 new_entry.id,
4146 if is_newly_loaded { Loaded } else { Added },
4147 ));
4148 new_paths.next(&());
4149 }
4150 }
4151 }
4152 (Some(old_entry), None) => {
4153 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4154 old_paths.next(&());
4155 }
4156 (None, Some(new_entry)) => {
4157 let is_newly_loaded = self.phase == InitialScan
4158 || last_newly_loaded_dir_path
4159 .as_ref()
4160 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4161 changes.push((
4162 new_entry.path.clone(),
4163 new_entry.id,
4164 if is_newly_loaded { Loaded } else { Added },
4165 ));
4166 new_paths.next(&());
4167 }
4168 (None, None) => break,
4169 }
4170 }
4171 }
4172
4173 changes.into()
4174 }
4175
4176 async fn progress_timer(&self, running: bool) {
4177 if !running {
4178 return futures::future::pending().await;
4179 }
4180
4181 #[cfg(any(test, feature = "test-support"))]
4182 if self.fs.is_fake() {
4183 return self.executor.simulate_random_delay().await;
4184 }
4185
4186 smol::Timer::after(Duration::from_millis(100)).await;
4187 }
4188}
4189
4190fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4191 let mut result = root_char_bag;
4192 result.extend(
4193 path.to_string_lossy()
4194 .chars()
4195 .map(|c| c.to_ascii_lowercase()),
4196 );
4197 result
4198}
4199
4200struct ScanJob {
4201 abs_path: Arc<Path>,
4202 path: Arc<Path>,
4203 ignore_stack: Arc<IgnoreStack>,
4204 scan_queue: Sender<ScanJob>,
4205 ancestor_inodes: TreeSet<u64>,
4206 is_external: bool,
4207 containing_repository: Option<(
4208 RepositoryWorkDirectory,
4209 Arc<Mutex<dyn GitRepository>>,
4210 TreeMap<RepoPath, GitFileStatus>,
4211 )>,
4212}
4213
4214struct UpdateIgnoreStatusJob {
4215 abs_path: Arc<Path>,
4216 ignore_stack: Arc<IgnoreStack>,
4217 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4218 scan_queue: Sender<ScanJob>,
4219}
4220
4221pub trait WorktreeModelHandle {
4222 #[cfg(any(test, feature = "test-support"))]
4223 fn flush_fs_events<'a>(
4224 &self,
4225 cx: &'a mut gpui::TestAppContext,
4226 ) -> futures::future::LocalBoxFuture<'a, ()>;
4227}
4228
4229impl WorktreeModelHandle for Model<Worktree> {
4230 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4231 // occurred before the worktree was constructed. These events can cause the worktree to perform
4232 // extra directory scans, and emit extra scan-state notifications.
4233 //
4234 // This function mutates the worktree's directory and waits for those mutations to be picked up,
4235 // to ensure that all redundant FS events have already been processed.
4236 #[cfg(any(test, feature = "test-support"))]
4237 fn flush_fs_events<'a>(
4238 &self,
4239 cx: &'a mut gpui::TestAppContext,
4240 ) -> futures::future::LocalBoxFuture<'a, ()> {
4241 let file_name = "fs-event-sentinel";
4242
4243 let tree = self.clone();
4244 let (fs, root_path) = self.update(cx, |tree, _| {
4245 let tree = tree.as_local().unwrap();
4246 (tree.fs.clone(), tree.abs_path().clone())
4247 });
4248
4249 async move {
4250 fs.create_file(&root_path.join(file_name), Default::default())
4251 .await
4252 .unwrap();
4253
4254 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4255 .await;
4256
4257 fs.remove_file(&root_path.join(file_name), Default::default())
4258 .await
4259 .unwrap();
4260 cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4261 .await;
4262
4263 cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4264 .await;
4265 }
4266 .boxed_local()
4267 }
4268}
4269
4270#[derive(Clone, Debug)]
4271struct TraversalProgress<'a> {
4272 max_path: &'a Path,
4273 count: usize,
4274 non_ignored_count: usize,
4275 file_count: usize,
4276 non_ignored_file_count: usize,
4277}
4278
4279impl<'a> TraversalProgress<'a> {
4280 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4281 match (include_ignored, include_dirs) {
4282 (true, true) => self.count,
4283 (true, false) => self.file_count,
4284 (false, true) => self.non_ignored_count,
4285 (false, false) => self.non_ignored_file_count,
4286 }
4287 }
4288}
4289
4290impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4291 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4292 self.max_path = summary.max_path.as_ref();
4293 self.count += summary.count;
4294 self.non_ignored_count += summary.non_ignored_count;
4295 self.file_count += summary.file_count;
4296 self.non_ignored_file_count += summary.non_ignored_file_count;
4297 }
4298}
4299
4300impl<'a> Default for TraversalProgress<'a> {
4301 fn default() -> Self {
4302 Self {
4303 max_path: Path::new(""),
4304 count: 0,
4305 non_ignored_count: 0,
4306 file_count: 0,
4307 non_ignored_file_count: 0,
4308 }
4309 }
4310}
4311
4312#[derive(Clone, Debug, Default, Copy)]
4313struct GitStatuses {
4314 added: usize,
4315 modified: usize,
4316 conflict: usize,
4317}
4318
4319impl AddAssign for GitStatuses {
4320 fn add_assign(&mut self, rhs: Self) {
4321 self.added += rhs.added;
4322 self.modified += rhs.modified;
4323 self.conflict += rhs.conflict;
4324 }
4325}
4326
4327impl Sub for GitStatuses {
4328 type Output = GitStatuses;
4329
4330 fn sub(self, rhs: Self) -> Self::Output {
4331 GitStatuses {
4332 added: self.added - rhs.added,
4333 modified: self.modified - rhs.modified,
4334 conflict: self.conflict - rhs.conflict,
4335 }
4336 }
4337}
4338
4339impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4340 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4341 *self += summary.statuses
4342 }
4343}
4344
4345pub struct Traversal<'a> {
4346 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4347 include_ignored: bool,
4348 include_dirs: bool,
4349}
4350
4351impl<'a> Traversal<'a> {
4352 pub fn advance(&mut self) -> bool {
4353 self.cursor.seek_forward(
4354 &TraversalTarget::Count {
4355 count: self.end_offset() + 1,
4356 include_dirs: self.include_dirs,
4357 include_ignored: self.include_ignored,
4358 },
4359 Bias::Left,
4360 &(),
4361 )
4362 }
4363
4364 pub fn advance_to_sibling(&mut self) -> bool {
4365 while let Some(entry) = self.cursor.item() {
4366 self.cursor.seek_forward(
4367 &TraversalTarget::PathSuccessor(&entry.path),
4368 Bias::Left,
4369 &(),
4370 );
4371 if let Some(entry) = self.cursor.item() {
4372 if (self.include_dirs || !entry.is_dir())
4373 && (self.include_ignored || !entry.is_ignored)
4374 {
4375 return true;
4376 }
4377 }
4378 }
4379 false
4380 }
4381
4382 pub fn entry(&self) -> Option<&'a Entry> {
4383 self.cursor.item()
4384 }
4385
4386 pub fn start_offset(&self) -> usize {
4387 self.cursor
4388 .start()
4389 .count(self.include_dirs, self.include_ignored)
4390 }
4391
4392 pub fn end_offset(&self) -> usize {
4393 self.cursor
4394 .end(&())
4395 .count(self.include_dirs, self.include_ignored)
4396 }
4397}
4398
4399impl<'a> Iterator for Traversal<'a> {
4400 type Item = &'a Entry;
4401
4402 fn next(&mut self) -> Option<Self::Item> {
4403 if let Some(item) = self.entry() {
4404 self.advance();
4405 Some(item)
4406 } else {
4407 None
4408 }
4409 }
4410}
4411
4412#[derive(Debug)]
4413enum TraversalTarget<'a> {
4414 Path(&'a Path),
4415 PathSuccessor(&'a Path),
4416 Count {
4417 count: usize,
4418 include_ignored: bool,
4419 include_dirs: bool,
4420 },
4421}
4422
4423impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4424 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4425 match self {
4426 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4427 TraversalTarget::PathSuccessor(path) => {
4428 if !cursor_location.max_path.starts_with(path) {
4429 Ordering::Equal
4430 } else {
4431 Ordering::Greater
4432 }
4433 }
4434 TraversalTarget::Count {
4435 count,
4436 include_dirs,
4437 include_ignored,
4438 } => Ord::cmp(
4439 count,
4440 &cursor_location.count(*include_dirs, *include_ignored),
4441 ),
4442 }
4443 }
4444}
4445
4446impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4447 for TraversalTarget<'b>
4448{
4449 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4450 self.cmp(&cursor_location.0, &())
4451 }
4452}
4453
4454struct ChildEntriesIter<'a> {
4455 parent_path: &'a Path,
4456 traversal: Traversal<'a>,
4457}
4458
4459impl<'a> Iterator for ChildEntriesIter<'a> {
4460 type Item = &'a Entry;
4461
4462 fn next(&mut self) -> Option<Self::Item> {
4463 if let Some(item) = self.traversal.entry() {
4464 if item.path.starts_with(&self.parent_path) {
4465 self.traversal.advance_to_sibling();
4466 return Some(item);
4467 }
4468 }
4469 None
4470 }
4471}
4472
4473pub struct DescendentEntriesIter<'a> {
4474 parent_path: &'a Path,
4475 traversal: Traversal<'a>,
4476}
4477
4478impl<'a> Iterator for DescendentEntriesIter<'a> {
4479 type Item = &'a Entry;
4480
4481 fn next(&mut self) -> Option<Self::Item> {
4482 if let Some(item) = self.traversal.entry() {
4483 if item.path.starts_with(&self.parent_path) {
4484 self.traversal.advance();
4485 return Some(item);
4486 }
4487 }
4488 None
4489 }
4490}
4491
4492impl<'a> From<&'a Entry> for proto::Entry {
4493 fn from(entry: &'a Entry) -> Self {
4494 Self {
4495 id: entry.id.to_proto(),
4496 is_dir: entry.is_dir(),
4497 path: entry.path.to_string_lossy().into(),
4498 inode: entry.inode,
4499 mtime: Some(entry.mtime.into()),
4500 is_symlink: entry.is_symlink,
4501 is_ignored: entry.is_ignored,
4502 is_external: entry.is_external,
4503 git_status: entry.git_status.map(git_status_to_proto),
4504 }
4505 }
4506}
4507
4508impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4509 type Error = anyhow::Error;
4510
4511 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4512 if let Some(mtime) = entry.mtime {
4513 let kind = if entry.is_dir {
4514 EntryKind::Dir
4515 } else {
4516 let mut char_bag = *root_char_bag;
4517 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4518 EntryKind::File(char_bag)
4519 };
4520 let path: Arc<Path> = PathBuf::from(entry.path).into();
4521 Ok(Entry {
4522 id: ProjectEntryId::from_proto(entry.id),
4523 kind,
4524 path,
4525 inode: entry.inode,
4526 mtime: mtime.into(),
4527 is_symlink: entry.is_symlink,
4528 is_ignored: entry.is_ignored,
4529 is_external: entry.is_external,
4530 git_status: git_status_from_proto(entry.git_status),
4531 })
4532 } else {
4533 Err(anyhow!(
4534 "missing mtime in remote worktree entry {:?}",
4535 entry.path
4536 ))
4537 }
4538 }
4539}
4540
4541fn combine_git_statuses(
4542 staged: Option<GitFileStatus>,
4543 unstaged: Option<GitFileStatus>,
4544) -> Option<GitFileStatus> {
4545 if let Some(staged) = staged {
4546 if let Some(unstaged) = unstaged {
4547 if unstaged != staged {
4548 Some(GitFileStatus::Modified)
4549 } else {
4550 Some(staged)
4551 }
4552 } else {
4553 Some(staged)
4554 }
4555 } else {
4556 unstaged
4557 }
4558}
4559
4560fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4561 git_status.and_then(|status| {
4562 proto::GitStatus::from_i32(status).map(|status| match status {
4563 proto::GitStatus::Added => GitFileStatus::Added,
4564 proto::GitStatus::Modified => GitFileStatus::Modified,
4565 proto::GitStatus::Conflict => GitFileStatus::Conflict,
4566 })
4567 })
4568}
4569
4570fn git_status_to_proto(status: GitFileStatus) -> i32 {
4571 match status {
4572 GitFileStatus::Added => proto::GitStatus::Added as i32,
4573 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4574 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4575 }
4576}