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