terminal_path_like_target.rs

   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::{
 521        HoveredWord, TerminalBuilder,
 522        alacritty_terminal::index::Point as AlacPoint,
 523        terminal_settings::{AlternateScroll, CursorShape},
 524    };
 525    use util::path;
 526    use workspace::AppState;
 527
 528    async fn init_test(
 529        app_cx: &mut TestAppContext,
 530        trees: impl IntoIterator<Item = (&str, serde_json::Value)>,
 531        worktree_roots: impl IntoIterator<Item = &str>,
 532    ) -> impl AsyncFnMut(
 533        HoveredWord,
 534        PathLikeTarget,
 535        BackgroundFsChecks,
 536    ) -> (Option<HoverTarget>, Option<OpenTarget>) {
 537        let fs = app_cx.update(AppState::test).fs.as_fake().clone();
 538
 539        app_cx.update(|cx| {
 540            theme::init(theme::LoadThemes::JustBase, cx);
 541            editor::init(cx);
 542        });
 543
 544        for (path, tree) in trees {
 545            fs.insert_tree(path, tree).await;
 546        }
 547
 548        let project: gpui::Entity<Project> = Project::test(
 549            fs.clone(),
 550            worktree_roots.into_iter().map(Path::new),
 551            app_cx,
 552        )
 553        .await;
 554
 555        let (workspace, _cx) =
 556            app_cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 557
 558        let terminal = app_cx.new(|cx| {
 559            TerminalBuilder::new_display_only(
 560                CursorShape::default(),
 561                AlternateScroll::On,
 562                None,
 563                0,
 564                cx.background_executor(),
 565                PathStyle::local(),
 566            )
 567            .expect("Failed to create display-only terminal")
 568            .subscribe(cx)
 569        });
 570
 571        let workspace_a = workspace.clone();
 572        let (terminal_view, cx) = app_cx.add_window_view(|window, cx| {
 573            TerminalView::new(
 574                terminal,
 575                workspace_a.downgrade(),
 576                None,
 577                project.downgrade(),
 578                window,
 579                cx,
 580            )
 581        });
 582
 583        async move |hovered_word: HoveredWord,
 584                    path_like_target: PathLikeTarget,
 585                    background_fs_checks: BackgroundFsChecks|
 586                    -> (Option<HoverTarget>, Option<OpenTarget>) {
 587            let workspace_a = workspace.clone();
 588            terminal_view
 589                .update(cx, |_, cx| {
 590                    possible_hover_target(
 591                        &workspace_a.downgrade(),
 592                        hovered_word,
 593                        &path_like_target,
 594                        cx,
 595                        background_fs_checks,
 596                    )
 597                })
 598                .await;
 599
 600            let hover_target =
 601                terminal_view.read_with(cx, |terminal_view, _| terminal_view.hover.clone());
 602
 603            let open_target = terminal_view
 604                .update_in(cx, |terminal_view, window, cx| {
 605                    possibly_open_target(
 606                        &workspace.downgrade(),
 607                        terminal_view,
 608                        &path_like_target,
 609                        window,
 610                        cx,
 611                        background_fs_checks,
 612                    )
 613                })
 614                .await
 615                .expect("Failed to possibly open target");
 616
 617            (hover_target, open_target)
 618        }
 619    }
 620
 621    async fn test_path_like_simple(
 622        test_path_like: &mut impl AsyncFnMut(
 623            HoveredWord,
 624            PathLikeTarget,
 625            BackgroundFsChecks,
 626        ) -> (Option<HoverTarget>, Option<OpenTarget>),
 627        maybe_path: &str,
 628        tooltip: &str,
 629        terminal_dir: Option<PathBuf>,
 630        background_fs_checks: BackgroundFsChecks,
 631        mut open_target_found_by: OpenTargetFoundBy,
 632        file: &str,
 633        line: u32,
 634    ) {
 635        let (hover_target, open_target) = test_path_like(
 636            HoveredWord {
 637                word: maybe_path.to_string(),
 638                word_match: AlacPoint::default()..=AlacPoint::default(),
 639                id: 0,
 640            },
 641            PathLikeTarget {
 642                maybe_path: maybe_path.to_string(),
 643                terminal_dir,
 644            },
 645            background_fs_checks,
 646        )
 647        .await;
 648
 649        let Some(hover_target) = hover_target else {
 650            assert!(
 651                hover_target.is_some(),
 652                "Hover target should not be `None` at {file}:{line}:"
 653            );
 654            return;
 655        };
 656
 657        assert_eq!(
 658            hover_target.tooltip, tooltip,
 659            "Tooltip mismatch at {file}:{line}:"
 660        );
 661        assert_eq!(
 662            hover_target.hovered_word.word, maybe_path,
 663            "Hovered word mismatch at {file}:{line}:"
 664        );
 665
 666        let Some(open_target) = open_target else {
 667            assert!(
 668                open_target.is_some(),
 669                "Open target should not be `None` at {file}:{line}:"
 670            );
 671            return;
 672        };
 673
 674        assert_eq!(
 675            open_target.path().path,
 676            Path::new(tooltip),
 677            "Open target path mismatch at {file}:{line}:"
 678        );
 679
 680        if background_fs_checks == BackgroundFsChecks::Disabled
 681            && open_target_found_by == OpenTargetFoundBy::FileSystemBackground
 682        {
 683            open_target_found_by = OpenTargetFoundBy::WorktreeScan;
 684        }
 685
 686        assert_eq!(
 687            open_target.found_by(),
 688            open_target_found_by,
 689            "Open target found by mismatch at {file}:{line}:"
 690        );
 691    }
 692
 693    macro_rules! none_or_some_pathbuf {
 694        (None) => {
 695            None
 696        };
 697        ($cwd:literal) => {
 698            Some($crate::PathBuf::from(path!($cwd)))
 699        };
 700    }
 701
 702    macro_rules! test_path_like {
 703        (
 704            $test_path_like:expr,
 705            $maybe_path:literal,
 706            $tooltip:literal,
 707            $cwd:tt,
 708            $found_by:expr
 709        ) => {{
 710            test_path_like!(
 711                $test_path_like,
 712                $maybe_path,
 713                $tooltip,
 714                $cwd,
 715                BackgroundFsChecks::Enabled,
 716                $found_by
 717            );
 718            test_path_like!(
 719                $test_path_like,
 720                $maybe_path,
 721                $tooltip,
 722                $cwd,
 723                BackgroundFsChecks::Disabled,
 724                $found_by
 725            );
 726        }};
 727
 728        (
 729            $test_path_like:expr,
 730            $maybe_path:literal,
 731            $tooltip:literal,
 732            $cwd:tt,
 733            $background_fs_checks:path,
 734            $found_by:expr
 735        ) => {
 736            test_path_like_simple(
 737                &mut $test_path_like,
 738                path!($maybe_path),
 739                path!($tooltip),
 740                none_or_some_pathbuf!($cwd),
 741                $background_fs_checks,
 742                $found_by,
 743                std::file!(),
 744                std::line!(),
 745            )
 746            .await
 747        };
 748    }
 749
 750    // Note the arms of `test`, `test_local`, and `test_remote` should be collapsed once macro
 751    // metavariable expressions (#![feature(macro_metavar_expr)]) are stabilized.
 752    // See https://github.com/rust-lang/rust/issues/83527
 753    #[doc = "test_path_likes!(<cx>, <trees>, <worktrees>, { $(<tests>;)+ })"]
 754    macro_rules! test_path_likes {
 755        ($cx:expr, $trees:expr, $worktrees:expr, { $($tests:expr;)+ }) => { {
 756            let mut test_path_like = init_test($cx, $trees, $worktrees).await;
 757            #[doc ="test!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
 758            #[doc ="\\[, found by \\])"]
 759            #[allow(unused_macros)]
 760            macro_rules! test {
 761                ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
 762                    test_path_like!(
 763                        test_path_like,
 764                        $maybe_path,
 765                        $tooltip,
 766                        $cwd,
 767                        OpenTargetFoundBy::WorktreeExact
 768                    )
 769                };
 770                ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
 771                    test_path_like!(
 772                        test_path_like,
 773                        $maybe_path,
 774                        $tooltip,
 775                        $cwd,
 776                        OpenTargetFoundBy::$found_by
 777                    )
 778                }
 779            }
 780            #[doc ="test_local!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
 781            #[doc ="\\[, found by \\])"]
 782            #[allow(unused_macros)]
 783            macro_rules! test_local {
 784                ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
 785                    test_path_like!(
 786                        test_path_like,
 787                        $maybe_path,
 788                        $tooltip,
 789                        $cwd,
 790                        BackgroundFsChecks::Enabled,
 791                        OpenTargetFoundBy::WorktreeExact
 792                    )
 793                };
 794                ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
 795                    test_path_like!(
 796                        test_path_like,
 797                        $maybe_path,
 798                        $tooltip,
 799                        $cwd,
 800                        BackgroundFsChecks::Enabled,
 801                        OpenTargetFoundBy::$found_by
 802                    )
 803                }
 804            }
 805            #[doc ="test_remote!(<hovered maybe_path>, <expected tooltip>, <terminal cwd> "]
 806            #[doc ="\\[, found by \\])"]
 807            #[allow(unused_macros)]
 808            macro_rules! test_remote {
 809                ($maybe_path:literal, $tooltip:literal, $cwd:tt) => {
 810                    test_path_like!(
 811                        test_path_like,
 812                        $maybe_path,
 813                        $tooltip,
 814                        $cwd,
 815                        BackgroundFsChecks::Disabled,
 816                        OpenTargetFoundBy::WorktreeExact
 817                    )
 818                };
 819                ($maybe_path:literal, $tooltip:literal, $cwd:tt, $found_by:ident) => {
 820                    test_path_like!(
 821                        test_path_like,
 822                        $maybe_path,
 823                        $tooltip,
 824                        $cwd,
 825                        BackgroundFsChecks::Disabled,
 826                        OpenTargetFoundBy::$found_by
 827                    )
 828                }
 829            }
 830            $($tests);+
 831        } }
 832    }
 833
 834    #[gpui::test]
 835    async fn one_folder_worktree(cx: &mut TestAppContext) {
 836        test_path_likes!(
 837            cx,
 838            vec![(
 839                path!("/test"),
 840                json!({
 841                    "lib.rs": "",
 842                    "test.rs": "",
 843                }),
 844            )],
 845            vec![path!("/test")],
 846            {
 847                test!("lib.rs", "/test/lib.rs", None);
 848                test!("/test/lib.rs", "/test/lib.rs", None);
 849                test!("test.rs", "/test/test.rs", None);
 850                test!("/test/test.rs", "/test/test.rs", None);
 851            }
 852        )
 853    }
 854
 855    #[gpui::test]
 856    async fn mixed_worktrees(cx: &mut TestAppContext) {
 857        test_path_likes!(
 858            cx,
 859            vec![
 860                (
 861                    path!("/"),
 862                    json!({
 863                        "file.txt": "",
 864                    }),
 865                ),
 866                (
 867                    path!("/test"),
 868                    json!({
 869                        "lib.rs": "",
 870                        "test.rs": "",
 871                        "file.txt": "",
 872                    }),
 873                ),
 874            ],
 875            vec![path!("/file.txt"), path!("/test")],
 876            {
 877                test!("file.txt", "/file.txt", "/");
 878                test!("/file.txt", "/file.txt", "/");
 879
 880                test!("lib.rs", "/test/lib.rs", "/test");
 881                test!("test.rs", "/test/test.rs", "/test");
 882                test!("file.txt", "/test/file.txt", "/test");
 883
 884                test!("/test/lib.rs", "/test/lib.rs", "/test");
 885                test!("/test/test.rs", "/test/test.rs", "/test");
 886                test!("/test/file.txt", "/test/file.txt", "/test");
 887            }
 888        )
 889    }
 890
 891    #[gpui::test]
 892    async fn worktree_file_preferred(cx: &mut TestAppContext) {
 893        test_path_likes!(
 894            cx,
 895            vec![
 896                (
 897                    path!("/"),
 898                    json!({
 899                        "file.txt": "",
 900                    }),
 901                ),
 902                (
 903                    path!("/test"),
 904                    json!({
 905                        "file.txt": "",
 906                    }),
 907                ),
 908            ],
 909            vec![path!("/test")],
 910            {
 911                test!("file.txt", "/test/file.txt", "/test");
 912            }
 913        )
 914    }
 915
 916    mod issues {
 917        use super::*;
 918
 919        // https://github.com/zed-industries/zed/issues/28407
 920        #[gpui::test]
 921        async fn issue_28407_siblings(cx: &mut TestAppContext) {
 922            test_path_likes!(
 923                cx,
 924                vec![(
 925                    path!("/dir1"),
 926                    json!({
 927                        "dir 2": {
 928                            "C.py": ""
 929                        },
 930                        "dir 3": {
 931                            "C.py": ""
 932                        },
 933                    }),
 934                )],
 935                vec![path!("/dir1")],
 936                {
 937                    test!("C.py", "/dir1/dir 2/C.py", "/dir1", WorktreeScan);
 938                    test!("C.py", "/dir1/dir 2/C.py", "/dir1/dir 2");
 939                    test!("C.py", "/dir1/dir 3/C.py", "/dir1/dir 3");
 940                }
 941            )
 942        }
 943
 944        // https://github.com/zed-industries/zed/issues/28407
 945        // See https://github.com/zed-industries/zed/issues/34027
 946        // See https://github.com/zed-industries/zed/issues/33498
 947        #[gpui::test]
 948        async fn issue_28407_nesting(cx: &mut TestAppContext) {
 949            test_path_likes!(
 950                cx,
 951                vec![(
 952                    path!("/project"),
 953                    json!({
 954                        "lib": {
 955                            "src": {
 956                                "main.rs": "",
 957                                "only_in_lib.rs": ""
 958                            },
 959                        },
 960                        "src": {
 961                            "main.rs": ""
 962                        },
 963                    }),
 964                )],
 965                vec![path!("/project")],
 966                {
 967                    test!("main.rs", "/project/src/main.rs", "/project/src");
 968                    test!("main.rs", "/project/lib/src/main.rs", "/project/lib/src");
 969
 970                    test!("src/main.rs", "/project/src/main.rs", "/project");
 971                    test!("src/main.rs", "/project/src/main.rs", "/project/src");
 972                    test!("src/main.rs", "/project/lib/src/main.rs", "/project/lib");
 973
 974                    test!("lib/src/main.rs", "/project/lib/src/main.rs", "/project");
 975                    test!(
 976                        "lib/src/main.rs",
 977                        "/project/lib/src/main.rs",
 978                        "/project/src"
 979                    );
 980                    test!(
 981                        "lib/src/main.rs",
 982                        "/project/lib/src/main.rs",
 983                        "/project/lib"
 984                    );
 985                    test!(
 986                        "lib/src/main.rs",
 987                        "/project/lib/src/main.rs",
 988                        "/project/lib/src"
 989                    );
 990                    test!(
 991                        "src/only_in_lib.rs",
 992                        "/project/lib/src/only_in_lib.rs",
 993                        "/project/lib/src",
 994                        WorktreeScan
 995                    );
 996                }
 997            )
 998        }
 999
1000        // https://github.com/zed-industries/zed/issues/28339
1001        // Note: These could all be found by WorktreeExact if we used
1002        // `fs::normalize_path(&maybe_path)`
1003        #[gpui::test]
1004        async fn issue_28339(cx: &mut TestAppContext) {
1005            test_path_likes!(
1006                cx,
1007                vec![(
1008                    path!("/tmp"),
1009                    json!({
1010                        "issue28339": {
1011                            "foo": {
1012                                "bar.txt": ""
1013                            },
1014                        },
1015                    }),
1016                )],
1017                vec![path!("/tmp")],
1018                {
1019                    test_local!(
1020                        "foo/./bar.txt",
1021                        "/tmp/issue28339/foo/bar.txt",
1022                        "/tmp/issue28339",
1023                        WorktreeExact
1024                    );
1025                    test_local!(
1026                        "foo/../foo/bar.txt",
1027                        "/tmp/issue28339/foo/bar.txt",
1028                        "/tmp/issue28339",
1029                        WorktreeExact
1030                    );
1031                    test_local!(
1032                        "foo/..///foo/bar.txt",
1033                        "/tmp/issue28339/foo/bar.txt",
1034                        "/tmp/issue28339",
1035                        WorktreeExact
1036                    );
1037                    test_local!(
1038                        "issue28339/../issue28339/foo/../foo/bar.txt",
1039                        "/tmp/issue28339/foo/bar.txt",
1040                        "/tmp/issue28339",
1041                        WorktreeExact
1042                    );
1043                    test_local!(
1044                        "./bar.txt",
1045                        "/tmp/issue28339/foo/bar.txt",
1046                        "/tmp/issue28339/foo",
1047                        WorktreeExact
1048                    );
1049                    test_local!(
1050                        "../foo/bar.txt",
1051                        "/tmp/issue28339/foo/bar.txt",
1052                        "/tmp/issue28339/foo",
1053                        FileSystemBackground
1054                    );
1055                }
1056            )
1057        }
1058
1059        // https://github.com/zed-industries/zed/issues/28339
1060        // Note: These could all be found by WorktreeExact if we used
1061        // `fs::normalize_path(&maybe_path)`
1062        #[gpui::test]
1063        #[should_panic(expected = "Hover target should not be `None`")]
1064        async fn issue_28339_remote(cx: &mut TestAppContext) {
1065            test_path_likes!(
1066                cx,
1067                vec![(
1068                    path!("/tmp"),
1069                    json!({
1070                        "issue28339": {
1071                            "foo": {
1072                                "bar.txt": ""
1073                            },
1074                        },
1075                    }),
1076                )],
1077                vec![path!("/tmp")],
1078                {
1079                    test_remote!(
1080                        "foo/./bar.txt",
1081                        "/tmp/issue28339/foo/bar.txt",
1082                        "/tmp/issue28339"
1083                    );
1084                    test_remote!(
1085                        "foo/../foo/bar.txt",
1086                        "/tmp/issue28339/foo/bar.txt",
1087                        "/tmp/issue28339"
1088                    );
1089                    test_remote!(
1090                        "foo/..///foo/bar.txt",
1091                        "/tmp/issue28339/foo/bar.txt",
1092                        "/tmp/issue28339"
1093                    );
1094                    test_remote!(
1095                        "issue28339/../issue28339/foo/../foo/bar.txt",
1096                        "/tmp/issue28339/foo/bar.txt",
1097                        "/tmp/issue28339"
1098                    );
1099                    test_remote!(
1100                        "./bar.txt",
1101                        "/tmp/issue28339/foo/bar.txt",
1102                        "/tmp/issue28339/foo"
1103                    );
1104                    test_remote!(
1105                        "../foo/bar.txt",
1106                        "/tmp/issue28339/foo/bar.txt",
1107                        "/tmp/issue28339/foo"
1108                    );
1109                }
1110            )
1111        }
1112
1113        // https://github.com/zed-industries/zed/issues/34027
1114        #[gpui::test]
1115        async fn issue_34027(cx: &mut TestAppContext) {
1116            test_path_likes!(
1117                cx,
1118                vec![(
1119                    path!("/tmp/issue34027"),
1120                    json!({
1121                        "test.txt": "",
1122                        "foo": {
1123                            "test.txt": "",
1124                        }
1125                    }),
1126                ),],
1127                vec![path!("/tmp/issue34027")],
1128                {
1129                    test!("test.txt", "/tmp/issue34027/test.txt", "/tmp/issue34027");
1130                    test!(
1131                        "test.txt",
1132                        "/tmp/issue34027/foo/test.txt",
1133                        "/tmp/issue34027/foo"
1134                    );
1135                }
1136            )
1137        }
1138
1139        // https://github.com/zed-industries/zed/issues/34027
1140        #[gpui::test]
1141        async fn issue_34027_siblings(cx: &mut TestAppContext) {
1142            test_path_likes!(
1143                cx,
1144                vec![(
1145                    path!("/test"),
1146                    json!({
1147                        "sub1": {
1148                            "file.txt": "",
1149                        },
1150                        "sub2": {
1151                            "file.txt": "",
1152                        }
1153                    }),
1154                ),],
1155                vec![path!("/test")],
1156                {
1157                    test!("file.txt", "/test/sub1/file.txt", "/test/sub1");
1158                    test!("file.txt", "/test/sub2/file.txt", "/test/sub2");
1159                    test!("sub1/file.txt", "/test/sub1/file.txt", "/test/sub1");
1160                    test!("sub2/file.txt", "/test/sub2/file.txt", "/test/sub2");
1161                    test!("sub1/file.txt", "/test/sub1/file.txt", "/test/sub2");
1162                    test!("sub2/file.txt", "/test/sub2/file.txt", "/test/sub1");
1163                }
1164            )
1165        }
1166
1167        // https://github.com/zed-industries/zed/issues/34027
1168        #[gpui::test]
1169        async fn issue_34027_nesting(cx: &mut TestAppContext) {
1170            test_path_likes!(
1171                cx,
1172                vec![(
1173                    path!("/test"),
1174                    json!({
1175                        "sub1": {
1176                            "file.txt": "",
1177                            "subsub1": {
1178                                "file.txt": "",
1179                            }
1180                        },
1181                        "sub2": {
1182                            "file.txt": "",
1183                            "subsub1": {
1184                                "file.txt": "",
1185                            }
1186                        }
1187                    }),
1188                ),],
1189                vec![path!("/test")],
1190                {
1191                    test!(
1192                        "file.txt",
1193                        "/test/sub1/subsub1/file.txt",
1194                        "/test/sub1/subsub1"
1195                    );
1196                    test!(
1197                        "file.txt",
1198                        "/test/sub2/subsub1/file.txt",
1199                        "/test/sub2/subsub1"
1200                    );
1201                    test!(
1202                        "subsub1/file.txt",
1203                        "/test/sub1/subsub1/file.txt",
1204                        "/test",
1205                        WorktreeScan
1206                    );
1207                    test!(
1208                        "subsub1/file.txt",
1209                        "/test/sub1/subsub1/file.txt",
1210                        "/test",
1211                        WorktreeScan
1212                    );
1213                    test!(
1214                        "subsub1/file.txt",
1215                        "/test/sub1/subsub1/file.txt",
1216                        "/test/sub1"
1217                    );
1218                    test!(
1219                        "subsub1/file.txt",
1220                        "/test/sub2/subsub1/file.txt",
1221                        "/test/sub2"
1222                    );
1223                    test!(
1224                        "subsub1/file.txt",
1225                        "/test/sub1/subsub1/file.txt",
1226                        "/test/sub1/subsub1",
1227                        WorktreeScan
1228                    );
1229                }
1230            )
1231        }
1232
1233        // https://github.com/zed-industries/zed/issues/34027
1234        #[gpui::test]
1235        async fn issue_34027_non_worktree_local_file(cx: &mut TestAppContext) {
1236            test_path_likes!(
1237                cx,
1238                vec![
1239                    (
1240                        path!("/"),
1241                        json!({
1242                            "file.txt": "",
1243                        }),
1244                    ),
1245                    (
1246                        path!("/test"),
1247                        json!({
1248                            "file.txt": "",
1249                        }),
1250                    ),
1251                ],
1252                vec![path!("/test")],
1253                {
1254                    // Note: Opening a non-worktree file adds that file as a single file worktree.
1255                    test_local!("file.txt", "/file.txt", "/", FileSystemBackground);
1256                }
1257            )
1258        }
1259
1260        // https://github.com/zed-industries/zed/issues/34027
1261        #[gpui::test]
1262        async fn issue_34027_non_worktree_remote_file(cx: &mut TestAppContext) {
1263            test_path_likes!(
1264                cx,
1265                vec![
1266                    (
1267                        path!("/"),
1268                        json!({
1269                            "file.txt": "",
1270                        }),
1271                    ),
1272                    (
1273                        path!("/test"),
1274                        json!({
1275                            "file.txt": "",
1276                        }),
1277                    ),
1278                ],
1279                vec![path!("/test")],
1280                {
1281                    // Note: Opening a non-worktree file adds that file as a single file worktree.
1282                    test_remote!("file.txt", "/test/file.txt", "/");
1283                    test_remote!("/test/file.txt", "/test/file.txt", "/");
1284                }
1285            )
1286        }
1287
1288        // See https://github.com/zed-industries/zed/issues/34027
1289        #[gpui::test]
1290        #[should_panic(expected = "Tooltip mismatch")]
1291        async fn issue_34027_gaps(cx: &mut TestAppContext) {
1292            test_path_likes!(
1293                cx,
1294                vec![(
1295                    path!("/project"),
1296                    json!({
1297                        "lib": {
1298                            "src": {
1299                                "main.rs": ""
1300                            },
1301                        },
1302                        "src": {
1303                            "main.rs": ""
1304                        },
1305                    }),
1306                )],
1307                vec![path!("/project")],
1308                {
1309                    test!("main.rs", "/project/src/main.rs", "/project");
1310                    test!("main.rs", "/project/lib/src/main.rs", "/project/lib");
1311                }
1312            )
1313        }
1314
1315        // See https://github.com/zed-industries/zed/issues/34027
1316        #[gpui::test]
1317        #[should_panic(expected = "Tooltip mismatch")]
1318        async fn issue_34027_overlap(cx: &mut TestAppContext) {
1319            test_path_likes!(
1320                cx,
1321                vec![(
1322                    path!("/project"),
1323                    json!({
1324                        "lib": {
1325                            "src": {
1326                                "main.rs": ""
1327                            },
1328                        },
1329                        "src": {
1330                            "main.rs": ""
1331                        },
1332                    }),
1333                )],
1334                vec![path!("/project")],
1335                {
1336                    // Finds "/project/src/main.rs"
1337                    test!(
1338                        "src/main.rs",
1339                        "/project/lib/src/main.rs",
1340                        "/project/lib/src"
1341                    );
1342                }
1343            )
1344        }
1345    }
1346}