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