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