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