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