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