go.rs

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