|
| 1 | +""" |
| 2 | +Provides Ruby specific instantiation of the LanguageServer class using Solargraph. |
| 3 | +Contains various configurations and settings specific to Ruby. |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import json |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import stat |
| 11 | +import subprocess |
| 12 | +import pathlib |
| 13 | +from contextlib import asynccontextmanager |
| 14 | +from typing import AsyncIterator |
| 15 | + |
| 16 | +from multilspy.multilspy_logger import MultilspyLogger |
| 17 | +from multilspy.language_server import LanguageServer |
| 18 | +from multilspy.lsp_protocol_handler.server import ProcessLaunchInfo |
| 19 | +from multilspy.lsp_protocol_handler.lsp_types import InitializeParams |
| 20 | +from multilspy.multilspy_config import MultilspyConfig |
| 21 | +from multilspy.multilspy_utils import FileUtils |
| 22 | +from multilspy.multilspy_utils import PlatformUtils, PlatformId |
| 23 | + |
| 24 | + |
| 25 | +class Solargraph(LanguageServer): |
| 26 | + """ |
| 27 | + Provides Ruby specific instantiation of the LanguageServer class using Solargraph. |
| 28 | + Contains various configurations and settings specific to Ruby. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self, config: MultilspyConfig, logger: MultilspyLogger, repository_root_path: str): |
| 32 | + """ |
| 33 | + Creates a Solargraph instance. This class is not meant to be instantiated directly. |
| 34 | + Use LanguageServer.create() instead. |
| 35 | + """ |
| 36 | + solargraph_executable_path = self.setup_runtime_dependencies(logger, config, repository_root_path) |
| 37 | + super().__init__( |
| 38 | + config, |
| 39 | + logger, |
| 40 | + repository_root_path, |
| 41 | + ProcessLaunchInfo(cmd=f"{solargraph_executable_path} stdio", cwd=repository_root_path), |
| 42 | + "ruby", |
| 43 | + ) |
| 44 | + self.server_ready = asyncio.Event() |
| 45 | + |
| 46 | + def setup_runtime_dependencies(self, logger: MultilspyLogger, config: MultilspyConfig, repository_root_path: str) -> str: |
| 47 | + """ |
| 48 | + Setup runtime dependencies for Solargraph. |
| 49 | + """ |
| 50 | + platform_id = PlatformUtils.get_platform_id() |
| 51 | + which_cmd = "which" |
| 52 | + if platform_id in [PlatformId.WIN_x64, PlatformId.WIN_arm64, PlatformId.WIN_x86]: |
| 53 | + which_cmd = "where" |
| 54 | + |
| 55 | + with open(os.path.join(os.path.dirname(__file__), "runtime_dependencies.json"), "r") as f: |
| 56 | + d = json.load(f) |
| 57 | + del d["_description"] |
| 58 | + |
| 59 | + dependency = d["runtimeDependencies"][0] |
| 60 | + |
| 61 | + # Check if Ruby is installed |
| 62 | + try: |
| 63 | + result = subprocess.run(["ruby", "--version"], check=True, capture_output=True, cwd=repository_root_path) |
| 64 | + ruby_version = result.stdout.strip() |
| 65 | + logger.log(f"Ruby version: {ruby_version}", logging.INFO) |
| 66 | + except subprocess.CalledProcessError as e: |
| 67 | + raise RuntimeError(f"Error checking for Ruby installation: {e.stderr}") |
| 68 | + except FileNotFoundError: |
| 69 | + raise RuntimeError("Ruby is not installed. Please install Ruby before continuing.") |
| 70 | + |
| 71 | + # Check if solargraph is installed |
| 72 | + try: |
| 73 | + result = subprocess.run(["gem", "list", "^solargraph$", "-i"], check=False, capture_output=True, text=True, cwd=repository_root_path) |
| 74 | + if result.stdout.strip() == "false": |
| 75 | + logger.log("Installing Solargraph...", logging.INFO) |
| 76 | + subprocess.run(dependency["installCommand"].split(), check=True, capture_output=True, cwd=repository_root_path) |
| 77 | + except subprocess.CalledProcessError as e: |
| 78 | + raise RuntimeError(f"Failed to check or install Solargraph. {e.stderr}") |
| 79 | + |
| 80 | + # Get the solargraph executable path |
| 81 | + try: |
| 82 | + result = subprocess.run([which_cmd, "solargraph"], check=True, capture_output=True, text=True, cwd=repository_root_path) |
| 83 | + executeable_path = result.stdout.strip() |
| 84 | + |
| 85 | + if not os.path.exists(executeable_path): |
| 86 | + raise RuntimeError(f"Solargraph executable not found at {executeable_path}") |
| 87 | + |
| 88 | + # Ensure the executable has the right permissions |
| 89 | + os.chmod(executeable_path, os.stat(executeable_path).st_mode | stat.S_IEXEC) |
| 90 | + |
| 91 | + return executeable_path |
| 92 | + except subprocess.CalledProcessError: |
| 93 | + raise RuntimeError("Failed to locate Solargraph executable.") |
| 94 | + |
| 95 | + def _get_initialize_params(self, repository_absolute_path: str) -> InitializeParams: |
| 96 | + """ |
| 97 | + Returns the initialize params for the Solargraph Language Server. |
| 98 | + """ |
| 99 | + with open(os.path.join(os.path.dirname(__file__), "initialize_params.json"), "r") as f: |
| 100 | + d = json.load(f) |
| 101 | + |
| 102 | + del d["_description"] |
| 103 | + |
| 104 | + d["processId"] = os.getpid() |
| 105 | + assert d["rootPath"] == "$rootPath" |
| 106 | + d["rootPath"] = repository_absolute_path |
| 107 | + |
| 108 | + assert d["rootUri"] == "$rootUri" |
| 109 | + d["rootUri"] = pathlib.Path(repository_absolute_path).as_uri() |
| 110 | + |
| 111 | + assert d["workspaceFolders"][0]["uri"] == "$uri" |
| 112 | + d["workspaceFolders"][0]["uri"] = pathlib.Path(repository_absolute_path).as_uri() |
| 113 | + |
| 114 | + assert d["workspaceFolders"][0]["name"] == "$name" |
| 115 | + d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path) |
| 116 | + |
| 117 | + return d |
| 118 | + |
| 119 | + @asynccontextmanager |
| 120 | + async def start_server(self) -> AsyncIterator["Solargraph"]: |
| 121 | + """ |
| 122 | + Starts the Solargraph Language Server for Ruby, waits for the server to be ready and yields the LanguageServer instance. |
| 123 | +
|
| 124 | + Usage: |
| 125 | + ``` |
| 126 | + async with lsp.start_server(): |
| 127 | + # LanguageServer has been initialized and ready to serve requests |
| 128 | + await lsp.request_definition(...) |
| 129 | + await lsp.request_references(...) |
| 130 | + # Shutdown the LanguageServer on exit from scope |
| 131 | + # LanguageServer has been shutdown |
| 132 | + """ |
| 133 | + |
| 134 | + async def register_capability_handler(params): |
| 135 | + assert "registrations" in params |
| 136 | + for registration in params["registrations"]: |
| 137 | + if registration["method"] == "workspace/executeCommand": |
| 138 | + self.initialize_searcher_command_available.set() |
| 139 | + self.resolve_main_method_available.set() |
| 140 | + return |
| 141 | + |
| 142 | + async def lang_status_handler(params): |
| 143 | + # TODO: Should we wait for |
| 144 | + # server -> client: {'jsonrpc': '2.0', 'method': 'language/status', 'params': {'type': 'ProjectStatus', 'message': 'OK'}} |
| 145 | + # Before proceeding? |
| 146 | + if params["type"] == "ServiceReady" and params["message"] == "ServiceReady": |
| 147 | + self.service_ready_event.set() |
| 148 | + |
| 149 | + async def execute_client_command_handler(params): |
| 150 | + return [] |
| 151 | + |
| 152 | + async def do_nothing(params): |
| 153 | + return |
| 154 | + |
| 155 | + async def window_log_message(msg): |
| 156 | + self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO) |
| 157 | + |
| 158 | + self.server.on_request("client/registerCapability", register_capability_handler) |
| 159 | + self.server.on_notification("language/status", lang_status_handler) |
| 160 | + self.server.on_notification("window/logMessage", window_log_message) |
| 161 | + self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) |
| 162 | + self.server.on_notification("$/progress", do_nothing) |
| 163 | + self.server.on_notification("textDocument/publishDiagnostics", do_nothing) |
| 164 | + self.server.on_notification("language/actionableNotification", do_nothing) |
| 165 | + |
| 166 | + async with super().start_server(): |
| 167 | + self.logger.log("Starting solargraph server process", logging.INFO) |
| 168 | + await self.server.start() |
| 169 | + initialize_params = self._get_initialize_params(self.repository_root_path) |
| 170 | + |
| 171 | + self.logger.log( |
| 172 | + "Sending initialize request from LSP client to LSP server and awaiting response", |
| 173 | + logging.INFO, |
| 174 | + ) |
| 175 | + self.logger.log(f"Sending init params: {json.dumps(initialize_params, indent=4)}", logging.INFO) |
| 176 | + init_response = await self.server.send.initialize(initialize_params) |
| 177 | + self.logger.log(f"Received init response: {init_response}", logging.INFO) |
| 178 | + assert init_response["capabilities"]["textDocumentSync"] == 2 |
| 179 | + assert "completionProvider" in init_response["capabilities"] |
| 180 | + assert init_response["capabilities"]["completionProvider"] == { |
| 181 | + "resolveProvider": True, |
| 182 | + "triggerCharacters": [".", ":", "@"], |
| 183 | + } |
| 184 | + self.server.notify.initialized({}) |
| 185 | + self.completions_available.set() |
| 186 | + |
| 187 | + self.server_ready.set() |
| 188 | + await self.server_ready.wait() |
| 189 | + |
| 190 | + yield self |
| 191 | + |
| 192 | + await self.server.shutdown() |
| 193 | + await self.server.stop() |
0 commit comments