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