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().to_string())
 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!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 640                command: "go".into(),
 641                args: vec!["test".into()],
 642                cwd: package_cwd.clone(),
 643                ..TaskTemplate::default()
 644            },
 645            TaskTemplate {
 646                label: "go test ./...".into(),
 647                command: "go".into(),
 648                args: vec!["test".into(), "./...".into()],
 649                cwd: module_cwd.clone(),
 650                ..TaskTemplate::default()
 651            },
 652            TaskTemplate {
 653                label: format!(
 654                    "go test {} -v -run {}/{}",
 655                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 656                    VariableName::Symbol.template_value(),
 657                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 658                ),
 659                command: "go".into(),
 660                args: vec![
 661                    "test".into(),
 662                    "-v".into(),
 663                    "-run".into(),
 664                    format!(
 665                        "\\^{}\\$/\\^{}\\$",
 666                        VariableName::Symbol.template_value(),
 667                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 668                    ),
 669                ],
 670                cwd: package_cwd.clone(),
 671                tags: vec!["go-subtest".to_owned()],
 672                ..TaskTemplate::default()
 673            },
 674            TaskTemplate {
 675                label: format!(
 676                    "go test {} -bench {}",
 677                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 678                    VariableName::Symbol.template_value()
 679                ),
 680                command: "go".into(),
 681                args: vec![
 682                    "test".into(),
 683                    "-benchmem".into(),
 684                    "-run='^$'".into(),
 685                    "-bench".into(),
 686                    format!("\\^{}\\$", VariableName::Symbol.template_value()),
 687                ],
 688                cwd: package_cwd.clone(),
 689                tags: vec!["go-benchmark".to_owned()],
 690                ..TaskTemplate::default()
 691            },
 692            TaskTemplate {
 693                label: format!(
 694                    "go test {} -fuzz=Fuzz -run {}",
 695                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 696                    VariableName::Symbol.template_value(),
 697                ),
 698                command: "go".into(),
 699                args: vec![
 700                    "test".into(),
 701                    "-fuzz=Fuzz".into(),
 702                    "-run".into(),
 703                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 704                ],
 705                tags: vec!["go-fuzz".to_owned()],
 706                cwd: package_cwd.clone(),
 707                ..TaskTemplate::default()
 708            },
 709            TaskTemplate {
 710                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
 711                command: "go".into(),
 712                args: vec!["run".into(), ".".into()],
 713                cwd: package_cwd.clone(),
 714                tags: vec!["go-main".to_owned()],
 715                ..TaskTemplate::default()
 716            },
 717            TaskTemplate {
 718                label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 719                command: "go".into(),
 720                args: vec!["generate".into()],
 721                cwd: package_cwd,
 722                tags: vec!["go-generate".to_owned()],
 723                ..TaskTemplate::default()
 724            },
 725            TaskTemplate {
 726                label: "go generate ./...".into(),
 727                command: "go".into(),
 728                args: vec!["generate".into(), "./...".into()],
 729                cwd: module_cwd,
 730                ..TaskTemplate::default()
 731            },
 732        ])))
 733    }
 734}
 735
 736fn extract_subtest_name(input: &str) -> Option<String> {
 737    let content = if input.starts_with('`') && input.ends_with('`') {
 738        input.trim_matches('`')
 739    } else {
 740        input.trim_matches('"')
 741    };
 742
 743    let processed = content
 744        .chars()
 745        .map(|c| if c.is_whitespace() { '_' } else { c })
 746        .collect::<String>();
 747
 748    Some(
 749        GO_ESCAPE_SUBTEST_NAME_REGEX
 750            .replace_all(&processed, |caps: &regex::Captures| {
 751                format!("\\{}", &caps[0])
 752            })
 753            .to_string(),
 754    )
 755}
 756
 757#[cfg(test)]
 758mod tests {
 759    use super::*;
 760    use crate::language;
 761    use gpui::{AppContext, Hsla, TestAppContext};
 762    use theme::SyntaxTheme;
 763
 764    #[gpui::test]
 765    async fn test_go_label_for_completion() {
 766        let adapter = Arc::new(GoLspAdapter);
 767        let language = language("go", tree_sitter_go::LANGUAGE.into());
 768
 769        let theme = SyntaxTheme::new_test([
 770            ("type", Hsla::default()),
 771            ("keyword", Hsla::default()),
 772            ("function", Hsla::default()),
 773            ("number", Hsla::default()),
 774            ("property", Hsla::default()),
 775        ]);
 776        language.set_theme(&theme);
 777
 778        let grammar = language.grammar().unwrap();
 779        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 780        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 781        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 782        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
 783        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 784
 785        assert_eq!(
 786            adapter
 787                .label_for_completion(
 788                    &lsp::CompletionItem {
 789                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 790                        label: "Hello".to_string(),
 791                        detail: Some("func(a B) c.D".to_string()),
 792                        ..Default::default()
 793                    },
 794                    &language
 795                )
 796                .await,
 797            Some(CodeLabel {
 798                text: "Hello(a B) c.D".to_string(),
 799                filter_range: 0..5,
 800                runs: vec![
 801                    (0..5, highlight_function),
 802                    (8..9, highlight_type),
 803                    (13..14, highlight_type),
 804                ],
 805            })
 806        );
 807
 808        // Nested methods
 809        assert_eq!(
 810            adapter
 811                .label_for_completion(
 812                    &lsp::CompletionItem {
 813                        kind: Some(lsp::CompletionItemKind::METHOD),
 814                        label: "one.two.Three".to_string(),
 815                        detail: Some("func() [3]interface{}".to_string()),
 816                        ..Default::default()
 817                    },
 818                    &language
 819                )
 820                .await,
 821            Some(CodeLabel {
 822                text: "one.two.Three() [3]interface{}".to_string(),
 823                filter_range: 0..13,
 824                runs: vec![
 825                    (8..13, highlight_function),
 826                    (17..18, highlight_number),
 827                    (19..28, highlight_keyword),
 828                ],
 829            })
 830        );
 831
 832        // Nested fields
 833        assert_eq!(
 834            adapter
 835                .label_for_completion(
 836                    &lsp::CompletionItem {
 837                        kind: Some(lsp::CompletionItemKind::FIELD),
 838                        label: "two.Three".to_string(),
 839                        detail: Some("a.Bcd".to_string()),
 840                        ..Default::default()
 841                    },
 842                    &language
 843                )
 844                .await,
 845            Some(CodeLabel {
 846                text: "two.Three a.Bcd".to_string(),
 847                filter_range: 0..9,
 848                runs: vec![(4..9, highlight_field), (12..15, highlight_type)],
 849            })
 850        );
 851    }
 852
 853    #[gpui::test]
 854    fn test_testify_suite_detection(cx: &mut TestAppContext) {
 855        let language = language("go", tree_sitter_go::LANGUAGE.into());
 856
 857        let testify_suite = r#"
 858        package main
 859
 860        import (
 861            "testing"
 862
 863            "github.com/stretchr/testify/suite"
 864        )
 865
 866        type ExampleSuite struct {
 867            suite.Suite
 868        }
 869
 870        func TestExampleSuite(t *testing.T) {
 871            suite.Run(t, new(ExampleSuite))
 872        }
 873
 874        func (s *ExampleSuite) TestSomething_Success() {
 875            // test code
 876        }
 877        "#;
 878
 879        let buffer = cx
 880            .new(|cx| crate::Buffer::local(testify_suite, cx).with_language(language.clone(), cx));
 881        cx.executor().run_until_parked();
 882
 883        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 884            let snapshot = buffer.snapshot();
 885            snapshot.runnable_ranges(0..testify_suite.len()).collect()
 886        });
 887
 888        let tag_strings: Vec<String> = runnables
 889            .iter()
 890            .flat_map(|r| &r.runnable.tags)
 891            .map(|tag| tag.0.to_string())
 892            .collect();
 893
 894        assert!(
 895            tag_strings.contains(&"go-test".to_string()),
 896            "Should find go-test tag, found: {:?}",
 897            tag_strings
 898        );
 899        assert!(
 900            tag_strings.contains(&"go-testify-suite".to_string()),
 901            "Should find go-testify-suite tag, found: {:?}",
 902            tag_strings
 903        );
 904    }
 905
 906    #[gpui::test]
 907    fn test_go_runnable_detection(cx: &mut TestAppContext) {
 908        let language = language("go", tree_sitter_go::LANGUAGE.into());
 909
 910        let interpreted_string_subtest = r#"
 911        package main
 912
 913        import "testing"
 914
 915        func TestExample(t *testing.T) {
 916            t.Run("subtest with double quotes", func(t *testing.T) {
 917                // test code
 918            })
 919        }
 920        "#;
 921
 922        let raw_string_subtest = r#"
 923        package main
 924
 925        import "testing"
 926
 927        func TestExample(t *testing.T) {
 928            t.Run(`subtest with
 929            multiline
 930            backticks`, func(t *testing.T) {
 931                // test code
 932            })
 933        }
 934        "#;
 935
 936        let buffer = cx.new(|cx| {
 937            crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
 938        });
 939        cx.executor().run_until_parked();
 940
 941        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 942            let snapshot = buffer.snapshot();
 943            snapshot
 944                .runnable_ranges(0..interpreted_string_subtest.len())
 945                .collect()
 946        });
 947
 948        let tag_strings: Vec<String> = runnables
 949            .iter()
 950            .flat_map(|r| &r.runnable.tags)
 951            .map(|tag| tag.0.to_string())
 952            .collect();
 953
 954        assert!(
 955            tag_strings.contains(&"go-test".to_string()),
 956            "Should find go-test tag, found: {:?}",
 957            tag_strings
 958        );
 959        assert!(
 960            tag_strings.contains(&"go-subtest".to_string()),
 961            "Should find go-subtest tag, found: {:?}",
 962            tag_strings
 963        );
 964
 965        let buffer = cx.new(|cx| {
 966            crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
 967        });
 968        cx.executor().run_until_parked();
 969
 970        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 971            let snapshot = buffer.snapshot();
 972            snapshot
 973                .runnable_ranges(0..raw_string_subtest.len())
 974                .collect()
 975        });
 976
 977        let tag_strings: Vec<String> = runnables
 978            .iter()
 979            .flat_map(|r| &r.runnable.tags)
 980            .map(|tag| tag.0.to_string())
 981            .collect();
 982
 983        assert!(
 984            tag_strings.contains(&"go-test".to_string()),
 985            "Should find go-test tag, found: {:?}",
 986            tag_strings
 987        );
 988        assert!(
 989            tag_strings.contains(&"go-subtest".to_string()),
 990            "Should find go-subtest tag, found: {:?}",
 991            tag_strings
 992        );
 993    }
 994
 995    #[gpui::test]
 996    fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
 997        let language = language("go", tree_sitter_go::LANGUAGE.into());
 998
 999        let table_test = r#"
