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