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};
   9use project::Fs;
  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    ) -> Result<Box<dyn 'static + Send + Any>> {
  63        let release =
  64            latest_github_release("golang/tools", false, false, delegate.http_client()).await?;
  65        let version: Option<String> = release.tag_name.strip_prefix("gopls/v").map(str::to_string);
  66        if version.is_none() {
  67            log::warn!(
  68                "couldn't infer gopls version from GitHub release tag name '{}'",
  69                release.tag_name
  70            );
  71        }
  72        Ok(Box::new(version) as Box<_>)
  73    }
  74
  75    async fn check_if_user_installed(
  76        &self,
  77        delegate: &dyn LspAdapterDelegate,
  78        _: Option<Toolchain>,
  79        _: &AsyncApp,
  80    ) -> Option<LanguageServerBinary> {
  81        let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
  82        Some(LanguageServerBinary {
  83            path,
  84            arguments: server_binary_arguments(),
  85            env: None,
  86        })
  87    }
  88
  89    fn will_fetch_server(
  90        &self,
  91        delegate: &Arc<dyn LspAdapterDelegate>,
  92        cx: &mut AsyncApp,
  93    ) -> Option<Task<Result<()>>> {
  94        static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
  95
  96        const NOTIFICATION_MESSAGE: &str =
  97            "Could not install the Go language server `gopls`, because `go` was not found.";
  98
  99        let delegate = delegate.clone();
 100        Some(cx.spawn(async move |cx| {
 101            if delegate.which("go".as_ref()).await.is_none() {
 102                if DID_SHOW_NOTIFICATION
 103                    .compare_exchange(false, true, SeqCst, SeqCst)
 104                    .is_ok()
 105                {
 106                    cx.update(|cx| {
 107                        delegate.show_notification(NOTIFICATION_MESSAGE, cx);
 108                    })?
 109                }
 110                anyhow::bail!("cannot install gopls");
 111            }
 112            Ok(())
 113        }))
 114    }
 115
 116    async fn fetch_server_binary(
 117        &self,
 118        version: Box<dyn 'static + Send + Any>,
 119        container_dir: PathBuf,
 120        delegate: &dyn LspAdapterDelegate,
 121    ) -> Result<LanguageServerBinary> {
 122        let go = delegate.which("go".as_ref()).await.unwrap_or("go".into());
 123        let go_version_output = util::command::new_smol_command(&go)
 124            .args(["version"])
 125            .output()
 126            .await
 127            .context("failed to get go version via `go version` command`")?;
 128        let go_version = parse_version_output(&go_version_output)?;
 129        let version = version.downcast::<Option<String>>().unwrap();
 130        let this = *self;
 131
 132        if let Some(version) = *version {
 133            let binary_path = container_dir.join(format!("gopls_{version}_go_{go_version}"));
 134            if let Ok(metadata) = fs::metadata(&binary_path).await
 135                && metadata.is_file()
 136            {
 137                remove_matching(&container_dir, |entry| {
 138                    entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
 139                })
 140                .await;
 141
 142                return Ok(LanguageServerBinary {
 143                    path: binary_path.to_path_buf(),
 144                    arguments: server_binary_arguments(),
 145                    env: None,
 146                });
 147            }
 148        } else if let Some(path) = this
 149            .cached_server_binary(container_dir.clone(), delegate)
 150            .await
 151        {
 152            return Ok(path);
 153        }
 154
 155        let gobin_dir = container_dir.join("gobin");
 156        fs::create_dir_all(&gobin_dir).await?;
 157        let install_output = util::command::new_smol_command(go)
 158            .env("GO111MODULE", "on")
 159            .env("GOBIN", &gobin_dir)
 160            .args(["install", "golang.org/x/tools/gopls@latest"])
 161            .output()
 162            .await?;
 163
 164        if !install_output.status.success() {
 165            log::error!(
 166                "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
 167                String::from_utf8_lossy(&install_output.stdout),
 168                String::from_utf8_lossy(&install_output.stderr)
 169            );
 170            anyhow::bail!(
 171                "failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
 172            );
 173        }
 174
 175        let installed_binary_path = gobin_dir.join(BINARY);
 176        let version_output = util::command::new_smol_command(&installed_binary_path)
 177            .arg("version")
 178            .output()
 179            .await
 180            .context("failed to run installed gopls binary")?;
 181        let gopls_version = parse_version_output(&version_output)?;
 182        let binary_path = container_dir.join(format!("gopls_{gopls_version}_go_{go_version}"));
 183        fs::rename(&installed_binary_path, &binary_path).await?;
 184
 185        Ok(LanguageServerBinary {
 186            path: binary_path.to_path_buf(),
 187            arguments: server_binary_arguments(),
 188            env: None,
 189        })
 190    }
 191
 192    async fn cached_server_binary(
 193        &self,
 194        container_dir: PathBuf,
 195        _: &dyn LspAdapterDelegate,
 196    ) -> Option<LanguageServerBinary> {
 197        get_cached_server_binary(container_dir).await
 198    }
 199
 200    async fn initialization_options(
 201        self: Arc<Self>,
 202        _: &dyn Fs,
 203        _: &Arc<dyn LspAdapterDelegate>,
 204    ) -> Result<Option<serde_json::Value>> {
 205        Ok(Some(json!({
 206            "usePlaceholders": true,
 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(
 571        &self,
 572        _: Arc<dyn Fs>,
 573        _: Option<Arc<dyn File>>,
 574        _: &App,
 575    ) -> Task<Option<TaskTemplates>> {
 576        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
 577            None
 578        } else {
 579            Some("$ZED_DIRNAME".to_string())
 580        };
 581        let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
 582
 583        Task::ready(Some(TaskTemplates(vec![
 584            TaskTemplate {
 585                label: format!(
 586                    "go test {} -v -run {}/{}",
 587                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 588                    VariableName::Symbol.template_value(),
 589                    GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 590                ),
 591                command: "go".into(),
 592                args: vec![
 593                    "test".into(),
 594                    "-v".into(),
 595                    "-run".into(),
 596                    format!(
 597                        "\\^{}\\$/\\^{}\\$",
 598                        VariableName::Symbol.template_value(),
 599                        GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 600                    ),
 601                ],
 602                cwd: package_cwd.clone(),
 603                tags: vec!["go-table-test-case".to_owned()],
 604                ..TaskTemplate::default()
 605            },
 606            TaskTemplate {
 607                label: format!(
 608                    "go test {} -run {}",
 609                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 610                    VariableName::Symbol.template_value(),
 611                ),
 612                command: "go".into(),
 613                args: vec![
 614                    "test".into(),
 615                    "-run".into(),
 616                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 617                ],
 618                tags: vec!["go-test".to_owned()],
 619                cwd: package_cwd.clone(),
 620                ..TaskTemplate::default()
 621            },
 622            TaskTemplate {
 623                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 624                command: "go".into(),
 625                args: vec!["test".into()],
 626                cwd: package_cwd.clone(),
 627                ..TaskTemplate::default()
 628            },
 629            TaskTemplate {
 630                label: "go test ./...".into(),
 631                command: "go".into(),
 632                args: vec!["test".into(), "./...".into()],
 633                cwd: module_cwd.clone(),
 634                ..TaskTemplate::default()
 635            },
 636            TaskTemplate {
 637                label: format!(
 638                    "go test {} -v -run {}/{}",
 639                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 640                    VariableName::Symbol.template_value(),
 641                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 642                ),
 643                command: "go".into(),
 644                args: vec![
 645                    "test".into(),
 646                    "-v".into(),
 647                    "-run".into(),
 648                    format!(
 649                        "\\^{}\\$/\\^{}\\$",
 650                        VariableName::Symbol.template_value(),
 651                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 652                    ),
 653                ],
 654                cwd: package_cwd.clone(),
 655                tags: vec!["go-subtest".to_owned()],
 656                ..TaskTemplate::default()
 657            },
 658            TaskTemplate {
 659                label: format!(
 660                    "go test {} -bench {}",
 661                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 662                    VariableName::Symbol.template_value()
 663                ),
 664                command: "go".into(),
 665                args: vec![
 666                    "test".into(),
 667                    "-benchmem".into(),
 668                    "-run='^$'".into(),
 669                    "-bench".into(),
 670                    format!("\\^{}\\$", VariableName::Symbol.template_value()),
 671                ],
 672                cwd: package_cwd.clone(),
 673                tags: vec!["go-benchmark".to_owned()],
 674                ..TaskTemplate::default()
 675            },
 676            TaskTemplate {
 677                label: format!(
 678                    "go test {} -fuzz=Fuzz -run {}",
 679                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 680                    VariableName::Symbol.template_value(),
 681                ),
 682                command: "go".into(),
 683                args: vec![
 684                    "test".into(),
 685                    "-fuzz=Fuzz".into(),
 686                    "-run".into(),
 687                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 688                ],
 689                tags: vec!["go-fuzz".to_owned()],
 690                cwd: package_cwd.clone(),
 691                ..TaskTemplate::default()
 692            },
 693            TaskTemplate {
 694                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
 695                command: "go".into(),
 696                args: vec!["run".into(), ".".into()],
 697                cwd: package_cwd.clone(),
 698                tags: vec!["go-main".to_owned()],
 699                ..TaskTemplate::default()
 700            },
 701            TaskTemplate {
 702                label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 703                command: "go".into(),
 704                args: vec!["generate".into()],
 705                cwd: package_cwd,
 706                tags: vec!["go-generate".to_owned()],
 707                ..TaskTemplate::default()
 708            },
 709            TaskTemplate {
 710                label: "go generate ./...".into(),
 711                command: "go".into(),
 712                args: vec!["generate".into(), "./...".into()],
 713                cwd: module_cwd,
 714                ..TaskTemplate::default()
 715            },
 716        ])))
 717    }
 718}
 719
 720fn extract_subtest_name(input: &str) -> Option<String> {
 721    let content = if input.starts_with('`') && input.ends_with('`') {
 722        input.trim_matches('`')
 723    } else {
 724        input.trim_matches('"')
 725    };
 726
 727    let processed = content
 728        .chars()
 729        .map(|c| if c.is_whitespace() { '_' } else { c })
 730        .collect::<String>();
 731
 732    Some(
 733        GO_ESCAPE_SUBTEST_NAME_REGEX
 734            .replace_all(&processed, |caps: &regex::Captures| {
 735                format!("\\{}", &caps[0])
 736            })
 737            .to_string(),
 738    )
 739}
 740
 741#[cfg(test)]
 742mod tests {
 743    use super::*;
 744    use crate::language;
 745    use gpui::{AppContext, Hsla, TestAppContext};
 746    use theme::SyntaxTheme;
 747
 748    #[gpui::test]
 749    async fn test_go_label_for_completion() {
 750        let adapter = Arc::new(GoLspAdapter);
 751        let language = language("go", tree_sitter_go::LANGUAGE.into());
 752
 753        let theme = SyntaxTheme::new_test([
 754            ("type", Hsla::default()),
 755            ("keyword", Hsla::default()),
 756            ("function", Hsla::default()),
 757            ("number", Hsla::default()),
 758            ("property", Hsla::default()),
 759        ]);
 760        language.set_theme(&theme);
 761
 762        let grammar = language.grammar().unwrap();
 763        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 764        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 765        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 766        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
 767
 768        assert_eq!(
 769            adapter
 770                .label_for_completion(
 771                    &lsp::CompletionItem {
 772                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 773                        label: "Hello".to_string(),
 774                        detail: Some("func(a B) c.D".to_string()),
 775                        ..Default::default()
 776                    },
 777                    &language
 778                )
 779                .await,
 780            Some(CodeLabel {
 781                text: "Hello(a B) c.D".to_string(),
 782                filter_range: 0..5,
 783                runs: vec![
 784                    (0..5, highlight_function),
 785                    (8..9, highlight_type),
 786                    (13..14, highlight_type),
 787                ],
 788            })
 789        );
 790
 791        // Nested methods
 792        assert_eq!(
 793            adapter
 794                .label_for_completion(
 795                    &lsp::CompletionItem {
 796                        kind: Some(lsp::CompletionItemKind::METHOD),
 797                        label: "one.two.Three".to_string(),
 798                        detail: Some("func() [3]interface{}".to_string()),
 799                        ..Default::default()
 800                    },
 801                    &language
 802                )
 803                .await,
 804            Some(CodeLabel {
 805                text: "one.two.Three() [3]interface{}".to_string(),
 806                filter_range: 0..13,
 807                runs: vec![
 808                    (8..13, highlight_function),
 809                    (17..18, highlight_number),
 810                    (19..28, highlight_keyword),
 811                ],
 812            })
 813        );
 814
 815        // Nested fields
 816        assert_eq!(
 817            adapter
 818                .label_for_completion(
 819                    &lsp::CompletionItem {
 820                        kind: Some(lsp::CompletionItemKind::FIELD),
 821                        label: "two.Three".to_string(),
 822                        detail: Some("a.Bcd".to_string()),
 823                        ..Default::default()
 824                    },
 825                    &language
 826                )
 827                .await,
 828            Some(CodeLabel {
 829                text: "two.Three a.Bcd".to_string(),
 830                filter_range: 0..9,
 831                runs: vec![(12..15, highlight_type)],
 832            })
 833        );
 834    }
 835
 836    #[gpui::test]
 837    fn test_go_runnable_detection(cx: &mut TestAppContext) {
 838        let language = language("go", tree_sitter_go::LANGUAGE.into());
 839
 840        let interpreted_string_subtest = r#"
 841        package main
 842
 843        import "testing"
 844
 845        func TestExample(t *testing.T) {
 846            t.Run("subtest with double quotes", func(t *testing.T) {
 847                // test code
 848            })
 849        }
 850        "#;
 851
 852        let raw_string_subtest = r#"
 853        package main
 854
 855        import "testing"
 856
 857        func TestExample(t *testing.T) {
 858            t.Run(`subtest with
 859            multiline
 860            backticks`, func(t *testing.T) {
 861                // test code
 862            })
 863        }
 864        "#;
 865
 866        let buffer = cx.new(|cx| {
 867            crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
 868        });
 869        cx.executor().run_until_parked();
 870
 871        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 872            let snapshot = buffer.snapshot();
 873            snapshot
 874                .runnable_ranges(0..interpreted_string_subtest.len())
 875                .collect()
 876        });
 877
 878        let tag_strings: Vec<String> = runnables
 879            .iter()
 880            .flat_map(|r| &r.runnable.tags)
 881            .map(|tag| tag.0.to_string())
 882            .collect();
 883
 884        assert!(
 885            tag_strings.contains(&"go-test".to_string()),
 886            "Should find go-test tag, found: {:?}",
 887            tag_strings
 888        );
 889        assert!(
 890            tag_strings.contains(&"go-subtest".to_string()),
 891            "Should find go-subtest tag, found: {:?}",
 892            tag_strings
 893        );
 894
 895        let buffer = cx.new(|cx| {
 896            crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
 897        });
 898        cx.executor().run_until_parked();
 899
 900        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 901            let snapshot = buffer.snapshot();
 902            snapshot
 903                .runnable_ranges(0..raw_string_subtest.len())
 904                .collect()
 905        });
 906
 907        let tag_strings: Vec<String> = runnables
 908            .iter()
 909            .flat_map(|r| &r.runnable.tags)
 910            .map(|tag| tag.0.to_string())
 911            .collect();
 912
 913        assert!(
 914            tag_strings.contains(&"go-test".to_string()),
 915            "Should find go-test tag, found: {:?}",
 916            tag_strings
 917        );
 918        assert!(
 919            tag_strings.contains(&"go-subtest".to_string()),
 920            "Should find go-subtest tag, found: {:?}",
 921            tag_strings
 922        );
 923    }
 924
 925    #[gpui::test]
 926    fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
 927        let language = language("go", tree_sitter_go::LANGUAGE.into());
 928
 929        let table_test = r#"
 930        package main
 931
 932        import "testing"
 933
 934        func TestExample(t *testing.T) {
 935            _ = "some random string"
 936
 937            testCases := []struct{
 938                name string
 939                anotherStr string
 940            }{
 941                {
 942                    name: "test case 1",
 943                    anotherStr: "foo",
 944                },
 945                {
 946                    name: "test case 2",
 947                    anotherStr: "bar",
 948                },
 949            }
 950
 951            notATableTest := []struct{
 952                name string
 953            }{
 954                {
 955                    name: "some string",
 956                },
 957                {
 958                    name: "some other string",
 959                },
 960            }
 961
 962            for _, tc := range testCases {
 963                t.Run(tc.name, func(t *testing.T) {
 964                    // test code here
 965                })
 966            }
 967        }
 968        "#;
 969
 970        let buffer =
 971            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
 972        cx.executor().run_until_parked();
 973
 974        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 975            let snapshot = buffer.snapshot();
 976            snapshot.runnable_ranges(0..table_test.len()).collect()
 977        });
 978
 979        let tag_strings: Vec<String> = runnables
 980            .iter()
 981            .flat_map(|r| &r.runnable.tags)
 982            .map(|tag| tag.0.to_string())
 983            .collect();
 984
 985        assert!(
 986            tag_strings.contains(&"go-test".to_string()),
 987            "Should find go-test tag, found: {:?}",
 988            tag_strings
 989        );
 990        assert!(
 991            tag_strings.contains(&"go-table-test-case".to_string()),
 992            "Should find go-table-test-case tag, found: {:?}",
 993            tag_strings
 994        );
 995
 996        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
 997        let go_table_test_count = tag_strings
 998            .iter()
 999            .filter(|&tag| tag == "go-table-test-case")
