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::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.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.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.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.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.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: &regex::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
 872            .new(|cx| crate::Buffer::local(testify_suite, cx).with_language(language.clone(), cx));
 873        cx.executor().run_until_parked();
 874
 875        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 876            let snapshot = buffer.snapshot();
 877            snapshot.runnable_ranges(0..testify_suite.len()).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-testify-suite".to_string()),
 893            "Should find go-testify-suite tag, found: {:?}",
 894            tag_strings
 895        );
 896    }
 897
 898    #[gpui::test]
 899    fn test_go_runnable_detection(cx: &mut TestAppContext) {
 900        let language = language("go", tree_sitter_go::LANGUAGE.into());
 901
 902        let interpreted_string_subtest = r#"
 903        package main
 904
 905        import "testing"
 906
 907        func TestExample(t *testing.T) {
 908            t.Run("subtest with double quotes", func(t *testing.T) {
 909                // test code
 910            })
 911        }
 912        "#;
 913
 914        let raw_string_subtest = r#"
 915        package main
 916
 917        import "testing"
 918
 919        func TestExample(t *testing.T) {
 920            t.Run(`subtest with
 921            multiline
 922            backticks`, func(t *testing.T) {
 923                // test code
 924            })
 925        }
 926        "#;
 927
 928        let buffer = cx.new(|cx| {
 929            crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
 930        });
 931        cx.executor().run_until_parked();
 932
 933        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 934            let snapshot = buffer.snapshot();
 935            snapshot
 936                .runnable_ranges(0..interpreted_string_subtest.len())
 937                .collect()
 938        });
 939
 940        let tag_strings: Vec<String> = runnables
 941            .iter()
 942            .flat_map(|r| &r.runnable.tags)
 943            .map(|tag| tag.0.to_string())
 944            .collect();
 945
 946        assert!(
 947            tag_strings.contains(&"go-test".to_string()),
 948            "Should find go-test tag, found: {:?}",
 949            tag_strings
 950        );
 951        assert!(
 952            tag_strings.contains(&"go-subtest".to_string()),
 953            "Should find go-subtest tag, found: {:?}",
 954            tag_strings
 955        );
 956
 957        let buffer = cx.new(|cx| {
 958            crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
 959        });
 960        cx.executor().run_until_parked();
 961
 962        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 963            let snapshot = buffer.snapshot();
 964            snapshot
 965                .runnable_ranges(0..raw_string_subtest.len())
 966                .collect()
 967        });
 968
 969        let tag_strings: Vec<String> = runnables
 970            .iter()
 971            .flat_map(|r| &r.runnable.tags)
 972            .map(|tag| tag.0.to_string())
 973            .collect();
 974
 975        assert!(
 976            tag_strings.contains(&"go-test".to_string()),
 977            "Should find go-test tag, found: {:?}",
 978            tag_strings
 979        );
 980        assert!(
 981            tag_strings.contains(&"go-subtest".to_string()),
 982            "Should find go-subtest tag, found: {:?}",
 983            tag_strings
 984        );
 985    }
 986
 987    #[gpui::test]
 988    fn test_go_example_test_detection(cx: &mut TestAppContext) {
 989        let language = language("go", tree_sitter_go::LANGUAGE.into());
 990
 991        let example_test = r#"
 992        package main
 993
 994        import "fmt"
 995
 996        func Example() {
 997            fmt.Println("Hello, world!")
 998            // Output: Hello, world!
 999        }
1000        "#;
1001
1002        let buffer =
1003            cx.new(|cx| crate::Buffer::local(example_test, cx).with_language(language.clone(), cx));
1004        cx.executor().run_until_parked();
1005
1006        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1007            let snapshot = buffer.snapshot();
1008            snapshot.runnable_ranges(0..example_test.len()).collect()
1009        });
1010
1011        let tag_strings: Vec<String> = runnables
1012            .iter()
1013            .flat_map(|r| &r.runnable.tags)
1014            .map(|tag| tag.0.to_string())
1015            .collect();
1016
1017        assert!(
1018            tag_strings.contains(&"go-example".to_string()),
1019            "Should find go-example tag, found: {:?}",
1020            tag_strings
1021        );
1022    }
1023
1024    #[gpui::test]
1025    fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
1026        let language = language("go", tree_sitter_go::LANGUAGE.into());
1027
1028        let table_test = r#"
1029        package main
1030
1031        import "testing"
1032
1033        func TestExample(t *testing.T) {
1034            _ = "some random string"
1035
1036            testCases := []struct{
1037                name string
1038                anotherStr string
1039            }{
1040                {
1041                    name: "test case 1",
1042                    anotherStr: "foo",
1043                },
1044                {
1045                    name: "test case 2",
1046                    anotherStr: "bar",
1047                },
1048                {
1049                    name: "test case 3",
1050                    anotherStr: "baz",
1051                },
1052            }
1053
1054            notATableTest := []struct{
1055                name string
1056            }{
1057                {
1058                    name: "some string",
1059                },
1060                {
1061                    name: "some other string",
1062                },
1063            }
1064
1065            for _, tc := range testCases {
1066                t.Run(tc.name, func(t *testing.T) {
1067                    // test code here
1068                })
1069            }
1070        }
1071        "#;
1072
1073        let buffer =
1074            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1075        cx.executor().run_until_parked();
1076
1077        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1078            let snapshot = buffer.snapshot();
1079            snapshot.runnable_ranges(0..table_test.len()).collect()
1080        });
1081
1082        let tag_strings: Vec<String> = runnables
1083            .iter()
1084            .flat_map(|r| &r.runnable.tags)
1085            .map(|tag| tag.0.to_string())
1086            .collect();
1087
1088        assert!(
1089            tag_strings.contains(&"go-test".to_string()),
1090            "Should find go-test tag, found: {:?}",
1091            tag_strings
1092        );
1093        assert!(
1094            tag_strings.contains(&"go-table-test-case".to_string()),
1095            "Should find go-table-test-case tag, found: {:?}",
1096            tag_strings
1097        );
1098
1099        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1100        // This is currently broken; see #39148
1101        // let go_table_test_count = tag_strings
1102        //     .iter()
1103        //     .filter(|&tag| tag == "go-table-test-case")
1104        //     .count();
1105
1106        assert!(
1107            go_test_count == 1,
1108            "Should find exactly 1 go-test, found: {}",
1109            go_test_count
1110        );
1111        // assert!(
1112        //     go_table_test_count == 3,
1113        //     "Should find exactly 3 go-table-test-case, found: {}",
1114        //     go_table_test_count
1115        // );
1116    }
1117
1118    #[gpui::test]
1119    fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1120        let language = language("go", tree_sitter_go::LANGUAGE.into());
1121
1122        let table_test = r#"
1123        package main
1124
1125        func Example() {
1126            _ = "some random string"
1127
1128            notATableTest := []struct{
1129                name string
1130            }{
1131                {
1132                    name: "some string",
1133                },
1134                {
1135                    name: "some other string",
1136                },
1137            }
1138        }
1139        "#;
1140
1141        let buffer =
1142            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1143        cx.executor().run_until_parked();
1144
1145        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1146            let snapshot = buffer.snapshot();
1147            snapshot.runnable_ranges(0..table_test.len()).collect()
1148        });
1149
1150        let tag_strings: Vec<String> = runnables
1151            .iter()
1152            .flat_map(|r| &r.runnable.tags)
1153            .map(|tag| tag.0.to_string())
1154            .collect();
1155
1156        assert!(
1157            !tag_strings.contains(&"go-test".to_string()),
1158            "Should find go-test tag, found: {:?}",
1159            tag_strings
1160        );
1161        assert!(
1162            !tag_strings.contains(&"go-table-test-case".to_string()),
1163            "Should find go-table-test-case tag, found: {:?}",
1164            tag_strings
1165        );
1166    }
1167
1168    #[gpui::test]
1169    fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1170        let language = language("go", tree_sitter_go::LANGUAGE.into());
1171
1172        let table_test = r#"
1173        package main
1174
1175        import "testing"
1176
1177        func TestExample(t *testing.T) {
1178            _ = "some random string"
1179
1180           	testCases := map[string]struct {
1181          		someStr string
1182          		fail    bool
1183           	}{
1184          		"test failure": {
1185         			someStr: "foo",
1186         			fail:    true,
1187          		},
1188          		"test success": {
1189         			someStr: "bar",
1190         			fail:    false,
1191          		},
1192           	}
1193
1194           	notATableTest := map[string]struct {
1195          		someStr string
1196           	}{
1197          		"some string": {
1198         			someStr: "foo",
1199          		},
1200          		"some other string": {
1201         			someStr: "bar",
1202          		},
1203           	}
1204
1205            for name, tc := range testCases {
1206                t.Run(name, func(t *testing.T) {
1207                    // test code here
1208                })
1209            }
1210        }
1211        "#;
1212
1213        let buffer =
1214            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1215        cx.executor().run_until_parked();
1216
1217        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1218            let snapshot = buffer.snapshot();
1219            snapshot.runnable_ranges(0..table_test.len()).collect()
1220        });
1221
1222        let tag_strings: Vec<String> = runnables
1223            .iter()
1224            .flat_map(|r| &r.runnable.tags)
1225            .map(|tag| tag.0.to_string())
1226            .collect();
1227
1228        assert!(
1229            tag_strings.contains(&"go-test".to_string()),
1230            "Should find go-test tag, found: {:?}",
1231            tag_strings
1232        );
1233        assert!(
1234            tag_strings.contains(&"go-table-test-case".to_string()),
1235            "Should find go-table-test-case tag, found: {:?}",
1236            tag_strings
1237        );
1238
1239        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1240        let go_table_test_count = tag_strings
1241            .iter()
1242            .filter(|&tag| tag == "go-table-test-case")
1243            .count();
1244
1245        assert!(
1246            go_test_count == 1,
1247            "Should find exactly 1 go-test, found: {}",
1248            go_test_count
1249        );
1250        assert!(
1251            go_table_test_count == 2,
1252            "Should find exactly 2 go-table-test-case, found: {}",
1253            go_table_test_count
1254        );
1255    }
1256
1257    #[gpui::test]
1258    fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1259        let language = language("go", tree_sitter_go::LANGUAGE.into());
1260
1261        let table_test = r#"
1262        package main
1263
1264        func Example() {
1265            _ = "some random string"
1266
1267           	notATableTest := map[string]struct {
1268          		someStr string
1269           	}{
1270          		"some string": {
1271         			someStr: "foo",
1272          		},
1273          		"some other string": {
1274         			someStr: "bar",
1275          		},
1276           	}
1277        }
1278        "#;
1279
1280        let buffer =
1281            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1282        cx.executor().run_until_parked();
1283
1284        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1285            let snapshot = buffer.snapshot();
1286            snapshot.runnable_ranges(0..table_test.len()).collect()
1287        });
1288
1289        let tag_strings: Vec<String> = runnables
1290            .iter()
1291            .flat_map(|r| &r.runnable.tags)
1292            .map(|tag| tag.0.to_string())
1293            .collect();
1294
1295        assert!(
1296            !tag_strings.contains(&"go-test".to_string()),
1297            "Should find go-test tag, found: {:?}",
1298            tag_strings
1299        );
1300        assert!(
1301            !tag_strings.contains(&"go-table-test-case".to_string()),
1302            "Should find go-table-test-case tag, found: {:?}",
1303            tag_strings
1304        );
1305    }
1306
1307    #[test]
1308    fn test_extract_subtest_name() {
1309        // Interpreted string literal
1310        let input_double_quoted = r#""subtest with double quotes""#;
1311        let result = extract_subtest_name(input_double_quoted);
1312        assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1313
1314        let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1315        let result = extract_subtest_name(input_double_quoted_with_backticks);
1316        assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1317
1318        // Raw string literal
1319        let input_with_backticks = r#"`subtest with backticks`"#;
1320        let result = extract_subtest_name(input_with_backticks);
1321        assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1322
1323        let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1324        let result = extract_subtest_name(input_raw_with_quotes);
1325        assert_eq!(
1326            result,
1327            Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1328        );
1329
1330        let input_multiline = r#"`subtest with
1331        multiline
1332        backticks`"#;
1333        let result = extract_subtest_name(input_multiline);
1334        assert_eq!(
1335            result,
1336            Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1337        );
1338
1339        let input_with_double_quotes = r#"`test with "double quotes"`"#;
1340        let result = extract_subtest_name(input_with_double_quotes);
1341        assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1342    }
1343}