From 680b8373398b264ff93462465a54cd08eb79546a Mon Sep 17 00:00:00 2001 From: Parker Wahle Date: Wed, 2 Dec 2026 17:21:31 -0500 Subject: [PATCH] Send workspace folder and initialization options lsp-cli-plus sent an empty InitializeParams, so a language server got no rootUri, no workspaceFolders and no initializationOptions. Send the current working directory as the workspace folder, as rootUri and as the only entry of workspaceFolders, and declare the workspace.workspaceFolders client capability. The new option --workspace-folder overrides the directory, and the new option --initialization-options names a JSON file whose value is sent as initializationOptions. In .lsp-cli-plus.json, relative defaults of both are resolved against the directory of that file. Fixes #67. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mv4cZ3LFVAJ9aG5SntwnAr --- README.md | 3 + changelog.xml | 3 + .../org/bsplines/lspcli/LspCliLauncher.kt | 45 ++++++++++ .../lspcli/client/LspCliLanguageClient.kt | 52 ++++++++++- .../bsplines/lspcli/tools/LspCliSettings.kt | 13 +++ .../resources/LspCliMessagesBundle.properties | 2 +- .../org/bsplines/lspcli/LspCliLauncherTest.kt | 89 +++++++++++++++++++ .../lspcli/client/LspCliLanguageClientTest.kt | 88 ++++++++++++++++++ .../lspcli/tools/LspCliSettingsTest.kt | 40 +++++++++ 9 files changed, 332 insertions(+), 3 deletions(-) create mode 100644 src/test/kotlin/org/bsplines/lspcli/client/LspCliLanguageClientTest.kt create mode 100644 src/test/kotlin/org/bsplines/lspcli/tools/LspCliSettingsTest.kt diff --git a/README.md b/README.md index 23f3706..c31e47d 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ This language client would not have been possible without the work of Julian Val - Printing diagnostics (linting) for each checked file - Printing code actions for each diagnostic - Supplying client configuration to the server +- Supplying a workspace folder and initialization options to the server - Customization of usage message and default argument values via JSON file (path supplied by environment variable) If you'd like support for other LSP features as well, please open a feature request or a pull request. @@ -59,10 +60,12 @@ Any command-line arguments supplied to the startup scripts are processed by `lsp Only for LTEX LS: A flattened JSON object (`{"latex.commands": ...}`) is also allowed, and setting names may be prefixed by a top level named `ltex` (e.g., `{"ltex.latex.commands": ...}` is accepted as well). - `-h`, `--help`: Show help message and exit. - `--hide-commands`: Hide commands in lists of code actions for diagnostics, only show quick fixes. +- `--initialization-options=`: Send the JSON value stored in the file `` to the language server as `initializationOptions`. In `.lsp-cli-plus.json`, a relative path is resolved against the directory of that file. - `--server-command-line=`: Required. Command line to start the language server, starting with the path of its executable. If you want to supply arguments to the language server, separate them with spaces. If the path of the executable or one of the arguments contain spaces, you can escape them by using `\ ` instead. In `.lsp-cli-plus.json`, this option can either be specified as an array of arguments or as a string with space-separated arguments. - `--server-working-directory=`: Working directory for `--server-command-line`. If omitted, use the parent directory of `.lsp-cli-plus.json` if given, otherwise use the current working directory. - `-V`, `--version`: Print version information as JSON to the standard output and exit. The format is a JSON object with `"java"` and `"lsp-cli-plus"` keys and string values. A key may be missing if no information about the corresponding version could be retrieved. - `--verbose`: Write to standard error output what is being done, along with the language server's standard error output (usually its log). +- `--workspace-folder=`: Send `` to the language server as the workspace folder, as `rootUri` and as the only entry of `workspaceFolders`. If omitted, use the current working directory. In `.lsp-cli-plus.json`, a relative path is resolved against the directory of that file. - ` ...`: Required. Paths of files or directories to check. Directories are traversed recursively for supported file types. If `-` is given, standard input will be checked as plain text. Instead of using the equals sign `=` to separate option names and values, it is also possible to use one or more spaces. diff --git a/changelog.xml b/changelog.xml index a37a32e..03e294a 100644 --- a/changelog.xml +++ b/changelog.xml @@ -20,6 +20,9 @@ Stop waiting forever for a language server whose process has ended, for example because it crashed on start. Waiting for the answer to `initialize`, for a file's diagnostics, or for code actions now fails with the server's exit code instead. + + Send a workspace folder to the language server with `initialize`, as `rootUri` and as the only entry of `workspaceFolders`: the current working directory, or the directory given with the new option `--workspace-folder`. Add `--initialization-options`, a JSON file whose value is sent as `initializationOptions`. The client now declares the `workspace.workspaceFolders` capability and answers `workspace/workspaceFolders`. + diff --git a/src/main/kotlin/org/bsplines/lspcli/LspCliLauncher.kt b/src/main/kotlin/org/bsplines/lspcli/LspCliLauncher.kt index ef5aeda..8eed7ed 100644 --- a/src/main/kotlin/org/bsplines/lspcli/LspCliLauncher.kt +++ b/src/main/kotlin/org/bsplines/lspcli/LspCliLauncher.kt @@ -66,6 +66,28 @@ class LspCliLauncher : Callable { ) var clientConfigurationFilePath: Path? = null + @CommandLine.Option( + names = ["--workspace-folder"], + paramLabel = "", + description = [ + "Send to the language server as the workspace folder, as rootUri and as the " + + "only entry of workspaceFolders. If omitted, use the current working directory. In " + + ".lsp-cli-plus.json, a relative path is resolved against the directory of that file.", + ], + ) + var workspaceFolderPath: Path? = null + + @CommandLine.Option( + names = ["--initialization-options"], + paramLabel = "", + description = [ + "Send the JSON value stored in the file to the language server as " + + "initializationOptions. In .lsp-cli-plus.json, a relative path is resolved against " + + "the directory of that file.", + ], + ) + var initializationOptionsFilePath: Path? = null + @CommandLine.Option( names = ["--hide-commands"], description = [ @@ -140,6 +162,10 @@ class LspCliLauncher : Callable { ?.let { Path.of(it) } } + this.workspaceFolderPath = getPathOption(parseResult, lspCliSettings, "--workspace-folder") + this.initializationOptionsFilePath = + getPathOption(parseResult, lspCliSettings, "--initialization-options") + this.hideCommands = if (parseResult.hasMatchedOption("--hide-commands")) { parseResult.matchedOptionValue("--hide-commands", false) @@ -178,6 +204,8 @@ class LspCliLauncher : Callable { serverCommandLine, this.serverWorkingDirPath, this.clientConfigurationFilePath, + this.workspaceFolderPath, + this.initializationOptionsFilePath, ) try { @@ -242,6 +270,23 @@ class LspCliLauncher : Callable { } } + // A path from the command line is taken as it is, so a relative one is resolved against the + // current working directory. A default from .lsp-cli-plus.json is resolved against the + // directory of that file, which is also what --server-working-directory defaults to. + private fun getPathOption( + parseResult: CommandLine.ParseResult, + lspCliSettings: LspCliSettings, + name: String, + ): Path? = + if (parseResult.hasMatchedOption(name)) { + parseResult.matchedOptionValue(name, null) + } else { + lspCliSettings + .getValue("defaultValues", name) + ?.asString + ?.let { lspCliSettings.resolvePath(it) } + } + private fun getLspCliSettingsFilePath(): Path? { val environmentVariable: String = System.getenv("LSP_CLI_JSON_SETTINGS_PATH") ?: "" val path: Path? = diff --git a/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt b/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt index 56dc670..3796523 100644 --- a/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt +++ b/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt @@ -15,6 +15,7 @@ import org.bsplines.lspcli.server.LspCliLanguageServer import org.bsplines.lspcli.tools.FileIo import org.bsplines.lspcli.tools.I18n import org.bsplines.lspcli.tools.Logging +import org.eclipse.lsp4j.ClientCapabilities import org.eclipse.lsp4j.ConfigurationItem import org.eclipse.lsp4j.ConfigurationParams import org.eclipse.lsp4j.Diagnostic @@ -23,6 +24,8 @@ import org.eclipse.lsp4j.MessageActionItem import org.eclipse.lsp4j.MessageParams import org.eclipse.lsp4j.PublishDiagnosticsParams import org.eclipse.lsp4j.ShowMessageRequestParams +import org.eclipse.lsp4j.WorkspaceClientCapabilities +import org.eclipse.lsp4j.WorkspaceFolder import org.eclipse.lsp4j.jsonrpc.Launcher import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints import org.eclipse.lsp4j.launch.LSPLauncher @@ -38,7 +41,16 @@ class LspCliLanguageClient( serverCommandLine: List, serverWorkingDirPath: Path? = null, clientConfigurationFilePath: Path? = null, + workspaceFolderPath: Path? = null, + initializationOptionsFilePath: Path? = null, ) : LanguageClient { + private val initializeParams: InitializeParams = + createInitializeParams( + workspaceFolderPath ?: Path.of(""), + initializationOptionsFilePath?.let { + JsonParser.parseString(FileIo.readFileWithException(it)) + }, + ) val languageServerProcess: Process = startLanguageServerProcess(serverCommandLine, serverWorkingDirPath) val languageServer: LanguageServer = initializeLanguageServer() @@ -85,7 +97,41 @@ class LspCliLanguageClient( return CompletableFuture.completedFuture(result) } + override fun workspaceFolders(): CompletableFuture> = + CompletableFuture.completedFuture(this.initializeParams.workspaceFolders) + companion object { + /** + * Create the parameters of the `initialize` request. The workspace folder is sent as + * `rootUri` and as the only entry of `workspaceFolders`, as an editor sends the folder it + * opened, and the client declares the `workspace.workspaceFolders` capability that the + * latter requires. A relative workspace folder is resolved against the current working + * directory. + */ + fun createInitializeParams( + workspaceFolderPath: Path, + initializationOptions: JsonElement? = null, + ): InitializeParams { + val absoluteWorkspaceFolderPath: Path = workspaceFolderPath.toAbsolutePath().normalize() + val workspaceFolderUri: String = absoluteWorkspaceFolderPath.toUri().toString() + // A root directory such as C:\ or / has no file name; use the whole path then. + val workspaceFolderName: String = + (absoluteWorkspaceFolderPath.fileName ?: absoluteWorkspaceFolderPath).toString() + + val workspaceClientCapabilities = WorkspaceClientCapabilities() + workspaceClientCapabilities.workspaceFolders = true + val clientCapabilities = ClientCapabilities() + clientCapabilities.workspace = workspaceClientCapabilities + + val initializeParams = InitializeParams() + initializeParams.capabilities = clientCapabilities + initializeParams.rootUri = workspaceFolderUri + initializeParams.workspaceFolders = + listOf(WorkspaceFolder(workspaceFolderUri, workspaceFolderName)) + initializeParams.initializationOptions = initializationOptions + return initializeParams + } + private fun startLanguageServerProcess( serverCommandLine: List, serverWorkingDirPath: Path? = null, @@ -146,8 +192,10 @@ class LspCliLanguageClient( launcher.startListening() executorService.shutdown() - Logging.logger.info(I18n.format("initializingLanguageServer")) - server.initialize(InitializeParams()).get() + Logging.logger.info( + I18n.format("initializingLanguageServer", this.initializeParams.rootUri), + ) + server.initialize(this.initializeParams).get() return server } } diff --git a/src/main/kotlin/org/bsplines/lspcli/tools/LspCliSettings.kt b/src/main/kotlin/org/bsplines/lspcli/tools/LspCliSettings.kt index 5d64009..ea6f5d6 100644 --- a/src/main/kotlin/org/bsplines/lspcli/tools/LspCliSettings.kt +++ b/src/main/kotlin/org/bsplines/lspcli/tools/LspCliSettings.kt @@ -31,6 +31,19 @@ class LspCliSettings( return jsonElement } + /** + * Resolve a path given in the settings file: a relative path is resolved against the + * directory of the settings file, as if it were the working directory. Without a settings + * file, the path is returned as it is. + */ + fun resolvePath(pathString: String): Path { + val path: Path = Path.of(pathString) + return this.settingsFilePath + ?.toAbsolutePath() + ?.parent + ?.resolve(path) ?: path + } + fun getValueAsListOfString(vararg keys: String): List? { val jsonElement: JsonElement = getValue(*keys) ?: return null val list = ArrayList() diff --git a/src/main/resources/LspCliMessagesBundle.properties b/src/main/resources/LspCliMessagesBundle.properties index 3d028d1..6980471 100644 --- a/src/main/resources/LspCliMessagesBundle.properties +++ b/src/main/resources/LspCliMessagesBundle.properties @@ -9,7 +9,7 @@ checkingFile = Checking '{0}'... couldNotReadFile = Could not read file '{0}' couldNotWriteFile = Could not write file '{0}' followingExceptionOccurred = The following exception occurred: -initializingLanguageServer = Initializing language server... +initializingLanguageServer = Initializing language server with workspace folder '{0}'... requiredArgumentNotSpecified = Required argument '{0}' not specified serverExitedWithExitCode = The language server exited with exit code {0} settingLocale = Setting locale to '{0}' diff --git a/src/test/kotlin/org/bsplines/lspcli/LspCliLauncherTest.kt b/src/test/kotlin/org/bsplines/lspcli/LspCliLauncherTest.kt index a353f38..3cc6732 100644 --- a/src/test/kotlin/org/bsplines/lspcli/LspCliLauncherTest.kt +++ b/src/test/kotlin/org/bsplines/lspcli/LspCliLauncherTest.kt @@ -9,9 +9,15 @@ package org.bsplines.lspcli import org.bsplines.lspcli.testtools.TestTools +import org.bsplines.lspcli.tools.LspCliSettings +import org.junit.jupiter.api.io.TempDir +import picocli.CommandLine +import java.nio.file.Files +import java.nio.file.Path import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull class LspCliLauncherTest { @BeforeTest @@ -79,6 +85,76 @@ class LspCliLauncherTest { assertEquals(0, returncode) } + @Test + fun testWorkspaceFolderAndInitializationOptions() { + val testfile = TestTools.createTextFile("This is a test.", "markdown-2.md") + val initializationOptions = + TestTools.createTextFile("""{"locale": "en"}""", "initialization-options.json") + val returncode = + LspCliLauncher.run( + arrayOf( + "--server-command-line", + TestTools.getExecutable(), + "--workspace-folder", + TestTools.getCurrentDirectory(), + "--initialization-options", + initializationOptions, + "--verbose", + testfile, + ), + ) + assertEquals(0, returncode) + } + + @Test + fun testUnknownInitializationOptionsFile() { + val testfile = TestTools.createTextFile("This is a test.", "markdown-3.md") + val returncode = + LspCliLauncher.run( + arrayOf( + "--server-command-line", + TestTools.getExecutable(), + "--initialization-options", + "unknownFile.json", + testfile, + ), + ) + assertEquals(1, returncode) + } + + @Test + fun testPathOptionDefaults( + @TempDir tempDirPath: Path, + ) { + val settingsFilePath: Path = + Files.writeString( + tempDirPath.resolve(".lsp-cli-plus.json"), + """{"defaultValues": {"--workspace-folder": "project", """ + + """"--initialization-options": "options.json"}}""", + ) + val lspCliSettings = LspCliSettings(settingsFilePath) + + // Defaults from .lsp-cli-plus.json are resolved against its directory. + var launcher = createLauncher(lspCliSettings) + assertEquals(tempDirPath.resolve("project"), launcher.workspaceFolderPath) + assertEquals(tempDirPath.resolve("options.json"), launcher.initializationOptionsFilePath) + + // Command-line values override them and are taken as they are. + launcher = + createLauncher( + lspCliSettings, + "--workspace-folder=other", + "--initialization-options=other.json", + ) + assertEquals(Path.of("other"), launcher.workspaceFolderPath) + assertEquals(Path.of("other.json"), launcher.initializationOptionsFilePath) + + // Without either, the client uses the current working directory and sends no options. + launcher = createLauncher(LspCliSettings()) + assertNull(launcher.workspaceFolderPath) + assertNull(launcher.initializationOptionsFilePath) + } + @Test fun testCheckFilesInDirectory() { val subdir = "test-dir" @@ -159,4 +235,17 @@ class LspCliLauncherTest { ) assertEquals(0, returncode) } + + private fun createLauncher( + lspCliSettings: LspCliSettings, + vararg arguments: String, + ): LspCliLauncher { + val parseResult: CommandLine.ParseResult = + CommandLine(LspCliLauncher()).parseArgs( + "--server-command-line=server", + *arguments, + "file.md", + ) + return LspCliLauncher(parseResult, lspCliSettings) + } } diff --git a/src/test/kotlin/org/bsplines/lspcli/client/LspCliLanguageClientTest.kt b/src/test/kotlin/org/bsplines/lspcli/client/LspCliLanguageClientTest.kt new file mode 100644 index 0000000..59debf5 --- /dev/null +++ b/src/test/kotlin/org/bsplines/lspcli/client/LspCliLanguageClientTest.kt @@ -0,0 +1,88 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.client + +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import org.eclipse.lsp4j.InitializeParams +import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler +import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints +import org.eclipse.lsp4j.services.LanguageServer +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class LspCliLanguageClientTest { + @TempDir + lateinit var tempDirPath: Path + + @Test + fun testCreateInitializeParamsSendsWorkspaceFolder() { + val workspaceFolderPath: Path = this.tempDirPath.resolve("project") + workspaceFolderPath.toFile().mkdir() + + val params: InitializeParams = + LspCliLanguageClient.createInitializeParams(workspaceFolderPath) + val expectedUri: String = workspaceFolderPath.toUri().toString() + + assertEquals(expectedUri, params.rootUri) + assertEquals(1, params.workspaceFolders.size) + assertEquals(expectedUri, params.workspaceFolders[0].uri) + assertEquals("project", params.workspaceFolders[0].name) + assertTrue(params.capabilities.workspace.workspaceFolders) + // The client answers workspace/configuration as before, without declaring it. + assertNull(params.capabilities.workspace.configuration) + assertNull(params.initializationOptions) + } + + @Test + fun testCreateInitializeParamsResolvesRelativeWorkspaceFolder() { + val params: InitializeParams = LspCliLanguageClient.createInitializeParams(Path.of("")) + val currentDirPath: Path = Path.of("").toAbsolutePath() + + assertEquals(currentDirPath.toUri().toString(), params.rootUri) + assertEquals(currentDirPath.fileName.toString(), params.workspaceFolders[0].name) + + val normalizedParams: InitializeParams = + LspCliLanguageClient.createInitializeParams(this.tempDirPath.resolve("project/..")) + assertEquals(this.tempDirPath.toUri().toString(), normalizedParams.rootUri) + } + + @Test + fun testCreateInitializeParamsSerializesInitializationOptions() { + val initializationOptions: JsonObject = + JsonParser + .parseString("""{"ltex": {"externalFiles": {"managedByEditor": false}}}""") + .asJsonObject + val params: InitializeParams = + LspCliLanguageClient.createInitializeParams(this.tempDirPath, initializationOptions) + + // Serialize the parameters as LSP4J sends them to the language server. + val jsonHandler = + MessageJsonHandler(ServiceEndpoints.getSupportedMethods(LanguageServer::class.java)) + val json: JsonObject = + JsonParser.parseString(jsonHandler.gson.toJson(params)).asJsonObject + + assertEquals(initializationOptions, json.get("initializationOptions")) + assertEquals(this.tempDirPath.toUri().toString(), json.get("rootUri").asString) + assertEquals(1, json.getAsJsonArray("workspaceFolders").size()) + assertFalse(json.has("rootPath")) + assertTrue( + json + .getAsJsonObject("capabilities") + .getAsJsonObject("workspace") + .get("workspaceFolders") + .asBoolean, + ) + } +} diff --git a/src/test/kotlin/org/bsplines/lspcli/tools/LspCliSettingsTest.kt b/src/test/kotlin/org/bsplines/lspcli/tools/LspCliSettingsTest.kt new file mode 100644 index 0000000..c809090 --- /dev/null +++ b/src/test/kotlin/org/bsplines/lspcli/tools/LspCliSettingsTest.kt @@ -0,0 +1,40 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.tools + +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals + +class LspCliSettingsTest { + @TempDir + lateinit var tempDirPath: Path + + @Test + fun testResolvePathAgainstSettingsFile() { + val settingsFilePath: Path = + Files.writeString(this.tempDirPath.resolve(".lsp-cli-plus.json"), "{}") + val lspCliSettings = LspCliSettings(settingsFilePath) + + assertEquals( + this.tempDirPath.resolve("options.json"), + lspCliSettings.resolvePath("options.json"), + ) + + val absolutePath: Path = this.tempDirPath.resolve("elsewhere").toAbsolutePath() + assertEquals(absolutePath, lspCliSettings.resolvePath(absolutePath.toString())) + } + + @Test + fun testResolvePathWithoutSettingsFile() { + assertEquals(Path.of("options.json"), LspCliSettings().resolvePath("options.json")) + } +}