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