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