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