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