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