1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use gpui::{App, AsyncApp, Task};
6use http_client::github::latest_github_release;
7pub use language::*;
8use lsp::{LanguageServerBinary, LanguageServerName};
9use project::Fs;
10use regex::Regex;
11use serde_json::json;
12use smol::fs;
13use std::{
14 any::Any,
15 borrow::Cow,
16 ffi::{OsStr, OsString},
17 ops::Range,
18 path::PathBuf,
19 process::Output,
20 str,
21 sync::{
22 Arc, LazyLock,
23 atomic::{AtomicBool, Ordering::SeqCst},
24 },
25};
26use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
27use util::{ResultExt, fs::remove_matching, maybe};
28
29fn server_binary_arguments() -> Vec<OsString> {
30 vec!["-mode=stdio".into()]
31}
32
33#[derive(Copy, Clone)]
34pub struct GoLspAdapter;
35
36impl GoLspAdapter {
37 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("gopls");
38}
39
40static VERSION_REGEX: LazyLock<Regex> =
41 LazyLock::new(|| Regex::new(r"\d+\.\d+\.\d+").expect("Failed to create VERSION_REGEX"));
42
43static GO_ESCAPE_SUBTEST_NAME_REGEX: LazyLock<Regex> = LazyLock::new(|| {
44 Regex::new(r#"[.*+?^${}()|\[\]\\"']"#).expect("Failed to create GO_ESCAPE_SUBTEST_NAME_REGEX")
45});
46
47const BINARY: &str = if cfg!(target_os = "windows") {
48 "gopls.exe"
49} else {
50 "gopls"
51};
52
53#[async_trait(?Send)]
54impl super::LspAdapter for GoLspAdapter {
55 fn name(&self) -> LanguageServerName {
56 Self::SERVER_NAME
57 }
58
59 async fn fetch_latest_server_version(
60 &self,
61 delegate: &dyn LspAdapterDelegate,
62 _: &AsyncApp,
63 ) -> Result<Box<dyn 'static + Send + Any>> {
64 let release =
65 latest_github_release("golang/tools", false, false, delegate.http_client()).await?;
66 let version: Option<String> = release.tag_name.strip_prefix("gopls/v").map(str::to_string);
67 if version.is_none() {
68 log::warn!(
69 "couldn't infer gopls version from GitHub release tag name '{}'",
70 release.tag_name
71 );
72 }
73 Ok(Box::new(version) as Box<_>)
74 }
75
76 async fn check_if_user_installed(
77 &self,
78 delegate: &dyn LspAdapterDelegate,
79 _: Option<Toolchain>,
80 _: &AsyncApp,
81 ) -> Option<LanguageServerBinary> {
82 let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
83 Some(LanguageServerBinary {
84 path,
85 arguments: server_binary_arguments(),
86 env: None,
87 })
88 }
89
90 fn will_fetch_server(
91 &self,
92 delegate: &Arc<dyn LspAdapterDelegate>,
93 cx: &mut AsyncApp,
94 ) -> Option<Task<Result<()>>> {
95 static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
96
97 const NOTIFICATION_MESSAGE: &str =
98 "Could not install the Go language server `gopls`, because `go` was not found.";
99
100 let delegate = delegate.clone();
101 Some(cx.spawn(async move |cx| {
102 if delegate.which("go".as_ref()).await.is_none() {
103 if DID_SHOW_NOTIFICATION
104 .compare_exchange(false, true, SeqCst, SeqCst)
105 .is_ok()
106 {
107 cx.update(|cx| {
108 delegate.show_notification(NOTIFICATION_MESSAGE, cx);
109 })?
110 }
111 anyhow::bail!("cannot install gopls");
112 }
113 Ok(())
114 }))
115 }
116
117 async fn fetch_server_binary(
118 &self,
119 version: Box<dyn 'static + Send + Any>,
120 container_dir: PathBuf,
121 delegate: &dyn LspAdapterDelegate,
122 ) -> Result<LanguageServerBinary> {
123 let go = delegate.which("go".as_ref()).await.unwrap_or("go".into());
124 let go_version_output = util::command::new_smol_command(&go)
125 .args(["version"])
126 .output()
127 .await
128 .context("failed to get go version via `go version` command`")?;
129 let go_version = parse_version_output(&go_version_output)?;
130 let version = version.downcast::<Option<String>>().unwrap();
131 let this = *self;
132
133 if let Some(version) = *version {
134 let binary_path = container_dir.join(format!("gopls_{version}_go_{go_version}"));
135 if let Ok(metadata) = fs::metadata(&binary_path).await
136 && metadata.is_file()
137 {
138 remove_matching(&container_dir, |entry| {
139 entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
140 })
141 .await;
142
143 return Ok(LanguageServerBinary {
144 path: binary_path.to_path_buf(),
145 arguments: server_binary_arguments(),
146 env: None,
147 });
148 }
149 } else if let Some(path) = this
150 .cached_server_binary(container_dir.clone(), delegate)
151 .await
152 {
153 return Ok(path);
154 }
155
156 let gobin_dir = container_dir.join("gobin");
157 fs::create_dir_all(&gobin_dir).await?;
158 let install_output = util::command::new_smol_command(go)
159 .env("GO111MODULE", "on")
160 .env("GOBIN", &gobin_dir)
161 .args(["install", "golang.org/x/tools/gopls@latest"])
162 .output()
163 .await?;
164
165 if !install_output.status.success() {
166 log::error!(
167 "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
168 String::from_utf8_lossy(&install_output.stdout),
169 String::from_utf8_lossy(&install_output.stderr)
170 );
171 anyhow::bail!(
172 "failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
173 );
174 }
175
176 let installed_binary_path = gobin_dir.join(BINARY);
177 let version_output = util::command::new_smol_command(&installed_binary_path)
178 .arg("version")
179 .output()
180 .await
181 .context("failed to run installed gopls binary")?;
182 let gopls_version = parse_version_output(&version_output)?;
183 let binary_path = container_dir.join(format!("gopls_{gopls_version}_go_{go_version}"));
184 fs::rename(&installed_binary_path, &binary_path).await?;
185
186 Ok(LanguageServerBinary {
187 path: binary_path.to_path_buf(),
188 arguments: server_binary_arguments(),
189 env: None,
190 })
191 }
192
193 async fn cached_server_binary(
194 &self,
195 container_dir: PathBuf,
196 _: &dyn LspAdapterDelegate,
197 ) -> Option<LanguageServerBinary> {
198 get_cached_server_binary(container_dir).await
199 }
200
201 async fn initialization_options(
202 self: Arc<Self>,
203 _: &dyn Fs,
204 _: &Arc<dyn LspAdapterDelegate>,
205 ) -> Result<Option<serde_json::Value>> {
206 Ok(Some(json!({
207 "usePlaceholders": false,
208 "hints": {
209 "assignVariableTypes": true,
210 "compositeLiteralFields": true,
211 "compositeLiteralTypes": true,
212 "constantValues": true,
213 "functionTypeParameters": true,
214 "parameterNames": true,
215 "rangeVariableTypes": true
216 }
217 })))
218 }
219
220 async fn label_for_completion(
221 &self,
222 completion: &lsp::CompletionItem,
223 language: &Arc<Language>,
224 ) -> Option<CodeLabel> {
225 let label = &completion.label;
226
227 // Gopls returns nested fields and methods as completions.
228 // To syntax highlight these, combine their final component
229 // with their detail.
230 let name_offset = label.rfind('.').unwrap_or(0);
231
232 match completion.kind.zip(completion.detail.as_ref()) {
233 Some((lsp::CompletionItemKind::MODULE, detail)) => {
234 let text = format!("{label} {detail}");
235 let source = Rope::from(format!("import {text}").as_str());
236 let runs = language.highlight_text(&source, 7..7 + text.len());
237 let filter_range = completion
238 .filter_text
239 .as_deref()
240 .and_then(|filter_text| {
241 text.find(filter_text)
242 .map(|start| start..start + filter_text.len())
243 })
244 .unwrap_or(0..label.len());
245 return Some(CodeLabel {
246 text,
247 runs,
248 filter_range,
249 });
250 }
251 Some((
252 lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
253 detail,
254 )) => {
255 let text = format!("{label} {detail}");
256 let source =
257 Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
258 let runs = adjust_runs(
259 name_offset,
260 language.highlight_text(&source, 4..4 + text.len()),
261 );
262 let filter_range = completion
263 .filter_text
264 .as_deref()
265 .and_then(|filter_text| {
266 text.find(filter_text)
267 .map(|start| start..start + filter_text.len())
268 })
269 .unwrap_or(0..label.len());
270 return Some(CodeLabel {
271 text,
272 runs,
273 filter_range,
274 });
275 }
276 Some((lsp::CompletionItemKind::STRUCT, _)) => {
277 let text = format!("{label} struct {{}}");
278 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
279 let runs = adjust_runs(
280 name_offset,
281 language.highlight_text(&source, 5..5 + text.len()),
282 );
283 let filter_range = completion
284 .filter_text
285 .as_deref()
286 .and_then(|filter_text| {
287 text.find(filter_text)
288 .map(|start| start..start + filter_text.len())
289 })
290 .unwrap_or(0..label.len());
291 return Some(CodeLabel {
292 text,
293 runs,
294 filter_range,
295 });
296 }
297 Some((lsp::CompletionItemKind::INTERFACE, _)) => {
298 let text = format!("{label} interface {{}}");
299 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
300 let runs = adjust_runs(
301 name_offset,
302 language.highlight_text(&source, 5..5 + text.len()),
303 );
304 let filter_range = completion
305 .filter_text
306 .as_deref()
307 .and_then(|filter_text| {
308 text.find(filter_text)
309 .map(|start| start..start + filter_text.len())
310 })
311 .unwrap_or(0..label.len());
312 return Some(CodeLabel {
313 text,
314 runs,
315 filter_range,
316 });
317 }
318 Some((lsp::CompletionItemKind::FIELD, detail)) => {
319 let text = format!("{label} {detail}");
320 let source =
321 Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
322 let runs = adjust_runs(
323 name_offset,
324 language.highlight_text(&source, 16..16 + text.len()),
325 );
326 let filter_range = completion
327 .filter_text
328 .as_deref()
329 .and_then(|filter_text| {
330 text.find(filter_text)
331 .map(|start| start..start + filter_text.len())
332 })
333 .unwrap_or(0..label.len());
334 return Some(CodeLabel {
335 text,
336 runs,
337 filter_range,
338 });
339 }
340 Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
341 if let Some(signature) = detail.strip_prefix("func") {
342 let text = format!("{label}{signature}");
343 let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
344 let runs = adjust_runs(
345 name_offset,
346 language.highlight_text(&source, 5..5 + text.len()),
347 );
348 let filter_range = completion
349 .filter_text
350 .as_deref()
351 .and_then(|filter_text| {
352 text.find(filter_text)
353 .map(|start| start..start + filter_text.len())
354 })
355 .unwrap_or(0..label.len());
356 return Some(CodeLabel {
357 filter_range,
358 text,
359 runs,
360 });
361 }
362 }
363 _ => {}
364 }
365 None
366 }
367
368 async fn label_for_symbol(
369 &self,
370 name: &str,
371 kind: lsp::SymbolKind,
372 language: &Arc<Language>,
373 ) -> Option<CodeLabel> {
374 let (text, filter_range, display_range) = match kind {
375 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
376 let text = format!("func {} () {{}}", name);
377 let filter_range = 5..5 + name.len();
378 let display_range = 0..filter_range.end;
379 (text, filter_range, display_range)
380 }
381 lsp::SymbolKind::STRUCT => {
382 let text = format!("type {} struct {{}}", name);
383 let filter_range = 5..5 + name.len();
384 let display_range = 0..text.len();
385 (text, filter_range, display_range)
386 }
387 lsp::SymbolKind::INTERFACE => {
388 let text = format!("type {} interface {{}}", name);
389 let filter_range = 5..5 + name.len();
390 let display_range = 0..text.len();
391 (text, filter_range, display_range)
392 }
393 lsp::SymbolKind::CLASS => {
394 let text = format!("type {} T", name);
395 let filter_range = 5..5 + name.len();
396 let display_range = 0..filter_range.end;
397 (text, filter_range, display_range)
398 }
399 lsp::SymbolKind::CONSTANT => {
400 let text = format!("const {} = nil", name);
401 let filter_range = 6..6 + name.len();
402 let display_range = 0..filter_range.end;
403 (text, filter_range, display_range)
404 }
405 lsp::SymbolKind::VARIABLE => {
406 let text = format!("var {} = nil", name);
407 let filter_range = 4..4 + name.len();
408 let display_range = 0..filter_range.end;
409 (text, filter_range, display_range)
410 }
411 lsp::SymbolKind::MODULE => {
412 let text = format!("package {}", name);
413 let filter_range = 8..8 + name.len();
414 let display_range = 0..filter_range.end;
415 (text, filter_range, display_range)
416 }
417 _ => return None,
418 };
419
420 Some(CodeLabel {
421 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
422 text: text[display_range].to_string(),
423 filter_range,
424 })
425 }
426
427 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
428 static REGEX: LazyLock<Regex> =
429 LazyLock::new(|| Regex::new(r"(?m)\n\s*").expect("Failed to create REGEX"));
430 Some(REGEX.replace_all(message, "\n\n").to_string())
431 }
432}
433
434fn parse_version_output(output: &Output) -> Result<&str> {
435 let version_stdout =
436 str::from_utf8(&output.stdout).context("version command produced invalid utf8 output")?;
437
438 let version = VERSION_REGEX
439 .find(version_stdout)
440 .with_context(|| format!("failed to parse version output '{version_stdout}'"))?
441 .as_str();
442
443 Ok(version)
444}
445
446async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
447 maybe!(async {
448 let mut last_binary_path = None;
449 let mut entries = fs::read_dir(&container_dir).await?;
450 while let Some(entry) = entries.next().await {
451 let entry = entry?;
452 if entry.file_type().await?.is_file()
453 && entry
454 .file_name()
455 .to_str()
456 .is_some_and(|name| name.starts_with("gopls_"))
457 {
458 last_binary_path = Some(entry.path());
459 }
460 }
461
462 let path = last_binary_path.context("no cached binary")?;
463 anyhow::Ok(LanguageServerBinary {
464 path,
465 arguments: server_binary_arguments(),
466 env: None,
467 })
468 })
469 .await
470 .log_err()
471}
472
473fn adjust_runs(
474 delta: usize,
475 mut runs: Vec<(Range<usize>, HighlightId)>,
476) -> Vec<(Range<usize>, HighlightId)> {
477 for (range, _) in &mut runs {
478 range.start += delta;
479 range.end += delta;
480 }
481 runs
482}
483
484pub(crate) struct GoContextProvider;
485
486const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
487const GO_MODULE_ROOT_TASK_VARIABLE: VariableName =
488 VariableName::Custom(Cow::Borrowed("GO_MODULE_ROOT"));
489const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
490 VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
491const GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE: VariableName =
492 VariableName::Custom(Cow::Borrowed("GO_TABLE_TEST_CASE_NAME"));
493
494impl ContextProvider for GoContextProvider {
495 fn build_context(
496 &self,
497 variables: &TaskVariables,
498 location: ContextLocation<'_>,
499 _: Option<HashMap<String, String>>,
500 _: Arc<dyn LanguageToolchainStore>,
501 cx: &mut gpui::App,
502 ) -> Task<Result<TaskVariables>> {
503 let local_abs_path = location
504 .file_location
505 .buffer
506 .read(cx)
507 .file()
508 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
509
510 let go_package_variable = local_abs_path
511 .as_deref()
512 .and_then(|local_abs_path| local_abs_path.parent())
513 .map(|buffer_dir| {
514 // Prefer the relative form `./my-nested-package/is-here` over
515 // absolute path, because it's more readable in the modal, but
516 // the absolute path also works.
517 let package_name = variables
518 .get(&VariableName::WorktreeRoot)
519 .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
520 .map(|relative_pkg_dir| {
521 if relative_pkg_dir.as_os_str().is_empty() {
522 ".".into()
523 } else {
524 format!("./{}", relative_pkg_dir.to_string_lossy())
525 }
526 })
527 .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
528
529 (GO_PACKAGE_TASK_VARIABLE.clone(), package_name)
530 });
531
532 let go_module_root_variable = local_abs_path
533 .as_deref()
534 .and_then(|local_abs_path| local_abs_path.parent())
535 .map(|buffer_dir| {
536 // Walk dirtree up until getting the first go.mod file
537 let module_dir = buffer_dir
538 .ancestors()
539 .find(|dir| dir.join("go.mod").is_file())
540 .map(|dir| dir.to_string_lossy().to_string())
541 .unwrap_or_else(|| ".".to_string());
542
543 (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
544 });
545
546 let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
547
548 let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
549 .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
550
551 let table_test_case_name = variables.get(&VariableName::Custom(Cow::Borrowed(
552 "_table_test_case_name",
553 )));
554
555 let go_table_test_case_variable = table_test_case_name
556 .and_then(extract_subtest_name)
557 .map(|case_name| (GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.clone(), case_name));
558
559 Task::ready(Ok(TaskVariables::from_iter(
560 [
561 go_package_variable,
562 go_subtest_variable,
563 go_table_test_case_variable,
564 go_module_root_variable,
565 ]
566 .into_iter()
567 .flatten(),
568 )))
569 }
570
571 fn associated_tasks(
572 &self,
573 _: Arc<dyn Fs>,
574 _: Option<Arc<dyn File>>,
575 _: &App,
576 ) -> Task<Option<TaskTemplates>> {
577 let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
578 None
579 } else {
580 Some("$ZED_DIRNAME".to_string())
581 };
582 let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
583
584 Task::ready(Some(TaskTemplates(vec![
585 TaskTemplate {
586 label: format!(
587 "go test {} -v -run {}/{}",
588 GO_PACKAGE_TASK_VARIABLE.template_value(),
589 VariableName::Symbol.template_value(),
590 GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
591 ),
592 command: "go".into(),
593 args: vec![
594 "test".into(),
595 "-v".into(),
596 "-run".into(),
597 format!(
598 "\\^{}\\$/\\^{}\\$",
599 VariableName::Symbol.template_value(),
600 GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
601 ),
602 ],
603 cwd: package_cwd.clone(),
604 tags: vec!["go-table-test-case".to_owned()],
605 ..TaskTemplate::default()
606 },
607 TaskTemplate {
608 label: format!(
609 "go test {} -run {}",
610 GO_PACKAGE_TASK_VARIABLE.template_value(),
611 VariableName::Symbol.template_value(),
612 ),
613 command: "go".into(),
614 args: vec![
615 "test".into(),
616 "-run".into(),
617 format!("\\^{}\\$", VariableName::Symbol.template_value(),),
618 ],
619 tags: vec!["go-test".to_owned()],
620 cwd: package_cwd.clone(),
621 ..TaskTemplate::default()
622 },
623 TaskTemplate {
624 label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
625 command: "go".into(),
626 args: vec!["test".into()],
627 cwd: package_cwd.clone(),
628 ..TaskTemplate::default()
629 },
630 TaskTemplate {
631 label: "go test ./...".into(),
632 command: "go".into(),
633 args: vec!["test".into(), "./...".into()],
634 cwd: module_cwd.clone(),
635 ..TaskTemplate::default()
636 },
637 TaskTemplate {
638 label: format!(
639 "go test {} -v -run {}/{}",
640 GO_PACKAGE_TASK_VARIABLE.template_value(),
641 VariableName::Symbol.template_value(),
642 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
643 ),
644 command: "go".into(),
645 args: vec![
646 "test".into(),
647 "-v".into(),
648 "-run".into(),
649 format!(
650 "\\^{}\\$/\\^{}\\$",
651 VariableName::Symbol.template_value(),
652 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
653 ),
654 ],
655 cwd: package_cwd.clone(),
656 tags: vec!["go-subtest".to_owned()],
657 ..TaskTemplate::default()
658 },
659 TaskTemplate {
660 label: format!(
661 "go test {} -bench {}",
662 GO_PACKAGE_TASK_VARIABLE.template_value(),
663 VariableName::Symbol.template_value()
664 ),
665 command: "go".into(),
666 args: vec![
667 "test".into(),
668 "-benchmem".into(),
669 "-run='^$'".into(),
670 "-bench".into(),
671 format!("\\^{}\\$", VariableName::Symbol.template_value()),
672 ],
673 cwd: package_cwd.clone(),
674 tags: vec!["go-benchmark".to_owned()],
675 ..TaskTemplate::default()
676 },
677 TaskTemplate {
678 label: format!(
679 "go test {} -fuzz=Fuzz -run {}",
680 GO_PACKAGE_TASK_VARIABLE.template_value(),
681 VariableName::Symbol.template_value(),
682 ),
683 command: "go".into(),
684 args: vec![
685 "test".into(),
686 "-fuzz=Fuzz".into(),
687 "-run".into(),
688 format!("\\^{}\\$", VariableName::Symbol.template_value(),),
689 ],
690 tags: vec!["go-fuzz".to_owned()],
691 cwd: package_cwd.clone(),
692 ..TaskTemplate::default()
693 },
694 TaskTemplate {
695 label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
696 command: "go".into(),
697 args: vec!["run".into(), ".".into()],
698 cwd: package_cwd.clone(),
699 tags: vec!["go-main".to_owned()],
700 ..TaskTemplate::default()
701 },
702 TaskTemplate {
703 label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
704 command: "go".into(),
705 args: vec!["generate".into()],
706 cwd: package_cwd,
707 tags: vec!["go-generate".to_owned()],
708 ..TaskTemplate::default()
709 },
710 TaskTemplate {
711 label: "go generate ./...".into(),
712 command: "go".into(),
713 args: vec!["generate".into(), "./...".into()],
714 cwd: module_cwd,
715 ..TaskTemplate::default()
716 },
717 ])))
718 }
719}
720
721fn extract_subtest_name(input: &str) -> Option<String> {
722 let content = if input.starts_with('`') && input.ends_with('`') {
723 input.trim_matches('`')
724 } else {
725 input.trim_matches('"')
726 };
727
728 let processed = content
729 .chars()
730 .map(|c| if c.is_whitespace() { '_' } else { c })
731 .collect::<String>();
732
733 Some(
734 GO_ESCAPE_SUBTEST_NAME_REGEX
735 .replace_all(&processed, |caps: ®ex::Captures| {
736 format!("\\{}", &caps[0])
737 })
738 .to_string(),
739 )
740}
741
742#[cfg(test)]
743mod tests {
744 use super::*;
745 use crate::language;
746 use gpui::{AppContext, Hsla, TestAppContext};
747 use theme::SyntaxTheme;
748
749 #[gpui::test]
750 async fn test_go_label_for_completion() {
751 let adapter = Arc::new(GoLspAdapter);
752 let language = language("go", tree_sitter_go::LANGUAGE.into());
753
754 let theme = SyntaxTheme::new_test([
755 ("type", Hsla::default()),
756 ("keyword", Hsla::default()),
757 ("function", Hsla::default()),
758 ("number", Hsla::default()),
759 ("property", Hsla::default()),
760 ]);
761 language.set_theme(&theme);
762
763 let grammar = language.grammar().unwrap();
764 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
765 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
766 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
767 let highlight_number = grammar.highlight_id_for_name("number").unwrap();
768 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
769
770 assert_eq!(
771 adapter
772 .label_for_completion(
773 &lsp::CompletionItem {
774 kind: Some(lsp::CompletionItemKind::FUNCTION),
775 label: "Hello".to_string(),
776 detail: Some("func(a B) c.D".to_string()),
777 ..Default::default()
778 },
779 &language
780 )
781 .await,
782 Some(CodeLabel {
783 text: "Hello(a B) c.D".to_string(),
784 filter_range: 0..5,
785 runs: vec![
786 (0..5, highlight_function),
787 (8..9, highlight_type),
788 (13..14, highlight_type),
789 ],
790 })
791 );
792
793 // Nested methods
794 assert_eq!(
795 adapter
796 .label_for_completion(
797 &lsp::CompletionItem {
798 kind: Some(lsp::CompletionItemKind::METHOD),
799 label: "one.two.Three".to_string(),
800 detail: Some("func() [3]interface{}".to_string()),
801 ..Default::default()
802 },
803 &language
804 )
805 .await,
806 Some(CodeLabel {
807 text: "one.two.Three() [3]interface{}".to_string(),
808 filter_range: 0..13,
809 runs: vec![
810 (8..13, highlight_function),
811 (17..18, highlight_number),
812 (19..28, highlight_keyword),
813 ],
814 })
815 );
816
817 // Nested fields
818 assert_eq!(
819 adapter
820 .label_for_completion(
821 &lsp::CompletionItem {
822 kind: Some(lsp::CompletionItemKind::FIELD),
823 label: "two.Three".to_string(),
824 detail: Some("a.Bcd".to_string()),
825 ..Default::default()
826 },
827 &language
828 )
829 .await,
830 Some(CodeLabel {
831 text: "two.Three a.Bcd".to_string(),
832 filter_range: 0..9,
833 runs: vec![(4..9, highlight_field), (12..15, highlight_type)],
834 })
835 );
836 }
837
838 #[gpui::test]
839 fn test_go_runnable_detection(cx: &mut TestAppContext) {
840 let language = language("go", tree_sitter_go::LANGUAGE.into());
841
842 let interpreted_string_subtest = r#"
843 package main
844
845 import "testing"
846
847 func TestExample(t *testing.T) {
848 t.Run("subtest with double quotes", func(t *testing.T) {
849 // test code
850 })
851 }
852 "#;
853
854 let raw_string_subtest = r#"
855 package main
856
857 import "testing"
858
859 func TestExample(t *testing.T) {
860 t.Run(`subtest with
861 multiline
862 backticks`, func(t *testing.T) {
863 // test code
864 })
865 }
866 "#;
867
868 let buffer = cx.new(|cx| {
869 crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
870 });
871 cx.executor().run_until_parked();
872
873 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
874 let snapshot = buffer.snapshot();
875 snapshot
876 .runnable_ranges(0..interpreted_string_subtest.len())
877 .collect()
878 });
879
880 let tag_strings: Vec<String> = runnables
881 .iter()
882 .flat_map(|r| &r.runnable.tags)
883 .map(|tag| tag.0.to_string())
884 .collect();
885
886 assert!(
887 tag_strings.contains(&"go-test".to_string()),
888 "Should find go-test tag, found: {:?}",
889 tag_strings
890 );
891 assert!(
892 tag_strings.contains(&"go-subtest".to_string()),
893 "Should find go-subtest tag, found: {:?}",
894 tag_strings
895 );
896
897 let buffer = cx.new(|cx| {
898 crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
899 });
900 cx.executor().run_until_parked();
901
902 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
903 let snapshot = buffer.snapshot();
904 snapshot
905 .runnable_ranges(0..raw_string_subtest.len())
906 .collect()
907 });
908
909 let tag_strings: Vec<String> = runnables
910 .iter()
911 .flat_map(|r| &r.runnable.tags)
912 .map(|tag| tag.0.to_string())
913 .collect();
914
915 assert!(
916 tag_strings.contains(&"go-test".to_string()),
917 "Should find go-test tag, found: {:?}",
918 tag_strings
919 );
920 assert!(
921 tag_strings.contains(&"go-subtest".to_string()),
922 "Should find go-subtest tag, found: {:?}",
923 tag_strings
924 );
925 }
926
927 #[gpui::test]
928 fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
929 let language = language("go", tree_sitter_go::LANGUAGE.into());
930
931 let table_test = r#"
932 package main
933
934 import "testing"
935
936 func TestExample(t *testing.T) {
937 _ = "some random string"
938
939 testCases := []struct{
940 name string
941 anotherStr string
942 }{
943 {
944 name: "test case 1",
945 anotherStr: "foo",
946 },
947 {
948 name: "test case 2",
949 anotherStr: "bar",
950 },
951 }
952
953 notATableTest := []struct{
954 name string
955 }{
956 {
957 name: "some string",
958 },
959 {
960 name: "some other string",
961 },
962 }
963
964 for _, tc := range testCases {
965 t.Run(tc.name, func(t *testing.T) {
966 // test code here
967 })
968 }
969 }
970 "#;
971
972 let buffer =
973 cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
974 cx.executor().run_until_parked();
975
976 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
977 let snapshot = buffer.snapshot();
978 snapshot.runnable_ranges(0..table_test.len()).collect()
979 });
980
981 let tag_strings: Vec<String> = runnables
982 .iter()
983 .flat_map(|r| &r.runnable.tags)
984 .map(|tag| tag.0.to_string())
985 .collect();
986
987 assert!(
988 tag_strings.contains(&"go-test".to_string()),
989 "Should find go-test tag, found: {:?}",
990 tag_strings
991 );
992 assert!(
993 tag_strings.contains(&"go-table-test-case".to_string()),
994 "Should find go-table-test-case tag, found: {:?}",
995 tag_strings
996 );
997
998 let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
999 let go_table_test_count = tag_strings
1000 .iter()
1001 .filter(|&tag| tag == "go-table-test-case")
1002 .count();
1003
1004 assert!(
1005 go_test_count == 1,
1006 "Should find exactly 1 go-test, found: {}",
1007 go_test_count
1008 );
1009 assert!(
1010 go_table_test_count == 2,
1011 "Should find exactly 2 go-table-test-case, found: {}",
1012 go_table_test_count
1013 );
1014 }
1015
1016 #[gpui::test]
1017 fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1018 let language = language("go", tree_sitter_go::LANGUAGE.into());
1019
1020 let table_test = r#"
1021 package main
1022
1023 func Example() {
1024 _ = "some random string"
1025
1026 notATableTest := []struct{
1027 name string
1028 }{
1029 {
1030 name: "some string",
1031 },
1032 {
1033 name: "some other string",
1034 },
1035 }
1036 }
1037 "#;
1038
1039 let buffer =
1040 cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1041 cx.executor().run_until_parked();
1042
1043 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1044 let snapshot = buffer.snapshot();
1045 snapshot.runnable_ranges(0..table_test.len()).collect()
1046 });
1047
1048 let tag_strings: Vec<String> = runnables
1049 .iter()
1050 .flat_map(|r| &r.runnable.tags)
1051 .map(|tag| tag.0.to_string())
1052 .collect();
1053
1054 assert!(
1055 !tag_strings.contains(&"go-test".to_string()),
1056 "Should find go-test tag, found: {:?}",
1057 tag_strings
1058 );
1059 assert!(
1060 !tag_strings.contains(&"go-table-test-case".to_string()),
1061 "Should find go-table-test-case tag, found: {:?}",
1062 tag_strings
1063 );
1064 }
1065
1066 #[gpui::test]
1067 fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1068 let language = language("go", tree_sitter_go::LANGUAGE.into());
1069
1070 let table_test = r#"
1071 package main
1072
1073 import "testing"
1074
1075 func TestExample(t *testing.T) {
1076 _ = "some random string"
1077
1078 testCases := map[string]struct {
1079 someStr string
1080 fail bool
1081 }{
1082 "test failure": {
1083 someStr: "foo",
1084 fail: true,
1085 },
1086 "test success": {
1087 someStr: "bar",
1088 fail: false,
1089 },
1090 }
1091
1092 notATableTest := map[string]struct {
1093 someStr string
1094 }{
1095 "some string": {
1096 someStr: "foo",
1097 },
1098 "some other string": {
1099 someStr: "bar",
1100 },
1101 }
1102
1103 for name, tc := range testCases {
1104 t.Run(name, func(t *testing.T) {
1105 // test code here
1106 })
1107 }
1108 }
1109 "#;
1110
1111 let buffer =
1112 cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1113 cx.executor().run_until_parked();
1114
1115 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1116 let snapshot = buffer.snapshot();
1117 snapshot.runnable_ranges(0..table_test.len()).collect()
1118 });
1119
1120 let tag_strings: Vec<String> = runnables
1121 .iter()
1122 .flat_map(|r| &r.runnable.tags)
1123 .map(|tag| tag.0.to_string())
1124 .collect();
1125
1126 assert!(
1127 tag_strings.contains(&"go-test".to_string()),
1128 "Should find go-test tag, found: {:?}",
1129 tag_strings
1130 );
1131 assert!(
1132 tag_strings.contains(&"go-table-test-case".to_string()),
1133 "Should find go-table-test-case tag, found: {:?}",
1134 tag_strings
1135 );
1136
1137 let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1138 let go_table_test_count = tag_strings
1139 .iter()
1140 .filter(|&tag| tag == "go-table-test-case")
1141 .count();
1142
1143 assert!(
1144 go_test_count == 1,
1145 "Should find exactly 1 go-test, found: {}",
1146 go_test_count
1147 );
1148 assert!(
1149 go_table_test_count == 2,
1150 "Should find exactly 2 go-table-test-case, found: {}",
1151 go_table_test_count
1152 );
1153 }
1154
1155 #[gpui::test]
1156 fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1157 let language = language("go", tree_sitter_go::LANGUAGE.into());
1158
1159 let table_test = r#"
1160 package main
1161
1162 func Example() {
1163 _ = "some random string"
1164
1165 notATableTest := map[string]struct {
1166 someStr string
1167 }{
1168 "some string": {
1169 someStr: "foo",
1170 },
1171 "some other string": {
1172 someStr: "bar",
1173 },
1174 }
1175 }
1176 "#;
1177
1178 let buffer =
1179 cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1180 cx.executor().run_until_parked();
1181
1182 let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1183 let snapshot = buffer.snapshot();
1184 snapshot.runnable_ranges(0..table_test.len()).collect()
1185 });
1186
1187 let tag_strings: Vec<String> = runnables
1188 .iter()
1189 .flat_map(|r| &r.runnable.tags)
1190 .map(|tag| tag.0.to_string())
1191 .collect();
1192
1193 assert!(
1194 !tag_strings.contains(&"go-test".to_string()),
1195 "Should find go-test tag, found: {:?}",
1196 tag_strings
1197 );
1198 assert!(
1199 !tag_strings.contains(&"go-table-test-case".to_string()),
1200 "Should find go-table-test-case tag, found: {:?}",
1201 tag_strings
1202 );
1203 }
1204
1205 #[test]
1206 fn test_extract_subtest_name() {
1207 // Interpreted string literal
1208 let input_double_quoted = r#""subtest with double quotes""#;
1209 let result = extract_subtest_name(input_double_quoted);
1210 assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1211
1212 let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1213 let result = extract_subtest_name(input_double_quoted_with_backticks);
1214 assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1215
1216 // Raw string literal
1217 let input_with_backticks = r#"`subtest with backticks`"#;
1218 let result = extract_subtest_name(input_with_backticks);
1219 assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1220
1221 let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1222 let result = extract_subtest_name(input_raw_with_quotes);
1223 assert_eq!(
1224 result,
1225 Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1226 );
1227
1228 let input_multiline = r#"`subtest with
1229 multiline
1230 backticks`"#;
1231 let result = extract_subtest_name(input_multiline);
1232 assert_eq!(
1233 result,
1234 Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1235 );
1236
1237 let input_with_double_quotes = r#"`test with "double quotes"`"#;
1238 let result = extract_subtest_name(input_with_double_quotes);
1239 assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1240 }
1241}