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