1000            .count();
1001
1002        assert!(
1003            go_test_count == 1,
1004            "Should find exactly 1 go-test, found: {}",
1005            go_test_count
1006        );
1007        assert!(
1008            go_table_test_count == 2,
1009            "Should find exactly 2 go-table-test-case, found: {}",
1010            go_table_test_count
1011        );
1012    }
1013
1014    #[gpui::test]
1015    fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1016        let language = language("go", tree_sitter_go::LANGUAGE.into());
1017
1018        let table_test = r#"
1019        package main
1020
1021        func Example() {
1022            _ = "some random string"
1023
1024            notATableTest := []struct{
1025                name string
1026            }{
1027                {
1028                    name: "some string",
1029                },
1030                {
1031                    name: "some other string",
1032                },
1033            }
1034        }
1035        "#;
1036
1037        let buffer =
1038            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1039        cx.executor().run_until_parked();
1040
1041        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1042            let snapshot = buffer.snapshot();
1043            snapshot.runnable_ranges(0..table_test.len()).collect()
1044        });
1045
1046        let tag_strings: Vec<String> = runnables
1047            .iter()
1048            .flat_map(|r| &r.runnable.tags)
1049            .map(|tag| tag.0.to_string())
1050            .collect();
1051
1052        assert!(
1053            !tag_strings.contains(&"go-test".to_string()),
1054            "Should find go-test tag, found: {:?}",
1055            tag_strings
1056        );
1057        assert!(
1058            !tag_strings.contains(&"go-table-test-case".to_string()),
1059            "Should find go-table-test-case tag, found: {:?}",
1060            tag_strings
1061        );
1062    }
1063
1064    #[gpui::test]
1065    fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1066        let language = language("go", tree_sitter_go::LANGUAGE.into());
1067
1068        let table_test = r#"
1069        package main
1070
1071        import "testing"
1072
1073        func TestExample(t *testing.T) {
1074            _ = "some random string"
1075
1076           	testCases := map[string]struct {
1077          		someStr string
1078          		fail    bool
1079           	}{
1080          		"test failure": {
1081         			someStr: "foo",
1082         			fail:    true,
1083          		},
1084          		"test success": {
1085         			someStr: "bar",
1086         			fail:    false,
1087          		},
1088           	}
1089
1090           	notATableTest := map[string]struct {
1091          		someStr string
1092           	}{
1093          		"some string": {
1094         			someStr: "foo",
1095          		},
1096          		"some other string": {
1097         			someStr: "bar",
1098          		},
1099           	}
1100
1101            for name, tc := range testCases {
1102                t.Run(name, func(t *testing.T) {
1103                    // test code here
1104                })
1105            }
1106        }
1107        "#;
1108
1109        let buffer =
1110            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1111        cx.executor().run_until_parked();
1112
1113        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1114            let snapshot = buffer.snapshot();
1115            snapshot.runnable_ranges(0..table_test.len()).collect()
1116        });
1117
1118        let tag_strings: Vec<String> = runnables
1119            .iter()
1120            .flat_map(|r| &r.runnable.tags)
1121            .map(|tag| tag.0.to_string())
1122            .collect();
1123
1124        assert!(
1125            tag_strings.contains(&"go-test".to_string()),
1126            "Should find go-test tag, found: {:?}",
1127            tag_strings
1128        );
1129        assert!(
1130            tag_strings.contains(&"go-table-test-case".to_string()),
1131            "Should find go-table-test-case tag, found: {:?}",
1132            tag_strings
1133        );
1134
1135        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1136        let go_table_test_count = tag_strings
1137            .iter()
1138            .filter(|&tag| tag == "go-table-test-case")
1139            .count();
1140
1141        assert!(
1142            go_test_count == 1,
1143            "Should find exactly 1 go-test, found: {}",
1144            go_test_count
1145        );
1146        assert!(
1147            go_table_test_count == 2,
1148            "Should find exactly 2 go-table-test-case, found: {}",
1149            go_table_test_count
1150        );
1151    }
1152
1153    #[gpui::test]
1154    fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1155        let language = language("go", tree_sitter_go::LANGUAGE.into());
1156
1157        let table_test = r#"
1158        package main
1159
1160        func Example() {
1161            _ = "some random string"
1162
1163           	notATableTest := map[string]struct {
1164          		someStr string
1165           	}{
1166          		"some string": {
1167         			someStr: "foo",
1168          		},
1169          		"some other string": {
1170         			someStr: "bar",
1171          		},
1172           	}
1173        }
1174        "#;
1175
1176        let buffer =
1177            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1178        cx.executor().run_until_parked();
1179
1180        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1181            let snapshot = buffer.snapshot();
1182            snapshot.runnable_ranges(0..table_test.len()).collect()
1183        });
1184
1185        let tag_strings: Vec<String> = runnables
1186            .iter()
1187            .flat_map(|r| &r.runnable.tags)
1188            .map(|tag| tag.0.to_string())
1189            .collect();
1190
1191        assert!(
1192            !tag_strings.contains(&"go-test".to_string()),
1193            "Should find go-test tag, found: {:?}",
1194            tag_strings
1195        );
1196        assert!(
1197            !tag_strings.contains(&"go-table-test-case".to_string()),
1198            "Should find go-table-test-case tag, found: {:?}",
1199            tag_strings
1200        );
1201    }
1202
1203    #[test]
1204    fn test_extract_subtest_name() {
1205        // Interpreted string literal
1206        let input_double_quoted = r#""subtest with double quotes""#;
1207        let result = extract_subtest_name(input_double_quoted);
1208        assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1209
1210        let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1211        let result = extract_subtest_name(input_double_quoted_with_backticks);
1212        assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1213
1214        // Raw string literal
1215        let input_with_backticks = r#"`subtest with backticks`"#;
1216        let result = extract_subtest_name(input_with_backticks);
1217        assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1218
1219        let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1220        let result = extract_subtest_name(input_raw_with_quotes);
1221        assert_eq!(
1222            result,
1223            Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1224        );
1225
1226        let input_multiline = r#"`subtest with
1227        multiline
1228        backticks`"#;
1229        let result = extract_subtest_name(input_multiline);
1230        assert_eq!(
1231            result,
1232            Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1233        );
1234
1235        let input_with_double_quotes = r#"`test with "double quotes"`"#;
1236        let result = extract_subtest_name(input_with_double_quotes);
1237        assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1238    }
1239}