1use crate::{
2 worktree_settings::WorktreeSettings, Entry, EntryKind, Event, PathChange, Snapshot, Worktree,
3 WorktreeModelHandle,
4};
5use anyhow::Result;
6use fs::{FakeFs, Fs, RealFs, RemoveOptions};
7use git::{repository::GitFileStatus, GITIGNORE};
8use gpui::{BorrowAppContext, ModelContext, Task, TestAppContext};
9use parking_lot::Mutex;
10use postage::stream::Stream;
11use pretty_assertions::assert_eq;
12use rand::prelude::*;
13use serde_json::json;
14use settings::{Settings, SettingsStore};
15use std::{env, fmt::Write, mem, path::Path, sync::Arc};
16use util::{test::temp_tree, ResultExt};
17
18#[gpui::test]
19async fn test_traversal(cx: &mut TestAppContext) {
20 init_test(cx);
21 let fs = FakeFs::new(cx.background_executor.clone());
22 fs.insert_tree(
23 "/root",
24 json!({
25 ".gitignore": "a/b\n",
26 "a": {
27 "b": "",
28 "c": "",
29 }
30 }),
31 )
32 .await;
33
34 let tree = Worktree::local(
35 Path::new("/root"),
36 true,
37 fs,
38 Default::default(),
39 &mut cx.to_async(),
40 )
41 .await
42 .unwrap();
43 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
44 .await;
45
46 tree.read_with(cx, |tree, _| {
47 assert_eq!(
48 tree.entries(false, 0)
49 .map(|entry| entry.path.as_ref())
50 .collect::<Vec<_>>(),
51 vec![
52 Path::new(""),
53 Path::new(".gitignore"),
54 Path::new("a"),
55 Path::new("a/c"),
56 ]
57 );
58 assert_eq!(
59 tree.entries(true, 0)
60 .map(|entry| entry.path.as_ref())
61 .collect::<Vec<_>>(),
62 vec![
63 Path::new(""),
64 Path::new(".gitignore"),
65 Path::new("a"),
66 Path::new("a/b"),
67 Path::new("a/c"),
68 ]
69 );
70 })
71}
72
73#[gpui::test(iterations = 10)]
74async fn test_circular_symlinks(cx: &mut TestAppContext) {
75 init_test(cx);
76 let fs = FakeFs::new(cx.background_executor.clone());
77 fs.insert_tree(
78 "/root",
79 json!({
80 "lib": {
81 "a": {
82 "a.txt": ""
83 },
84 "b": {
85 "b.txt": ""
86 }
87 }
88 }),
89 )
90 .await;
91 fs.create_symlink("/root/lib/a/lib".as_ref(), "..".into())
92 .await
93 .unwrap();
94 fs.create_symlink("/root/lib/b/lib".as_ref(), "..".into())
95 .await
96 .unwrap();
97
98 let tree = Worktree::local(
99 Path::new("/root"),
100 true,
101 fs.clone(),
102 Default::default(),
103 &mut cx.to_async(),
104 )
105 .await
106 .unwrap();
107
108 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
109 .await;
110
111 tree.read_with(cx, |tree, _| {
112 assert_eq!(
113 tree.entries(false, 0)
114 .map(|entry| entry.path.as_ref())
115 .collect::<Vec<_>>(),
116 vec![
117 Path::new(""),
118 Path::new("lib"),
119 Path::new("lib/a"),
120 Path::new("lib/a/a.txt"),
121 Path::new("lib/a/lib"),
122 Path::new("lib/b"),
123 Path::new("lib/b/b.txt"),
124 Path::new("lib/b/lib"),
125 ]
126 );
127 });
128
129 fs.rename(
130 Path::new("/root/lib/a/lib"),
131 Path::new("/root/lib/a/lib-2"),
132 Default::default(),
133 )
134 .await
135 .unwrap();
136 cx.executor().run_until_parked();
137 tree.read_with(cx, |tree, _| {
138 assert_eq!(
139 tree.entries(false, 0)
140 .map(|entry| entry.path.as_ref())
141 .collect::<Vec<_>>(),
142 vec![
143 Path::new(""),
144 Path::new("lib"),
145 Path::new("lib/a"),
146 Path::new("lib/a/a.txt"),
147 Path::new("lib/a/lib-2"),
148 Path::new("lib/b"),
149 Path::new("lib/b/b.txt"),
150 Path::new("lib/b/lib"),
151 ]
152 );
153 });
154}
155
156#[gpui::test]
157async fn test_symlinks_pointing_outside(cx: &mut TestAppContext) {
158 init_test(cx);
159 let fs = FakeFs::new(cx.background_executor.clone());
160 fs.insert_tree(
161 "/root",
162 json!({
163 "dir1": {
164 "deps": {
165 // symlinks here
166 },
167 "src": {
168 "a.rs": "",
169 "b.rs": "",
170 },
171 },
172 "dir2": {
173 "src": {
174 "c.rs": "",
175 "d.rs": "",
176 }
177 },
178 "dir3": {
179 "deps": {},
180 "src": {
181 "e.rs": "",
182 "f.rs": "",
183 },
184 }
185 }),
186 )
187 .await;
188
189 // These symlinks point to directories outside of the worktree's root, dir1.
190 fs.create_symlink("/root/dir1/deps/dep-dir2".as_ref(), "../../dir2".into())
191 .await
192 .unwrap();
193 fs.create_symlink("/root/dir1/deps/dep-dir3".as_ref(), "../../dir3".into())
194 .await
195 .unwrap();
196
197 let tree = Worktree::local(
198 Path::new("/root/dir1"),
199 true,
200 fs.clone(),
201 Default::default(),
202 &mut cx.to_async(),
203 )
204 .await
205 .unwrap();
206
207 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
208 .await;
209
210 let tree_updates = Arc::new(Mutex::new(Vec::new()));
211 tree.update(cx, |_, cx| {
212 let tree_updates = tree_updates.clone();
213 cx.subscribe(&tree, move |_, _, event, _| {
214 if let Event::UpdatedEntries(update) = event {
215 tree_updates.lock().extend(
216 update
217 .iter()
218 .map(|(path, _, change)| (path.clone(), *change)),
219 );
220 }
221 })
222 .detach();
223 });
224
225 // The symlinked directories are not scanned by default.
226 tree.read_with(cx, |tree, _| {
227 assert_eq!(
228 tree.entries(true, 0)
229 .map(|entry| (entry.path.as_ref(), entry.is_external))
230 .collect::<Vec<_>>(),
231 vec![
232 (Path::new(""), false),
233 (Path::new("deps"), false),
234 (Path::new("deps/dep-dir2"), true),
235 (Path::new("deps/dep-dir3"), true),
236 (Path::new("src"), false),
237 (Path::new("src/a.rs"), false),
238 (Path::new("src/b.rs"), false),
239 ]
240 );
241
242 assert_eq!(
243 tree.entry_for_path("deps/dep-dir2").unwrap().kind,
244 EntryKind::UnloadedDir
245 );
246 });
247
248 // Expand one of the symlinked directories.
249 tree.read_with(cx, |tree, _| {
250 tree.as_local()
251 .unwrap()
252 .refresh_entries_for_paths(vec![Path::new("deps/dep-dir3").into()])
253 })
254 .recv()
255 .await;
256
257 // The expanded directory's contents are loaded. Subdirectories are
258 // not scanned yet.
259 tree.read_with(cx, |tree, _| {
260 assert_eq!(
261 tree.entries(true, 0)
262 .map(|entry| (entry.path.as_ref(), entry.is_external))
263 .collect::<Vec<_>>(),
264 vec![
265 (Path::new(""), false),
266 (Path::new("deps"), false),
267 (Path::new("deps/dep-dir2"), true),
268 (Path::new("deps/dep-dir3"), true),
269 (Path::new("deps/dep-dir3/deps"), true),
270 (Path::new("deps/dep-dir3/src"), true),
271 (Path::new("src"), false),
272 (Path::new("src/a.rs"), false),
273 (Path::new("src/b.rs"), false),
274 ]
275 );
276 });
277 assert_eq!(
278 mem::take(&mut *tree_updates.lock()),
279 &[
280 (Path::new("deps/dep-dir3").into(), PathChange::Loaded),
281 (Path::new("deps/dep-dir3/deps").into(), PathChange::Loaded),
282 (Path::new("deps/dep-dir3/src").into(), PathChange::Loaded)
283 ]
284 );
285
286 // Expand a subdirectory of one of the symlinked directories.
287 tree.read_with(cx, |tree, _| {
288 tree.as_local()
289 .unwrap()
290 .refresh_entries_for_paths(vec![Path::new("deps/dep-dir3/src").into()])
291 })
292 .recv()
293 .await;
294
295 // The expanded subdirectory's contents are loaded.
296 tree.read_with(cx, |tree, _| {
297 assert_eq!(
298 tree.entries(true, 0)
299 .map(|entry| (entry.path.as_ref(), entry.is_external))
300 .collect::<Vec<_>>(),
301 vec![
302 (Path::new(""), false),
303 (Path::new("deps"), false),
304 (Path::new("deps/dep-dir2"), true),
305 (Path::new("deps/dep-dir3"), true),
306 (Path::new("deps/dep-dir3/deps"), true),
307 (Path::new("deps/dep-dir3/src"), true),
308 (Path::new("deps/dep-dir3/src/e.rs"), true),
309 (Path::new("deps/dep-dir3/src/f.rs"), true),
310 (Path::new("src"), false),
311 (Path::new("src/a.rs"), false),
312 (Path::new("src/b.rs"), false),
313 ]
314 );
315 });
316
317 assert_eq!(
318 mem::take(&mut *tree_updates.lock()),
319 &[
320 (Path::new("deps/dep-dir3/src").into(), PathChange::Loaded),
321 (
322 Path::new("deps/dep-dir3/src/e.rs").into(),
323 PathChange::Loaded
324 ),
325 (
326 Path::new("deps/dep-dir3/src/f.rs").into(),
327 PathChange::Loaded
328 )
329 ]
330 );
331}
332
333#[cfg(target_os = "macos")]
334#[gpui::test]
335async fn test_renaming_case_only(cx: &mut TestAppContext) {
336 cx.executor().allow_parking();
337 init_test(cx);
338
339 const OLD_NAME: &str = "aaa.rs";
340 const NEW_NAME: &str = "AAA.rs";
341
342 let fs = Arc::new(RealFs::default());
343 let temp_root = temp_tree(json!({
344 OLD_NAME: "",
345 }));
346
347 let tree = Worktree::local(
348 temp_root.path(),
349 true,
350 fs.clone(),
351 Default::default(),
352 &mut cx.to_async(),
353 )
354 .await
355 .unwrap();
356
357 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
358 .await;
359 tree.read_with(cx, |tree, _| {
360 assert_eq!(
361 tree.entries(true, 0)
362 .map(|entry| entry.path.as_ref())
363 .collect::<Vec<_>>(),
364 vec![Path::new(""), Path::new(OLD_NAME)]
365 );
366 });
367
368 fs.rename(
369 &temp_root.path().join(OLD_NAME),
370 &temp_root.path().join(NEW_NAME),
371 fs::RenameOptions {
372 overwrite: true,
373 ignore_if_exists: true,
374 },
375 )
376 .await
377 .unwrap();
378
379 tree.flush_fs_events(cx).await;
380
381 tree.read_with(cx, |tree, _| {
382 assert_eq!(
383 tree.entries(true, 0)
384 .map(|entry| entry.path.as_ref())
385 .collect::<Vec<_>>(),
386 vec![Path::new(""), Path::new(NEW_NAME)]
387 );
388 });
389}
390
391#[gpui::test]
392async fn test_open_gitignored_files(cx: &mut TestAppContext) {
393 init_test(cx);
394 let fs = FakeFs::new(cx.background_executor.clone());
395 fs.insert_tree(
396 "/root",
397 json!({
398 ".gitignore": "node_modules\n",
399 "one": {
400 "node_modules": {
401 "a": {
402 "a1.js": "a1",
403 "a2.js": "a2",
404 },
405 "b": {
406 "b1.js": "b1",
407 "b2.js": "b2",
408 },
409 "c": {
410 "c1.js": "c1",
411 "c2.js": "c2",
412 }
413 },
414 },
415 "two": {
416 "x.js": "",
417 "y.js": "",
418 },
419 }),
420 )
421 .await;
422
423 let tree = Worktree::local(
424 Path::new("/root"),
425 true,
426 fs.clone(),
427 Default::default(),
428 &mut cx.to_async(),
429 )
430 .await
431 .unwrap();
432
433 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
434 .await;
435
436 tree.read_with(cx, |tree, _| {
437 assert_eq!(
438 tree.entries(true, 0)
439 .map(|entry| (entry.path.as_ref(), entry.is_ignored))
440 .collect::<Vec<_>>(),
441 vec![
442 (Path::new(""), false),
443 (Path::new(".gitignore"), false),
444 (Path::new("one"), false),
445 (Path::new("one/node_modules"), true),
446 (Path::new("two"), false),
447 (Path::new("two/x.js"), false),
448 (Path::new("two/y.js"), false),
449 ]
450 );
451 });
452
453 // Open a file that is nested inside of a gitignored directory that
454 // has not yet been expanded.
455 let prev_read_dir_count = fs.read_dir_call_count();
456 let loaded = tree
457 .update(cx, |tree, cx| {
458 tree.load_file("one/node_modules/b/b1.js".as_ref(), cx)
459 })
460 .await
461 .unwrap();
462
463 tree.read_with(cx, |tree, _| {
464 assert_eq!(
465 tree.entries(true, 0)
466 .map(|entry| (entry.path.as_ref(), entry.is_ignored))
467 .collect::<Vec<_>>(),
468 vec![
469 (Path::new(""), false),
470 (Path::new(".gitignore"), false),
471 (Path::new("one"), false),
472 (Path::new("one/node_modules"), true),
473 (Path::new("one/node_modules/a"), true),
474 (Path::new("one/node_modules/b"), true),
475 (Path::new("one/node_modules/b/b1.js"), true),
476 (Path::new("one/node_modules/b/b2.js"), true),
477 (Path::new("one/node_modules/c"), true),
478 (Path::new("two"), false),
479 (Path::new("two/x.js"), false),
480 (Path::new("two/y.js"), false),
481 ]
482 );
483
484 assert_eq!(
485 loaded.file.path.as_ref(),
486 Path::new("one/node_modules/b/b1.js")
487 );
488
489 // Only the newly-expanded directories are scanned.
490 assert_eq!(fs.read_dir_call_count() - prev_read_dir_count, 2);
491 });
492
493 // Open another file in a different subdirectory of the same
494 // gitignored directory.
495 let prev_read_dir_count = fs.read_dir_call_count();
496 let loaded = tree
497 .update(cx, |tree, cx| {
498 tree.load_file("one/node_modules/a/a2.js".as_ref(), cx)
499 })
500 .await
501 .unwrap();
502
503 tree.read_with(cx, |tree, _| {
504 assert_eq!(
505 tree.entries(true, 0)
506 .map(|entry| (entry.path.as_ref(), entry.is_ignored))
507 .collect::<Vec<_>>(),
508 vec![
509 (Path::new(""), false),
510 (Path::new(".gitignore"), false),
511 (Path::new("one"), false),
512 (Path::new("one/node_modules"), true),
513 (Path::new("one/node_modules/a"), true),
514 (Path::new("one/node_modules/a/a1.js"), true),
515 (Path::new("one/node_modules/a/a2.js"), true),
516 (Path::new("one/node_modules/b"), true),
517 (Path::new("one/node_modules/b/b1.js"), true),
518 (Path::new("one/node_modules/b/b2.js"), true),
519 (Path::new("one/node_modules/c"), true),
520 (Path::new("two"), false),
521 (Path::new("two/x.js"), false),
522 (Path::new("two/y.js"), false),
523 ]
524 );
525
526 assert_eq!(
527 loaded.file.path.as_ref(),
528 Path::new("one/node_modules/a/a2.js")
529 );
530
531 // Only the newly-expanded directory is scanned.
532 assert_eq!(fs.read_dir_call_count() - prev_read_dir_count, 1);
533 });
534
535 // No work happens when files and directories change within an unloaded directory.
536 let prev_fs_call_count = fs.read_dir_call_count() + fs.metadata_call_count();
537 fs.create_dir("/root/one/node_modules/c/lib".as_ref())
538 .await
539 .unwrap();
540 cx.executor().run_until_parked();
541 assert_eq!(
542 fs.read_dir_call_count() + fs.metadata_call_count() - prev_fs_call_count,
543 0
544 );
545}
546
547#[gpui::test]
548async fn test_dirs_no_longer_ignored(cx: &mut TestAppContext) {
549 init_test(cx);
550 let fs = FakeFs::new(cx.background_executor.clone());
551 fs.insert_tree(
552 "/root",
553 json!({
554 ".gitignore": "node_modules\n",
555 "a": {
556 "a.js": "",
557 },
558 "b": {
559 "b.js": "",
560 },
561 "node_modules": {
562 "c": {
563 "c.js": "",
564 },
565 "d": {
566 "d.js": "",
567 "e": {
568 "e1.js": "",
569 "e2.js": "",
570 },
571 "f": {
572 "f1.js": "",
573 "f2.js": "",
574 }
575 },
576 },
577 }),
578 )
579 .await;
580
581 let tree = Worktree::local(
582 Path::new("/root"),
583 true,
584 fs.clone(),
585 Default::default(),
586 &mut cx.to_async(),
587 )
588 .await
589 .unwrap();
590
591 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
592 .await;
593
594 // Open a file within the gitignored directory, forcing some of its
595 // subdirectories to be read, but not all.
596 let read_dir_count_1 = fs.read_dir_call_count();
597 tree.read_with(cx, |tree, _| {
598 tree.as_local()
599 .unwrap()
600 .refresh_entries_for_paths(vec![Path::new("node_modules/d/d.js").into()])
601 })
602 .recv()
603 .await;
604
605 // Those subdirectories are now loaded.
606 tree.read_with(cx, |tree, _| {
607 assert_eq!(
608 tree.entries(true, 0)
609 .map(|e| (e.path.as_ref(), e.is_ignored))
610 .collect::<Vec<_>>(),
611 &[
612 (Path::new(""), false),
613 (Path::new(".gitignore"), false),
614 (Path::new("a"), false),
615 (Path::new("a/a.js"), false),
616 (Path::new("b"), false),
617 (Path::new("b/b.js"), false),
618 (Path::new("node_modules"), true),
619 (Path::new("node_modules/c"), true),
620 (Path::new("node_modules/d"), true),
621 (Path::new("node_modules/d/d.js"), true),
622 (Path::new("node_modules/d/e"), true),
623 (Path::new("node_modules/d/f"), true),
624 ]
625 );
626 });
627 let read_dir_count_2 = fs.read_dir_call_count();
628 assert_eq!(read_dir_count_2 - read_dir_count_1, 2);
629
630 // Update the gitignore so that node_modules is no longer ignored,
631 // but a subdirectory is ignored
632 fs.save("/root/.gitignore".as_ref(), &"e".into(), Default::default())
633 .await
634 .unwrap();
635 cx.executor().run_until_parked();
636
637 // All of the directories that are no longer ignored are now loaded.
638 tree.read_with(cx, |tree, _| {
639 assert_eq!(
640 tree.entries(true, 0)
641 .map(|e| (e.path.as_ref(), e.is_ignored))
642 .collect::<Vec<_>>(),
643 &[
644 (Path::new(""), false),
645 (Path::new(".gitignore"), false),
646 (Path::new("a"), false),
647 (Path::new("a/a.js"), false),
648 (Path::new("b"), false),
649 (Path::new("b/b.js"), false),
650 // This directory is no longer ignored
651 (Path::new("node_modules"), false),
652 (Path::new("node_modules/c"), false),
653 (Path::new("node_modules/c/c.js"), false),
654 (Path::new("node_modules/d"), false),
655 (Path::new("node_modules/d/d.js"), false),
656 // This subdirectory is now ignored
657 (Path::new("node_modules/d/e"), true),
658 (Path::new("node_modules/d/f"), false),
659 (Path::new("node_modules/d/f/f1.js"), false),
660 (Path::new("node_modules/d/f/f2.js"), false),
661 ]
662 );
663 });
664
665 // Each of the newly-loaded directories is scanned only once.
666 let read_dir_count_3 = fs.read_dir_call_count();
667 assert_eq!(read_dir_count_3 - read_dir_count_2, 2);
668}
669
670#[gpui::test(iterations = 10)]
671async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
672 init_test(cx);
673 cx.update(|cx| {
674 cx.update_global::<SettingsStore, _>(|store, cx| {
675 store.update_user_settings::<WorktreeSettings>(cx, |project_settings| {
676 project_settings.file_scan_exclusions = Vec::new();
677 });
678 });
679 });
680 let fs = FakeFs::new(cx.background_executor.clone());
681 fs.insert_tree(
682 "/root",
683 json!({
684 ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
685 "tree": {
686 ".git": {},
687 ".gitignore": "ignored-dir\n",
688 "tracked-dir": {
689 "tracked-file1": "",
690 "ancestor-ignored-file1": "",
691 },
692 "ignored-dir": {
693 "ignored-file1": ""
694 }
695 }
696 }),
697 )
698 .await;
699
700 let tree = Worktree::local(
701 "/root/tree".as_ref(),
702 true,
703 fs.clone(),
704 Default::default(),
705 &mut cx.to_async(),
706 )
707 .await
708 .unwrap();
709 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
710 .await;
711
712 tree.read_with(cx, |tree, _| {
713 tree.as_local()
714 .unwrap()
715 .refresh_entries_for_paths(vec![Path::new("ignored-dir").into()])
716 })
717 .recv()
718 .await;
719
720 cx.read(|cx| {
721 let tree = tree.read(cx);
722 assert_entry_git_state(tree, "tracked-dir/tracked-file1", None, false);
723 assert_entry_git_state(tree, "tracked-dir/ancestor-ignored-file1", None, true);
724 assert_entry_git_state(tree, "ignored-dir/ignored-file1", None, true);
725 });
726
727 fs.set_status_for_repo_via_working_copy_change(
728 Path::new("/root/tree/.git"),
729 &[(Path::new("tracked-dir/tracked-file2"), GitFileStatus::Added)],
730 );
731
732 fs.create_file(
733 "/root/tree/tracked-dir/tracked-file2".as_ref(),
734 Default::default(),
735 )
736 .await
737 .unwrap();
738 fs.create_file(
739 "/root/tree/tracked-dir/ancestor-ignored-file2".as_ref(),
740 Default::default(),
741 )
742 .await
743 .unwrap();
744 fs.create_file(
745 "/root/tree/ignored-dir/ignored-file2".as_ref(),
746 Default::default(),
747 )
748 .await
749 .unwrap();
750
751 cx.executor().run_until_parked();
752 cx.read(|cx| {
753 let tree = tree.read(cx);
754 assert_entry_git_state(
755 tree,
756 "tracked-dir/tracked-file2",
757 Some(GitFileStatus::Added),
758 false,
759 );
760 assert_entry_git_state(tree, "tracked-dir/ancestor-ignored-file2", None, true);
761 assert_entry_git_state(tree, "ignored-dir/ignored-file2", None, true);
762 assert!(tree.entry_for_path(".git").unwrap().is_ignored);
763 });
764}
765
766#[gpui::test]
767async fn test_update_gitignore(cx: &mut TestAppContext) {
768 init_test(cx);
769 let fs = FakeFs::new(cx.background_executor.clone());
770 fs.insert_tree(
771 "/root",
772 json!({
773 ".git": {},
774 ".gitignore": "*.txt\n",
775 "a.xml": "<a></a>",
776 "b.txt": "Some text"
777 }),
778 )
779 .await;
780
781 let tree = Worktree::local(
782 "/root".as_ref(),
783 true,
784 fs.clone(),
785 Default::default(),
786 &mut cx.to_async(),
787 )
788 .await
789 .unwrap();
790 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
791 .await;
792
793 tree.read_with(cx, |tree, _| {
794 tree.as_local()
795 .unwrap()
796 .refresh_entries_for_paths(vec![Path::new("").into()])
797 })
798 .recv()
799 .await;
800
801 cx.read(|cx| {
802 let tree = tree.read(cx);
803 assert_entry_git_state(tree, "a.xml", None, false);
804 assert_entry_git_state(tree, "b.txt", None, true);
805 });
806
807 fs.atomic_write("/root/.gitignore".into(), "*.xml".into())
808 .await
809 .unwrap();
810
811 fs.set_status_for_repo_via_working_copy_change(
812 Path::new("/root/.git"),
813 &[(Path::new("b.txt"), GitFileStatus::Added)],
814 );
815
816 cx.executor().run_until_parked();
817 cx.read(|cx| {
818 let tree = tree.read(cx);
819 assert_entry_git_state(tree, "a.xml", None, true);
820 assert_entry_git_state(tree, "b.txt", Some(GitFileStatus::Added), false);
821 });
822}
823
824#[gpui::test]
825async fn test_write_file(cx: &mut TestAppContext) {
826 init_test(cx);
827 cx.executor().allow_parking();
828 let dir = temp_tree(json!({
829 ".git": {},
830 ".gitignore": "ignored-dir\n",
831 "tracked-dir": {},
832 "ignored-dir": {}
833 }));
834
835 let tree = Worktree::local(
836 dir.path(),
837 true,
838 Arc::new(RealFs::default()),
839 Default::default(),
840 &mut cx.to_async(),
841 )
842 .await
843 .unwrap();
844
845 #[cfg(target_os = "linux")]
846 fs::watcher::global(|_| {}).unwrap();
847
848 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
849 .await;
850 tree.flush_fs_events(cx).await;
851
852 tree.update(cx, |tree, cx| {
853 tree.write_file(
854 Path::new("tracked-dir/file.txt"),
855 "hello".into(),
856 Default::default(),
857 cx,
858 )
859 })
860 .await
861 .unwrap();
862 tree.update(cx, |tree, cx| {
863 tree.write_file(
864 Path::new("ignored-dir/file.txt"),
865 "world".into(),
866 Default::default(),
867 cx,
868 )
869 })
870 .await
871 .unwrap();
872
873 tree.read_with(cx, |tree, _| {
874 let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
875 let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
876 assert!(!tracked.is_ignored);
877 assert!(ignored.is_ignored);
878 });
879}
880
881#[gpui::test]
882async fn test_file_scan_exclusions(cx: &mut TestAppContext) {
883 init_test(cx);
884 cx.executor().allow_parking();
885 let dir = temp_tree(json!({
886 ".gitignore": "**/target\n/node_modules\n",
887 "target": {
888 "index": "blah2"
889 },
890 "node_modules": {
891 ".DS_Store": "",
892 "prettier": {
893 "package.json": "{}",
894 },
895 },
896 "src": {
897 ".DS_Store": "",
898 "foo": {
899 "foo.rs": "mod another;\n",
900 "another.rs": "// another",
901 },
902 "bar": {
903 "bar.rs": "// bar",
904 },
905 "lib.rs": "mod foo;\nmod bar;\n",
906 },
907 ".DS_Store": "",
908 }));
909 cx.update(|cx| {
910 cx.update_global::<SettingsStore, _>(|store, cx| {
911 store.update_user_settings::<WorktreeSettings>(cx, |project_settings| {
912 project_settings.file_scan_exclusions =
913 vec!["**/foo/**".to_string(), "**/.DS_Store".to_string()];
914 });
915 });
916 });
917
918 let tree = Worktree::local(
919 dir.path(),
920 true,
921 Arc::new(RealFs::default()),
922 Default::default(),
923 &mut cx.to_async(),
924 )
925 .await
926 .unwrap();
927 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
928 .await;
929 tree.flush_fs_events(cx).await;
930 tree.read_with(cx, |tree, _| {
931 check_worktree_entries(
932 tree,
933 &[
934 "src/foo/foo.rs",
935 "src/foo/another.rs",
936 "node_modules/.DS_Store",
937 "src/.DS_Store",
938 ".DS_Store",
939 ],
940 &["target", "node_modules"],
941 &["src/lib.rs", "src/bar/bar.rs", ".gitignore"],
942 )
943 });
944
945 cx.update(|cx| {
946 cx.update_global::<SettingsStore, _>(|store, cx| {
947 store.update_user_settings::<WorktreeSettings>(cx, |project_settings| {
948 project_settings.file_scan_exclusions = vec!["**/node_modules/**".to_string()];
949 });
950 });
951 });
952 tree.flush_fs_events(cx).await;
953 cx.executor().run_until_parked();
954 tree.read_with(cx, |tree, _| {
955 check_worktree_entries(
956 tree,
957 &[
958 "node_modules/prettier/package.json",
959 "node_modules/.DS_Store",
960 "node_modules",
961 ],
962 &["target"],
963 &[
964 ".gitignore",
965 "src/lib.rs",
966 "src/bar/bar.rs",
967 "src/foo/foo.rs",
968 "src/foo/another.rs",
969 "src/.DS_Store",
970 ".DS_Store",
971 ],
972 )
973 });
974}
975
976#[gpui::test]
977async fn test_fs_events_in_exclusions(cx: &mut TestAppContext) {
978 init_test(cx);
979 cx.executor().allow_parking();
980 let dir = temp_tree(json!({
981 ".git": {
982 "HEAD": "ref: refs/heads/main\n",
983 "foo": "bar",
984 },
985 ".gitignore": "**/target\n/node_modules\ntest_output\n",
986 "target": {
987 "index": "blah2"
988 },
989 "node_modules": {
990 ".DS_Store": "",
991 "prettier": {
992 "package.json": "{}",
993 },
994 },
995 "src": {
996 ".DS_Store": "",
997 "foo": {
998 "foo.rs": "mod another;\n",
999 "another.rs": "// another",
1000 },
1001 "bar": {
1002 "bar.rs": "// bar",
1003 },
1004 "lib.rs": "mod foo;\nmod bar;\n",
1005 },
1006 ".DS_Store": "",
1007 }));
1008 cx.update(|cx| {
1009 cx.update_global::<SettingsStore, _>(|store, cx| {
1010 store.update_user_settings::<WorktreeSettings>(cx, |project_settings| {
1011 project_settings.file_scan_exclusions = vec![
1012 "**/.git".to_string(),
1013 "node_modules/".to_string(),
1014 "build_output".to_string(),
1015 ];
1016 });
1017 });
1018 });
1019
1020 let tree = Worktree::local(
1021 dir.path(),
1022 true,
1023 Arc::new(RealFs::default()),
1024 Default::default(),
1025 &mut cx.to_async(),
1026 )
1027 .await
1028 .unwrap();
1029 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1030 .await;
1031 tree.flush_fs_events(cx).await;
1032 tree.read_with(cx, |tree, _| {
1033 check_worktree_entries(
1034 tree,
1035 &[
1036 ".git/HEAD",
1037 ".git/foo",
1038 "node_modules",
1039 "node_modules/.DS_Store",
1040 "node_modules/prettier",
1041 "node_modules/prettier/package.json",
1042 ],
1043 &["target"],
1044 &[
1045 ".DS_Store",
1046 "src/.DS_Store",
1047 "src/lib.rs",
1048 "src/foo/foo.rs",
1049 "src/foo/another.rs",
1050 "src/bar/bar.rs",
1051 ".gitignore",
1052 ],
1053 )
1054 });
1055
1056 let new_excluded_dir = dir.path().join("build_output");
1057 let new_ignored_dir = dir.path().join("test_output");
1058 std::fs::create_dir_all(&new_excluded_dir)
1059 .unwrap_or_else(|e| panic!("Failed to create a {new_excluded_dir:?} directory: {e}"));
1060 std::fs::create_dir_all(&new_ignored_dir)
1061 .unwrap_or_else(|e| panic!("Failed to create a {new_ignored_dir:?} directory: {e}"));
1062 let node_modules_dir = dir.path().join("node_modules");
1063 let dot_git_dir = dir.path().join(".git");
1064 let src_dir = dir.path().join("src");
1065 for existing_dir in [&node_modules_dir, &dot_git_dir, &src_dir] {
1066 assert!(
1067 existing_dir.is_dir(),
1068 "Expect {existing_dir:?} to be present in the FS already"
1069 );
1070 }
1071
1072 for directory_for_new_file in [
1073 new_excluded_dir,
1074 new_ignored_dir,
1075 node_modules_dir,
1076 dot_git_dir,
1077 src_dir,
1078 ] {
1079 std::fs::write(directory_for_new_file.join("new_file"), "new file contents")
1080 .unwrap_or_else(|e| {
1081 panic!("Failed to create in {directory_for_new_file:?} a new file: {e}")
1082 });
1083 }
1084 tree.flush_fs_events(cx).await;
1085
1086 tree.read_with(cx, |tree, _| {
1087 check_worktree_entries(
1088 tree,
1089 &[
1090 ".git/HEAD",
1091 ".git/foo",
1092 ".git/new_file",
1093 "node_modules",
1094 "node_modules/.DS_Store",
1095 "node_modules/prettier",
1096 "node_modules/prettier/package.json",
1097 "node_modules/new_file",
1098 "build_output",
1099 "build_output/new_file",
1100 "test_output/new_file",
1101 ],
1102 &["target", "test_output"],
1103 &[
1104 ".DS_Store",
1105 "src/.DS_Store",
1106 "src/lib.rs",
1107 "src/foo/foo.rs",
1108 "src/foo/another.rs",
1109 "src/bar/bar.rs",
1110 "src/new_file",
1111 ".gitignore",
1112 ],
1113 )
1114 });
1115}
1116
1117#[gpui::test]
1118async fn test_fs_events_in_dot_git_worktree(cx: &mut TestAppContext) {
1119 init_test(cx);
1120 cx.executor().allow_parking();
1121 let dir = temp_tree(json!({
1122 ".git": {
1123 "HEAD": "ref: refs/heads/main\n",
1124 "foo": "foo contents",
1125 },
1126 }));
1127 let dot_git_worktree_dir = dir.path().join(".git");
1128
1129 let tree = Worktree::local(
1130 dot_git_worktree_dir.clone(),
1131 true,
1132 Arc::new(RealFs::default()),
1133 Default::default(),
1134 &mut cx.to_async(),
1135 )
1136 .await
1137 .unwrap();
1138 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1139 .await;
1140 tree.flush_fs_events(cx).await;
1141 tree.read_with(cx, |tree, _| {
1142 check_worktree_entries(tree, &[], &["HEAD", "foo"], &[])
1143 });
1144
1145 std::fs::write(dot_git_worktree_dir.join("new_file"), "new file contents")
1146 .unwrap_or_else(|e| panic!("Failed to create in {dot_git_worktree_dir:?} a new file: {e}"));
1147 tree.flush_fs_events(cx).await;
1148 tree.read_with(cx, |tree, _| {
1149 check_worktree_entries(tree, &[], &["HEAD", "foo", "new_file"], &[])
1150 });
1151}
1152
1153#[gpui::test(iterations = 30)]
1154async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
1155 init_test(cx);
1156 let fs = FakeFs::new(cx.background_executor.clone());
1157 fs.insert_tree(
1158 "/root",
1159 json!({
1160 "b": {},
1161 "c": {},
1162 "d": {},
1163 }),
1164 )
1165 .await;
1166
1167 let tree = Worktree::local(
1168 "/root".as_ref(),
1169 true,
1170 fs,
1171 Default::default(),
1172 &mut cx.to_async(),
1173 )
1174 .await
1175 .unwrap();
1176
1177 let snapshot1 = tree.update(cx, |tree, cx| {
1178 let tree = tree.as_local_mut().unwrap();
1179 let snapshot = Arc::new(Mutex::new(tree.snapshot()));
1180 tree.observe_updates(0, cx, {
1181 let snapshot = snapshot.clone();
1182 move |update| {
1183 snapshot.lock().apply_remote_update(update).unwrap();
1184 async { true }
1185 }
1186 });
1187 snapshot
1188 });
1189
1190 let entry = tree
1191 .update(cx, |tree, cx| {
1192 tree.as_local_mut()
1193 .unwrap()
1194 .create_entry("a/e".as_ref(), true, cx)
1195 })
1196 .await
1197 .unwrap()
1198 .to_included()
1199 .unwrap();
1200 assert!(entry.is_dir());
1201
1202 cx.executor().run_until_parked();
1203 tree.read_with(cx, |tree, _| {
1204 assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
1205 });
1206
1207 let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
1208 assert_eq!(
1209 snapshot1.lock().entries(true, 0).collect::<Vec<_>>(),
1210 snapshot2.entries(true, 0).collect::<Vec<_>>()
1211 );
1212}
1213
1214#[gpui::test]
1215async fn test_bump_mtime_of_git_repo_workdir(cx: &mut TestAppContext) {
1216 init_test(cx);
1217
1218 // Create a worktree with a git directory.
1219 let fs = FakeFs::new(cx.background_executor.clone());
1220 fs.insert_tree(
1221 "/root",
1222 json!({
1223 ".git": {},
1224 "a.txt": "",
1225 "b": {
1226 "c.txt": "",
1227 },
1228 }),
1229 )
1230 .await;
1231
1232 let tree = Worktree::local(
1233 "/root".as_ref(),
1234 true,
1235 fs.clone(),
1236 Default::default(),
1237 &mut cx.to_async(),
1238 )
1239 .await
1240 .unwrap();
1241 cx.executor().run_until_parked();
1242
1243 let (old_entry_ids, old_mtimes) = tree.read_with(cx, |tree, _| {
1244 (
1245 tree.entries(true, 0).map(|e| e.id).collect::<Vec<_>>(),
1246 tree.entries(true, 0).map(|e| e.mtime).collect::<Vec<_>>(),
1247 )
1248 });
1249
1250 // Regression test: after the directory is scanned, touch the git repo's
1251 // working directory, bumping its mtime. That directory keeps its project
1252 // entry id after the directories are re-scanned.
1253 fs.touch_path("/root").await;
1254 cx.executor().run_until_parked();
1255
1256 let (new_entry_ids, new_mtimes) = tree.read_with(cx, |tree, _| {
1257 (
1258 tree.entries(true, 0).map(|e| e.id).collect::<Vec<_>>(),
1259 tree.entries(true, 0).map(|e| e.mtime).collect::<Vec<_>>(),
1260 )
1261 });
1262 assert_eq!(new_entry_ids, old_entry_ids);
1263 assert_ne!(new_mtimes, old_mtimes);
1264
1265 // Regression test: changes to the git repository should still be
1266 // detected.
1267 fs.set_status_for_repo_via_git_operation(
1268 Path::new("/root/.git"),
1269 &[(Path::new("b/c.txt"), GitFileStatus::Modified)],
1270 );
1271 cx.executor().run_until_parked();
1272
1273 let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());
1274 check_propagated_statuses(
1275 &snapshot,
1276 &[
1277 (Path::new(""), Some(GitFileStatus::Modified)),
1278 (Path::new("a.txt"), None),
1279 (Path::new("b/c.txt"), Some(GitFileStatus::Modified)),
1280 ],
1281 );
1282}
1283
1284#[gpui::test]
1285async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
1286 init_test(cx);
1287 cx.executor().allow_parking();
1288
1289 let fs_fake = FakeFs::new(cx.background_executor.clone());
1290 fs_fake
1291 .insert_tree(
1292 "/root",
1293 json!({
1294 "a": {},
1295 }),
1296 )
1297 .await;
1298
1299 let tree_fake = Worktree::local(
1300 "/root".as_ref(),
1301 true,
1302 fs_fake,
1303 Default::default(),
1304 &mut cx.to_async(),
1305 )
1306 .await
1307 .unwrap();
1308
1309 let entry = tree_fake
1310 .update(cx, |tree, cx| {
1311 tree.as_local_mut()
1312 .unwrap()
1313 .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1314 })
1315 .await
1316 .unwrap()
1317 .to_included()
1318 .unwrap();
1319 assert!(entry.is_file());
1320
1321 cx.executor().run_until_parked();
1322 tree_fake.read_with(cx, |tree, _| {
1323 assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1324 assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1325 assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1326 });
1327
1328 let fs_real = Arc::new(RealFs::default());
1329 let temp_root = temp_tree(json!({
1330 "a": {}
1331 }));
1332
1333 let tree_real = Worktree::local(
1334 temp_root.path(),
1335 true,
1336 fs_real,
1337 Default::default(),
1338 &mut cx.to_async(),
1339 )
1340 .await
1341 .unwrap();
1342
1343 let entry = tree_real
1344 .update(cx, |tree, cx| {
1345 tree.as_local_mut()
1346 .unwrap()
1347 .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1348 })
1349 .await
1350 .unwrap()
1351 .to_included()
1352 .unwrap();
1353 assert!(entry.is_file());
1354
1355 cx.executor().run_until_parked();
1356 tree_real.read_with(cx, |tree, _| {
1357 assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1358 assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1359 assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1360 });
1361
1362 // Test smallest change
1363 let entry = tree_real
1364 .update(cx, |tree, cx| {
1365 tree.as_local_mut()
1366 .unwrap()
1367 .create_entry("a/b/c/e.txt".as_ref(), false, cx)
1368 })
1369 .await
1370 .unwrap()
1371 .to_included()
1372 .unwrap();
1373 assert!(entry.is_file());
1374
1375 cx.executor().run_until_parked();
1376 tree_real.read_with(cx, |tree, _| {
1377 assert!(tree.entry_for_path("a/b/c/e.txt").unwrap().is_file());
1378 });
1379
1380 // Test largest change
1381 let entry = tree_real
1382 .update(cx, |tree, cx| {
1383 tree.as_local_mut()
1384 .unwrap()
1385 .create_entry("d/e/f/g.txt".as_ref(), false, cx)
1386 })
1387 .await
1388 .unwrap()
1389 .to_included()
1390 .unwrap();
1391 assert!(entry.is_file());
1392
1393 cx.executor().run_until_parked();
1394 tree_real.read_with(cx, |tree, _| {
1395 assert!(tree.entry_for_path("d/e/f/g.txt").unwrap().is_file());
1396 assert!(tree.entry_for_path("d/e/f").unwrap().is_dir());
1397 assert!(tree.entry_for_path("d/e/").unwrap().is_dir());
1398 assert!(tree.entry_for_path("d/").unwrap().is_dir());
1399 });
1400}
1401
1402#[gpui::test(iterations = 100)]
1403async fn test_random_worktree_operations_during_initial_scan(
1404 cx: &mut TestAppContext,
1405 mut rng: StdRng,
1406) {
1407 init_test(cx);
1408 let operations = env::var("OPERATIONS")
1409 .map(|o| o.parse().unwrap())
1410 .unwrap_or(5);
1411 let initial_entries = env::var("INITIAL_ENTRIES")
1412 .map(|o| o.parse().unwrap())
1413 .unwrap_or(20);
1414
1415 let root_dir = Path::new("/test");
1416 let fs = FakeFs::new(cx.background_executor.clone()) as Arc<dyn Fs>;
1417 fs.as_fake().insert_tree(root_dir, json!({})).await;
1418 for _ in 0..initial_entries {
1419 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1420 }
1421 log::info!("generated initial tree");
1422
1423 let worktree = Worktree::local(
1424 root_dir,
1425 true,
1426 fs.clone(),
1427 Default::default(),
1428 &mut cx.to_async(),
1429 )
1430 .await
1431 .unwrap();
1432
1433 let mut snapshots = vec![worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot())];
1434 let updates = Arc::new(Mutex::new(Vec::new()));
1435 worktree.update(cx, |tree, cx| {
1436 check_worktree_change_events(tree, cx);
1437
1438 tree.as_local_mut().unwrap().observe_updates(0, cx, {
1439 let updates = updates.clone();
1440 move |update| {
1441 updates.lock().push(update);
1442 async { true }
1443 }
1444 });
1445 });
1446
1447 for _ in 0..operations {
1448 worktree
1449 .update(cx, |worktree, cx| {
1450 randomly_mutate_worktree(worktree, &mut rng, cx)
1451 })
1452 .await
1453 .log_err();
1454 worktree.read_with(cx, |tree, _| {
1455 tree.as_local().unwrap().snapshot().check_invariants(true)
1456 });
1457
1458 if rng.gen_bool(0.6) {
1459 snapshots.push(worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot()));
1460 }
1461 }
1462
1463 worktree
1464 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1465 .await;
1466
1467 cx.executor().run_until_parked();
1468
1469 let final_snapshot = worktree.read_with(cx, |tree, _| {
1470 let tree = tree.as_local().unwrap();
1471 let snapshot = tree.snapshot();
1472 snapshot.check_invariants(true);
1473 snapshot
1474 });
1475
1476 for (i, snapshot) in snapshots.into_iter().enumerate().rev() {
1477 let mut updated_snapshot = snapshot.clone();
1478 for update in updates.lock().iter() {
1479 if update.scan_id >= updated_snapshot.scan_id() as u64 {
1480 updated_snapshot
1481 .apply_remote_update(update.clone())
1482 .unwrap();
1483 }
1484 }
1485
1486 assert_eq!(
1487 updated_snapshot.entries(true, 0).collect::<Vec<_>>(),
1488 final_snapshot.entries(true, 0).collect::<Vec<_>>(),
1489 "wrong updates after snapshot {i}: {snapshot:#?} {updates:#?}",
1490 );
1491 }
1492}
1493
1494#[gpui::test(iterations = 100)]
1495async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
1496 init_test(cx);
1497 let operations = env::var("OPERATIONS")
1498 .map(|o| o.parse().unwrap())
1499 .unwrap_or(40);
1500 let initial_entries = env::var("INITIAL_ENTRIES")
1501 .map(|o| o.parse().unwrap())
1502 .unwrap_or(20);
1503
1504 let root_dir = Path::new("/test");
1505 let fs = FakeFs::new(cx.background_executor.clone()) as Arc<dyn Fs>;
1506 fs.as_fake().insert_tree(root_dir, json!({})).await;
1507 for _ in 0..initial_entries {
1508 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1509 }
1510 log::info!("generated initial tree");
1511
1512 let worktree = Worktree::local(
1513 root_dir,
1514 true,
1515 fs.clone(),
1516 Default::default(),
1517 &mut cx.to_async(),
1518 )
1519 .await
1520 .unwrap();
1521
1522 let updates = Arc::new(Mutex::new(Vec::new()));
1523 worktree.update(cx, |tree, cx| {
1524 check_worktree_change_events(tree, cx);
1525
1526 tree.as_local_mut().unwrap().observe_updates(0, cx, {
1527 let updates = updates.clone();
1528 move |update| {
1529 updates.lock().push(update);
1530 async { true }
1531 }
1532 });
1533 });
1534
1535 worktree
1536 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1537 .await;
1538
1539 fs.as_fake().pause_events();
1540 let mut snapshots = Vec::new();
1541 let mut mutations_len = operations;
1542 while mutations_len > 1 {
1543 if rng.gen_bool(0.2) {
1544 worktree
1545 .update(cx, |worktree, cx| {
1546 randomly_mutate_worktree(worktree, &mut rng, cx)
1547 })
1548 .await
1549 .log_err();
1550 } else {
1551 randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1552 }
1553
1554 let buffered_event_count = fs.as_fake().buffered_event_count();
1555 if buffered_event_count > 0 && rng.gen_bool(0.3) {
1556 let len = rng.gen_range(0..=buffered_event_count);
1557 log::info!("flushing {} events", len);
1558 fs.as_fake().flush_events(len);
1559 } else {
1560 randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
1561 mutations_len -= 1;
1562 }
1563
1564 cx.executor().run_until_parked();
1565 if rng.gen_bool(0.2) {
1566 log::info!("storing snapshot {}", snapshots.len());
1567 let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1568 snapshots.push(snapshot);
1569 }
1570 }
1571
1572 log::info!("quiescing");
1573 fs.as_fake().flush_events(usize::MAX);
1574 cx.executor().run_until_parked();
1575
1576 let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1577 snapshot.check_invariants(true);
1578 let expanded_paths = snapshot
1579 .expanded_entries()
1580 .map(|e| e.path.clone())
1581 .collect::<Vec<_>>();
1582
1583 {
1584 let new_worktree = Worktree::local(
1585 root_dir,
1586 true,
1587 fs.clone(),
1588 Default::default(),
1589 &mut cx.to_async(),
1590 )
1591 .await
1592 .unwrap();
1593 new_worktree
1594 .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1595 .await;
1596 new_worktree
1597 .update(cx, |tree, _| {
1598 tree.as_local_mut()
1599 .unwrap()
1600 .refresh_entries_for_paths(expanded_paths)
1601 })
1602 .recv()
1603 .await;
1604 let new_snapshot =
1605 new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1606 assert_eq!(
1607 snapshot.entries_without_ids(true),
1608 new_snapshot.entries_without_ids(true)
1609 );
1610 }
1611
1612 for (i, mut prev_snapshot) in snapshots.into_iter().enumerate().rev() {
1613 for update in updates.lock().iter() {
1614 if update.scan_id >= prev_snapshot.scan_id() as u64 {
1615 prev_snapshot.apply_remote_update(update.clone()).unwrap();
1616 }
1617 }
1618
1619 assert_eq!(
1620 prev_snapshot
1621 .entries(true, 0)
1622 .map(ignore_pending_dir)
1623 .collect::<Vec<_>>(),
1624 snapshot
1625 .entries(true, 0)
1626 .map(ignore_pending_dir)
1627 .collect::<Vec<_>>(),
1628 "wrong updates after snapshot {i}: {updates:#?}",
1629 );
1630 }
1631
1632 fn ignore_pending_dir(entry: &Entry) -> Entry {
1633 let mut entry = entry.clone();
1634 if entry.kind.is_dir() {
1635 entry.kind = EntryKind::Dir
1636 }
1637 entry
1638 }
1639}
1640
1641// The worktree's `UpdatedEntries` event can be used to follow along with
1642// all changes to the worktree's snapshot.
1643fn check_worktree_change_events(tree: &mut Worktree, cx: &mut ModelContext<Worktree>) {
1644 let mut entries = tree.entries(true, 0).cloned().collect::<Vec<_>>();
1645 cx.subscribe(&cx.handle(), move |tree, _, event, _| {
1646 if let Event::UpdatedEntries(changes) = event {
1647 for (path, _, change_type) in changes.iter() {
1648 let entry = tree.entry_for_path(path).cloned();
1649 let ix = match entries.binary_search_by_key(&path, |e| &e.path) {
1650 Ok(ix) | Err(ix) => ix,
1651 };
1652 match change_type {
1653 PathChange::Added => entries.insert(ix, entry.unwrap()),
1654 PathChange::Removed => drop(entries.remove(ix)),
1655 PathChange::Updated => {
1656 let entry = entry.unwrap();
1657 let existing_entry = entries.get_mut(ix).unwrap();
1658 assert_eq!(existing_entry.path, entry.path);
1659 *existing_entry = entry;
1660 }
1661 PathChange::AddedOrUpdated | PathChange::Loaded => {
1662 let entry = entry.unwrap();
1663 if entries.get(ix).map(|e| &e.path) == Some(&entry.path) {
1664 *entries.get_mut(ix).unwrap() = entry;
1665 } else {
1666 entries.insert(ix, entry);
1667 }
1668 }
1669 }
1670 }
1671
1672 let new_entries = tree.entries(true, 0).cloned().collect::<Vec<_>>();
1673 assert_eq!(entries, new_entries, "incorrect changes: {:?}", changes);
1674 }
1675 })
1676 .detach();
1677}
1678
1679fn randomly_mutate_worktree(
1680 worktree: &mut Worktree,
1681 rng: &mut impl Rng,
1682 cx: &mut ModelContext<Worktree>,
1683) -> Task<Result<()>> {
1684 log::info!("mutating worktree");
1685 let worktree = worktree.as_local_mut().unwrap();
1686 let snapshot = worktree.snapshot();
1687 let entry = snapshot.entries(false, 0).choose(rng).unwrap();
1688
1689 match rng.gen_range(0_u32..100) {
1690 0..=33 if entry.path.as_ref() != Path::new("") => {
1691 log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
1692 worktree.delete_entry(entry.id, false, cx).unwrap()
1693 }
1694 ..=66 if entry.path.as_ref() != Path::new("") => {
1695 let other_entry = snapshot.entries(false, 0).choose(rng).unwrap();
1696 let new_parent_path = if other_entry.is_dir() {
1697 other_entry.path.clone()
1698 } else {
1699 other_entry.path.parent().unwrap().into()
1700 };
1701 let mut new_path = new_parent_path.join(random_filename(rng));
1702 if new_path.starts_with(&entry.path) {
1703 new_path = random_filename(rng).into();
1704 }
1705
1706 log::info!(
1707 "renaming entry {:?} ({}) to {:?}",
1708 entry.path,
1709 entry.id.0,
1710 new_path
1711 );
1712 let task = worktree.rename_entry(entry.id, new_path, cx);
1713 cx.background_executor().spawn(async move {
1714 task.await?.to_included().unwrap();
1715 Ok(())
1716 })
1717 }
1718 _ => {
1719 if entry.is_dir() {
1720 let child_path = entry.path.join(random_filename(rng));
1721 let is_dir = rng.gen_bool(0.3);
1722 log::info!(
1723 "creating {} at {:?}",
1724 if is_dir { "dir" } else { "file" },
1725 child_path,
1726 );
1727 let task = worktree.create_entry(child_path, is_dir, cx);
1728 cx.background_executor().spawn(async move {
1729 task.await?;
1730 Ok(())
1731 })
1732 } else {
1733 log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
1734 let task =
1735 worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx);
1736 cx.background_executor().spawn(async move {
1737 task.await?;
1738 Ok(())
1739 })
1740 }
1741 }
1742 }
1743}
1744
1745async fn randomly_mutate_fs(
1746 fs: &Arc<dyn Fs>,
1747 root_path: &Path,
1748 insertion_probability: f64,
1749 rng: &mut impl Rng,
1750) {
1751 log::info!("mutating fs");
1752 let mut files = Vec::new();
1753 let mut dirs = Vec::new();
1754 for path in fs.as_fake().paths(false) {
1755 if path.starts_with(root_path) {
1756 if fs.is_file(&path).await {
1757 files.push(path);
1758 } else {
1759 dirs.push(path);
1760 }
1761 }
1762 }
1763
1764 if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
1765 let path = dirs.choose(rng).unwrap();
1766 let new_path = path.join(random_filename(rng));
1767
1768 if rng.gen() {
1769 log::info!(
1770 "creating dir {:?}",
1771 new_path.strip_prefix(root_path).unwrap()
1772 );
1773 fs.create_dir(&new_path).await.unwrap();
1774 } else {
1775 log::info!(
1776 "creating file {:?}",
1777 new_path.strip_prefix(root_path).unwrap()
1778 );
1779 fs.create_file(&new_path, Default::default()).await.unwrap();
1780 }
1781 } else if rng.gen_bool(0.05) {
1782 let ignore_dir_path = dirs.choose(rng).unwrap();
1783 let ignore_path = ignore_dir_path.join(*GITIGNORE);
1784
1785 let subdirs = dirs
1786 .iter()
1787 .filter(|d| d.starts_with(ignore_dir_path))
1788 .cloned()
1789 .collect::<Vec<_>>();
1790 let subfiles = files
1791 .iter()
1792 .filter(|d| d.starts_with(ignore_dir_path))
1793 .cloned()
1794 .collect::<Vec<_>>();
1795 let files_to_ignore = {
1796 let len = rng.gen_range(0..=subfiles.len());
1797 subfiles.choose_multiple(rng, len)
1798 };
1799 let dirs_to_ignore = {
1800 let len = rng.gen_range(0..subdirs.len());
1801 subdirs.choose_multiple(rng, len)
1802 };
1803
1804 let mut ignore_contents = String::new();
1805 for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
1806 writeln!(
1807 ignore_contents,
1808 "{}",
1809 path_to_ignore
1810 .strip_prefix(ignore_dir_path)
1811 .unwrap()
1812 .to_str()
1813 .unwrap()
1814 )
1815 .unwrap();
1816 }
1817 log::info!(
1818 "creating gitignore {:?} with contents:\n{}",
1819 ignore_path.strip_prefix(root_path).unwrap(),
1820 ignore_contents
1821 );
1822 fs.save(
1823 &ignore_path,
1824 &ignore_contents.as_str().into(),
1825 Default::default(),
1826 )
1827 .await
1828 .unwrap();
1829 } else {
1830 let old_path = {
1831 let file_path = files.choose(rng);
1832 let dir_path = dirs[1..].choose(rng);
1833 file_path.into_iter().chain(dir_path).choose(rng).unwrap()
1834 };
1835
1836 let is_rename = rng.gen();
1837 if is_rename {
1838 let new_path_parent = dirs
1839 .iter()
1840 .filter(|d| !d.starts_with(old_path))
1841 .choose(rng)
1842 .unwrap();
1843
1844 let overwrite_existing_dir =
1845 !old_path.starts_with(new_path_parent) && rng.gen_bool(0.3);
1846 let new_path = if overwrite_existing_dir {
1847 fs.remove_dir(
1848 new_path_parent,
1849 RemoveOptions {
1850 recursive: true,
1851 ignore_if_not_exists: true,
1852 },
1853 )
1854 .await
1855 .unwrap();
1856 new_path_parent.to_path_buf()
1857 } else {
1858 new_path_parent.join(random_filename(rng))
1859 };
1860
1861 log::info!(
1862 "renaming {:?} to {}{:?}",
1863 old_path.strip_prefix(root_path).unwrap(),
1864 if overwrite_existing_dir {
1865 "overwrite "
1866 } else {
1867 ""
1868 },
1869 new_path.strip_prefix(root_path).unwrap()
1870 );
1871 fs.rename(
1872 old_path,
1873 &new_path,
1874 fs::RenameOptions {
1875 overwrite: true,
1876 ignore_if_exists: true,
1877 },
1878 )
1879 .await
1880 .unwrap();
1881 } else if fs.is_file(old_path).await {
1882 log::info!(
1883 "deleting file {:?}",
1884 old_path.strip_prefix(root_path).unwrap()
1885 );
1886 fs.remove_file(old_path, Default::default()).await.unwrap();
1887 } else {
1888 log::info!(
1889 "deleting dir {:?}",
1890 old_path.strip_prefix(root_path).unwrap()
1891 );
1892 fs.remove_dir(
1893 old_path,
1894 RemoveOptions {
1895 recursive: true,
1896 ignore_if_not_exists: true,
1897 },
1898 )
1899 .await
1900 .unwrap();
1901 }
1902 }
1903}
1904
1905fn random_filename(rng: &mut impl Rng) -> String {
1906 (0..6)
1907 .map(|_| rng.sample(rand::distributions::Alphanumeric))
1908 .map(char::from)
1909 .collect()
1910}
1911
1912#[gpui::test]
1913async fn test_rename_work_directory(cx: &mut TestAppContext) {
1914 init_test(cx);
1915 cx.executor().allow_parking();
1916 let root = temp_tree(json!({
1917 "projects": {
1918 "project1": {
1919 "a": "",
1920 "b": "",
1921 }
1922 },
1923
1924 }));
1925 let root_path = root.path();
1926
1927 let tree = Worktree::local(
1928 root_path,
1929 true,
1930 Arc::new(RealFs::default()),
1931 Default::default(),
1932 &mut cx.to_async(),
1933 )
1934 .await
1935 .unwrap();
1936
1937 let repo = git_init(&root_path.join("projects/project1"));
1938 git_add("a", &repo);
1939 git_commit("init", &repo);
1940 std::fs::write(root_path.join("projects/project1/a"), "aa").ok();
1941
1942 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1943 .await;
1944
1945 tree.flush_fs_events(cx).await;
1946
1947 cx.read(|cx| {
1948 let tree = tree.read(cx);
1949 let (work_dir, _) = tree.repositories().next().unwrap();
1950 assert_eq!(work_dir.as_ref(), Path::new("projects/project1"));
1951 assert_eq!(
1952 tree.status_for_file(Path::new("projects/project1/a")),
1953 Some(GitFileStatus::Modified)
1954 );
1955 assert_eq!(
1956 tree.status_for_file(Path::new("projects/project1/b")),
1957 Some(GitFileStatus::Added)
1958 );
1959 });
1960
1961 std::fs::rename(
1962 root_path.join("projects/project1"),
1963 root_path.join("projects/project2"),
1964 )
1965 .ok();
1966 tree.flush_fs_events(cx).await;
1967
1968 cx.read(|cx| {
1969 let tree = tree.read(cx);
1970 let (work_dir, _) = tree.repositories().next().unwrap();
1971 assert_eq!(work_dir.as_ref(), Path::new("projects/project2"));
1972 assert_eq!(
1973 tree.status_for_file(Path::new("projects/project2/a")),
1974 Some(GitFileStatus::Modified)
1975 );
1976 assert_eq!(
1977 tree.status_for_file(Path::new("projects/project2/b")),
1978 Some(GitFileStatus::Added)
1979 );
1980 });
1981}
1982
1983#[gpui::test]
1984async fn test_git_repository_for_path(cx: &mut TestAppContext) {
1985 init_test(cx);
1986 cx.executor().allow_parking();
1987 let root = temp_tree(json!({
1988 "c.txt": "",
1989 "dir1": {
1990 ".git": {},
1991 "deps": {
1992 "dep1": {
1993 ".git": {},
1994 "src": {
1995 "a.txt": ""
1996 }
1997 }
1998 },
1999 "src": {
2000 "b.txt": ""
2001 }
2002 },
2003 }));
2004
2005 let tree = Worktree::local(
2006 root.path(),
2007 true,
2008 Arc::new(RealFs::default()),
2009 Default::default(),
2010 &mut cx.to_async(),
2011 )
2012 .await
2013 .unwrap();
2014
2015 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2016 .await;
2017 tree.flush_fs_events(cx).await;
2018
2019 tree.read_with(cx, |tree, _cx| {
2020 let tree = tree.as_local().unwrap();
2021
2022 assert!(tree.repository_for_path("c.txt".as_ref()).is_none());
2023
2024 let entry = tree.repository_for_path("dir1/src/b.txt".as_ref()).unwrap();
2025 assert_eq!(
2026 entry
2027 .work_directory(tree)
2028 .map(|directory| directory.as_ref().to_owned()),
2029 Some(Path::new("dir1").to_owned())
2030 );
2031
2032 let entry = tree
2033 .repository_for_path("dir1/deps/dep1/src/a.txt".as_ref())
2034 .unwrap();
2035 assert_eq!(
2036 entry
2037 .work_directory(tree)
2038 .map(|directory| directory.as_ref().to_owned()),
2039 Some(Path::new("dir1/deps/dep1").to_owned())
2040 );
2041
2042 let entries = tree.files(false, 0);
2043
2044 let paths_with_repos = tree
2045 .entries_with_repositories(entries)
2046 .map(|(entry, repo)| {
2047 (
2048 entry.path.as_ref(),
2049 repo.and_then(|repo| {
2050 repo.work_directory(tree)
2051 .map(|work_directory| work_directory.0.to_path_buf())
2052 }),
2053 )
2054 })
2055 .collect::<Vec<_>>();
2056
2057 assert_eq!(
2058 paths_with_repos,
2059 &[
2060 (Path::new("c.txt"), None),
2061 (
2062 Path::new("dir1/deps/dep1/src/a.txt"),
2063 Some(Path::new("dir1/deps/dep1").into())
2064 ),
2065 (Path::new("dir1/src/b.txt"), Some(Path::new("dir1").into())),
2066 ]
2067 );
2068 });
2069
2070 let repo_update_events = Arc::new(Mutex::new(vec![]));
2071 tree.update(cx, |_, cx| {
2072 let repo_update_events = repo_update_events.clone();
2073 cx.subscribe(&tree, move |_, _, event, _| {
2074 if let Event::UpdatedGitRepositories(update) = event {
2075 repo_update_events.lock().push(update.clone());
2076 }
2077 })
2078 .detach();
2079 });
2080
2081 std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
2082 tree.flush_fs_events(cx).await;
2083
2084 assert_eq!(
2085 repo_update_events.lock()[0]
2086 .iter()
2087 .map(|e| e.0.clone())
2088 .collect::<Vec<Arc<Path>>>(),
2089 vec![Path::new("dir1").into()]
2090 );
2091
2092 std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
2093 tree.flush_fs_events(cx).await;
2094
2095 tree.read_with(cx, |tree, _cx| {
2096 let tree = tree.as_local().unwrap();
2097
2098 assert!(tree
2099 .repository_for_path("dir1/src/b.txt".as_ref())
2100 .is_none());
2101 });
2102}
2103
2104#[gpui::test]
2105async fn test_git_status(cx: &mut TestAppContext) {
2106 init_test(cx);
2107 cx.executor().allow_parking();
2108 const IGNORE_RULE: &str = "**/target";
2109
2110 let root = temp_tree(json!({
2111 "project": {
2112 "a.txt": "a",
2113 "b.txt": "bb",
2114 "c": {
2115 "d": {
2116 "e.txt": "eee"
2117 }
2118 },
2119 "f.txt": "ffff",
2120 "target": {
2121 "build_file": "???"
2122 },
2123 ".gitignore": IGNORE_RULE
2124 },
2125
2126 }));
2127
2128 const A_TXT: &str = "a.txt";
2129 const B_TXT: &str = "b.txt";
2130 const E_TXT: &str = "c/d/e.txt";
2131 const F_TXT: &str = "f.txt";
2132 const DOTGITIGNORE: &str = ".gitignore";
2133 const BUILD_FILE: &str = "target/build_file";
2134 let project_path = Path::new("project");
2135
2136 // Set up git repository before creating the worktree.
2137 let work_dir = root.path().join("project");
2138 let mut repo = git_init(work_dir.as_path());
2139 repo.add_ignore_rule(IGNORE_RULE).unwrap();
2140 git_add(A_TXT, &repo);
2141 git_add(E_TXT, &repo);
2142 git_add(DOTGITIGNORE, &repo);
2143 git_commit("Initial commit", &repo);
2144
2145 let tree = Worktree::local(
2146 root.path(),
2147 true,
2148 Arc::new(RealFs::default()),
2149 Default::default(),
2150 &mut cx.to_async(),
2151 )
2152 .await
2153 .unwrap();
2154
2155 tree.flush_fs_events(cx).await;
2156 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2157 .await;
2158 cx.executor().run_until_parked();
2159
2160 // Check that the right git state is observed on startup
2161 tree.read_with(cx, |tree, _cx| {
2162 let snapshot = tree.snapshot();
2163 assert_eq!(snapshot.repositories().count(), 1);
2164 let (dir, repo_entry) = snapshot.repositories().next().unwrap();
2165 assert_eq!(dir.as_ref(), Path::new("project"));
2166 assert!(repo_entry.location_in_repo.is_none());
2167
2168 assert_eq!(
2169 snapshot.status_for_file(project_path.join(B_TXT)),
2170 Some(GitFileStatus::Added)
2171 );
2172 assert_eq!(
2173 snapshot.status_for_file(project_path.join(F_TXT)),
2174 Some(GitFileStatus::Added)
2175 );
2176 });
2177
2178 // Modify a file in the working copy.
2179 std::fs::write(work_dir.join(A_TXT), "aa").unwrap();
2180 tree.flush_fs_events(cx).await;
2181 cx.executor().run_until_parked();
2182
2183 // The worktree detects that the file's git status has changed.
2184 tree.read_with(cx, |tree, _cx| {
2185 let snapshot = tree.snapshot();
2186 assert_eq!(
2187 snapshot.status_for_file(project_path.join(A_TXT)),
2188 Some(GitFileStatus::Modified)
2189 );
2190 });
2191
2192 // Create a commit in the git repository.
2193 git_add(A_TXT, &repo);
2194 git_add(B_TXT, &repo);
2195 git_commit("Committing modified and added", &repo);
2196 tree.flush_fs_events(cx).await;
2197 cx.executor().run_until_parked();
2198
2199 // The worktree detects that the files' git status have changed.
2200 tree.read_with(cx, |tree, _cx| {
2201 let snapshot = tree.snapshot();
2202 assert_eq!(
2203 snapshot.status_for_file(project_path.join(F_TXT)),
2204 Some(GitFileStatus::Added)
2205 );
2206 assert_eq!(snapshot.status_for_file(project_path.join(B_TXT)), None);
2207 assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
2208 });
2209
2210 // Modify files in the working copy and perform git operations on other files.
2211 git_reset(0, &repo);
2212 git_remove_index(Path::new(B_TXT), &repo);
2213 git_stash(&mut repo);
2214 std::fs::write(work_dir.join(E_TXT), "eeee").unwrap();
2215 std::fs::write(work_dir.join(BUILD_FILE), "this should be ignored").unwrap();
2216 tree.flush_fs_events(cx).await;
2217 cx.executor().run_until_parked();
2218
2219 // Check that more complex repo changes are tracked
2220 tree.read_with(cx, |tree, _cx| {
2221 let snapshot = tree.snapshot();
2222
2223 assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
2224 assert_eq!(
2225 snapshot.status_for_file(project_path.join(B_TXT)),
2226 Some(GitFileStatus::Added)
2227 );
2228 assert_eq!(
2229 snapshot.status_for_file(project_path.join(E_TXT)),
2230 Some(GitFileStatus::Modified)
2231 );
2232 });
2233
2234 std::fs::remove_file(work_dir.join(B_TXT)).unwrap();
2235 std::fs::remove_dir_all(work_dir.join("c")).unwrap();
2236 std::fs::write(
2237 work_dir.join(DOTGITIGNORE),
2238 [IGNORE_RULE, "f.txt"].join("\n"),
2239 )
2240 .unwrap();
2241
2242 git_add(Path::new(DOTGITIGNORE), &repo);
2243 git_commit("Committing modified git ignore", &repo);
2244
2245 tree.flush_fs_events(cx).await;
2246 cx.executor().run_until_parked();
2247
2248 let mut renamed_dir_name = "first_directory/second_directory";
2249 const RENAMED_FILE: &str = "rf.txt";
2250
2251 std::fs::create_dir_all(work_dir.join(renamed_dir_name)).unwrap();
2252 std::fs::write(
2253 work_dir.join(renamed_dir_name).join(RENAMED_FILE),
2254 "new-contents",
2255 )
2256 .unwrap();
2257
2258 tree.flush_fs_events(cx).await;
2259 cx.executor().run_until_parked();
2260
2261 tree.read_with(cx, |tree, _cx| {
2262 let snapshot = tree.snapshot();
2263 assert_eq!(
2264 snapshot.status_for_file(project_path.join(renamed_dir_name).join(RENAMED_FILE)),
2265 Some(GitFileStatus::Added)
2266 );
2267 });
2268
2269 renamed_dir_name = "new_first_directory/second_directory";
2270
2271 std::fs::rename(
2272 work_dir.join("first_directory"),
2273 work_dir.join("new_first_directory"),
2274 )
2275 .unwrap();
2276
2277 tree.flush_fs_events(cx).await;
2278 cx.executor().run_until_parked();
2279
2280 tree.read_with(cx, |tree, _cx| {
2281 let snapshot = tree.snapshot();
2282
2283 assert_eq!(
2284 snapshot.status_for_file(
2285 project_path
2286 .join(Path::new(renamed_dir_name))
2287 .join(RENAMED_FILE)
2288 ),
2289 Some(GitFileStatus::Added)
2290 );
2291 });
2292}
2293
2294#[gpui::test]
2295async fn test_repository_subfolder_git_status(cx: &mut TestAppContext) {
2296 init_test(cx);
2297 cx.executor().allow_parking();
2298
2299 let root = temp_tree(json!({
2300 "my-repo": {
2301 // .git folder will go here
2302 "a.txt": "a",
2303 "sub-folder-1": {
2304 "sub-folder-2": {
2305 "c.txt": "cc",
2306 "d": {
2307 "e.txt": "eee"
2308 }
2309 },
2310 }
2311 },
2312
2313 }));
2314
2315 const C_TXT: &str = "sub-folder-1/sub-folder-2/c.txt";
2316 const E_TXT: &str = "sub-folder-1/sub-folder-2/d/e.txt";
2317
2318 // Set up git repository before creating the worktree.
2319 let git_repo_work_dir = root.path().join("my-repo");
2320 let repo = git_init(git_repo_work_dir.as_path());
2321 git_add(C_TXT, &repo);
2322 git_commit("Initial commit", &repo);
2323
2324 // Open the worktree in subfolder
2325 let project_root = Path::new("my-repo/sub-folder-1/sub-folder-2");
2326 let tree = Worktree::local(
2327 root.path().join(project_root),
2328 true,
2329 Arc::new(RealFs::default()),
2330 Default::default(),
2331 &mut cx.to_async(),
2332 )
2333 .await
2334 .unwrap();
2335
2336 tree.flush_fs_events(cx).await;
2337 tree.flush_fs_events_in_root_git_repository(cx).await;
2338 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2339 .await;
2340 cx.executor().run_until_parked();
2341
2342 // Ensure that the git status is loaded correctly
2343 tree.read_with(cx, |tree, _cx| {
2344 let snapshot = tree.snapshot();
2345 assert_eq!(snapshot.repositories().count(), 1);
2346 let (dir, repo_entry) = snapshot.repositories().next().unwrap();
2347 // Path is blank because the working directory of
2348 // the git repository is located at the root of the project
2349 assert_eq!(dir.as_ref(), Path::new(""));
2350
2351 // This is the missing path between the root of the project (sub-folder-2) and its
2352 // location relative to the root of the repository.
2353 assert_eq!(
2354 repo_entry.location_in_repo,
2355 Some(Arc::from(Path::new("sub-folder-1/sub-folder-2")))
2356 );
2357
2358 assert_eq!(snapshot.status_for_file("c.txt"), None);
2359 assert_eq!(
2360 snapshot.status_for_file("d/e.txt"),
2361 Some(GitFileStatus::Added)
2362 );
2363 });
2364
2365 // Now we simulate FS events, but ONLY in the .git folder that's outside
2366 // of out project root.
2367 // Meaning: we don't produce any FS events for files inside the project.
2368 git_add(E_TXT, &repo);
2369 git_commit("Second commit", &repo);
2370 tree.flush_fs_events_in_root_git_repository(cx).await;
2371 cx.executor().run_until_parked();
2372
2373 tree.read_with(cx, |tree, _cx| {
2374 let snapshot = tree.snapshot();
2375
2376 assert!(snapshot.repositories().next().is_some());
2377
2378 assert_eq!(snapshot.status_for_file("c.txt"), None);
2379 assert_eq!(snapshot.status_for_file("d/e.txt"), None);
2380 });
2381}
2382
2383#[gpui::test]
2384async fn test_propagate_git_statuses(cx: &mut TestAppContext) {
2385 init_test(cx);
2386 let fs = FakeFs::new(cx.background_executor.clone());
2387 fs.insert_tree(
2388 "/root",
2389 json!({
2390 ".git": {},
2391 "a": {
2392 "b": {
2393 "c1.txt": "",
2394 "c2.txt": "",
2395 },
2396 "d": {
2397 "e1.txt": "",
2398 "e2.txt": "",
2399 "e3.txt": "",
2400 }
2401 },
2402 "f": {
2403 "no-status.txt": ""
2404 },
2405 "g": {
2406 "h1.txt": "",
2407 "h2.txt": ""
2408 },
2409
2410 }),
2411 )
2412 .await;
2413
2414 fs.set_status_for_repo_via_git_operation(
2415 Path::new("/root/.git"),
2416 &[
2417 (Path::new("a/b/c1.txt"), GitFileStatus::Added),
2418 (Path::new("a/d/e2.txt"), GitFileStatus::Modified),
2419 (Path::new("g/h2.txt"), GitFileStatus::Conflict),
2420 ],
2421 );
2422
2423 let tree = Worktree::local(
2424 Path::new("/root"),
2425 true,
2426 fs.clone(),
2427 Default::default(),
2428 &mut cx.to_async(),
2429 )
2430 .await
2431 .unwrap();
2432
2433 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2434 .await;
2435
2436 cx.executor().run_until_parked();
2437 let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());
2438
2439 check_propagated_statuses(
2440 &snapshot,
2441 &[
2442 (Path::new(""), Some(GitFileStatus::Conflict)),
2443 (Path::new("a"), Some(GitFileStatus::Modified)),
2444 (Path::new("a/b"), Some(GitFileStatus::Added)),
2445 (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2446 (Path::new("a/b/c2.txt"), None),
2447 (Path::new("a/d"), Some(GitFileStatus::Modified)),
2448 (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2449 (Path::new("f"), None),
2450 (Path::new("f/no-status.txt"), None),
2451 (Path::new("g"), Some(GitFileStatus::Conflict)),
2452 (Path::new("g/h2.txt"), Some(GitFileStatus::Conflict)),
2453 ],
2454 );
2455
2456 check_propagated_statuses(
2457 &snapshot,
2458 &[
2459 (Path::new("a/b"), Some(GitFileStatus::Added)),
2460 (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2461 (Path::new("a/b/c2.txt"), None),
2462 (Path::new("a/d"), Some(GitFileStatus::Modified)),
2463 (Path::new("a/d/e1.txt"), None),
2464 (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2465 (Path::new("f"), None),
2466 (Path::new("f/no-status.txt"), None),
2467 (Path::new("g"), Some(GitFileStatus::Conflict)),
2468 ],
2469 );
2470
2471 check_propagated_statuses(
2472 &snapshot,
2473 &[
2474 (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2475 (Path::new("a/b/c2.txt"), None),
2476 (Path::new("a/d/e1.txt"), None),
2477 (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2478 (Path::new("f/no-status.txt"), None),
2479 ],
2480 );
2481}
2482
2483#[track_caller]
2484fn check_propagated_statuses(
2485 snapshot: &Snapshot,
2486 expected_statuses: &[(&Path, Option<GitFileStatus>)],
2487) {
2488 let mut entries = expected_statuses
2489 .iter()
2490 .map(|(path, _)| snapshot.entry_for_path(path).unwrap().clone())
2491 .collect::<Vec<_>>();
2492 snapshot.propagate_git_statuses(&mut entries);
2493 assert_eq!(
2494 entries
2495 .iter()
2496 .map(|e| (e.path.as_ref(), e.git_status))
2497 .collect::<Vec<_>>(),
2498 expected_statuses
2499 );
2500}
2501
2502#[track_caller]
2503fn git_init(path: &Path) -> git2::Repository {
2504 git2::Repository::init(path).expect("Failed to initialize git repository")
2505}
2506
2507#[track_caller]
2508fn git_add<P: AsRef<Path>>(path: P, repo: &git2::Repository) {
2509 let path = path.as_ref();
2510 let mut index = repo.index().expect("Failed to get index");
2511 index.add_path(path).expect("Failed to add a.txt");
2512 index.write().expect("Failed to write index");
2513}
2514
2515#[track_caller]
2516fn git_remove_index(path: &Path, repo: &git2::Repository) {
2517 let mut index = repo.index().expect("Failed to get index");
2518 index.remove_path(path).expect("Failed to add a.txt");
2519 index.write().expect("Failed to write index");
2520}
2521
2522#[track_caller]
2523fn git_commit(msg: &'static str, repo: &git2::Repository) {
2524 use git2::Signature;
2525
2526 let signature = Signature::now("test", "test@zed.dev").unwrap();
2527 let oid = repo.index().unwrap().write_tree().unwrap();
2528 let tree = repo.find_tree(oid).unwrap();
2529 if let Ok(head) = repo.head() {
2530 let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
2531
2532 let parent_commit = parent_obj.as_commit().unwrap();
2533
2534 repo.commit(
2535 Some("HEAD"),
2536 &signature,
2537 &signature,
2538 msg,
2539 &tree,
2540 &[parent_commit],
2541 )
2542 .expect("Failed to commit with parent");
2543 } else {
2544 repo.commit(Some("HEAD"), &signature, &signature, msg, &tree, &[])
2545 .expect("Failed to commit");
2546 }
2547}
2548
2549#[track_caller]
2550fn git_stash(repo: &mut git2::Repository) {
2551 use git2::Signature;
2552
2553 let signature = Signature::now("test", "test@zed.dev").unwrap();
2554 repo.stash_save(&signature, "N/A", None)
2555 .expect("Failed to stash");
2556}
2557
2558#[track_caller]
2559fn git_reset(offset: usize, repo: &git2::Repository) {
2560 let head = repo.head().expect("Couldn't get repo head");
2561 let object = head.peel(git2::ObjectType::Commit).unwrap();
2562 let commit = object.as_commit().unwrap();
2563 let new_head = commit
2564 .parents()
2565 .inspect(|parnet| {
2566 parnet.message();
2567 })
2568 .nth(offset)
2569 .expect("Not enough history");
2570 repo.reset(new_head.as_object(), git2::ResetType::Soft, None)
2571 .expect("Could not reset");
2572}
2573
2574#[allow(dead_code)]
2575#[track_caller]
2576fn git_status(repo: &git2::Repository) -> collections::HashMap<String, git2::Status> {
2577 repo.statuses(None)
2578 .unwrap()
2579 .iter()
2580 .map(|status| (status.path().unwrap().to_string(), status.status()))
2581 .collect()
2582}
2583
2584#[track_caller]
2585fn check_worktree_entries(
2586 tree: &Worktree,
2587 expected_excluded_paths: &[&str],
2588 expected_ignored_paths: &[&str],
2589 expected_tracked_paths: &[&str],
2590) {
2591 for path in expected_excluded_paths {
2592 let entry = tree.entry_for_path(path);
2593 assert!(
2594 entry.is_none(),
2595 "expected path '{path}' to be excluded, but got entry: {entry:?}",
2596 );
2597 }
2598 for path in expected_ignored_paths {
2599 let entry = tree
2600 .entry_for_path(path)
2601 .unwrap_or_else(|| panic!("Missing entry for expected ignored path '{path}'"));
2602 assert!(
2603 entry.is_ignored,
2604 "expected path '{path}' to be ignored, but got entry: {entry:?}",
2605 );
2606 }
2607 for path in expected_tracked_paths {
2608 let entry = tree
2609 .entry_for_path(path)
2610 .unwrap_or_else(|| panic!("Missing entry for expected tracked path '{path}'"));
2611 assert!(
2612 !entry.is_ignored,
2613 "expected path '{path}' to be tracked, but got entry: {entry:?}",
2614 );
2615 }
2616}
2617
2618fn init_test(cx: &mut gpui::TestAppContext) {
2619 if std::env::var("RUST_LOG").is_ok() {
2620 env_logger::try_init().ok();
2621 }
2622
2623 cx.update(|cx| {
2624 let settings_store = SettingsStore::test(cx);
2625 cx.set_global(settings_store);
2626 WorktreeSettings::register(cx);
2627 });
2628}
2629
2630fn assert_entry_git_state(
2631 tree: &Worktree,
2632 path: &str,
2633 git_status: Option<GitFileStatus>,
2634 is_ignored: bool,
2635) {
2636 let entry = tree.entry_for_path(path).expect("entry {path} not found");
2637 assert_eq!(entry.git_status, git_status);
2638 assert_eq!(entry.is_ignored, is_ignored);
2639}