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