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