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