Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
126 changes: 126 additions & 0 deletions python/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions python/vscode_common_python_lsp/_settings.py
Original file line number Diff line number Diff line change
@@ -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}
62 changes: 17 additions & 45 deletions python/vscode_common_python_lsp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -118,34 +118,17 @@ 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."""
if not settings:
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:
Expand All @@ -159,24 +142,19 @@ 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."""
if not self.workspace_settings:
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()}

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
Loading