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