Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
editor: Fix off by one in Open Docs action (#64317)
xdBronch8385157b2f35
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rsindex 917a70e5ab0..6b7e23c0431 100644--- a/crates/editor/src/editor_tests.rs+++ b/crates/editor/src/editor_tests.rs@@ -46,6 +46,7 @@ use project::{FakeFs, Project, ProjectPath,bookmark_store::{BookmarkStore, BookmarkStoreEvent, SerializedBookmark},debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},+ lsp_store::lsp_ext_command::{DocsUrls, LspOpenDocs},project_settings::LspSettings,trusted_worktrees::{PathTrust, TrustedWorktrees},};@@ -69,7 +70,7 @@ use unindent::Unindent;use util::{assert_set_eq, path,rel_path::rel_path,- test::{TextRangeMarker, marked_text_ranges, marked_text_ranges_by, sample_text},+ test::{TempTree, TextRangeMarker, marked_text_ranges, marked_text_ranges_by, sample_text},};use workspace::{CloseActiveItem, CloseAllItems, CloseOtherItems, MultiWorkspace, NavigationEntry, OpenOptions,@@ -49537,6 +49538,79 @@ async fn test_scroll_range_hold_freezes_before_first_settled_frame(cx: &mut Test});}+#[gpui::test]+async fn test_open_docs(cx: &mut TestAppContext) {+ init_test(cx, |_| {});+ let docs_urls = Arc::new(Mutex::new(DocsUrls::default()));+ let mut cx = EditorLspTestContext::new_with_adapter(+ Arc::into_inner(rust_lang()).expect("Rust language should have a single owner"),+ FakeLspAdapter {+ name: "rust-analyzer",+ initializer: Some(Box::new({+ let docs_urls = docs_urls.clone();+ move |server| {+ let docs_urls = docs_urls.clone();+ server.set_request_handler::<LspOpenDocs, _, _>(move |_, _| {+ let response = std::mem::take(&mut *docs_urls.lock());+ async move { Ok(Some(response)) }+ });+ }+ })),+ ..FakeLspAdapter::default()+ },+ cx,+ )+ .await;+ cx.set_state("fn «mainˇ»() {}");++ let tree = TempTree::new(json!({+ "index.html": "",+ "docs é # %20": { "struct.Example.html": "" }+ }));+ let root_url = url::Url::from_directory_path(tree.path())+ .expect("temporary directory should have a file URL");+ let local_url = format!("{root_url}index.html");+ let encoded_url = format!("{root_url}docs%20%C3%A9%20%23%20%2520/struct.Example.html");++ cx.dispatch_action(OpenDocs);+ cx.run_until_parked();+ assert_eq!(cx.opened_url(), None);++ for (index, (local, prefer_local)) in [+ (Some(local_url.clone()), true),+ (Some(encoded_url.clone()), true),+ (Some(format!("{local_url}#method.example")), true),+ (+ Some(format!("{encoded_url}?search=a%20b#method.example")),+ true,+ ),+ (Some(format!("{root_url}missing.html")), false),+ (None, false),+ (Some(String::new()), false),+ (Some("other:é".to_owned()), false),+ (Some("file://[invalid".to_owned()), false),+ (Some(local_url.replacen("file:", "other:", 1)), false),+ (Some(format!("{local_url}%00")), false),+ ]+ .into_iter()+ .enumerate()+ {+ let web = format!("https://docs.rs/example/{index}/example/struct.Example.html");+ let expected_url = if prefer_local {+ local.clone().expect("local documentation URL should exist")+ } else {+ web.clone()+ };+ *docs_urls.lock() = DocsUrls {+ local,+ web: Some(web),+ };+ cx.dispatch_action(OpenDocs);+ cx.run_until_parked();+ assert_eq!(cx.opened_url(), Some(expected_url), "case {index}");+ }+}+#[gpui::test]async fn test_lsp_show_document(cx: &mut TestAppContext) {init_test(cx, |_| {});diff --git a/crates/editor/src/rust_analyzer_ext.rs b/crates/editor/src/rust_analyzer_ext.rsindex b65a5082e9f..ec714a96f26 100644--- a/crates/editor/src/rust_analyzer_ext.rs+++ b/crates/editor/src/rust_analyzer_ext.rs@@ -1,4 +1,4 @@-use std::{fs, path::Path};+use std::fs;use anyhow::Context as _;use gpui::{App, AppContext as _, Context, Entity, TaskExt, Window};@@ -14,6 +14,7 @@ use project::{};use rpc::proto;use text::ToPointUtf16;+use url::Url;use crate::{CancelFlycheck, ClearFlycheck, Editor, ExpandMacroRecursively, GoToParentModule,@@ -300,18 +301,23 @@ pub fn open_docs(editor: &mut Editor, _: &OpenDocs, window: &mut Window, cx: &mureturn Ok(());}- workspace.update(cx, |_workspace, cx| {- // Check if the local document exists, otherwise fallback to the online document.- // Open with the default browser.- if let Some(local_url) = docs_urls.local- && fs::metadata(Path::new(&local_url[8..])).is_ok()- {- cx.open_url(&local_url);- return;- }+ // Check if the local document exists, otherwise fallback to the online document.+ let url = if let Some(local_url) = docs_urls.local+ && let Ok(url) = Url::parse(&local_url)+ && url.scheme() == "file"+ && let Ok(path) = url.to_file_path()+ && cx+ .background_spawn(async move { fs::metadata(path).is_ok() })+ .await+ {+ Some(local_url)+ } else {+ docs_urls.web+ };- if let Some(web_url) = docs_urls.web {- cx.open_url(&web_url);+ workspace.update(cx, |_workspace, cx| {+ if let Some(url) = url {+ cx.open_url(&url);}});anyhow::Ok(())diff --git a/crates/editor/src/test/editor_lsp_test_context.rs b/crates/editor/src/test/editor_lsp_test_context.rsindex b248c090e1d..7d08be60167 100644--- a/crates/editor/src/test/editor_lsp_test_context.rs+++ b/crates/editor/src/test/editor_lsp_test_context.rs@@ -50,6 +50,22 @@ impl EditorLspTestContext {language: Language,capabilities: lsp::ServerCapabilities,cx: &mut gpui::TestAppContext,+ ) -> EditorLspTestContext {+ Self::new_with_adapter(+ language,+ FakeLspAdapter {+ capabilities,+ ..FakeLspAdapter::default()+ },+ cx,+ )+ .await+ }++ pub async fn new_with_adapter(+ language: Language,+ adapter: FakeLspAdapter,+ cx: &mut gpui::TestAppContext,) -> EditorLspTestContext {let app_state = cx.update(AppState::test);@@ -70,13 +86,7 @@ impl EditorLspTestContext {let project = Project::test(app_state.fs.clone(), [], cx).await;let language_registry = project.read_with(cx, |project, _| project.languages().clone());- let mut fake_servers = language_registry.register_fake_lsp(- language.name(),- FakeLspAdapter {- capabilities,- ..Default::default()- },- );+ let mut fake_servers = language_registry.register_fake_lsp(language.name(), adapter);language_registry.add(Arc::new(language));let root = Self::root_path();