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