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"));
 482
 483impl ContextProvider for GoContextProvider {
 484    fn build_context(
 485        &self,
 486        variables: &TaskVariables,
 487        location: ContextLocation<'_>,
 488        _: Option<HashMap<String, String>>,
 489        _: Arc<dyn LanguageToolchainStore>,
 490        cx: &mut gpui::App,
 491    ) -> Task<Result<TaskVariables>> {
 492        let local_abs_path = location
 493            .file_location
 494            .buffer
 495            .read(cx)
 496            .file()
 497            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 498
 499        let go_package_variable = local_abs_path
 500            .as_deref()
 501            .and_then(|local_abs_path| local_abs_path.parent())
 502            .map(|buffer_dir| {
 503                // Prefer the relative form `./my-nested-package/is-here` over
 504                // absolute path, because it's more readable in the modal, but
 505                // the absolute path also works.
 506                let package_name = variables
 507                    .get(&VariableName::WorktreeRoot)
 508                    .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
 509                    .map(|relative_pkg_dir| {
 510                        if relative_pkg_dir.as_os_str().is_empty() {
 511                            ".".into()
 512                        } else {
 513                            format!("./{}", relative_pkg_dir.to_string_lossy())
 514                        }
 515                    })
 516                    .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
 517
 518                (GO_PACKAGE_TASK_VARIABLE.clone(), package_name)
 519            });
 520
 521        let go_module_root_variable = local_abs_path
 522            .as_deref()
 523            .and_then(|local_abs_path| local_abs_path.parent())
 524            .map(|buffer_dir| {
 525                // Walk dirtree up until getting the first go.mod file
 526                let module_dir = buffer_dir
 527                    .ancestors()
 528                    .find(|dir| dir.join("go.mod").is_file())
 529                    .map(|dir| dir.to_string_lossy().to_string())
 530                    .unwrap_or_else(|| ".".to_string());
 531
 532                (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
 533            });
 534
 535        let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
 536
 537        let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
 538            .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
 539
 540        let table_test_case_name = variables.get(&VariableName::Custom(Cow::Borrowed(
 541            "_table_test_case_name",
 542        )));
 543
 544        let go_table_test_case_variable = table_test_case_name
 545            .and_then(extract_subtest_name)
 546            .map(|case_name| (GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.clone(), case_name));
 547
 548        Task::ready(Ok(TaskVariables::from_iter(
 549            [
 550                go_package_variable,
 551                go_subtest_variable,
 552                go_table_test_case_variable,
 553                go_module_root_variable,
 554            ]
 555            .into_iter()
 556            .flatten(),
 557        )))
 558    }
 559
 560    fn associated_tasks(&self, _: Option<Arc<dyn File>>, _: &App) -> Task<Option<TaskTemplates>> {
 561        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
 562            None
 563        } else {
 564            Some("$ZED_DIRNAME".to_string())
 565        };
 566        let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
 567
 568        Task::ready(Some(TaskTemplates(vec![
 569            TaskTemplate {
 570                label: format!(
 571                    "go test {} -v -run {}/{}",
 572                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 573                    VariableName::Symbol.template_value(),
 574                    GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 575                ),
 576                command: "go".into(),
 577                args: vec![
 578                    "test".into(),
 579                    "-v".into(),
 580                    "-run".into(),
 581                    format!(
 582                        "\\^{}\\$/\\^{}\\$",
 583                        VariableName::Symbol.template_value(),
 584                        GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 585                    ),
 586                ],
 587                cwd: package_cwd.clone(),
 588                tags: vec!["go-table-test-case".to_owned()],
 589                ..TaskTemplate::default()
 590            },
 591            TaskTemplate {
 592                label: format!(
 593                    "go test {} -run {}",
 594                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 595                    VariableName::Symbol.template_value(),
 596                ),
 597                command: "go".into(),
 598                args: vec![
 599                    "test".into(),
 600                    "-run".into(),
 601                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 602                ],
 603                tags: vec!["go-test".to_owned()],
 604                cwd: package_cwd.clone(),
 605                ..TaskTemplate::default()
 606            },
 607            TaskTemplate {
 608                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 609                command: "go".into(),
 610                args: vec!["test".into()],
 611                cwd: package_cwd.clone(),
 612                ..TaskTemplate::default()
 613            },
 614            TaskTemplate {
 615                label: "go test ./...".into(),
 616                command: "go".into(),
 617                args: vec!["test".into(), "./...".into()],
 618                cwd: module_cwd.clone(),
 619                ..TaskTemplate::default()
 620            },
 621            TaskTemplate {
 622                label: format!(
 623                    "go test {} -v -run {}/{}",
 624                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 625                    VariableName::Symbol.template_value(),
 626                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 627                ),
 628                command: "go".into(),
 629                args: vec![
 630                    "test".into(),
 631                    "-v".into(),
 632                    "-run".into(),
 633                    format!(
 634                        "\\^{}\\$/\\^{}\\$",
 635                        VariableName::Symbol.template_value(),
 636                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 637                    ),
 638                ],
 639                cwd: package_cwd.clone(),
 640                tags: vec!["go-subtest".to_owned()],
 641                ..TaskTemplate::default()
 642            },
 643            TaskTemplate {
 644                label: format!(
 645                    "go test {} -bench {}",
 646                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 647                    VariableName::Symbol.template_value()
 648                ),
 649                command: "go".into(),
 650                args: vec![
 651                    "test".into(),
 652                    "-benchmem".into(),
 653                    "-run='^$'".into(),
 654                    "-bench".into(),
 655                    format!("\\^{}\\$", VariableName::Symbol.template_value()),
 656                ],
 657                cwd: package_cwd.clone(),
 658                tags: vec!["go-benchmark".to_owned()],
 659                ..TaskTemplate::default()
 660            },
 661            TaskTemplate {
 662                label: format!(
 663                    "go test {} -fuzz=Fuzz -run {}",
 664                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 665                    VariableName::Symbol.template_value(),
 666                ),
 667                command: "go".into(),
 668                args: vec![
 669                    "test".into(),
 670                    "-fuzz=Fuzz".into(),
 671                    "-run".into(),
 672                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 673                ],
 674                tags: vec!["go-fuzz".to_owned()],
 675                cwd: package_cwd.clone(),
 676                ..TaskTemplate::default()
 677            },
 678            TaskTemplate {
 679                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
 680                command: "go".into(),
 681                args: vec!["run".into(), ".".into()],
 682                cwd: package_cwd.clone(),
 683                tags: vec!["go-main".to_owned()],
 684                ..TaskTemplate::default()
 685            },
 686            TaskTemplate {
 687                label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 688                command: "go".into(),
 689                args: vec!["generate".into()],
 690                cwd: package_cwd,
 691                tags: vec!["go-generate".to_owned()],
 692                ..TaskTemplate::default()
 693            },
 694            TaskTemplate {
 695                label: "go generate ./...".into(),
 696                command: "go".into(),
 697                args: vec!["generate".into(), "./...".into()],
 698                cwd: module_cwd,
 699                ..TaskTemplate::default()
 700            },
 701        ])))
 702    }
 703}
 704
 705fn extract_subtest_name(input: &str) -> Option<String> {
 706    let content = if input.starts_with('`') && input.ends_with('`') {
 707        input.trim_matches('`')
 708    } else {
 709        input.trim_matches('"')
 710    };
 711
 712    let processed = content
 713        .chars()
 714        .map(|c| if c.is_whitespace() { '_' } else { c })
 715        .collect::<String>();
 716
 717    Some(
 718        GO_ESCAPE_SUBTEST_NAME_REGEX
 719            .replace_all(&processed, |caps: &regex::Captures| {
 720                format!("\\{}", &caps[0])
 721            })
 722            .to_string(),
 723    )
 724}
 725
 726#[cfg(test)]
 727mod tests {
 728    use super::*;
 729    use crate::language;
 730    use gpui::{AppContext, Hsla, TestAppContext};
 731    use theme::SyntaxTheme;
 732
 733    #[gpui::test]
 734    async fn test_go_label_for_completion() {
 735        let adapter = Arc::new(GoLspAdapter);
 736        let language = language("go", tree_sitter_go::LANGUAGE.into());
 737
 738        let theme = SyntaxTheme::new_test([
 739            ("type", Hsla::default()),
 740            ("keyword", Hsla::default()),
 741            ("function", Hsla::default()),
 742            ("number", Hsla::default()),
 743            ("property", Hsla::default()),
 744        ]);
 745        language.set_theme(&theme);
 746
 747        let grammar = language.grammar().unwrap();
 748        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 749        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 750        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 751        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
 752        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 753
 754        assert_eq!(
 755            adapter
 756                .label_for_completion(
 757                    &lsp::CompletionItem {
 758                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 759                        label: "Hello".to_string(),
 760                        detail: Some("func(a B) c.D".to_string()),
 761                        ..Default::default()
 762                    },
 763                    &language
 764                )
 765                .await,
 766            Some(CodeLabel {
 767                text: "Hello(a B) c.D".to_string(),
 768                filter_range: 0..5,
 769                runs: vec![
 770                    (0..5, highlight_function),
 771                    (8..9, highlight_type),
 772                    (13..14, highlight_type),
 773                ],
 774            })
 775        );
 776
 777        // Nested methods
 778        assert_eq!(
 779            adapter
 780                .label_for_completion(
 781                    &lsp::CompletionItem {
 782                        kind: Some(lsp::CompletionItemKind::METHOD),
 783                        label: "one.two.Three".to_string(),
 784                        detail: Some("func() [3]interface{}".to_string()),
 785                        ..Default::default()
 786                    },
 787                    &language
 788                )
 789                .await,
 790            Some(CodeLabel {
 791                text: "one.two.Three() [3]interface{}".to_string(),
 792                filter_range: 0..13,
 793                runs: vec![
 794                    (8..13, highlight_function),
 795                    (17..18, highlight_number),
 796                    (19..28, highlight_keyword),
 797                ],
 798            })
 799        );
 800
 801        // Nested fields
 802        assert_eq!(
 803            adapter
 804                .label_for_completion(
 805                    &lsp::CompletionItem {
 806                        kind: Some(lsp::CompletionItemKind::FIELD),
 807                        label: "two.Three".to_string(),
 808                        detail: Some("a.Bcd".to_string()),
 809                        ..Default::default()
 810                    },
 811                    &language
 812                )
 813                .await,
 814            Some(CodeLabel {
 815                text: "two.Three a.Bcd".to_string(),
 816                filter_range: 0..9,
 817                runs: vec![(4..9, highlight_field), (12..15, highlight_type)],
 818            })
 819        );
 820    }
 821
 822    #[gpui::test]
 823    fn test_go_runnable_detection(cx: &mut TestAppContext) {
 824        let language = language("go", tree_sitter_go::LANGUAGE.into());
 825
 826        let interpreted_string_subtest = r#"
 827        package main
 828
 829        import "testing"
 830
 831        func TestExample(t *testing.T) {
 832            t.Run("subtest with double quotes", func(t *testing.T) {
 833                // test code
 834            })
 835        }
 836        "#;
 837
 838        let raw_string_subtest = r#"
 839        package main
 840
 841        import "testing"
 842
 843        func TestExample(t *testing.T) {
 844            t.Run(`subtest with
 845            multiline
 846            backticks`, func(t *testing.T) {
 847                // test code
 848            })
 849        }
 850        "#;
 851
 852        let buffer = cx.new(|cx| {
 853            crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
 854        });
 855        cx.executor().run_until_parked();
 856
 857        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 858            let snapshot = buffer.snapshot();
 859            snapshot
 860                .runnable_ranges(0..interpreted_string_subtest.len())
 861                .collect()
 862        });
 863
 864        let tag_strings: Vec<String> = runnables
 865            .iter()
 866            .flat_map(|r| &r.runnable.tags)
 867            .map(|tag| tag.0.to_string())
 868            .collect();
 869
 870        assert!(
 871            tag_strings.contains(&"go-test".to_string()),
 872            "Should find go-test tag, found: {:?}",
 873            tag_strings
 874        );
 875        assert!(
 876            tag_strings.contains(&"go-subtest".to_string()),
 877            "Should find go-subtest tag, found: {:?}",
 878            tag_strings
 879        );
 880
 881        let buffer = cx.new(|cx| {
 882            crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
 883        });
 884        cx.executor().run_until_parked();
 885
 886        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 887            let snapshot = buffer.snapshot();
 888            snapshot
 889                .runnable_ranges(0..raw_string_subtest.len())
 890                .collect()
 891        });
 892
 893        let tag_strings: Vec<String> = runnables
 894            .iter()
 895            .flat_map(|r| &r.runnable.tags)
 896            .map(|tag| tag.0.to_string())
 897            .collect();
 898
 899        assert!(
 900            tag_strings.contains(&"go-test".to_string()),
 901            "Should find go-test tag, found: {:?}",
 902            tag_strings
 903        );
 904        assert!(
 905            tag_strings.contains(&"go-subtest".to_string()),
 906            "Should find go-subtest tag, found: {:?}",
 907            tag_strings
 908        );
 909    }
 910
 911    #[gpui::test]
 912    fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
 913        let language = language("go", tree_sitter_go::LANGUAGE.into());
 914
 915        let table_test = r#"
 916        package main
 917
 918        import "testing"
 919
 920        func TestExample(t *testing.T) {
 921            _ = "some random string"
 922
 923            testCases := []struct{
 924                name string
 925                anotherStr string
 926            }{
 927                {
 928                    name: "test case 1",
 929                    anotherStr: "foo",
 930                },
 931                {
 932                    name: "test case 2",
 933                    anotherStr: "bar",
 934                },
 935            }
 936
 937            notATableTest := []struct{
 938                name string
 939            }{
 940                {
 941                    name: "some string",
 942                },
 943                {
 944                    name: "some other string",
 945                },
 946            }
 947
 948            for _, tc := range testCases {
 949                t.Run(tc.name, func(t *testing.T) {
 950                    // test code here
 951                })
 952            }
 953        }
 954        "#;
 955
 956        let buffer =
 957            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
 958        cx.executor().run_until_parked();
 959
 960        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 961            let snapshot = buffer.snapshot();
 962            snapshot.runnable_ranges(0..table_test.len()).collect()
 963        });
 964
 965        let tag_strings: Vec<String> = runnables
 966            .iter()
 967            .flat_map(|r| &r.runnable.tags)
 968            .map(|tag| tag.0.to_string())
 969            .collect();
 970
 971        assert!(
 972            tag_strings.contains(&"go-test".to_string()),
 973            "Should find go-test tag, found: {:?}",
 974            tag_strings
 975        );
 976        assert!(
 977            tag_strings.contains(&"go-table-test-case".to_string()),
 978            "Should find go-table-test-case tag, found: {:?}",
 979            tag_strings
 980        );
 981
 982        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
 983        let go_table_test_count = tag_strings
 984            .iter()
 985            .filter(|&tag| tag == "go-table-test-case")
 986            .count();
 987
 988        assert!(
 989            go_test_count == 1,
 990            "Should find exactly 1 go-test, found: {}",
 991            go_test_count
 992        );
 993        assert!(
 994            go_table_test_count == 2,
 995            "Should find exactly 2 go-table-test-case, found: {}",
 996            go_table_test_count
 997        );
 998    }
 999
