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