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