|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import pathlib |
| 6 | +import subprocess |
| 7 | +from contextlib import asynccontextmanager |
| 8 | +from typing import AsyncIterator |
| 9 | + |
| 10 | +from multilspy.multilspy_logger import MultilspyLogger |
| 11 | +from multilspy.language_server import LanguageServer |
| 12 | +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo |
| 13 | +from multilspy.lsp_protocol_handler.lsp_types import InitializeParams |
| 14 | +from multilspy.multilspy_config import MultilspyConfig |
| 15 | + |
| 16 | + |
| 17 | +class Gopls(LanguageServer): |
| 18 | + """ |
| 19 | + Provides Go specific instantiation of the LanguageServer class using gopls. |
| 20 | + """ |
| 21 | + |
| 22 | + @staticmethod |
| 23 | + def _get_go_version(): |
| 24 | + """Get the installed Go version or None if not found.""" |
| 25 | + try: |
| 26 | + result = subprocess.run(['go', 'version'], capture_output=True, text=True) |
| 27 | + if result.returncode == 0: |
| 28 | + return result.stdout.strip() |
| 29 | + except FileNotFoundError: |
| 30 | + return None |
| 31 | + return None |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def _get_gopls_version(): |
| 35 | + """Get the installed gopls version or None if not found.""" |
| 36 | + try: |
| 37 | + result = subprocess.run(['gopls', 'version'], capture_output=True, text=True) |
| 38 | + if result.returncode == 0: |
| 39 | + return result.stdout.strip() |
| 40 | + except FileNotFoundError: |
| 41 | + return None |
| 42 | + return None |
| 43 | + |
| 44 | + @classmethod |
| 45 | + def setup_runtime_dependency(cls): |
| 46 | + """ |
| 47 | + Check if required Go runtime dependencies are available. |
| 48 | + Raises RuntimeError with helpful message if dependencies are missing. |
| 49 | + """ |
| 50 | + missing_deps = [] |
| 51 | + |
| 52 | + # Check for Go installation |
| 53 | + go_version = cls._get_go_version() |
| 54 | + if not go_version: |
| 55 | + missing_deps.append(("Go", "https://golang.org/doc/install")) |
| 56 | + |
| 57 | + # Check for gopls |
| 58 | + gopls_version = cls._get_gopls_version() |
| 59 | + if not gopls_version: |
| 60 | + missing_deps.append(("gopls", "https://pkg.go.dev/golang.org/x/tools/gopls#section-readme")) |
| 61 | + |
| 62 | + if missing_deps: |
| 63 | + error_msg = "Missing required dependencies:\n" |
| 64 | + for dep, install_url in missing_deps: |
| 65 | + error_msg += f"- {dep}: Please install from {install_url}\n" |
| 66 | + raise RuntimeError(error_msg) |
| 67 | + |
| 68 | + return True |
| 69 | + |
| 70 | + def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str): |
| 71 | + # Check runtime dependencies before initializing |
| 72 | + self.setup_runtime_dependency() |
| 73 | + |
| 74 | + super().__init__( |
| 75 | + config, |
| 76 | + logger, |
| 77 | + repository_root_path, |
| 78 | + ProcessLaunchInfo(cmd="gopls", cwd=repository_root_path), |
| 79 | + "go", |
| 80 | + ) |
| 81 | + self.server_ready = asyncio.Event() |
| 82 | + self.request_id = 0 |
| 83 | + |
| 84 | + def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: |
| 85 | + """ |
| 86 | + Returns the initialize params for the TypeScript Language Server. |
| 87 | + """ |
| 88 | + with open(os.path.join(os.path.dirname(__file__), "initialize_params.json"), "r") as f: |
| 89 | + d = json.load(f) |
| 90 | + |
| 91 | + del d["_description"] |
| 92 | + |
| 93 | + d["processId"] = os.getpid() |
| 94 | + assert d["rootPath"] == "$rootPath" |
| 95 | + d["rootPath"] = repository_absolute_path |
| 96 | + |
| 97 | + assert d["rootUri"] == "$rootUri" |
| 98 | + d["rootUri"] = pathlib.Path(repository_absolute_path).as_uri() |
| 99 | + |
| 100 | + assert d["workspaceFolders"][0]["uri"] == "$uri" |
| 101 | + d["workspaceFolders"][0]["uri"] = pathlib.Path(repository_absolute_path).as_uri() |
| 102 | + |
| 103 | + assert d["workspaceFolders"][0]["name"] == "$name" |
| 104 | + d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path) |
| 105 | + |
| 106 | + return d |
| 107 | + |
| 108 | + @asynccontextmanager |
| 109 | + async def start_server(self) -> AsyncIterator["Gopls"]: |
| 110 | + """Start gopls server process""" |
| 111 | + async def register_capability_handler(params): |
| 112 | + return |
| 113 | + |
| 114 | + async def window_log_message(msg): |
| 115 | + self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO) |
| 116 | + |
| 117 | + async def do_nothing(params): |
| 118 | + return |
| 119 | + |
| 120 | + self.server.on_request("client/registerCapability", register_capability_handler) |
| 121 | + self.server.on_notification("window/logMessage", window_log_message) |
| 122 | + self.server.on_notification("$/progress", do_nothing) |
| 123 | + self.server.on_notification("textDocument/publishDiagnostics", do_nothing) |
| 124 | + |
| 125 | + async with super().start_server(): |
| 126 | + self.logger.log("Starting gopls server process", logging.INFO) |
| 127 | + await self.server.start() |
| 128 | + initialize_params = self._get_initialize_params(self.repository_root_path) |
| 129 | + |
| 130 | + self.logger.log( |
| 131 | + "Sending initialize request from LSP client to LSP server and awaiting response", |
| 132 | + logging.INFO, |
| 133 | + ) |
| 134 | + init_response = await self.server.send.initialize(initialize_params) |
| 135 | + |
| 136 | + # Verify server capabilities |
| 137 | + assert "textDocumentSync" in init_response["capabilities"] |
| 138 | + assert "completionProvider" in init_response["capabilities"] |
| 139 | + assert "definitionProvider" in init_response["capabilities"] |
| 140 | + |
| 141 | + self.server.notify.initialized({}) |
| 142 | + self.completions_available.set() |
| 143 | + |
| 144 | + # gopls server is typically ready immediately after initialization |
| 145 | + self.server_ready.set() |
| 146 | + await self.server_ready.wait() |
| 147 | + |
| 148 | + yield self |
| 149 | + |
| 150 | + await self.server.shutdown() |
| 151 | + await self.server.stop() |
0 commit comments