1000        package main
1001
1002        import "testing"
1003
1004        func TestExample(t *testing.T) {
1005            _ = "some random string"
1006
1007            testCases := []struct{
1008                name string
1009                anotherStr string
1010            }{
1011                {
1012                    name: "test case 1",
1013                    anotherStr: "foo",
1014                },
1015                {
1016                    name: "test case 2",
1017                    anotherStr: "bar",
1018                },
1019            }
1020
1021            notATableTest := []struct{
1022                name string
1023            }{
1024                {
1025                    name: "some string",
1026                },
1027                {
1028                    name: "some other string",
1029                },
1030            }
1031
1032            for _, tc := range testCases {
1033                t.Run(tc.name, func(t *testing.T) {
1034                    // test code here
1035                })
1036            }
1037        }
1038        "#;
1039
1040        let buffer =
1041            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1042        cx.executor().run_until_parked();
1043
1044        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1045            let snapshot = buffer.snapshot();
1046            snapshot.runnable_ranges(0..table_test.len()).collect()
1047        });
1048
1049        let tag_strings: Vec<String> = runnables
1050            .iter()
1051            .flat_map(|r| &r.runnable.tags)
1052            .map(|tag| tag.0.to_string())
1053            .collect();
1054
1055        assert!(
1056            tag_strings.contains(&"go-test".to_string()),
1057            "Should find go-test tag, found: {:?}",
1058            tag_strings
1059        );
1060        assert!(
1061            tag_strings.contains(&"go-table-test-case".to_string()),
1062            "Should find go-table-test-case tag, found: {:?}",
1063            tag_strings
1064        );
1065
1066        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1067        let go_table_test_count = tag_strings
1068            .iter()
1069            .filter(|&tag| tag == "go-table-test-case")
1070            .count();
1071
1072        assert!(
1073            go_test_count == 1,
1074            "Should find exactly 1 go-test, found: {}",
1075            go_test_count
1076        );
1077        assert!(
1078            go_table_test_count == 2,
1079            "Should find exactly 2 go-table-test-case, found: {}",
1080            go_table_test_count
1081        );
1082    }
1083
1084    #[gpui::test]
1085    fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1086        let language = language("go", tree_sitter_go::LANGUAGE.into());
1087
1088        let table_test = r#"
1089        package main
1090
1091        func Example() {
1092            _ = "some random string"
1093
1094            notATableTest := []struct{
1095                name string
1096            }{
1097                {
1098                    name: "some string",
1099                },
1100                {
1101                    name: "some other string",
1102                },
1103            }
1104        }
1105        "#;
1106
1107        let buffer =
1108            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1109        cx.executor().run_until_parked();
1110
1111        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1112            let snapshot = buffer.snapshot();
1113            snapshot.runnable_ranges(0..table_test.len()).collect()
1114        });
1115
1116        let tag_strings: Vec<String> = runnables
1117            .iter()
1118            .flat_map(|r| &r.runnable.tags)
1119            .map(|tag| tag.0.to_string())
1120            .collect();
1121
1122        assert!(
1123            !tag_strings.contains(&"go-test".to_string()),
1124            "Should find go-test tag, found: {:?}",
1125            tag_strings
1126        );
1127        assert!(
1128            !tag_strings.contains(&"go-table-test-case".to_string()),
1129            "Should find go-table-test-case tag, found: {:?}",
1130            tag_strings
1131        );
1132    }
1133
1134    #[gpui::test]
1135    fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1136        let language = language("go", tree_sitter_go::LANGUAGE.into());
1137
1138        let table_test = r#"
1139        package main
1140
1141        import "testing"
1142
1143        func TestExample(t *testing.T) {
1144            _ = "some random string"
1145
1146           	testCases := map[string]struct {
1147          		someStr string
1148          		fail    bool
1149           	}{
1150          		"test failure": {
1151         			someStr: "foo",
1152         			fail:    true,
1153          		},
1154          		"test success": {
1155         			someStr: "bar",
1156         			fail:    false,
1157          		},
1158           	}
1159
1160           	notATableTest := map[string]struct {
1161          		someStr string
1162           	}{
1163          		"some string": {
1164         			someStr: "foo",
1165          		},
1166          		"some other string": {
1167         			someStr: "bar",
1168          		},
1169           	}
1170
1171            for name, tc := range testCases {
1172                t.Run(name, func(t *testing.T) {
1173                    // test code here
1174                })
1175            }
1176        }
1177        "#;
1178
1179        let buffer =
1180            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1181        cx.executor().run_until_parked();
1182
1183        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1184            let snapshot = buffer.snapshot();
1185            snapshot.runnable_ranges(0..table_test.len()).collect()
1186        });
1187
1188        let tag_strings: Vec<String> = runnables
1189            .iter()
1190            .flat_map(|r| &r.runnable.tags)
1191            .map(|tag| tag.0.to_string())
1192            .collect();
1193
1194        assert!(
1195            tag_strings.contains(&"go-test".to_string()),
1196            "Should find go-test tag, found: {:?}",
1197            tag_strings
1198        );
1199        assert!(
1200            tag_strings.contains(&"go-table-test-case".to_string()),
1201            "Should find go-table-test-case tag, found: {:?}",
1202            tag_strings
1203        );
1204
1205        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1206        let go_table_test_count = tag_strings
1207            .iter()
1208            .filter(|&tag| tag == "go-table-test-case")
1209            .count();
1210
1211        assert!(
1212            go_test_count == 1,
1213            "Should find exactly 1 go-test, found: {}",
1214            go_test_count
1215        );
1216        assert!(
1217            go_table_test_count == 2,
1218            "Should find exactly 2 go-table-test-case, found: {}",
1219            go_table_test_count
1220        );
1221    }
1222
1223    #[gpui::test]
1224    fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1225        let language = language("go", tree_sitter_go::LANGUAGE.into());
1226
1227        let table_test = r#"
1228        package main
1229
1230        func Example() {
1231            _ = "some random string"
1232
1233           	notATableTest := map[string]struct {
1234          		someStr string
1235           	}{
1236          		"some string": {
1237         			someStr: "foo",
1238          		},
1239          		"some other string": {
1240         			someStr: "bar",
1241          		},
1242           	}
1243        }
1244        "#;
1245
1246        let buffer =
1247            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1248        cx.executor().run_until_parked();
1249
1250        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1251            let snapshot = buffer.snapshot();
1252            snapshot.runnable_ranges(0..table_test.len()).collect()
1253        });
1254
1255        let tag_strings: Vec<String> = runnables
1256            .iter()
1257            .flat_map(|r| &r.runnable.tags)
1258            .map(|tag| tag.0.to_string())
1259            .collect();
1260
1261        assert!(
1262            !tag_strings.contains(&"go-test".to_string()),
1263            "Should find go-test tag, found: {:?}",
1264            tag_strings
1265        );
1266        assert!(
1267            !tag_strings.contains(&"go-table-test-case".to_string()),
1268            "Should find go-table-test-case tag, found: {:?}",
1269            tag_strings
1270        );
1271    }
1272
1273    #[test]
1274    fn test_extract_subtest_name() {
1275        // Interpreted string literal
1276        let input_double_quoted = r#""subtest with double quotes""#;
1277        let result = extract_subtest_name(input_double_quoted);
1278        assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1279
1280        let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1281        let result = extract_subtest_name(input_double_quoted_with_backticks);
1282        assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1283
1284        // Raw string literal
1285        let input_with_backticks = r#"`subtest with backticks`"#;
1286        let result = extract_subtest_name(input_with_backticks);
1287        assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1288
1289        let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1290        let result = extract_subtest_name(input_raw_with_quotes);
1291        assert_eq!(
1292            result,
1293            Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1294        );
1295
1296        let input_multiline = r#"`subtest with
1297        multiline
1298        backticks`"#;
1299        let result = extract_subtest_name(input_multiline);
1300        assert_eq!(
1301            result,
1302            Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1303        );
1304
1305        let input_with_double_quotes = r#"`test with "double quotes"`"#;
1306        let result = extract_subtest_name(input_with_double_quotes);
1307        assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1308    }
1309}