1000    #[gpui::test]
1001    fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1002        let language = language("go", tree_sitter_go::LANGUAGE.into());
1003
1004        let table_test = r#"
1005        package main
1006
1007        func Example() {
1008            _ = "some random string"
1009
1010            notATableTest := []struct{
1011                name string
1012            }{
1013                {
1014                    name: "some string",
1015                },
1016                {
1017                    name: "some other string",
1018                },
1019            }
1020        }
1021        "#;
1022
1023        let buffer =
1024            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1025        cx.executor().run_until_parked();
1026
1027        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1028            let snapshot = buffer.snapshot();
1029            snapshot.runnable_ranges(0..table_test.len()).collect()
1030        });
1031
1032        let tag_strings: Vec<String> = runnables
1033            .iter()
1034            .flat_map(|r| &r.runnable.tags)
1035            .map(|tag| tag.0.to_string())
1036            .collect();
1037
1038        assert!(
1039            !tag_strings.contains(&"go-test".to_string()),
1040            "Should find go-test tag, found: {:?}",
1041            tag_strings
1042        );
1043        assert!(
1044            !tag_strings.contains(&"go-table-test-case".to_string()),
1045            "Should find go-table-test-case tag, found: {:?}",
1046            tag_strings
1047        );
1048    }
1049
1050    #[gpui::test]
1051    fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1052        let language = language("go", tree_sitter_go::LANGUAGE.into());
1053
1054        let table_test = r#"
1055        package main
1056
1057        import "testing"
1058
1059        func TestExample(t *testing.T) {
1060            _ = "some random string"
1061
1062           	testCases := map[string]struct {
1063          		someStr string
1064          		fail    bool
1065           	}{
1066          		"test failure": {
1067         			someStr: "foo",
1068         			fail:    true,
1069          		},
1070          		"test success": {
1071         			someStr: "bar",
1072         			fail:    false,
1073          		},
1074           	}
1075
1076           	notATableTest := map[string]struct {
1077          		someStr string
1078           	}{
1079          		"some string": {
1080         			someStr: "foo",
1081          		},
1082          		"some other string": {
1083         			someStr: "bar",
1084          		},
1085           	}
1086
1087            for name, tc := range testCases {
1088                t.Run(name, func(t *testing.T) {
1089                    // test code here
1090                })
1091            }
1092        }
1093        "#;
1094
1095        let buffer =
1096            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1097        cx.executor().run_until_parked();
1098
1099        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1100            let snapshot = buffer.snapshot();
1101            snapshot.runnable_ranges(0..table_test.len()).collect()
1102        });
1103
1104        let tag_strings: Vec<String> = runnables
1105            .iter()
1106            .flat_map(|r| &r.runnable.tags)
1107            .map(|tag| tag.0.to_string())
1108            .collect();
1109
1110        assert!(
1111            tag_strings.contains(&"go-test".to_string()),
1112            "Should find go-test tag, found: {:?}",
1113            tag_strings
1114        );
1115        assert!(
1116            tag_strings.contains(&"go-table-test-case".to_string()),
1117            "Should find go-table-test-case tag, found: {:?}",
1118            tag_strings
1119        );
1120
1121        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1122        let go_table_test_count = tag_strings
1123            .iter()
1124            .filter(|&tag| tag == "go-table-test-case")
1125            .count();
1126
1127        assert!(
1128            go_test_count == 1,
1129            "Should find exactly 1 go-test, found: {}",
1130            go_test_count
1131        );
1132        assert!(
1133            go_table_test_count == 2,
1134            "Should find exactly 2 go-table-test-case, found: {}",
1135            go_table_test_count
1136        );
1137    }
1138
1139    #[gpui::test]
1140    fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1141        let language = language("go", tree_sitter_go::LANGUAGE.into());
1142
1143        let table_test = r#"
1144        package main
1145
1146        func Example() {
1147            _ = "some random string"
1148
1149           	notATableTest := map[string]struct {
1150          		someStr string
1151           	}{
1152          		"some string": {
1153         			someStr: "foo",
1154          		},
1155          		"some other string": {
1156         			someStr: "bar",
1157          		},
1158           	}
1159        }
1160        "#;
1161
1162        let buffer =
1163            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1164        cx.executor().run_until_parked();
1165
1166        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1167            let snapshot = buffer.snapshot();
1168            snapshot.runnable_ranges(0..table_test.len()).collect()
1169        });
1170
1171        let tag_strings: Vec<String> = runnables
1172            .iter()
1173            .flat_map(|r| &r.runnable.tags)
1174            .map(|tag| tag.0.to_string())
1175            .collect();
1176
1177        assert!(
1178            !tag_strings.contains(&"go-test".to_string()),
1179            "Should find go-test tag, found: {:?}",
1180            tag_strings
1181        );
1182        assert!(
1183            !tag_strings.contains(&"go-table-test-case".to_string()),
1184            "Should find go-table-test-case tag, found: {:?}",
1185            tag_strings
1186        );
1187    }
1188
1189    #[test]
1190    fn test_extract_subtest_name() {
1191        // Interpreted string literal
1192        let input_double_quoted = r#""subtest with double quotes""#;
1193        let result = extract_subtest_name(input_double_quoted);
1194        assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1195
1196        let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1197        let result = extract_subtest_name(input_double_quoted_with_backticks);
1198        assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1199
1200        // Raw string literal
1201        let input_with_backticks = r#"`subtest with backticks`"#;
1202        let result = extract_subtest_name(input_with_backticks);
1203        assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1204
1205        let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1206        let result = extract_subtest_name(input_raw_with_quotes);
1207        assert_eq!(
1208            result,
1209            Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1210        );
1211
1212        let input_multiline = r#"`subtest with
1213        multiline
1214        backticks`"#;
1215        let result = extract_subtest_name(input_multiline);
1216        assert_eq!(
1217            result,
1218            Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1219        );
1220
1221        let input_with_double_quotes = r#"`test with "double quotes"`"#;
1222        let result = extract_subtest_name(input_with_double_quotes);
1223        assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1224    }
1225}