go.rs

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