1use super::{HoverTarget, HoveredWord, TerminalView};
2use anyhow::{Context as _, Result};
3use editor::Editor;
4use gpui::{App, AppContext, Context, Task, WeakEntity, Window};
5use itertools::Itertools;
6use project::{Entry, Metadata};
7use std::path::PathBuf;
8use terminal::PathLikeTarget;
9use util::{
10 ResultExt, debug_panic,
11 paths::{PathStyle, PathWithPosition},
12 rel_path::RelPath,
13};
14use workspace::{OpenOptions, OpenVisible, Workspace};
15
16/// The way we found the open target. This is important to have for test assertions.
17/// For example, remote projects never look in the file system.
18#[cfg(test)]
19#[derive(Debug, Clone, Copy, Eq, PartialEq)]
20enum OpenTargetFoundBy {
21 WorktreeExact,
22 WorktreeScan,
23 FileSystemBackground,
24}
25
26#[cfg(test)]
27#[derive(Debug, Clone, Copy, Eq, PartialEq)]
28enum BackgroundFsChecks {
29 Enabled,
30 Disabled,
31}
32
33#[derive(Debug, Clone)]
34enum OpenTarget {
35 Worktree(PathWithPosition, Entry, #[cfg(test)] OpenTargetFoundBy),
36 File(PathWithPosition, Metadata),
37}
38
39impl OpenTarget {
40 fn is_file(&self) -> bool {
41 match self {
42 OpenTarget::Worktree(_, entry, ..) => entry.is_file(),
43 OpenTarget::File(_, metadata) => !metadata.is_dir,
44 }
45 }
46
47 fn is_dir(&self) -> bool {
48 match self {
49 OpenTarget::Worktree(_, entry, ..) => entry.is_dir(),
50 OpenTarget::File(_, metadata) => metadata.is_dir,
51 }
52 }
53
54 fn path(&self) -> &PathWithPosition {
55 match self {
56 OpenTarget::Worktree(path, ..) => path,
57 OpenTarget::File(path, _) => path,
58 }
59 }
60
61 #[cfg(test)]
62 fn found_by(&self) -> OpenTargetFoundBy {
63 match self {
64 OpenTarget::Worktree(.., found_by) => *found_by,
65 OpenTarget::File(..) => OpenTargetFoundBy::FileSystemBackground,
66 }
67 }
68}
69
70pub(super) fn hover_path_like_target(
71 workspace: &WeakEntity<Workspace>,
72 hovered_word: HoveredWord,
73 path_like_target: &PathLikeTarget,
74 cx: &mut Context<TerminalView>,
75) -> Task<()> {
76 #[cfg(not(test))]
77 {
78 possible_hover_target(workspace, hovered_word, path_like_target, cx)
79 }
80 #[cfg(test)]
81 {
82 possible_hover_target(
83 workspace,
84 hovered_word,
85 path_like_target,
86 cx,
87 BackgroundFsChecks::Enabled,
88 )
89 }
90}
91
92fn possible_hover_target(
93 workspace: &WeakEntity<Workspace>,
94 hovered_word: HoveredWord,
95 path_like_target: &PathLikeTarget,
96 cx: &mut Context<TerminalView>,
97 #[cfg(test)] background_fs_checks: BackgroundFsChecks,
98) -> Task<()> {
99 let file_to_open_task = possible_open_target(
100 workspace,
101 path_like_target,
102 cx,
103 #[cfg(test)]
104 background_fs_checks,
105 );
106 cx.spawn(async move |terminal_view, cx| {
107 let file_to_open = file_to_open_task.await;
108 terminal_view
109 .update(cx, |terminal_view, _| match file_to_open {
110 Some(OpenTarget::File(path, _) | OpenTarget::Worktree(path, ..)) => {
111 terminal_view.hover = Some(HoverTarget {
112 tooltip: path.to_string(|path| path.to_string_lossy().into_owned()),
113 hovered_word,
114 });
115 }
116 None => {
117 terminal_view.hover = None;
118 }
119 })
120 .ok();
121 })
122}
123
124fn possible_open_target(
125 workspace: &WeakEntity<Workspace>,
126 path_like_target: &PathLikeTarget,
127 cx: &App,
128 #[cfg(test)] background_fs_checks: BackgroundFsChecks,
129) -> Task<Option<OpenTarget>> {
130 let Some(workspace) = workspace.upgrade() else {
131 return Task::ready(None);
132 };
133 // We have to check for both paths, as on Unix, certain paths with positions are valid file paths too.
134 // We can be on FS remote part, without real FS, so cannot canonicalize or check for existence the path right away.
135 let mut potential_paths = Vec::new();
136 let cwd = path_like_target.terminal_dir.as_ref();
137 let maybe_path = &path_like_target.maybe_path;
138 let original_path = PathWithPosition::from_path(PathBuf::from(maybe_path));
139 let path_with_position = PathWithPosition::parse_str(maybe_path);
140 let worktree_candidates = workspace
141 .read(cx)
142 .worktrees(cx)
143 .sorted_by_key(|worktree| {
144 let worktree_root = worktree.read(cx).abs_path();
145 match cwd.and_then(|cwd| worktree_root.strip_prefix(cwd).ok()) {
146 Some(cwd_child) => cwd_child.components().count(),
147 None => usize::MAX,
148 }
149 })
150 .collect::<Vec<_>>();
151 // Since we do not check paths via FS and joining, we need to strip off potential `./`, `a/`, `b/` prefixes out of it.
152 const GIT_DIFF_PATH_PREFIXES: &[&str] = &["a", "b"];
153 for prefix_str in GIT_DIFF_PATH_PREFIXES.iter().chain(std::iter::once(&".")) {
154 if let Some(stripped) = original_path.path.strip_prefix(prefix_str).ok() {
155 potential_paths.push(PathWithPosition {
156 path: stripped.to_owned(),
157 row: original_path.row,
158 column: original_path.column,
159 });
160 }
161 if let Some(stripped) = path_with_position.path.strip_prefix(prefix_str).ok() {
162 potential_paths.push(PathWithPosition {
163 path: stripped.to_owned(),
164 row: path_with_position.row,
165 column: path_with_position.column,
166 });
167 }
168 }
169
170 let insert_both_paths = original_path != path_with_position;
171 potential_paths.insert(0, original_path);
172 if insert_both_paths {
173 potential_paths.insert(1, path_with_position);
174 }
175
176 // If we won't find paths "easily", we can traverse the entire worktree to look what ends with the potential path suffix.
177 // That will be slow, though, so do the fast checks first.
178 let mut worktree_paths_to_check = Vec::new();
179 let mut is_cwd_in_worktree = false;
180 let mut open_target = None;
181 'worktree_loop: for worktree in &worktree_candidates {
182 let worktree_root = worktree.read(cx).abs_path();
183 let mut paths_to_check = Vec::with_capacity(potential_paths.len());
184 let relative_cwd = cwd
185 .and_then(|cwd| cwd.strip_prefix(&worktree_root).ok())
186 .and_then(|cwd| RelPath::new(cwd, PathStyle::local()).ok())
187 .and_then(|cwd_stripped| {
188 (cwd_stripped.as_ref() != RelPath::empty()).then(|| {
189 is_cwd_in_worktree = true;
190 cwd_stripped
191 })
192 });
193
194 for path_with_position in &potential_paths {
195 let path_to_check = if worktree_root.ends_with(&path_with_position.path) {
196 let root_path_with_position = PathWithPosition {
197 path: worktree_root.to_path_buf(),
198 row: path_with_position.row,
199 column: path_with_position.column,
200 };
201 match worktree.read(cx).root_entry() {
202 Some(root_entry) => {
203 open_target = Some(OpenTarget::Worktree(
204 root_path_with_position,
205 root_entry.clone(),
206 #[cfg(test)]
207 OpenTargetFoundBy::WorktreeExact,
208 ));
209 break 'worktree_loop;
210 }
211 None => root_path_with_position,
212 }
213 } else {
214 PathWithPosition {
215 path: path_with_position
216 .path
217 .strip_prefix(&worktree_root)
218 .unwrap_or(&path_with_position.path)
219 .to_owned(),
220 row: path_with_position.row,
221 column: path_with_position.column,
222 }
223 };
224
225 if let Ok(relative_path_to_check) =
226 RelPath::new(&path_to_check.path, PathStyle::local())
227 && !worktree.read(cx).is_single_file()
228 && let Some(entry) = relative_cwd
229 .clone()
230 .and_then(|relative_cwd| {
231 worktree
232 .read(cx)
233 .entry_for_path(&relative_cwd.join(&relative_path_to_check))
234 })
235 .or_else(|| worktree.read(cx).entry_for_path(&relative_path_to_check))
236 {
237 open_target = Some(OpenTarget::Worktree(
238 PathWithPosition {
239 path: worktree.read(cx).absolutize(&entry.path),
240 row: path_to_check.row,
241 column: path_to_check.column,
242 },
243 entry.clone(),
244 #[cfg(test)]
245 OpenTargetFoundBy::WorktreeExact,
246 ));
247 break 'worktree_loop;
248 }
249
250 paths_to_check.push(path_to_check);
251 }
252
253 if !paths_to_check.is_empty() {
254 worktree_paths_to_check.push((worktree.clone(), paths_to_check));
255 }
256 }
257
258 #[cfg(not(test))]
259 let enable_background_fs_checks = workspace.read(cx).project().read(cx).is_local();
260 #[cfg(test)]
261 let enable_background_fs_checks = background_fs_checks == BackgroundFsChecks::Enabled;
262
263 if open_target.is_some() {
264 // We we want to prefer open targets found via background fs checks over worktree matches,
265 // however we can return early if either:
266 // - This is a remote project, or
267 // - If the terminal working directory is inside of at least one worktree
268 if !enable_background_fs_checks || is_cwd_in_worktree {
269 return Task::ready(open_target);
270 }
271 }
272
273 // Before entire worktree traversal(s), make an attempt to do FS checks if available.
274 let fs_paths_to_check =
275 if enable_background_fs_checks {
276 let fs_cwd_paths_to_check = cwd
277 .iter()
278 .flat_map(|cwd| {
279 let mut paths_to_check = Vec::new();
280 for path_to_check in &potential_paths {
281 let maybe_path = &path_to_check.path;
282 if path_to_check.path.is_relative() {
283 paths_to_check.push(PathWithPosition {
284 path: cwd.join(&maybe_path),
285 row: path_to_check.row,
286 column: path_to_check.column,
287 });
288 }
289 }
290 paths_to_check
291 })
292 .collect::<Vec<_>>();
293 fs_cwd_paths_to_check
294 .into_iter()
295 .chain(
296 potential_paths
297 .into_iter()
298 .flat_map(|path_to_check| {
299 let mut paths_to_check = Vec::new();
300 let maybe_path = &path_to_check.path;
301 if maybe_path.starts_with("~") {
302 if let Some(home_path) = maybe_path.strip_prefix("~").ok().and_then(
303 |stripped_maybe_path| {
304 Some(dirs::home_dir()?.join(stripped_maybe_path))
305 },
306 ) {
307 paths_to_check.push(PathWithPosition {
308 path: home_path,
309 row: path_to_check.row,
310 column: path_to_check.column,
311 });
312 }
313 } else {
314 paths_to_check.push(PathWithPosition {
315 path: maybe_path.clone(),
316 row: path_to_check.row,
317 column: path_to_check.column,
318 });
319 if maybe_path.is_relative() {
320 for worktree in &worktree_candidates {
321 if !worktree.read(cx).is_single_file() {
322 paths_to_check.push(PathWithPosition {
323 path: worktree.read(cx).abs_path().join(maybe_path),
324 row: path_to_check.row,
325 column: path_to_check.column,
326 });
327 }
328 }
329 }
330 }
331 paths_to_check
332 })
333 .collect::<Vec<_>>(),
334 )
335 .collect()
336 } else {
337 Vec::new()
338 };
339
340 let fs = workspace.read(cx).project().read(cx).fs().clone();
341 let background_fs_checks_task = cx.background_spawn(async move {
342 for mut path_to_check in fs_paths_to_check {
343 if let Some(fs_path_to_check) = fs.canonicalize(&path_to_check.path).await.ok()
344 && let Some(metadata) = fs.metadata(&fs_path_to_check).await.ok().flatten()
345 {
346 if open_target
347 .as_ref()
348 .map(|open_target| open_target.path().path != fs_path_to_check)
349 .unwrap_or(true)
350 {
351 path_to_check.path = fs_path_to_check;
352 return Some(OpenTarget::File(path_to_check, metadata));
353 }
354
355 break;
356 }
357 }
358
359 open_target
360 });
361
362 cx.spawn(async move |cx| {
363 background_fs_checks_task.await.or_else(|| {
364 for (worktree, worktree_paths_to_check) in worktree_paths_to_check {
365 if let Some(found_entry) =
366 worktree.update(cx, |worktree, _| -> Option<OpenTarget> {
367 let traversal =
368 worktree.traverse_from_path(true, true, false, RelPath::empty());
369 for entry in traversal {
370 if let Some(path_in_worktree) =
371 worktree_paths_to_check.iter().find(|path_to_check| {
372 RelPath::new(&path_to_check.path, PathStyle::local())
373 .is_ok_and(|path| entry.path.ends_with(&path))
374 })
375 {
376 return Some(OpenTarget::Worktree(
377 PathWithPosition {
378 path: worktree.absolutize(&entry.path),
379 row: path_in_worktree.row,
380 column: path_in_worktree.column,
381 },
382 entry.clone(),
383 #[cfg(test)]
384 OpenTargetFoundBy::WorktreeScan,
385 ));
386 }
387 }
388 None
389 })
390 {
391 return Some(found_entry);
392 }
393 }
394 None
395 })
396 })
397}
398
399pub(super) fn open_path_like_target(
400 workspace: &WeakEntity<Workspace>,
401 terminal_view: &mut TerminalView,
402 path_like_target: &PathLikeTarget,
403 window: &mut Window,
404 cx: &mut Context<TerminalView>,
405) {
406 #[cfg(not(test))]
407 {
408 possibly_open_target(workspace, terminal_view, path_like_target, window, cx)
409 .detach_and_log_err(cx)
410 }
411 #[cfg(test)]
412 {
413 possibly_open_target(
414 workspace,
415 terminal_view,
416 path_like_target,
417 window,
418 cx,
419 BackgroundFsChecks::Enabled,
420 )
421 .detach_and_log_err(cx)
422 }
423}
424
425fn possibly_open_target(
426 workspace: &WeakEntity<Workspace>,
427 terminal_view: &mut TerminalView,
428 path_like_target: &PathLikeTarget,
429 window: &mut Window,
430 cx: &mut Context<TerminalView>,
431 #[cfg(test)] background_fs_checks: BackgroundFsChecks,
432) -> Task<Result<Option<OpenTarget>>> {
433 if terminal_view.hover.is_none() {
434 return Task::ready(Ok(None));
435 }
436 let workspace = workspace.clone();
437 let path_like_target = path_like_target.clone();
438 cx.spawn_in(window, async move |terminal_view, cx| {
439 let Some(open_target) = terminal_view
440 .update(cx, |_, cx| {
441 possible_open_target(
442 &workspace,
443 &path_like_target,
444 cx,
445 #[cfg(test)]
446 background_fs_checks,
447 )
448 })?
449 .await
450 else {
451 return Ok(None);
452 };
453
454 let path_to_open = open_target.path();
455 let opened_items = workspace
456 .update_in(cx, |workspace, window, cx| {
457 workspace.open_paths(
458 vec![path_to_open.path.clone()],
459 OpenOptions {
460 visible: Some(OpenVisible::OnlyDirectories),
461 ..Default::default()
462 },
463 None,
464 window,
465 cx,
466 )
467 })
468 .context("workspace update")?
469 .await;
470 if opened_items.len() != 1 {
471 debug_panic!(
472 "Received {} items for one path {path_to_open:?}",
473 opened_items.len(),
474 );
475 }
476
477 if let Some(opened_item) = opened_items.first() {
478 if open_target.is_file() {
479 if let Some(Ok(opened_item)) = opened_item {
480 if let Some(row) = path_to_open.row {
481 let col = path_to_open.column.unwrap_or(0);
482 if let Some(active_editor) = opened_item.downcast::<Editor>() {
483 active_editor
484 .downgrade()
485 .update_in(cx, |editor, window, cx| {
486 editor.go_to_singleton_buffer_point(
487 language::Point::new(
488 row.saturating_sub(1),
489 col.saturating_sub(1),
490 ),
491 window,
492 cx,
493 )
494 })
495 .log_err();
496 }
497 }
498 return Ok(Some(open_target));
499 }
500 } else if open_target.is_dir() {
501 workspace.update(cx, |workspace, cx| {
502 workspace.project().update(cx, |_, cx| {
503 cx.emit(project::Event::ActivateProjectPanel);
504 })
505 })?;
506 return Ok(Some(open_target));
507 }
508 }
509 Ok(None)
510 })
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use gpui::TestAppContext;
517 use project::Project;
518 use serde_json::json;
519 use std::path::{Path, PathBuf};
520 use terminal::{HoveredWord, alacritty_terminal::index::Point as AlacPoint};
521 use util::path;
522 use workspace::AppState;
523
524 async fn init_test(
525 app_cx: &mut TestAppContext,
526 trees: impl IntoIterator<Item = (&str, serde_json::Value)>,
527 worktree_roots: impl IntoIterator<Item = &str>,
528 ) -> impl AsyncFnMut(
529 HoveredWord,
530 PathLikeTarget,
531 BackgroundFsChecks,
532 ) -> (Option<HoverTarget>, Option<OpenTarget>) {
533 let fs = app_cx.update(AppState::test).fs.as_fake().clone();
534
535 app_cx.update(|cx| {
536 theme::init(theme::LoadThemes::JustBase, cx);
537 editor::init(cx);
538 });
539
540 for (path, tree) in trees {
541 fs.insert_tree(path, tree).await;
542 }
543
544 let project: gpui::Entity<Project> = Project::test(
545 fs.clone(),
546 worktree_roots.into_iter().map(Path::new),
547 app_cx,
548 )
549 .await;
550
551 let (workspace, cx) =
552 app_cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
553
554 let cwd = std::env::current_dir().expect("Failed to get working directory");
555 let terminal = project
556 .update(cx, |project: &mut Project, cx| {
557 project.create_terminal_shell(Some(cwd), cx)
558 })
559 .await
560 .expect("Failed to create a terminal");
561
562 let workspace_a = workspace.clone();
563 let (terminal_view, cx) = app_cx.add_window_view(|window, cx| {
564 TerminalView::new(
565 terminal,
566 workspace_a.downgrade(),
567 None,
568 project.downgrade(),
569 window,
570 cx,
571 )
572 });
573
574 async move |hovered_word: HoveredWord,
575 path_like_target: PathLikeTarget,
576 background_fs_checks: BackgroundFsChecks|
577 -> (Option<HoverTarget>, Option<OpenTarget>) {
578 let workspace_a = workspace.clone();
579 terminal_view
580 .update(cx, |_, cx| {
581 possible_hover_target(
582 &workspace_a.downgrade(),
583 hovered_word,
584 &path_like_target,
585 cx,
586 background_fs_checks,
587 )
588 })
589 .await;
590
591 let hover_target =
592 terminal_view.read_with(cx, |terminal_view, _| terminal_view.hover.clone());
593
594 let open_target = terminal_view
595 .update_in(cx, |terminal_view, window, cx| {
596 possibly_open_target(
597 &workspace.downgrade(),
598 terminal_view,
599 &path_like_target,
600 window,
601 cx,
602 background_fs_checks,
603 )
604 })
605 .await
606 .expect("Failed to possibly open target");
607
608 (hover_target, open_target)
609 }
610 }
611
612 async fn test_path_like_simple(
613 test_path_like: &mut impl AsyncFnMut(
614 HoveredWord,
615 PathLikeTarget,
616 BackgroundFsChecks,
617 ) -> (Option<HoverTarget>, Option<OpenTarget>),
618 maybe_path: &str,
619 tooltip: &str,
620 terminal_dir: Option<PathBuf>,
621 background_fs_checks: BackgroundFsChecks,
622 mut open_target_found_by: OpenTargetFoundBy,
623 file: &str,
624 line: u32,
625 ) {
626 let (hover_target, open_target) = test_path_like(
627 HoveredWord {
628 word: maybe_path.to_string(),
629 word_match: AlacPoint::default()..=AlacPoint::default(),
630 id: 0,
631 },
632 PathLikeTarget {
633 maybe_path: maybe_path.to_string(),
634 terminal_dir,
635 },
636 background_fs_checks,
637 )
638 .await;
639
640 let Some(hover_target) = hover_target else {
641 assert!(
642 hover_target.is_some(),
643 "Hover target should not be `None` at {file}:{line}:"
644 );
645 return;
646 };
647
648 assert_eq!(
649 hover_target.tooltip, tooltip,
650 "Tooltip mismatch at {file}:{line}:"
651 );
652 assert_eq!(
653 hover_target.hovered_word.word, maybe_path,
654 "Hovered word mismatch at {file}:{line}:"
655 );
656
657 let Some(open_target) = open_target else {
658 assert!(
659 open_target.is_some(),
660 "Open target should not be `None` at {file}:{line}:"
661 );
662 return;
663 };
664
665 assert_eq!(
666 open_target.path().path,
667 Path::new(tooltip),
668 "Open target path mismatch at {file}:{line}:"
669 );
670
671 if background_fs_checks == BackgroundFsChecks::Disabled
672 && open_target_found_by == OpenTargetFoundBy::FileSystemBackground
673 {
674 open_target_found_by = OpenTargetFoundBy::WorktreeScan;
675 }
676
677 assert_eq!(
678 open_target.found_by(),
679 open_target_found_by,
680 "Open target found by mismatch at {file}:{line}:"
681 );
682 }
683
684 macro_rules! none_or_some_pathbuf {
685 (None) => {
686 None
687 };
688 ($cwd:literal) => {
689 Some($crate::PathBuf::from(path!($cwd)))
690 };
691 }
692
693 macro_rules! test_path_like {
694 (
695 $test_path_like:expr,
696 $maybe_path:literal,
697 $tooltip:literal,
698 $cwd:tt,
699 $found_by:expr
700 ) => {{
701 test_path_like!(
702 $test_path_like,
703 $maybe_path,
704 $tooltip,
705 $cwd,
706 BackgroundFsChecks::Enabled,
707 $found_by
708 );
709 test_path_like!(
710 $test_path_like,
711 $maybe_path,
712 $tooltip,
713 $cwd,
714 BackgroundFsChecks::Disabled,
715 $found_by
716 );
717 }};
718
719 (
720 $test_path_like:expr,
721 $maybe_path:literal,
722 $tooltip:literal,
723 $cwd:tt,
724 $background_fs_checks:path,
725 $found_by:expr
726 ) => {
727 test_path_like_simple(
728 &mut $test_path_like,
729 path!($maybe_path),
730 path!($tooltip),
731 none_or_some_pathbuf!($cwd),
732 $background_fs_checks,
733 $found_by,
734 std::file!(),
735 std::line!(),
736 )
737 .await
738 };
739 }
740
741 // Note the arms of `test`, `test_local`, and `test_remote` should be collapsed once macro
742 // metavariable expressions (#![feature(macro_metavar_expr)]) are stabilized.
743 // See https://github.com/rust-lang/rust/issues/83527
744 #[doc = "test_path_likes!(<cx>, <trees>, <worktrees>, { $(<tests>;)+ })"]
745 macro_rules! test_path_likes {
746 ($cx:expr, $trees:expr, $worktrees:expr, { $($tests:expr;)+ }) => { {
747 let mut test_path_like = init_test($cx, $trees, $worktrees).await;
748 #[doc ="test!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
749 #[doc ="\\[, found by \\])"]
750 #[allow(unused_macros)]
751 macro_rules! test {
752 ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
753 test_path_like!(
754 test_path_like,
755 $maybe_path,
756 $tooltip,
757 $cwd,
758 OpenTargetFoundBy::WorktreeExact
759 )
760 };
761 ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
762 test_path_like!(
763 test_path_like,
764 $maybe_path,
765 $tooltip,
766 $cwd,
767 OpenTargetFoundBy::$found_by
768 )
769 }
770 }
771 #[doc ="test_local!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
772 #[doc ="\\[, found by \\])"]
773 #[allow(unused_macros)]
774 macro_rules! test_local {
775 ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
776 test_path_like!(
777 test_path_like,
778 $maybe_path,
779 $tooltip,
780 $cwd,
781 BackgroundFsChecks::Enabled,
782 OpenTargetFoundBy::WorktreeExact
783 )
784 };
785 ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
786 test_path_like!(
787 test_path_like,
788 $maybe_path,
789 $tooltip,
790 $cwd,
791 BackgroundFsChecks::Enabled,
792 OpenTargetFoundBy::$found_by
793 )
794 }
795 }
796 #[doc ="test_remote!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
797 #[doc ="\\[, found by \\])"]
798 #[allow(unused_macros)]
799 macro_rules! test_remote {
800 ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
801 test_path_like!(
802 test_path_like,
803 $maybe_path,
804 $tooltip,
805 $cwd,
806 BackgroundFsChecks::Disabled,
807 OpenTargetFoundBy::WorktreeExact
808 )
809 };
810 ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
811 test_path_like!(
812 test_path_like,
813 $maybe_path,
814 $tooltip,
815 $cwd,
816 BackgroundFsChecks::Disabled,
817 OpenTargetFoundBy::$found_by
818 )
819 }
820 }
821 $($tests);+
822 } }
823 }
824
825 #[gpui::test]
826 async fn one_folder_worktree(cx: &mut TestAppContext) {
827 test_path_likes!(
828 cx,
829 vec![(
830 path!("/test"),
831 json!({
832 "lib.rs": "",
833 "test.rs": "",
834 }),
835 )],
836 vec![path!("/test")],
837 {
838 test!("lib.rs", "/test/lib.rs", None);
839 test!("/test/lib.rs", "/test/lib.rs", None);
840 test!("test.rs", "/test/test.rs", None);
841 test!("/test/test.rs", "/test/test.rs", None);
842 }
843 )
844 }
845
846 #[gpui::test]
847 async fn mixed_worktrees(cx: &mut TestAppContext) {
848 test_path_likes!(
849 cx,
850 vec![
851 (
852 path!("/"),
853 json!({
854 "file.txt": "",
855 }),
856 ),
857 (
858 path!("/test"),
859 json!({
860 "lib.rs": "",
861 "test.rs": "",
862 "file.txt": "",
863 }),
864 ),
865 ],
866 vec![path!("/file.txt"), path!("/test")],
867 {
868 test!("file.txt", "/file.txt", "/");
869 test!("/file.txt", "/file.txt", "/");
870
871 test!("lib.rs", "/test/lib.rs", "/test");
872 test!("test.rs", "/test/test.rs", "/test");
873 test!("file.txt", "/test/file.txt", "/test");
874
875 test!("/test/lib.rs", "/test/lib.rs", "/test");
876 test!("/test/test.rs", "/test/test.rs", "/test");
877 test!("/test/file.txt", "/test/file.txt", "/test");
878 }
879 )
880 }
881
882 #[gpui::test]
883 async fn worktree_file_preferred(cx: &mut TestAppContext) {
884 test_path_likes!(
885 cx,
886 vec![
887 (
888 path!("/"),
889 json!({
890 "file.txt": "",
891 }),
892 ),
893 (
894 path!("/test"),
895 json!({
896 "file.txt": "",
897 }),
898 ),
899 ],
900 vec![path!("/test")],
901 {
902 test!("file.txt", "/test/file.txt", "/test");
903 }
904 )
905 }
906
907 mod issues {
908 use super::*;
909
910 // https://github.com/zed-industries/zed/issues/28407
911 #[gpui::test]
912 async fn issue_28407_siblings(cx: &mut TestAppContext) {
913 test_path_likes!(
914 cx,
915 vec![(
916 path!("/dir1"),
917 json!({
918 "dir 2": {
919 "C.py": ""
920 },
921 "dir 3": {
922 "C.py": ""
923 },
924 }),
925 )],
926 vec![path!("/dir1")],
927 {
928 test!("C.py", "/dir1/dir 2/C.py", "/dir1", WorktreeScan);
929 test!("C.py", "/dir1/dir 2/C.py", "/dir1/dir 2");
930 test!("C.py", "/dir1/dir 3/C.py", "/dir1/dir 3");
931 }
932 )
933 }
934
935 // https://github.com/zed-industries/zed/issues/28407
936 // See https://github.com/zed-industries/zed/issues/34027
937 // See https://github.com/zed-industries/zed/issues/33498
938 #[gpui::test]
939 async fn issue_28407_nesting(cx: &mut TestAppContext) {
940 test_path_likes!(
941 cx,
942 vec![(
943 path!("/project"),
944 json!({
945 "lib": {
946 "src": {
947 "main.rs": "",
948 "only_in_lib.rs": ""
949 },
950 },
951 "src": {
952 "main.rs": ""
953 },
954 }),
955 )],
956 vec![path!("/project")],
957 {
958 test!("main.rs", "/project/src/main.rs", "/project/src");
959 test!("main.rs", "/project/lib/src/main.rs", "/project/lib/src");
960
961 test!("src/main.rs", "/project/src/main.rs", "/project");
962 test!("src/main.rs", "/project/src/main.rs", "/project/src");
963 test!("src/main.rs", "/project/lib/src/main.rs", "/project/lib");
964
965 test!("lib/src/main.rs", "/project/lib/src/main.rs", "/project");
966 test!(
967 "lib/src/main.rs",
968 "/project/lib/src/main.rs",
969 "/project/src"
970 );
971 test!(
972 "lib/src/main.rs",
973 "/project/lib/src/main.rs",
974 "/project/lib"
975 );
976 test!(
977 "lib/src/main.rs",
978 "/project/lib/src/main.rs",
979 "/project/lib/src"
980 );
981 test!(
982 "src/only_in_lib.rs",
983 "/project/lib/src/only_in_lib.rs",
984 "/project/lib/src",
985 WorktreeScan
986 );
987 }
988 )
989 }
990
991 // https://github.com/zed-industries/zed/issues/28339
992 // Note: These could all be found by WorktreeExact if we used
993 // `fs::normalize_path(&maybe_path)`
994 #[gpui::test]
995 async fn issue_28339(cx: &mut TestAppContext) {
996 test_path_likes!(
997 cx,
998 vec![(
999 path!("/tmp"),
1000 json!({
1001 "issue28339": {
1002 "foo": {
1003 "bar.txt": ""
1004 },
1005 },
1006 }),
1007 )],
1008 vec![path!("/tmp")],
1009 {
1010 test_local!(
1011 "foo/./bar.txt",
1012 "/tmp/issue28339/foo/bar.txt",
1013 "/tmp/issue28339",
1014 WorktreeExact
1015 );
1016 test_local!(
1017 "foo/../foo/bar.txt",
1018 "/tmp/issue28339/foo/bar.txt",
1019 "/tmp/issue28339",
1020 WorktreeExact
1021 );
1022 test_local!(
1023 "foo/..///foo/bar.txt",
1024 "/tmp/issue28339/foo/bar.txt",
1025 "/tmp/issue28339",
1026 WorktreeExact
1027 );
1028 test_local!(
1029 "issue28339/../issue28339/foo/../foo/bar.txt",
1030 "/tmp/issue28339/foo/bar.txt",
1031 "/tmp/issue28339",
1032 WorktreeExact
1033 );
1034 test_local!(
1035 "./bar.txt",
1036 "/tmp/issue28339/foo/bar.txt",
1037 "/tmp/issue28339/foo",
1038 WorktreeExact
1039 );
1040 test_local!(
1041 "../foo/bar.txt",
1042 "/tmp/issue28339/foo/bar.txt",
1043 "/tmp/issue28339/foo",
1044 FileSystemBackground
1045 );
1046 }
1047 )
1048 }
1049
1050 // https://github.com/zed-industries/zed/issues/28339
1051 // Note: These could all be found by WorktreeExact if we used
1052 // `fs::normalize_path(&maybe_path)`
1053 #[gpui::test]
1054 #[should_panic(expected = "Hover target should not be `None`")]
1055 async fn issue_28339_remote(cx: &mut TestAppContext) {
1056 test_path_likes!(
1057 cx,
1058 vec![(
1059 path!("/tmp"),
1060 json!({
1061 "issue28339": {
1062 "foo": {
1063 "bar.txt": ""
1064 },
1065 },
1066 }),
1067 )],
1068 vec![path!("/tmp")],
1069 {
1070 test_remote!(
1071 "foo/./bar.txt",
1072 "/tmp/issue28339/foo/bar.txt",
1073 "/tmp/issue28339"
1074 );
1075 test_remote!(
1076 "foo/../foo/bar.txt",
1077 "/tmp/issue28339/foo/bar.txt",
1078 "/tmp/issue28339"
1079 );
1080 test_remote!(
1081 "foo/..///foo/bar.txt",
1082 "/tmp/issue28339/foo/bar.txt",
1083 "/tmp/issue28339"
1084 );
1085 test_remote!(
1086 "issue28339/../issue28339/foo/../foo/bar.txt",
1087 "/tmp/issue28339/foo/bar.txt",
1088 "/tmp/issue28339"
1089 );
1090 test_remote!(
1091 "./bar.txt",
1092 "/tmp/issue28339/foo/bar.txt",
1093 "/tmp/issue28339/foo"
1094 );
1095 test_remote!(
1096 "../foo/bar.txt",
1097 "/tmp/issue28339/foo/bar.txt",
1098 "/tmp/issue28339/foo"
1099 );
1100 }
1101 )
1102 }
1103
1104 // https://github.com/zed-industries/zed/issues/34027
1105 #[gpui::test]
1106 async fn issue_34027(cx: &mut TestAppContext) {
1107 test_path_likes!(
1108 cx,
1109 vec![(
1110 path!("/tmp/issue34027"),
1111 json!({
1112 "test.txt": "",
1113 "foo": {
1114 "test.txt": "",
1115 }
1116 }),
1117 ),],
1118 vec![path!("/tmp/issue34027")],
1119 {
1120 test!("test.txt", "/tmp/issue34027/test.txt", "/tmp/issue34027");
1121 test!(
1122 "test.txt",
1123 "/tmp/issue34027/foo/test.txt",
1124 "/tmp/issue34027/foo"
1125 );
1126 }
1127 )
1128 }
1129
1130 // https://github.com/zed-industries/zed/issues/34027
1131 #[gpui::test]
1132 async fn issue_34027_siblings(cx: &mut TestAppContext) {
1133 test_path_likes!(
1134 cx,
1135 vec![(
1136 path!("/test"),
1137 json!({
1138 "sub1": {
1139 "file.txt": "",
1140 },
1141 "sub2": {
1142 "file.txt": "",
1143 }
1144 }),
1145 ),],
1146 vec![path!("/test")],
1147 {
1148 test!("file.txt", "/test/sub1/file.txt", "/test/sub1");
1149 test!("file.txt", "/test/sub2/file.txt", "/test/sub2");
1150 test!("sub1/file.txt", "/test/sub1/file.txt", "/test/sub1");
1151 test!("sub2/file.txt", "/test/sub2/file.txt", "/test/sub2");
1152 test!("sub1/file.txt", "/test/sub1/file.txt", "/test/sub2");
1153 test!("sub2/file.txt", "/test/sub2/file.txt", "/test/sub1");
1154 }
1155 )
1156 }
1157
1158 // https://github.com/zed-industries/zed/issues/34027
1159 #[gpui::test]
1160 async fn issue_34027_nesting(cx: &mut TestAppContext) {
1161 test_path_likes!(
1162 cx,
1163 vec![(
1164 path!("/test"),
1165 json!({
1166 "sub1": {
1167 "file.txt": "",
1168 "subsub1": {
1169 "file.txt": "",
1170 }
1171 },
1172 "sub2": {
1173 "file.txt": "",
1174 "subsub1": {
1175 "file.txt": "",
1176 }
1177 }
1178 }),
1179 ),],
1180 vec![path!("/test")],
1181 {
1182 test!(
1183 "file.txt",
1184 "/test/sub1/subsub1/file.txt",
1185 "/test/sub1/subsub1"
1186 );
1187 test!(
1188 "file.txt",
1189 "/test/sub2/subsub1/file.txt",
1190 "/test/sub2/subsub1"
1191 );
1192 test!(
1193 "subsub1/file.txt",
1194 "/test/sub1/subsub1/file.txt",
1195 "/test",
1196 WorktreeScan
1197 );
1198 test!(
1199 "subsub1/file.txt",
1200 "/test/sub1/subsub1/file.txt",
1201 "/test",
1202 WorktreeScan
1203 );
1204 test!(
1205 "subsub1/file.txt",
1206 "/test/sub1/subsub1/file.txt",
1207 "/test/sub1"
1208 );
1209 test!(
1210 "subsub1/file.txt",
1211 "/test/sub2/subsub1/file.txt",
1212 "/test/sub2"
1213 );
1214 test!(
1215 "subsub1/file.txt",
1216 "/test/sub1/subsub1/file.txt",
1217 "/test/sub1/subsub1",
1218 WorktreeScan
1219 );
1220 }
1221 )
1222 }
1223
1224 // https://github.com/zed-industries/zed/issues/34027
1225 #[gpui::test]
1226 async fn issue_34027_non_worktree_local_file(cx: &mut TestAppContext) {
1227 test_path_likes!(
1228 cx,
1229 vec![
1230 (
1231 path!("/"),
1232 json!({
1233 "file.txt": "",
1234 }),
1235 ),
1236 (
1237 path!("/test"),
1238 json!({
1239 "file.txt": "",
1240 }),
1241 ),
1242 ],
1243 vec![path!("/test")],
1244 {
1245 // Note: Opening a non-worktree file adds that file as a single file worktree.
1246 test_local!("file.txt", "/file.txt", "/", FileSystemBackground);
1247 }
1248 )
1249 }
1250
1251 // https://github.com/zed-industries/zed/issues/34027
1252 #[gpui::test]
1253 async fn issue_34027_non_worktree_remote_file(cx: &mut TestAppContext) {
1254 test_path_likes!(
1255 cx,
1256 vec![
1257 (
1258 path!("/"),
1259 json!({
1260 "file.txt": "",
1261 }),
1262 ),
1263 (
1264 path!("/test"),
1265 json!({
1266 "file.txt": "",
1267 }),
1268 ),
1269 ],
1270 vec![path!("/test")],
1271 {
1272 // Note: Opening a non-worktree file adds that file as a single file worktree.
1273 test_remote!("file.txt", "/test/file.txt", "/");
1274 test_remote!("/test/file.txt", "/test/file.txt", "/");
1275 }
1276 )
1277 }
1278
1279 // See https://github.com/zed-industries/zed/issues/34027
1280 #[gpui::test]
1281 #[should_panic(expected = "Tooltip mismatch")]
1282 async fn issue_34027_gaps(cx: &mut TestAppContext) {
1283 test_path_likes!(
1284 cx,
1285 vec![(
1286 path!("/project"),
1287 json!({
1288 "lib": {
1289 "src": {
1290 "main.rs": ""
1291 },
1292 },
1293 "src": {
1294 "main.rs": ""
1295 },
1296 }),
1297 )],
1298 vec![path!("/project")],
1299 {
1300 test!("main.rs", "/project/src/main.rs", "/project");
1301 test!("main.rs", "/project/lib/src/main.rs", "/project/lib");
1302 }
1303 )
1304 }
1305
1306 // See https://github.com/zed-industries/zed/issues/34027
1307 #[gpui::test]
1308 #[should_panic(expected = "Tooltip mismatch")]
1309 async fn issue_34027_overlap(cx: &mut TestAppContext) {
1310 test_path_likes!(
1311 cx,
1312 vec![(
1313 path!("/project"),
1314 json!({
1315 "lib": {
1316 "src": {
1317 "main.rs": ""
1318 },
1319 },
1320 "src": {
1321 "main.rs": ""
1322 },
1323 }),
1324 )],
1325 vec![path!("/project")],
1326 {
1327 // Finds "/project/src/main.rs"
1328 test!(
1329 "src/main.rs",
1330 "/project/lib/src/main.rs",
1331 "/project/lib/src"
1332 );
1333 }
1334 )
1335 }
1336 }
1337}