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_abs_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, changed_paths: &[Arc<Path>], fs: &dyn Fs) {
2403 let scan_id = self.snapshot.scan_id;
2404
2405 // Find each of the .git directories that contain any of the given paths.
2406 let mut prev_dot_git_dir = None;
2407 for changed_path in changed_paths {
2408 let Some(dot_git_dir) = changed_path
2409 .ancestors()
2410 .find(|ancestor| ancestor.file_name() == Some(&*DOT_GIT))
2411 else {
2412 continue;
2413 };
2414
2415 // Avoid processing the same repository multiple times, if multiple paths
2416 // within it have changed.
2417 if prev_dot_git_dir == Some(dot_git_dir) {
2418 continue;
2419 }
2420 prev_dot_git_dir = Some(dot_git_dir);
2421
2422 // If there is already a repository for this .git directory, reload
2423 // the status for all of its files.
2424 let repository = self
2425 .snapshot
2426 .git_repositories
2427 .iter()
2428 .find_map(|(entry_id, repo)| {
2429 (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2430 });
2431 match repository {
2432 None => {
2433 self.build_git_repository(dot_git_dir.into(), fs);
2434 }
2435 Some((entry_id, repository)) => {
2436 if repository.git_dir_scan_id == scan_id {
2437 continue;
2438 }
2439 let Some(work_dir) = self
2440 .snapshot
2441 .entry_for_id(entry_id)
2442 .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2443 else {
2444 continue;
2445 };
2446
2447 log::info!("reload git repository {:?}", dot_git_dir);
2448 let repository = repository.repo_ptr.lock();
2449 let branch = repository.branch_name();
2450 repository.reload_index();
2451
2452 self.snapshot
2453 .git_repositories
2454 .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2455 self.snapshot
2456 .snapshot
2457 .repository_entries
2458 .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2459
2460 self.update_git_statuses(&work_dir, &*repository);
2461 }
2462 }
2463 }
2464
2465 // Remove any git repositories whose .git entry no longer exists.
2466 let snapshot = &mut self.snapshot;
2467 let mut repositories = mem::take(&mut snapshot.git_repositories);
2468 let mut repository_entries = mem::take(&mut snapshot.repository_entries);
2469 repositories.retain(|work_directory_id, _| {
2470 snapshot
2471 .entry_for_id(*work_directory_id)
2472 .map_or(false, |entry| {
2473 snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2474 })
2475 });
2476 repository_entries.retain(|_, entry| repositories.get(&entry.work_directory.0).is_some());
2477 snapshot.git_repositories = repositories;
2478 snapshot.repository_entries = repository_entries;
2479 }
2480
2481 fn build_git_repository(
2482 &mut self,
2483 dot_git_path: Arc<Path>,
2484 fs: &dyn Fs,
2485 ) -> Option<(
2486 RepositoryWorkDirectory,
2487 Arc<Mutex<dyn GitRepository>>,
2488 TreeMap<RepoPath, GitFileStatus>,
2489 )> {
2490 log::info!("build git repository {:?}", dot_git_path);
2491
2492 let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2493
2494 // Guard against repositories inside the repository metadata
2495 if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2496 return None;
2497 };
2498
2499 let work_dir_id = self
2500 .snapshot
2501 .entry_for_path(work_dir_path.clone())
2502 .map(|entry| entry.id)?;
2503
2504 if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2505 return None;
2506 }
2507
2508 let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2509 let repository = fs.open_repo(abs_path.as_path())?;
2510 let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2511
2512 let repo_lock = repository.lock();
2513 self.snapshot.repository_entries.insert(
2514 work_directory.clone(),
2515 RepositoryEntry {
2516 work_directory: work_dir_id.into(),
2517 branch: repo_lock.branch_name().map(Into::into),
2518 },
2519 );
2520
2521 let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2522 drop(repo_lock);
2523
2524 self.snapshot.git_repositories.insert(
2525 work_dir_id,
2526 LocalRepositoryEntry {
2527 git_dir_scan_id: 0,
2528 repo_ptr: repository.clone(),
2529 git_dir_path: dot_git_path.clone(),
2530 },
2531 );
2532
2533 Some((work_directory, repository, staged_statuses))
2534 }
2535
2536 fn update_git_statuses(
2537 &mut self,
2538 work_directory: &RepositoryWorkDirectory,
2539 repo: &dyn GitRepository,
2540 ) -> TreeMap<RepoPath, GitFileStatus> {
2541 let staged_statuses = repo.staged_statuses(Path::new(""));
2542
2543 let mut changes = vec![];
2544 let mut edits = vec![];
2545
2546 for mut entry in self
2547 .snapshot
2548 .descendent_entries(false, false, &work_directory.0)
2549 .cloned()
2550 {
2551 let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2552 continue;
2553 };
2554 let repo_path = RepoPath(repo_path.to_path_buf());
2555 let git_file_status = combine_git_statuses(
2556 staged_statuses.get(&repo_path).copied(),
2557 repo.unstaged_status(&repo_path, entry.mtime),
2558 );
2559 if entry.git_status != git_file_status {
2560 entry.git_status = git_file_status;
2561 changes.push(entry.path.clone());
2562 edits.push(Edit::Insert(entry));
2563 }
2564 }
2565
2566 self.snapshot.entries_by_path.edit(edits, &());
2567 util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2568 staged_statuses
2569 }
2570}
2571
2572async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2573 let contents = fs.load(abs_path).await?;
2574 let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2575 let mut builder = GitignoreBuilder::new(parent);
2576 for line in contents.lines() {
2577 builder.add_line(Some(abs_path.into()), line)?;
2578 }
2579 Ok(builder.build()?)
2580}
2581
2582impl WorktreeId {
2583 pub fn from_usize(handle_id: usize) -> Self {
2584 Self(handle_id)
2585 }
2586
2587 pub(crate) fn from_proto(id: u64) -> Self {
2588 Self(id as usize)
2589 }
2590
2591 pub fn to_proto(&self) -> u64 {
2592 self.0 as u64
2593 }
2594
2595 pub fn to_usize(&self) -> usize {
2596 self.0
2597 }
2598}
2599
2600impl fmt::Display for WorktreeId {
2601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2602 self.0.fmt(f)
2603 }
2604}
2605
2606impl Deref for Worktree {
2607 type Target = Snapshot;
2608
2609 fn deref(&self) -> &Self::Target {
2610 match self {
2611 Worktree::Local(worktree) => &worktree.snapshot,
2612 Worktree::Remote(worktree) => &worktree.snapshot,
2613 }
2614 }
2615}
2616
2617impl Deref for LocalWorktree {
2618 type Target = LocalSnapshot;
2619
2620 fn deref(&self) -> &Self::Target {
2621 &self.snapshot
2622 }
2623}
2624
2625impl Deref for RemoteWorktree {
2626 type Target = Snapshot;
2627
2628 fn deref(&self) -> &Self::Target {
2629 &self.snapshot
2630 }
2631}
2632
2633impl fmt::Debug for LocalWorktree {
2634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2635 self.snapshot.fmt(f)
2636 }
2637}
2638
2639impl fmt::Debug for Snapshot {
2640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2641 struct EntriesById<'a>(&'a SumTree<PathEntry>);
2642 struct EntriesByPath<'a>(&'a SumTree<Entry>);
2643
2644 impl<'a> fmt::Debug for EntriesByPath<'a> {
2645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2646 f.debug_map()
2647 .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2648 .finish()
2649 }
2650 }
2651
2652 impl<'a> fmt::Debug for EntriesById<'a> {
2653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2654 f.debug_list().entries(self.0.iter()).finish()
2655 }
2656 }
2657
2658 f.debug_struct("Snapshot")
2659 .field("id", &self.id)
2660 .field("root_name", &self.root_name)
2661 .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2662 .field("entries_by_id", &EntriesById(&self.entries_by_id))
2663 .finish()
2664 }
2665}
2666
2667#[derive(Clone, PartialEq)]
2668pub struct File {
2669 pub worktree: ModelHandle<Worktree>,
2670 pub path: Arc<Path>,
2671 pub mtime: SystemTime,
2672 pub(crate) entry_id: ProjectEntryId,
2673 pub(crate) is_local: bool,
2674 pub(crate) is_deleted: bool,
2675}
2676
2677impl language::File for File {
2678 fn as_local(&self) -> Option<&dyn language::LocalFile> {
2679 if self.is_local {
2680 Some(self)
2681 } else {
2682 None
2683 }
2684 }
2685
2686 fn mtime(&self) -> SystemTime {
2687 self.mtime
2688 }
2689
2690 fn path(&self) -> &Arc<Path> {
2691 &self.path
2692 }
2693
2694 fn full_path(&self, cx: &AppContext) -> PathBuf {
2695 let mut full_path = PathBuf::new();
2696 let worktree = self.worktree.read(cx);
2697
2698 if worktree.is_visible() {
2699 full_path.push(worktree.root_name());
2700 } else {
2701 let path = worktree.abs_path();
2702
2703 if worktree.is_local() && path.starts_with(HOME.as_path()) {
2704 full_path.push("~");
2705 full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2706 } else {
2707 full_path.push(path)
2708 }
2709 }
2710
2711 if self.path.components().next().is_some() {
2712 full_path.push(&self.path);
2713 }
2714
2715 full_path
2716 }
2717
2718 /// Returns the last component of this handle's absolute path. If this handle refers to the root
2719 /// of its worktree, then this method will return the name of the worktree itself.
2720 fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2721 self.path
2722 .file_name()
2723 .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2724 }
2725
2726 fn worktree_id(&self) -> usize {
2727 self.worktree.id()
2728 }
2729
2730 fn is_deleted(&self) -> bool {
2731 self.is_deleted
2732 }
2733
2734 fn as_any(&self) -> &dyn Any {
2735 self
2736 }
2737
2738 fn to_proto(&self) -> rpc::proto::File {
2739 rpc::proto::File {
2740 worktree_id: self.worktree.id() as u64,
2741 entry_id: self.entry_id.to_proto(),
2742 path: self.path.to_string_lossy().into(),
2743 mtime: Some(self.mtime.into()),
2744 is_deleted: self.is_deleted,
2745 }
2746 }
2747}
2748
2749impl language::LocalFile for File {
2750 fn abs_path(&self, cx: &AppContext) -> PathBuf {
2751 let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2752 if self.path.as_ref() == Path::new("") {
2753 worktree_path.to_path_buf()
2754 } else {
2755 worktree_path.join(&self.path)
2756 }
2757 }
2758
2759 fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2760 let worktree = self.worktree.read(cx).as_local().unwrap();
2761 let abs_path = worktree.absolutize(&self.path);
2762 let fs = worktree.fs.clone();
2763 cx.background()
2764 .spawn(async move { fs.load(&abs_path).await })
2765 }
2766
2767 fn buffer_reloaded(
2768 &self,
2769 buffer_id: u64,
2770 version: &clock::Global,
2771 fingerprint: RopeFingerprint,
2772 line_ending: LineEnding,
2773 mtime: SystemTime,
2774 cx: &mut AppContext,
2775 ) {
2776 let worktree = self.worktree.read(cx).as_local().unwrap();
2777 if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2778 worktree
2779 .client
2780 .send(proto::BufferReloaded {
2781 project_id,
2782 buffer_id,
2783 version: serialize_version(version),
2784 mtime: Some(mtime.into()),
2785 fingerprint: serialize_fingerprint(fingerprint),
2786 line_ending: serialize_line_ending(line_ending) as i32,
2787 })
2788 .log_err();
2789 }
2790 }
2791}
2792
2793impl File {
2794 pub fn for_entry(entry: Entry, worktree: ModelHandle<Worktree>) -> Arc<Self> {
2795 Arc::new(Self {
2796 worktree,
2797 path: entry.path.clone(),
2798 mtime: entry.mtime,
2799 entry_id: entry.id,
2800 is_local: true,
2801 is_deleted: false,
2802 })
2803 }
2804
2805 pub fn from_proto(
2806 proto: rpc::proto::File,
2807 worktree: ModelHandle<Worktree>,
2808 cx: &AppContext,
2809 ) -> Result<Self> {
2810 let worktree_id = worktree
2811 .read(cx)
2812 .as_remote()
2813 .ok_or_else(|| anyhow!("not remote"))?
2814 .id();
2815
2816 if worktree_id.to_proto() != proto.worktree_id {
2817 return Err(anyhow!("worktree id does not match file"));
2818 }
2819
2820 Ok(Self {
2821 worktree,
2822 path: Path::new(&proto.path).into(),
2823 mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2824 entry_id: ProjectEntryId::from_proto(proto.entry_id),
2825 is_local: false,
2826 is_deleted: proto.is_deleted,
2827 })
2828 }
2829
2830 pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2831 file.and_then(|f| f.as_any().downcast_ref())
2832 }
2833
2834 pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2835 self.worktree.read(cx).id()
2836 }
2837
2838 pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2839 if self.is_deleted {
2840 None
2841 } else {
2842 Some(self.entry_id)
2843 }
2844 }
2845}
2846
2847#[derive(Clone, Debug, PartialEq, Eq)]
2848pub struct Entry {
2849 pub id: ProjectEntryId,
2850 pub kind: EntryKind,
2851 pub path: Arc<Path>,
2852 pub inode: u64,
2853 pub mtime: SystemTime,
2854 pub is_symlink: bool,
2855
2856 /// Whether this entry is ignored by Git.
2857 ///
2858 /// We only scan ignored entries once the directory is expanded and
2859 /// exclude them from searches.
2860 pub is_ignored: bool,
2861
2862 /// Whether this entry's canonical path is outside of the worktree.
2863 /// This means the entry is only accessible from the worktree root via a
2864 /// symlink.
2865 ///
2866 /// We only scan entries outside of the worktree once the symlinked
2867 /// directory is expanded. External entries are treated like gitignored
2868 /// entries in that they are not included in searches.
2869 pub is_external: bool,
2870 pub git_status: Option<GitFileStatus>,
2871}
2872
2873#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2874pub enum EntryKind {
2875 UnloadedDir,
2876 PendingDir,
2877 Dir,
2878 File(CharBag),
2879}
2880
2881#[derive(Clone, Copy, Debug, PartialEq)]
2882pub enum PathChange {
2883 /// A filesystem entry was was created.
2884 Added,
2885 /// A filesystem entry was removed.
2886 Removed,
2887 /// A filesystem entry was updated.
2888 Updated,
2889 /// A filesystem entry was either updated or added. We don't know
2890 /// whether or not it already existed, because the path had not
2891 /// been loaded before the event.
2892 AddedOrUpdated,
2893 /// A filesystem entry was found during the initial scan of the worktree.
2894 Loaded,
2895}
2896
2897pub struct GitRepositoryChange {
2898 /// The previous state of the repository, if it already existed.
2899 pub old_repository: Option<RepositoryEntry>,
2900}
2901
2902pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2903pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2904
2905impl Entry {
2906 fn new(
2907 path: Arc<Path>,
2908 metadata: &fs::Metadata,
2909 next_entry_id: &AtomicUsize,
2910 root_char_bag: CharBag,
2911 ) -> Self {
2912 Self {
2913 id: ProjectEntryId::new(next_entry_id),
2914 kind: if metadata.is_dir {
2915 EntryKind::PendingDir
2916 } else {
2917 EntryKind::File(char_bag_for_path(root_char_bag, &path))
2918 },
2919 path,
2920 inode: metadata.inode,
2921 mtime: metadata.mtime,
2922 is_symlink: metadata.is_symlink,
2923 is_ignored: false,
2924 is_external: false,
2925 git_status: None,
2926 }
2927 }
2928
2929 pub fn is_dir(&self) -> bool {
2930 self.kind.is_dir()
2931 }
2932
2933 pub fn is_file(&self) -> bool {
2934 self.kind.is_file()
2935 }
2936
2937 pub fn git_status(&self) -> Option<GitFileStatus> {
2938 self.git_status
2939 }
2940}
2941
2942impl EntryKind {
2943 pub fn is_dir(&self) -> bool {
2944 matches!(
2945 self,
2946 EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
2947 )
2948 }
2949
2950 pub fn is_unloaded(&self) -> bool {
2951 matches!(self, EntryKind::UnloadedDir)
2952 }
2953
2954 pub fn is_file(&self) -> bool {
2955 matches!(self, EntryKind::File(_))
2956 }
2957}
2958
2959impl sum_tree::Item for Entry {
2960 type Summary = EntrySummary;
2961
2962 fn summary(&self) -> Self::Summary {
2963 let non_ignored_count = if self.is_ignored || self.is_external {
2964 0
2965 } else {
2966 1
2967 };
2968 let file_count;
2969 let non_ignored_file_count;
2970 if self.is_file() {
2971 file_count = 1;
2972 non_ignored_file_count = non_ignored_count;
2973 } else {
2974 file_count = 0;
2975 non_ignored_file_count = 0;
2976 }
2977
2978 let mut statuses = GitStatuses::default();
2979 match self.git_status {
2980 Some(status) => match status {
2981 GitFileStatus::Added => statuses.added = 1,
2982 GitFileStatus::Modified => statuses.modified = 1,
2983 GitFileStatus::Conflict => statuses.conflict = 1,
2984 },
2985 None => {}
2986 }
2987
2988 EntrySummary {
2989 max_path: self.path.clone(),
2990 count: 1,
2991 non_ignored_count,
2992 file_count,
2993 non_ignored_file_count,
2994 statuses,
2995 }
2996 }
2997}
2998
2999impl sum_tree::KeyedItem for Entry {
3000 type Key = PathKey;
3001
3002 fn key(&self) -> Self::Key {
3003 PathKey(self.path.clone())
3004 }
3005}
3006
3007#[derive(Clone, Debug)]
3008pub struct EntrySummary {
3009 max_path: Arc<Path>,
3010 count: usize,
3011 non_ignored_count: usize,
3012 file_count: usize,
3013 non_ignored_file_count: usize,
3014 statuses: GitStatuses,
3015}
3016
3017impl Default for EntrySummary {
3018 fn default() -> Self {
3019 Self {
3020 max_path: Arc::from(Path::new("")),
3021 count: 0,
3022 non_ignored_count: 0,
3023 file_count: 0,
3024 non_ignored_file_count: 0,
3025 statuses: Default::default(),
3026 }
3027 }
3028}
3029
3030impl sum_tree::Summary for EntrySummary {
3031 type Context = ();
3032
3033 fn add_summary(&mut self, rhs: &Self, _: &()) {
3034 self.max_path = rhs.max_path.clone();
3035 self.count += rhs.count;
3036 self.non_ignored_count += rhs.non_ignored_count;
3037 self.file_count += rhs.file_count;
3038 self.non_ignored_file_count += rhs.non_ignored_file_count;
3039 self.statuses += rhs.statuses;
3040 }
3041}
3042
3043#[derive(Clone, Debug)]
3044struct PathEntry {
3045 id: ProjectEntryId,
3046 path: Arc<Path>,
3047 is_ignored: bool,
3048 scan_id: usize,
3049}
3050
3051impl sum_tree::Item for PathEntry {
3052 type Summary = PathEntrySummary;
3053
3054 fn summary(&self) -> Self::Summary {
3055 PathEntrySummary { max_id: self.id }
3056 }
3057}
3058
3059impl sum_tree::KeyedItem for PathEntry {
3060 type Key = ProjectEntryId;
3061
3062 fn key(&self) -> Self::Key {
3063 self.id
3064 }
3065}
3066
3067#[derive(Clone, Debug, Default)]
3068struct PathEntrySummary {
3069 max_id: ProjectEntryId,
3070}
3071
3072impl sum_tree::Summary for PathEntrySummary {
3073 type Context = ();
3074
3075 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3076 self.max_id = summary.max_id;
3077 }
3078}
3079
3080impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3081 fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3082 *self = summary.max_id;
3083 }
3084}
3085
3086#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3087pub struct PathKey(Arc<Path>);
3088
3089impl Default for PathKey {
3090 fn default() -> Self {
3091 Self(Path::new("").into())
3092 }
3093}
3094
3095impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3096 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3097 self.0 = summary.max_path.clone();
3098 }
3099}
3100
3101struct BackgroundScanner {
3102 state: Mutex<BackgroundScannerState>,
3103 fs: Arc<dyn Fs>,
3104 status_updates_tx: UnboundedSender<ScanState>,
3105 executor: Arc<executor::Background>,
3106 scan_requests_rx: channel::Receiver<ScanRequest>,
3107 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3108 next_entry_id: Arc<AtomicUsize>,
3109 phase: BackgroundScannerPhase,
3110}
3111
3112#[derive(PartialEq)]
3113enum BackgroundScannerPhase {
3114 InitialScan,
3115 EventsReceivedDuringInitialScan,
3116 Events,
3117}
3118
3119impl BackgroundScanner {
3120 fn new(
3121 snapshot: LocalSnapshot,
3122 next_entry_id: Arc<AtomicUsize>,
3123 fs: Arc<dyn Fs>,
3124 status_updates_tx: UnboundedSender<ScanState>,
3125 executor: Arc<executor::Background>,
3126 scan_requests_rx: channel::Receiver<ScanRequest>,
3127 path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3128 ) -> Self {
3129 Self {
3130 fs,
3131 status_updates_tx,
3132 executor,
3133 scan_requests_rx,
3134 path_prefixes_to_scan_rx,
3135 next_entry_id,
3136 state: Mutex::new(BackgroundScannerState {
3137 prev_snapshot: snapshot.snapshot.clone(),
3138 snapshot,
3139 scanned_dirs: Default::default(),
3140 path_prefixes_to_scan: Default::default(),
3141 paths_to_scan: Default::default(),
3142 removed_entry_ids: Default::default(),
3143 changed_paths: Default::default(),
3144 }),
3145 phase: BackgroundScannerPhase::InitialScan,
3146 }
3147 }
3148
3149 async fn run(
3150 &mut self,
3151 mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
3152 ) {
3153 use futures::FutureExt as _;
3154
3155 // Populate ignores above the root.
3156 let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3157 for (index, ancestor) in root_abs_path.ancestors().enumerate() {
3158 if index != 0 {
3159 if let Ok(ignore) =
3160 build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3161 {
3162 self.state
3163 .lock()
3164 .snapshot
3165 .ignores_by_parent_abs_path
3166 .insert(ancestor.into(), (ignore.into(), false));
3167 }
3168 }
3169 if ancestor.join(&*DOT_GIT).is_dir() {
3170 // Reached root of git repository.
3171 break;
3172 }
3173 }
3174
3175 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3176 {
3177 let mut state = self.state.lock();
3178 state.snapshot.scan_id += 1;
3179 if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3180 let ignore_stack = state
3181 .snapshot
3182 .ignore_stack_for_abs_path(&root_abs_path, true);
3183 if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3184 root_entry.is_ignored = true;
3185 state.insert_entry(root_entry.clone(), self.fs.as_ref());
3186 }
3187 state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3188 }
3189 };
3190
3191 // Perform an initial scan of the directory.
3192 drop(scan_job_tx);
3193 self.scan_dirs(true, scan_job_rx).await;
3194 {
3195 let mut state = self.state.lock();
3196 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3197 }
3198
3199 self.send_status_update(false, None);
3200
3201 // Process any any FS events that occurred while performing the initial scan.
3202 // For these events, update events cannot be as precise, because we didn't
3203 // have the previous state loaded yet.
3204 self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3205 if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3206 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3207 while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3208 paths.extend(more_events.into_iter().map(|e| e.path));
3209 }
3210 self.process_events(paths).await;
3211 }
3212
3213 // Continue processing events until the worktree is dropped.
3214 self.phase = BackgroundScannerPhase::Events;
3215 loop {
3216 select_biased! {
3217 // Process any path refresh requests from the worktree. Prioritize
3218 // these before handling changes reported by the filesystem.
3219 request = self.scan_requests_rx.recv().fuse() => {
3220 let Ok(request) = request else { break };
3221 if !self.process_scan_request(request, false).await {
3222 return;
3223 }
3224 }
3225
3226 path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3227 let Ok(path_prefix) = path_prefix else { break };
3228 log::trace!("adding path prefix {:?}", path_prefix);
3229
3230 let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3231 if did_scan {
3232 let abs_path =
3233 {
3234 let mut state = self.state.lock();
3235 state.path_prefixes_to_scan.insert(path_prefix.clone());
3236 state.snapshot.abs_path.join(&path_prefix)
3237 };
3238
3239 if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3240 self.process_events(vec![abs_path]).await;
3241 }
3242 }
3243 }
3244
3245 events = fs_events_rx.next().fuse() => {
3246 let Some(events) = events else { break };
3247 let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3248 while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3249 paths.extend(more_events.into_iter().map(|e| e.path));
3250 }
3251 self.process_events(paths.clone()).await;
3252 }
3253 }
3254 }
3255 }
3256
3257 async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3258 log::debug!("rescanning paths {:?}", request.relative_paths);
3259
3260 request.relative_paths.sort_unstable();
3261 self.forcibly_load_paths(&request.relative_paths).await;
3262
3263 let root_path = self.state.lock().snapshot.abs_path.clone();
3264 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3265 Ok(path) => path,
3266 Err(err) => {
3267 log::error!("failed to canonicalize root path: {}", err);
3268 return false;
3269 }
3270 };
3271 let abs_paths = request
3272 .relative_paths
3273 .iter()
3274 .map(|path| {
3275 if path.file_name().is_some() {
3276 root_canonical_path.join(path)
3277 } else {
3278 root_canonical_path.clone()
3279 }
3280 })
3281 .collect::<Vec<_>>();
3282
3283 self.reload_entries_for_paths(
3284 root_path,
3285 root_canonical_path,
3286 &request.relative_paths,
3287 abs_paths,
3288 None,
3289 )
3290 .await;
3291 self.send_status_update(scanning, Some(request.done))
3292 }
3293
3294 async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3295 let root_path = self.state.lock().snapshot.abs_path.clone();
3296 let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3297 Ok(path) => path,
3298 Err(err) => {
3299 log::error!("failed to canonicalize root path: {}", err);
3300 return;
3301 }
3302 };
3303
3304 let mut relative_paths = Vec::with_capacity(abs_paths.len());
3305 abs_paths.sort_unstable();
3306 abs_paths.dedup_by(|a, b| a.starts_with(&b));
3307 abs_paths.retain(|abs_path| {
3308 let snapshot = &self.state.lock().snapshot;
3309 {
3310 let relative_path: Arc<Path> =
3311 if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3312 path.into()
3313 } else {
3314 log::error!(
3315 "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3316 );
3317 return false;
3318 };
3319
3320 let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3321 snapshot
3322 .entry_for_path(parent)
3323 .map_or(false, |entry| entry.kind == EntryKind::Dir)
3324 });
3325 if !parent_dir_is_loaded {
3326 log::debug!("ignoring event {relative_path:?} within unloaded directory");
3327 return false;
3328 }
3329 if snapshot.is_abs_path_excluded(abs_path) {
3330 log::debug!(
3331 "ignoring FS event for path {relative_path:?} within excluded directory"
3332 );
3333 return false;
3334 }
3335
3336 relative_paths.push(relative_path);
3337 true
3338 }
3339 });
3340
3341 if relative_paths.is_empty() {
3342 return;
3343 }
3344
3345 log::debug!("received fs events {:?}", relative_paths);
3346
3347 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3348 self.reload_entries_for_paths(
3349 root_path,
3350 root_canonical_path,
3351 &relative_paths,
3352 abs_paths,
3353 Some(scan_job_tx.clone()),
3354 )
3355 .await;
3356 drop(scan_job_tx);
3357 self.scan_dirs(false, scan_job_rx).await;
3358
3359 let (scan_job_tx, scan_job_rx) = channel::unbounded();
3360 self.update_ignore_statuses(scan_job_tx).await;
3361 self.scan_dirs(false, scan_job_rx).await;
3362
3363 {
3364 let mut state = self.state.lock();
3365 state.reload_repositories(&relative_paths, self.fs.as_ref());
3366 state.snapshot.completed_scan_id = state.snapshot.scan_id;
3367 for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3368 state.scanned_dirs.remove(&entry_id);
3369 }
3370 }
3371
3372 self.send_status_update(false, None);
3373 }
3374
3375 async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3376 let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3377 {
3378 let mut state = self.state.lock();
3379 let root_path = state.snapshot.abs_path.clone();
3380 for path in paths {
3381 for ancestor in path.ancestors() {
3382 if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3383 if entry.kind == EntryKind::UnloadedDir {
3384 let abs_path = root_path.join(ancestor);
3385 state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3386 state.paths_to_scan.insert(path.clone());
3387 break;
3388 }
3389 }
3390 }
3391 }
3392 drop(scan_job_tx);
3393 }
3394 while let Some(job) = scan_job_rx.next().await {
3395 self.scan_dir(&job).await.log_err();
3396 }
3397
3398 mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3399 }
3400
3401 async fn scan_dirs(
3402 &self,
3403 enable_progress_updates: bool,
3404 scan_jobs_rx: channel::Receiver<ScanJob>,
3405 ) {
3406 use futures::FutureExt as _;
3407
3408 if self
3409 .status_updates_tx
3410 .unbounded_send(ScanState::Started)
3411 .is_err()
3412 {
3413 return;
3414 }
3415
3416 let progress_update_count = AtomicUsize::new(0);
3417 self.executor
3418 .scoped(|scope| {
3419 for _ in 0..self.executor.num_cpus() {
3420 scope.spawn(async {
3421 let mut last_progress_update_count = 0;
3422 let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3423 futures::pin_mut!(progress_update_timer);
3424
3425 loop {
3426 select_biased! {
3427 // Process any path refresh requests before moving on to process
3428 // the scan queue, so that user operations are prioritized.
3429 request = self.scan_requests_rx.recv().fuse() => {
3430 let Ok(request) = request else { break };
3431 if !self.process_scan_request(request, true).await {
3432 return;
3433 }
3434 }
3435
3436 // Send periodic progress updates to the worktree. Use an atomic counter
3437 // to ensure that only one of the workers sends a progress update after
3438 // the update interval elapses.
3439 _ = progress_update_timer => {
3440 match progress_update_count.compare_exchange(
3441 last_progress_update_count,
3442 last_progress_update_count + 1,
3443 SeqCst,
3444 SeqCst
3445 ) {
3446 Ok(_) => {
3447 last_progress_update_count += 1;
3448 self.send_status_update(true, None);
3449 }
3450 Err(count) => {
3451 last_progress_update_count = count;
3452 }
3453 }
3454 progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3455 }
3456
3457 // Recursively load directories from the file system.
3458 job = scan_jobs_rx.recv().fuse() => {
3459 let Ok(job) = job else { break };
3460 if let Err(err) = self.scan_dir(&job).await {
3461 if job.path.as_ref() != Path::new("") {
3462 log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3463 }
3464 }
3465 }
3466 }
3467 }
3468 })
3469 }
3470 })
3471 .await;
3472 }
3473
3474 fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3475 let mut state = self.state.lock();
3476 if state.changed_paths.is_empty() && scanning {
3477 return true;
3478 }
3479
3480 let new_snapshot = state.snapshot.clone();
3481 let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3482 let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3483 state.changed_paths.clear();
3484
3485 self.status_updates_tx
3486 .unbounded_send(ScanState::Updated {
3487 snapshot: new_snapshot,
3488 changes,
3489 scanning,
3490 barrier,
3491 })
3492 .is_ok()
3493 }
3494
3495 async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3496 let root_abs_path;
3497 let mut ignore_stack;
3498 let mut new_ignore;
3499 let root_char_bag;
3500 let next_entry_id;
3501 {
3502 let state = self.state.lock();
3503 let snapshot = &state.snapshot;
3504 root_abs_path = snapshot.abs_path().clone();
3505 if snapshot.is_abs_path_excluded(&job.abs_path) {
3506 log::error!("skipping excluded directory {:?}", job.path);
3507 return Ok(());
3508 }
3509 log::debug!("scanning directory {:?}", job.path);
3510 ignore_stack = job.ignore_stack.clone();
3511 new_ignore = None;
3512 root_char_bag = snapshot.root_char_bag;
3513 next_entry_id = self.next_entry_id.clone();
3514 drop(state);
3515 }
3516
3517 let mut dotgit_path = None;
3518 let mut root_canonical_path = None;
3519 let mut new_entries: Vec<Entry> = Vec::new();
3520 let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3521 let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3522 while let Some(child_abs_path) = child_paths.next().await {
3523 let child_abs_path: Arc<Path> = match child_abs_path {
3524 Ok(child_abs_path) => child_abs_path.into(),
3525 Err(error) => {
3526 log::error!("error processing entry {:?}", error);
3527 continue;
3528 }
3529 };
3530 let child_name = child_abs_path.file_name().unwrap();
3531 {
3532 let mut state = self.state.lock();
3533 if state.snapshot.is_abs_path_excluded(&child_abs_path) {
3534 let relative_path = job.path.join(child_name);
3535 log::debug!("skipping excluded child entry {relative_path:?}");
3536 state.remove_path(&relative_path);
3537 continue;
3538 }
3539 drop(state);
3540 }
3541
3542 let child_path: Arc<Path> = job.path.join(child_name).into();
3543 let child_metadata = match self.fs.metadata(&child_abs_path).await {
3544 Ok(Some(metadata)) => metadata,
3545 Ok(None) => continue,
3546 Err(err) => {
3547 log::error!("error processing {:?}: {:?}", child_abs_path, err);
3548 continue;
3549 }
3550 };
3551
3552 // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3553 if child_name == *GITIGNORE {
3554 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3555 Ok(ignore) => {
3556 let ignore = Arc::new(ignore);
3557 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3558 new_ignore = Some(ignore);
3559 }
3560 Err(error) => {
3561 log::error!(
3562 "error loading .gitignore file {:?} - {:?}",
3563 child_name,
3564 error
3565 );
3566 }
3567 }
3568
3569 // Update ignore status of any child entries we've already processed to reflect the
3570 // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3571 // there should rarely be too numerous. Update the ignore stack associated with any
3572 // new jobs as well.
3573 let mut new_jobs = new_jobs.iter_mut();
3574 for entry in &mut new_entries {
3575 let entry_abs_path = root_abs_path.join(&entry.path);
3576 entry.is_ignored =
3577 ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3578
3579 if entry.is_dir() {
3580 if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3581 job.ignore_stack = if entry.is_ignored {
3582 IgnoreStack::all()
3583 } else {
3584 ignore_stack.clone()
3585 };
3586 }
3587 }
3588 }
3589 }
3590 // If we find a .git, we'll need to load the repository.
3591 else if child_name == *DOT_GIT {
3592 dotgit_path = Some(child_path.clone());
3593 }
3594
3595 let mut child_entry = Entry::new(
3596 child_path.clone(),
3597 &child_metadata,
3598 &next_entry_id,
3599 root_char_bag,
3600 );
3601
3602 if job.is_external {
3603 child_entry.is_external = true;
3604 } else if child_metadata.is_symlink {
3605 let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3606 Ok(path) => path,
3607 Err(err) => {
3608 log::error!(
3609 "error reading target of symlink {:?}: {:?}",
3610 child_abs_path,
3611 err
3612 );
3613 continue;
3614 }
3615 };
3616
3617 // lazily canonicalize the root path in order to determine if
3618 // symlinks point outside of the worktree.
3619 let root_canonical_path = match &root_canonical_path {
3620 Some(path) => path,
3621 None => match self.fs.canonicalize(&root_abs_path).await {
3622 Ok(path) => root_canonical_path.insert(path),
3623 Err(err) => {
3624 log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3625 continue;
3626 }
3627 },
3628 };
3629
3630 if !canonical_path.starts_with(root_canonical_path) {
3631 child_entry.is_external = true;
3632 }
3633 }
3634
3635 if child_entry.is_dir() {
3636 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3637
3638 // Avoid recursing until crash in the case of a recursive symlink
3639 if !job.ancestor_inodes.contains(&child_entry.inode) {
3640 let mut ancestor_inodes = job.ancestor_inodes.clone();
3641 ancestor_inodes.insert(child_entry.inode);
3642
3643 new_jobs.push(Some(ScanJob {
3644 abs_path: child_abs_path,
3645 path: child_path,
3646 is_external: child_entry.is_external,
3647 ignore_stack: if child_entry.is_ignored {
3648 IgnoreStack::all()
3649 } else {
3650 ignore_stack.clone()
3651 },
3652 ancestor_inodes,
3653 scan_queue: job.scan_queue.clone(),
3654 containing_repository: job.containing_repository.clone(),
3655 }));
3656 } else {
3657 new_jobs.push(None);
3658 }
3659 } else {
3660 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3661 if !child_entry.is_ignored {
3662 if let Some((repository_dir, repository, staged_statuses)) =
3663 &job.containing_repository
3664 {
3665 if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3666 let repo_path = RepoPath(repo_path.into());
3667 child_entry.git_status = combine_git_statuses(
3668 staged_statuses.get(&repo_path).copied(),
3669 repository
3670 .lock()
3671 .unstaged_status(&repo_path, child_entry.mtime),
3672 );
3673 }
3674 }
3675 }
3676 }
3677
3678 new_entries.push(child_entry);
3679 }
3680
3681 let mut state = self.state.lock();
3682
3683 // Identify any subdirectories that should not be scanned.
3684 let mut job_ix = 0;
3685 for entry in &mut new_entries {
3686 state.reuse_entry_id(entry);
3687 if entry.is_dir() {
3688 if state.should_scan_directory(&entry) {
3689 job_ix += 1;
3690 } else {
3691 log::debug!("defer scanning directory {:?}", entry.path);
3692 entry.kind = EntryKind::UnloadedDir;
3693 new_jobs.remove(job_ix);
3694 }
3695 }
3696 }
3697
3698 state.populate_dir(&job.path, new_entries, new_ignore);
3699
3700 let repository =
3701 dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3702
3703 for new_job in new_jobs {
3704 if let Some(mut new_job) = new_job {
3705 if let Some(containing_repository) = &repository {
3706 new_job.containing_repository = Some(containing_repository.clone());
3707 }
3708
3709 job.scan_queue
3710 .try_send(new_job)
3711 .expect("channel is unbounded");
3712 }
3713 }
3714
3715 Ok(())
3716 }
3717
3718 async fn reload_entries_for_paths(
3719 &self,
3720 root_abs_path: Arc<Path>,
3721 root_canonical_path: PathBuf,
3722 relative_paths: &[Arc<Path>],
3723 abs_paths: Vec<PathBuf>,
3724 scan_queue_tx: Option<Sender<ScanJob>>,
3725 ) {
3726 let metadata = futures::future::join_all(
3727 abs_paths
3728 .iter()
3729 .map(|abs_path| async move {
3730 let metadata = self.fs.metadata(&abs_path).await?;
3731 if let Some(metadata) = metadata {
3732 let canonical_path = self.fs.canonicalize(&abs_path).await?;
3733 anyhow::Ok(Some((metadata, canonical_path)))
3734 } else {
3735 Ok(None)
3736 }
3737 })
3738 .collect::<Vec<_>>(),
3739 )
3740 .await;
3741
3742 let mut state = self.state.lock();
3743 let snapshot = &mut state.snapshot;
3744 let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3745 let doing_recursive_update = scan_queue_tx.is_some();
3746 snapshot.scan_id += 1;
3747 if is_idle && !doing_recursive_update {
3748 snapshot.completed_scan_id = snapshot.scan_id;
3749 }
3750
3751 // Remove any entries for paths that no longer exist or are being recursively
3752 // refreshed. Do this before adding any new entries, so that renames can be
3753 // detected regardless of the order of the paths.
3754 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3755 if matches!(metadata, Ok(None)) || doing_recursive_update {
3756 log::trace!("remove path {:?}", path);
3757 state.remove_path(path);
3758 }
3759 }
3760
3761 for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3762 let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3763 match metadata {
3764 Ok(Some((metadata, canonical_path))) => {
3765 let ignore_stack = state
3766 .snapshot
3767 .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3768
3769 let mut fs_entry = Entry::new(
3770 path.clone(),
3771 metadata,
3772 self.next_entry_id.as_ref(),
3773 state.snapshot.root_char_bag,
3774 );
3775 let is_dir = fs_entry.is_dir();
3776 fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3777 fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3778
3779 if !is_dir && !fs_entry.is_ignored {
3780 if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(&path) {
3781 if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
3782 let repo_path = RepoPath(repo_path.into());
3783 let repo = repo.repo_ptr.lock();
3784 fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
3785 }
3786 }
3787 }
3788
3789 if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3790 if state.should_scan_directory(&fs_entry) {
3791 state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3792 } else {
3793 fs_entry.kind = EntryKind::UnloadedDir;
3794 }
3795 }
3796
3797 state.insert_entry(fs_entry, self.fs.as_ref());
3798 }
3799 Ok(None) => {
3800 self.remove_repo_path(&path, &mut state.snapshot);
3801 }
3802 Err(err) => {
3803 // TODO - create a special 'error' entry in the entries tree to mark this
3804 log::error!("error reading file {abs_path:?} on event: {err:#}");
3805 }
3806 }
3807 }
3808
3809 util::extend_sorted(
3810 &mut state.changed_paths,
3811 relative_paths.iter().cloned(),
3812 usize::MAX,
3813 Ord::cmp,
3814 );
3815 }
3816
3817 fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3818 if !path
3819 .components()
3820 .any(|component| component.as_os_str() == *DOT_GIT)
3821 {
3822 if let Some(repository) = snapshot.repository_for_work_directory(path) {
3823 let entry = repository.work_directory.0;
3824 snapshot.git_repositories.remove(&entry);
3825 snapshot
3826 .snapshot
3827 .repository_entries
3828 .remove(&RepositoryWorkDirectory(path.into()));
3829 return Some(());
3830 }
3831 }
3832
3833 // TODO statuses
3834 // Track when a .git is removed and iterate over the file system there
3835
3836 Some(())
3837 }
3838
3839 async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3840 use futures::FutureExt as _;
3841
3842 let mut snapshot = self.state.lock().snapshot.clone();
3843 let mut ignores_to_update = Vec::new();
3844 let mut ignores_to_delete = Vec::new();
3845 let abs_path = snapshot.abs_path.clone();
3846 for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3847 if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3848 if *needs_update {
3849 *needs_update = false;
3850 if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3851 ignores_to_update.push(parent_abs_path.clone());
3852 }
3853 }
3854
3855 let ignore_path = parent_path.join(&*GITIGNORE);
3856 if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3857 ignores_to_delete.push(parent_abs_path.clone());
3858 }
3859 }
3860 }
3861
3862 for parent_abs_path in ignores_to_delete {
3863 snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3864 self.state
3865 .lock()
3866 .snapshot
3867 .ignores_by_parent_abs_path
3868 .remove(&parent_abs_path);
3869 }
3870
3871 let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3872 ignores_to_update.sort_unstable();
3873 let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3874 while let Some(parent_abs_path) = ignores_to_update.next() {
3875 while ignores_to_update
3876 .peek()
3877 .map_or(false, |p| p.starts_with(&parent_abs_path))
3878 {
3879 ignores_to_update.next().unwrap();
3880 }
3881
3882 let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3883 smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3884 abs_path: parent_abs_path,
3885 ignore_stack,
3886 ignore_queue: ignore_queue_tx.clone(),
3887 scan_queue: scan_job_tx.clone(),
3888 }))
3889 .unwrap();
3890 }
3891 drop(ignore_queue_tx);
3892
3893 self.executor
3894 .scoped(|scope| {
3895 for _ in 0..self.executor.num_cpus() {
3896 scope.spawn(async {
3897 loop {
3898 select_biased! {
3899 // Process any path refresh requests before moving on to process
3900 // the queue of ignore statuses.
3901 request = self.scan_requests_rx.recv().fuse() => {
3902 let Ok(request) = request else { break };
3903 if !self.process_scan_request(request, true).await {
3904 return;
3905 }
3906 }
3907
3908 // Recursively process directories whose ignores have changed.
3909 job = ignore_queue_rx.recv().fuse() => {
3910 let Ok(job) = job else { break };
3911 self.update_ignore_status(job, &snapshot).await;
3912 }
3913 }
3914 }
3915 });
3916 }
3917 })
3918 .await;
3919 }
3920
3921 async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3922 log::trace!("update ignore status {:?}", job.abs_path);
3923
3924 let mut ignore_stack = job.ignore_stack;
3925 if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3926 ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3927 }
3928
3929 let mut entries_by_id_edits = Vec::new();
3930 let mut entries_by_path_edits = Vec::new();
3931 let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3932 for mut entry in snapshot.child_entries(path).cloned() {
3933 let was_ignored = entry.is_ignored;
3934 let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
3935 entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3936 if entry.is_dir() {
3937 let child_ignore_stack = if entry.is_ignored {
3938 IgnoreStack::all()
3939 } else {
3940 ignore_stack.clone()
3941 };
3942
3943 // Scan any directories that were previously ignored and weren't previously scanned.
3944 if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
3945 let state = self.state.lock();
3946 if state.should_scan_directory(&entry) {
3947 state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
3948 }
3949 }
3950
3951 job.ignore_queue
3952 .send(UpdateIgnoreStatusJob {
3953 abs_path: abs_path.clone(),
3954 ignore_stack: child_ignore_stack,
3955 ignore_queue: job.ignore_queue.clone(),
3956 scan_queue: job.scan_queue.clone(),
3957 })
3958 .await
3959 .unwrap();
3960 }
3961
3962 if entry.is_ignored != was_ignored {
3963 let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3964 path_entry.scan_id = snapshot.scan_id;
3965 path_entry.is_ignored = entry.is_ignored;
3966 entries_by_id_edits.push(Edit::Insert(path_entry));
3967 entries_by_path_edits.push(Edit::Insert(entry));
3968 }
3969 }
3970
3971 let state = &mut self.state.lock();
3972 for edit in &entries_by_path_edits {
3973 if let Edit::Insert(entry) = edit {
3974 if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
3975 state.changed_paths.insert(ix, entry.path.clone());
3976 }
3977 }
3978 }
3979
3980 state
3981 .snapshot
3982 .entries_by_path
3983 .edit(entries_by_path_edits, &());
3984 state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3985 }
3986
3987 fn build_change_set(
3988 &self,
3989 old_snapshot: &Snapshot,
3990 new_snapshot: &Snapshot,
3991 event_paths: &[Arc<Path>],
3992 ) -> UpdatedEntriesSet {
3993 use BackgroundScannerPhase::*;
3994 use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
3995
3996 // Identify which paths have changed. Use the known set of changed
3997 // parent paths to optimize the search.
3998 let mut changes = Vec::new();
3999 let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4000 let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4001 let mut last_newly_loaded_dir_path = None;
4002 old_paths.next(&());
4003 new_paths.next(&());
4004 for path in event_paths {
4005 let path = PathKey(path.clone());
4006 if old_paths.item().map_or(false, |e| e.path < path.0) {
4007 old_paths.seek_forward(&path, Bias::Left, &());
4008 }
4009 if new_paths.item().map_or(false, |e| e.path < path.0) {
4010 new_paths.seek_forward(&path, Bias::Left, &());
4011 }
4012 loop {
4013 match (old_paths.item(), new_paths.item()) {
4014 (Some(old_entry), Some(new_entry)) => {
4015 if old_entry.path > path.0
4016 && new_entry.path > path.0
4017 && !old_entry.path.starts_with(&path.0)
4018 && !new_entry.path.starts_with(&path.0)
4019 {
4020 break;
4021 }
4022
4023 match Ord::cmp(&old_entry.path, &new_entry.path) {
4024 Ordering::Less => {
4025 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4026 old_paths.next(&());
4027 }
4028 Ordering::Equal => {
4029 if self.phase == EventsReceivedDuringInitialScan {
4030 if old_entry.id != new_entry.id {
4031 changes.push((
4032 old_entry.path.clone(),
4033 old_entry.id,
4034 Removed,
4035 ));
4036 }
4037 // If the worktree was not fully initialized when this event was generated,
4038 // we can't know whether this entry was added during the scan or whether
4039 // it was merely updated.
4040 changes.push((
4041 new_entry.path.clone(),
4042 new_entry.id,
4043 AddedOrUpdated,
4044 ));
4045 } else if old_entry.id != new_entry.id {
4046 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4047 changes.push((new_entry.path.clone(), new_entry.id, Added));
4048 } else if old_entry != new_entry {
4049 if old_entry.kind.is_unloaded() {
4050 last_newly_loaded_dir_path = Some(&new_entry.path);
4051 changes.push((
4052 new_entry.path.clone(),
4053 new_entry.id,
4054 Loaded,
4055 ));
4056 } else {
4057 changes.push((
4058 new_entry.path.clone(),
4059 new_entry.id,
4060 Updated,
4061 ));
4062 }
4063 }
4064 old_paths.next(&());
4065 new_paths.next(&());
4066 }
4067 Ordering::Greater => {
4068 let is_newly_loaded = self.phase == InitialScan
4069 || last_newly_loaded_dir_path
4070 .as_ref()
4071 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4072 changes.push((
4073 new_entry.path.clone(),
4074 new_entry.id,
4075 if is_newly_loaded { Loaded } else { Added },
4076 ));
4077 new_paths.next(&());
4078 }
4079 }
4080 }
4081 (Some(old_entry), None) => {
4082 changes.push((old_entry.path.clone(), old_entry.id, Removed));
4083 old_paths.next(&());
4084 }
4085 (None, Some(new_entry)) => {
4086 let is_newly_loaded = self.phase == InitialScan
4087 || last_newly_loaded_dir_path
4088 .as_ref()
4089 .map_or(false, |dir| new_entry.path.starts_with(&dir));
4090 changes.push((
4091 new_entry.path.clone(),
4092 new_entry.id,
4093 if is_newly_loaded { Loaded } else { Added },
4094 ));
4095 new_paths.next(&());
4096 }
4097 (None, None) => break,
4098 }
4099 }
4100 }
4101
4102 changes.into()
4103 }
4104
4105 async fn progress_timer(&self, running: bool) {
4106 if !running {
4107 return futures::future::pending().await;
4108 }
4109
4110 #[cfg(any(test, feature = "test-support"))]
4111 if self.fs.is_fake() {
4112 return self.executor.simulate_random_delay().await;
4113 }
4114
4115 smol::Timer::after(Duration::from_millis(100)).await;
4116 }
4117}
4118
4119fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4120 let mut result = root_char_bag;
4121 result.extend(
4122 path.to_string_lossy()
4123 .chars()
4124 .map(|c| c.to_ascii_lowercase()),
4125 );
4126 result
4127}
4128
4129struct ScanJob {
4130 abs_path: Arc<Path>,
4131 path: Arc<Path>,
4132 ignore_stack: Arc<IgnoreStack>,
4133 scan_queue: Sender<ScanJob>,
4134 ancestor_inodes: TreeSet<u64>,
4135 is_external: bool,
4136 containing_repository: Option<(
4137 RepositoryWorkDirectory,
4138 Arc<Mutex<dyn GitRepository>>,
4139 TreeMap<RepoPath, GitFileStatus>,
4140 )>,
4141}
4142
4143struct UpdateIgnoreStatusJob {
4144 abs_path: Arc<Path>,
4145 ignore_stack: Arc<IgnoreStack>,
4146 ignore_queue: Sender<UpdateIgnoreStatusJob>,
4147 scan_queue: Sender<ScanJob>,
4148}
4149
4150pub trait WorktreeModelHandle {
4151 #[cfg(any(test, feature = "test-support"))]
4152 fn flush_fs_events<'a>(
4153 &self,
4154 cx: &'a gpui::TestAppContext,
4155 ) -> futures::future::LocalBoxFuture<'a, ()>;
4156}
4157
4158impl WorktreeModelHandle for ModelHandle<Worktree> {
4159 // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4160 // occurred before the worktree was constructed. These events can cause the worktree to perform
4161 // extra directory scans, and emit extra scan-state notifications.
4162 //
4163 // This function mutates the worktree's directory and waits for those mutations to be picked up,
4164 // to ensure that all redundant FS events have already been processed.
4165 #[cfg(any(test, feature = "test-support"))]
4166 fn flush_fs_events<'a>(
4167 &self,
4168 cx: &'a gpui::TestAppContext,
4169 ) -> futures::future::LocalBoxFuture<'a, ()> {
4170 let filename = "fs-event-sentinel";
4171 let tree = self.clone();
4172 let (fs, root_path) = self.read_with(cx, |tree, _| {
4173 let tree = tree.as_local().unwrap();
4174 (tree.fs.clone(), tree.abs_path().clone())
4175 });
4176
4177 async move {
4178 fs.create_file(&root_path.join(filename), Default::default())
4179 .await
4180 .unwrap();
4181 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
4182 .await;
4183
4184 fs.remove_file(&root_path.join(filename), Default::default())
4185 .await
4186 .unwrap();
4187 tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
4188 .await;
4189
4190 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4191 .await;
4192 }
4193 .boxed_local()
4194 }
4195}
4196
4197#[derive(Clone, Debug)]
4198struct TraversalProgress<'a> {
4199 max_path: &'a Path,
4200 count: usize,
4201 non_ignored_count: usize,
4202 file_count: usize,
4203 non_ignored_file_count: usize,
4204}
4205
4206impl<'a> TraversalProgress<'a> {
4207 fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4208 match (include_ignored, include_dirs) {
4209 (true, true) => self.count,
4210 (true, false) => self.file_count,
4211 (false, true) => self.non_ignored_count,
4212 (false, false) => self.non_ignored_file_count,
4213 }
4214 }
4215}
4216
4217impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4218 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4219 self.max_path = summary.max_path.as_ref();
4220 self.count += summary.count;
4221 self.non_ignored_count += summary.non_ignored_count;
4222 self.file_count += summary.file_count;
4223 self.non_ignored_file_count += summary.non_ignored_file_count;
4224 }
4225}
4226
4227impl<'a> Default for TraversalProgress<'a> {
4228 fn default() -> Self {
4229 Self {
4230 max_path: Path::new(""),
4231 count: 0,
4232 non_ignored_count: 0,
4233 file_count: 0,
4234 non_ignored_file_count: 0,
4235 }
4236 }
4237}
4238
4239#[derive(Clone, Debug, Default, Copy)]
4240struct GitStatuses {
4241 added: usize,
4242 modified: usize,
4243 conflict: usize,
4244}
4245
4246impl AddAssign for GitStatuses {
4247 fn add_assign(&mut self, rhs: Self) {
4248 self.added += rhs.added;
4249 self.modified += rhs.modified;
4250 self.conflict += rhs.conflict;
4251 }
4252}
4253
4254impl Sub for GitStatuses {
4255 type Output = GitStatuses;
4256
4257 fn sub(self, rhs: Self) -> Self::Output {
4258 GitStatuses {
4259 added: self.added - rhs.added,
4260 modified: self.modified - rhs.modified,
4261 conflict: self.conflict - rhs.conflict,
4262 }
4263 }
4264}
4265
4266impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4267 fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4268 *self += summary.statuses
4269 }
4270}
4271
4272pub struct Traversal<'a> {
4273 cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4274 include_ignored: bool,
4275 include_dirs: bool,
4276}
4277
4278impl<'a> Traversal<'a> {
4279 pub fn advance(&mut self) -> bool {
4280 self.cursor.seek_forward(
4281 &TraversalTarget::Count {
4282 count: self.end_offset() + 1,
4283 include_dirs: self.include_dirs,
4284 include_ignored: self.include_ignored,
4285 },
4286 Bias::Left,
4287 &(),
4288 )
4289 }
4290
4291 pub fn advance_to_sibling(&mut self) -> bool {
4292 while let Some(entry) = self.cursor.item() {
4293 self.cursor.seek_forward(
4294 &TraversalTarget::PathSuccessor(&entry.path),
4295 Bias::Left,
4296 &(),
4297 );
4298 if let Some(entry) = self.cursor.item() {
4299 if (self.include_dirs || !entry.is_dir())
4300 && (self.include_ignored || !entry.is_ignored)
4301 {
4302 return true;
4303 }
4304 }
4305 }
4306 false
4307 }
4308
4309 pub fn entry(&self) -> Option<&'a Entry> {
4310 self.cursor.item()
4311 }
4312
4313 pub fn start_offset(&self) -> usize {
4314 self.cursor
4315 .start()
4316 .count(self.include_dirs, self.include_ignored)
4317 }
4318
4319 pub fn end_offset(&self) -> usize {
4320 self.cursor
4321 .end(&())
4322 .count(self.include_dirs, self.include_ignored)
4323 }
4324}
4325
4326impl<'a> Iterator for Traversal<'a> {
4327 type Item = &'a Entry;
4328
4329 fn next(&mut self) -> Option<Self::Item> {
4330 if let Some(item) = self.entry() {
4331 self.advance();
4332 Some(item)
4333 } else {
4334 None
4335 }
4336 }
4337}
4338
4339#[derive(Debug)]
4340enum TraversalTarget<'a> {
4341 Path(&'a Path),
4342 PathSuccessor(&'a Path),
4343 Count {
4344 count: usize,
4345 include_ignored: bool,
4346 include_dirs: bool,
4347 },
4348}
4349
4350impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4351 fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4352 match self {
4353 TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4354 TraversalTarget::PathSuccessor(path) => {
4355 if !cursor_location.max_path.starts_with(path) {
4356 Ordering::Equal
4357 } else {
4358 Ordering::Greater
4359 }
4360 }
4361 TraversalTarget::Count {
4362 count,
4363 include_dirs,
4364 include_ignored,
4365 } => Ord::cmp(
4366 count,
4367 &cursor_location.count(*include_dirs, *include_ignored),
4368 ),
4369 }
4370 }
4371}
4372
4373impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4374 for TraversalTarget<'b>
4375{
4376 fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4377 self.cmp(&cursor_location.0, &())
4378 }
4379}
4380
4381struct ChildEntriesIter<'a> {
4382 parent_path: &'a Path,
4383 traversal: Traversal<'a>,
4384}
4385
4386impl<'a> Iterator for ChildEntriesIter<'a> {
4387 type Item = &'a Entry;
4388
4389 fn next(&mut self) -> Option<Self::Item> {
4390 if let Some(item) = self.traversal.entry() {
4391 if item.path.starts_with(&self.parent_path) {
4392 self.traversal.advance_to_sibling();
4393 return Some(item);
4394 }
4395 }
4396 None
4397 }
4398}
4399
4400pub struct DescendentEntriesIter<'a> {
4401 parent_path: &'a Path,
4402 traversal: Traversal<'a>,
4403}
4404
4405impl<'a> Iterator for DescendentEntriesIter<'a> {
4406 type Item = &'a Entry;
4407
4408 fn next(&mut self) -> Option<Self::Item> {
4409 if let Some(item) = self.traversal.entry() {
4410 if item.path.starts_with(&self.parent_path) {
4411 self.traversal.advance();
4412 return Some(item);
4413 }
4414 }
4415 None
4416 }
4417}
4418
4419impl<'a> From<&'a Entry> for proto::Entry {
4420 fn from(entry: &'a Entry) -> Self {
4421 Self {
4422 id: entry.id.to_proto(),
4423 is_dir: entry.is_dir(),
4424 path: entry.path.to_string_lossy().into(),
4425 inode: entry.inode,
4426 mtime: Some(entry.mtime.into()),
4427 is_symlink: entry.is_symlink,
4428 is_ignored: entry.is_ignored,
4429 is_external: entry.is_external,
4430 git_status: entry.git_status.map(git_status_to_proto),
4431 }
4432 }
4433}
4434
4435impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4436 type Error = anyhow::Error;
4437
4438 fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4439 if let Some(mtime) = entry.mtime {
4440 let kind = if entry.is_dir {
4441 EntryKind::Dir
4442 } else {
4443 let mut char_bag = *root_char_bag;
4444 char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4445 EntryKind::File(char_bag)
4446 };
4447 let path: Arc<Path> = PathBuf::from(entry.path).into();
4448 Ok(Entry {
4449 id: ProjectEntryId::from_proto(entry.id),
4450 kind,
4451 path,
4452 inode: entry.inode,
4453 mtime: mtime.into(),
4454 is_symlink: entry.is_symlink,
4455 is_ignored: entry.is_ignored,
4456 is_external: entry.is_external,
4457 git_status: git_status_from_proto(entry.git_status),
4458 })
4459 } else {
4460 Err(anyhow!(
4461 "missing mtime in remote worktree entry {:?}",
4462 entry.path
4463 ))
4464 }
4465 }
4466}
4467
4468fn combine_git_statuses(
4469 staged: Option<GitFileStatus>,
4470 unstaged: Option<GitFileStatus>,
4471) -> Option<GitFileStatus> {
4472 if let Some(staged) = staged {
4473 if let Some(unstaged) = unstaged {
4474 if unstaged != staged {
4475 Some(GitFileStatus::Modified)
4476 } else {
4477 Some(staged)
4478 }
4479 } else {
4480 Some(staged)
4481 }
4482 } else {
4483 unstaged
4484 }
4485}
4486
4487fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4488 git_status.and_then(|status| {
4489 proto::GitStatus::from_i32(status).map(|status| match status {
4490 proto::GitStatus::Added => GitFileStatus::Added,
4491 proto::GitStatus::Modified => GitFileStatus::Modified,
4492 proto::GitStatus::Conflict => GitFileStatus::Conflict,
4493 })
4494 })
4495}
4496
4497fn git_status_to_proto(status: GitFileStatus) -> i32 {
4498 match status {
4499 GitFileStatus::Added => proto::GitStatus::Added as i32,
4500 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4501 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4502 }
4503}