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