From 0b0130e28c77ba94ae1f255fe05e6c222038a03b Mon Sep 17 00:00:00 2001 From: Eduardo Villalpando Mello Date: Tue, 17 Nov 2026 10:49:01 -0800 Subject: [PATCH] Extract private Python settings/default helpers Part 1 of #154. Keep the ToolServer facade, dictionary ownership, path normalization, and workspace/document routing unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 85ef72cc-9e26-4bc4-b1c3-55256d9bef91 --- CONTRIBUTING.md | 5 + python/tests/test_server.py | 126 +++++++++++++++++++ python/vscode_common_python_lsp/_settings.py | 50 ++++++++ python/vscode_common_python_lsp/server.py | 62 +++------ 4 files changed, 198 insertions(+), 45 deletions(-) create mode 100644 python/vscode_common_python_lsp/_settings.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e2dff02..1248fe0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,11 @@ stdio and checks initialize/initialized/settings/shutdown/exit. It needs no tool installation, VS Code host or Node build. Repeated settings application is covered separately in-process, not by reinitializing a live LSP session. +`ToolServer` remains the public settings facade and owns the writable global and +workspace dictionaries, in-place updates, path normalization and routing. +Private `_settings` helpers only construct fresh, shallow settings dictionaries +from the current values; they retain nested value aliases and cache no state. + ## Adoption and milestones Extensions consume this repository at a pinned Git commit and build both the diff --git a/python/tests/test_server.py b/python/tests/test_server.py index 3d99e82..266e584 100644 --- a/python/tests/test_server.py +++ b/python/tests/test_server.py @@ -1152,6 +1152,132 @@ def test_null_global_settings_are_rejected(self): ) ) + def test_replaced_settings_maps_are_used_after_initial_application(self, tmp_path): + ts = _make_server() + params = lsp.InitializeParams( + capabilities=lsp.ClientCapabilities(), + process_id=None, + initialization_options={ + "globalSettings": {"args": ["--original"]}, + "settings": [{"workspace": tmp_path.as_uri()}], + }, + ) + ts.apply_settings(params) + old_globals = ts.global_settings + old_workspaces = ts.workspace_settings + old_entry = next(iter(old_workspaces.values())) + + args = ["--replacement"] + globals_ = {"args": args, "unknownGlobal": {"keep": True}} + retained = {"workspaceFS": "retained"} + workspaces = {"retained": retained} + ts.global_settings = globals_ + ts.workspace_settings = workspaces + params.initialization_options = { + "globalSettings": {"path": []}, + "settings": [{"workspace": tmp_path.as_uri()}], + } + ts.apply_settings(params) + + key = str(pathlib.Path(uris.to_fs_path(tmp_path.as_uri()))) + assert ts.global_settings is globals_ + assert ts.workspace_settings is workspaces + assert globals_["path"] == [] + assert ts.get_global_defaults()["args"] is args + assert workspaces[key]["args"] is args + assert workspaces["retained"] is retained + assert old_globals == {"args": ["--original"]} + assert old_workspaces == {key: old_entry} + assert old_entry["args"] == ["--original"] + + args.append("--mutated") + ts.global_settings["path"] = ["replacement-tool"] + ts.update_workspace_settings([{"workspace": tmp_path.as_uri()}]) + assert workspaces[key]["args"] is args + assert workspaces[key]["path"] is globals_["path"] + + def test_settings_values_keep_shallow_aliases_and_live_config(self, tmp_path): + severity = {"E": "Error"} + ignored = ["configured/**"] + config = ToolServerConfig( + tool_module="testtool", + tool_display="Test Tool", + default_settings={"severity": severity}, + hardcoded_settings={"ignorePatterns": ignored}, + ) + ts = _make_server(config) + ts.global_settings["ignorePatterns"] = ["ignored-global/**"] + first_defaults = ts.get_global_defaults() + defaults = ts.get_global_defaults() + assert defaults is not first_defaults + assert defaults["args"] is not first_defaults["args"] + assert defaults["severity"] is severity + assert defaults["ignorePatterns"] is ignored + + supplied_severity = {"W": "Hint"} + settings = [ + {"workspace": tmp_path.as_uri()}, + { + "workspace": (tmp_path / "nested").as_uri(), + "severity": supplied_severity, + }, + ] + ts.update_workspace_settings(settings) + inherited, explicit = ts.workspace_settings.values() + assert inherited["severity"] is severity + assert explicit["severity"] is supplied_severity + assert explicit is not settings[1] + assert inherited["ignorePatterns"] is explicit["ignorePatterns"] is ignored + inherited["severity"]["E"] = "Warning" + assert ts.get_global_defaults()["severity"] == {"E": "Warning"} + + config.default_settings = {"severity": {}} + config.hardcoded_settings = {"ignorePatterns": []} + ts.update_workspace_settings(settings[:1]) + refreshed = next(iter(ts.workspace_settings.values())) + assert refreshed["severity"] is config.default_settings["severity"] + assert ( + refreshed["ignorePatterns"] is config.hardcoded_settings["ignorePatterns"] + ) + assert explicit["severity"] is supplied_severity + + @pytest.mark.parametrize("lookup", ["populate", "path", "none", "outside"]) + def test_fallback_context_is_overlaid_by_configured_defaults( + self, tmp_path, lookup + ): + contextual_defaults = { + "cwd": "", + "workspaceFS": "configured-path", + "workspace": None, + } + ts = _make_server( + ToolServerConfig( + tool_module="testtool", + tool_display="Test Tool", + default_settings=contextual_defaults, + ) + ) + if lookup == "populate": + ts.update_workspace_settings(None) + settings = next(iter(ts.workspace_settings.values())) + elif lookup == "path": + settings = ts.get_settings_by_path(tmp_path / "demo.py") + elif lookup == "none": + settings = ts.get_settings_by_document(None) + else: + settings = ts.get_settings_by_document( + TextDocument((tmp_path / "demo.py").as_uri()) + ) + + assert { + key: settings[key] for key in contextual_defaults + } == contextual_defaults + ts.update_workspace_settings([{"workspace": tmp_path.as_uri()}]) + key = str(pathlib.Path(uris.to_fs_path(tmp_path.as_uri()))) + assert ts.workspace_settings[key]["workspaceFS"] == key + assert ts.workspace_settings[key]["workspace"] == tmp_path.as_uri() + assert ts.workspace_settings[key]["cwd"] == "" + def test_repeated_application_retains_aliases_and_routes_real_uris(self, tmp_path): ts = _make_server() workspaces = ts.workspace_settings diff --git a/python/vscode_common_python_lsp/_settings.py b/python/vscode_common_python_lsp/_settings.py new file mode 100644 index 0000000..6438f70 --- /dev/null +++ b/python/vscode_common_python_lsp/_settings.py @@ -0,0 +1,50 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +"""Private, stateless settings construction for the ToolServer facade.""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .server import ToolServerConfig + + +def get_global_defaults( + config: ToolServerConfig, global_settings: dict[str, Any] +) -> dict[str, Any]: + """Build fresh defaults while retaining the configured value objects.""" + base: dict[str, Any] = { + "path": global_settings.get("path", []), + "interpreter": global_settings.get("interpreter", [sys.executable]), + "args": global_settings.get("args", []), + "importStrategy": global_settings.get("importStrategy", "useBundled"), + "showNotifications": global_settings.get( + "showNotifications", config.default_notification_level + ), + } + for key, default in config.default_settings.items(): + base[key] = global_settings.get(key, default) + # Hardcoded settings ignore whatever the client sent in GLOBAL_SETTINGS. + base.update(config.hardcoded_settings) + return base + + +def get_fallback_settings( + workspace_fs: str, workspace_uri: str, defaults: dict[str, Any] +) -> dict[str, Any]: + """Use contextual paths unless the configured defaults supply those keys.""" + return { + "cwd": workspace_fs, + "workspaceFS": workspace_fs, + "workspace": workspace_uri, + **defaults, + } + + +def get_workspace_settings( + workspace_fs: str, defaults: dict[str, Any], settings: dict[str, Any] +) -> dict[str, Any]: + """Shallowly overlay client settings, keeping the normalized workspace path.""" + return {**defaults, **settings, "workspaceFS": workspace_fs} diff --git a/python/vscode_common_python_lsp/server.py b/python/vscode_common_python_lsp/server.py index e8f63be..47294ae 100644 --- a/python/vscode_common_python_lsp/server.py +++ b/python/vscode_common_python_lsp/server.py @@ -19,7 +19,7 @@ from pygls.lsp.server import LanguageServer from pygls.workspace import TextDocument -from . import jsonrpc +from . import _settings, jsonrpc from .context import substitute_attr from .paths import normalize_path from .runner import RunResult, run_module, run_path @@ -118,21 +118,7 @@ def __init__( def get_global_defaults(self) -> dict[str, Any]: """Return merged base + tool-specific default settings.""" - base: dict[str, Any] = { - "path": self.global_settings.get("path", []), - "interpreter": self.global_settings.get("interpreter", [sys.executable]), - "args": self.global_settings.get("args", []), - "importStrategy": self.global_settings.get("importStrategy", "useBundled"), - "showNotifications": self.global_settings.get( - "showNotifications", self.config.default_notification_level - ), - } - for key, default in self.config.default_settings.items(): - base[key] = self.global_settings.get(key, default) - # Hardcoded settings always use the configured value, ignoring - # whatever the client sent in GLOBAL_SETTINGS. - base.update(self.config.hardcoded_settings) - return base + return _settings.get_global_defaults(self.config, self.global_settings) def update_workspace_settings(self, settings: list[dict[str, Any]] | None) -> None: """Populate :attr:`workspace_settings` from the client payload.""" @@ -140,12 +126,9 @@ def update_workspace_settings(self, settings: list[dict[str, Any]] | None) -> No key = normalize_path( os.getcwd(), resolve_symlinks=self.config.resolve_symlinks ) - self.workspace_settings[key] = { - "cwd": key, - "workspaceFS": key, - "workspace": uris.from_fs_path(key), - **self.get_global_defaults(), - } + self.workspace_settings[key] = _settings.get_fallback_settings( + key, uris.from_fs_path(key), self.get_global_defaults() + ) return for setting in settings: @@ -159,11 +142,9 @@ def update_workspace_settings(self, settings: list[dict[str, Any]] | None) -> No workspace_path, resolve_symlinks=self.config.resolve_symlinks, ) - self.workspace_settings[key] = { - **self.get_global_defaults(), - **setting, - "workspaceFS": key, - } + self.workspace_settings[key] = _settings.get_workspace_settings( + key, self.get_global_defaults(), setting + ) def get_settings_by_path(self, file_path: pathlib.Path) -> dict[str, Any]: """Return workspace settings for the given file path.""" @@ -171,12 +152,9 @@ def get_settings_by_path(self, file_path: pathlib.Path) -> dict[str, Any]: cwd = normalize_path( os.getcwd(), resolve_symlinks=self.config.resolve_symlinks ) - return { - "cwd": cwd, - "workspaceFS": cwd, - "workspace": uris.from_fs_path(cwd), - **self.get_global_defaults(), - } + return _settings.get_fallback_settings( + cwd, uris.from_fs_path(cwd), self.get_global_defaults() + ) workspaces = {s["workspaceFS"] for s in self.workspace_settings.values()} @@ -214,12 +192,9 @@ def get_settings_by_document(self, document: TextDocument | None) -> dict[str, A cwd = normalize_path( os.getcwd(), resolve_symlinks=self.config.resolve_symlinks ) - return { - "cwd": cwd, - "workspaceFS": cwd, - "workspace": uris.from_fs_path(cwd), - **self.get_global_defaults(), - } + return _settings.get_fallback_settings( + cwd, uris.from_fs_path(cwd), self.get_global_defaults() + ) return list(self.workspace_settings.values())[0] key = self.get_document_key(document) @@ -230,12 +205,9 @@ def get_settings_by_document(self, document: TextDocument | None) -> dict[str, A str(pathlib.Path(document.path).parent), resolve_symlinks=self.config.resolve_symlinks, ) - return { - "cwd": key, - "workspaceFS": key, - "workspace": uris.from_fs_path(key), - **self.get_global_defaults(), - } + return _settings.get_fallback_settings( + key, uris.from_fs_path(key), self.get_global_defaults() + ) # ----------------------------------------------------------------- # CWD resolution