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