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