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
8 changes: 5 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ 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.
workspace dictionaries. Private `_settings` helpers construct fresh, shallow
settings dictionaries while retaining nested value aliases. Private `_routing`
helpers consult the facade on each call for in-place updates and workspace/document
selection, preserving path normalization and the distinct lookup fallbacks.
Neither private module caches settings or owns persistent state.

## Adoption and milestones

Expand Down
81 changes: 81 additions & 0 deletions python/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,14 @@ def test_workspace_without_filesystem_path_is_skipped(self, mock_uris):
assert settings["workspace"] == "file:///local-workspace"
assert settings["workspaceFS"]

def test_only_virtual_workspaces_do_not_add_a_cwd_fallback(self):
ts = _make_server()
workspaces = ts.workspace_settings
ts.update_workspace_settings([{"workspace": "pico:"}])

assert ts.workspace_settings is workspaces
assert workspaces == {}


class TestGetSettingsByPath:
def test_matches_closest_workspace(self):
Expand Down Expand Up @@ -961,6 +969,79 @@ def test_get_cwd_different_drives_no_crash(self):


class TestSettingsContract:
def test_routing_uses_replaced_and_mutated_settings_maps(self, tmp_path):
ts = _make_server()
root = tmp_path / "workspace"
project = root / "project"
document = TextDocument((project / "demo.py").as_uri())
file_path = pathlib.Path(document.path)
ts.update_workspace_settings([{"workspace": root.as_uri()}])
original = next(iter(ts.workspace_settings.values()))
assert ts.get_settings_by_document(document) is original
assert ts.get_settings_by_path(file_path) is original

root_key = str(pathlib.Path(uris.to_fs_path(root.as_uri())))
project_key = str(pathlib.Path(uris.to_fs_path(project.as_uri())))
root_settings = {"workspaceFS": root_key}
project_settings = {"workspaceFS": project_key}
workspaces = {root_key: root_settings, project_key: project_settings}
globals_ = {"args": ["--replacement"]}
ts.workspace_settings = workspaces
ts.global_settings = globals_

assert ts.get_document_key(document) == project_key
assert ts.get_settings_by_document(document) is project_settings
assert ts.get_settings_by_path(file_path) is project_settings

del workspaces[project_key]
assert ts.get_document_key(document) == root_key
assert ts.get_settings_by_document(document) is root_settings
assert ts.get_settings_by_path(file_path) is root_settings

workspaces.clear()
assert ts.get_document_key(document) is None
assert ts.get_settings_by_path(file_path)["args"] is globals_["args"]
globals_["args"] = ["--mutated"]
assert ts.get_settings_by_document(document)["args"] is globals_["args"]
assert ts.workspace_settings is workspaces
assert workspaces == {}

def test_document_routing_preserves_facade_method_overrides(self, tmp_path):
ts = _make_server()
document = TextDocument((tmp_path / "demo.py").as_uri())
settings = {"custom": True}
ts.workspace_settings = {"custom-key": settings}
ts.get_document_key = MagicMock(return_value="custom-key")

assert ts.get_settings_by_document(document) is settings
ts.get_document_key.assert_called_once_with(document)

args = ["--custom-default"]
ts.get_global_defaults = MagicMock(return_value={"args": args})
ts.get_document_key.return_value = None
fallback = ts.get_settings_by_document(document)
assert fallback["args"] is args
ts.get_global_defaults.assert_called_once_with()
assert ts.workspace_settings == {"custom-key": settings}

@pytest.mark.parametrize("relative", [False, True], ids=["anchor", "rootless"])
def test_routing_does_not_match_the_terminal_parent(self, tmp_path, relative):
ts = _make_server()
terminal = pathlib.Path(".") if relative else pathlib.Path(tmp_path.anchor)
file_path = terminal / "src" / "demo.py"
document = _make_document(str(file_path))
first = {"workspaceFS": "first-workspace"}
ts.workspace_settings = {
"first-workspace": first,
str(terminal): {"workspaceFS": str(terminal)},
}

assert ts.get_document_key(document) is None
assert ts.get_settings_by_path(file_path) is first
fallback = ts.get_settings_by_document(document)
assert fallback["workspaceFS"] == str(file_path.parent)
assert fallback is not first

def test_shared_producer_payload_and_staged_cwd(self, tmp_path):
root = tmp_path / "workspace café"
root.mkdir()
Expand Down
134 changes: 134 additions & 0 deletions python/vscode_common_python_lsp/_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Private, stateless workspace/document routing for the ToolServer facade."""

from __future__ import annotations

import os
import pathlib
from collections.abc import Callable
from types import ModuleType
from typing import TYPE_CHECKING, Any

from pygls.workspace import TextDocument

from . import _settings

if TYPE_CHECKING:
from .server import ToolServer


def update_workspace_settings(
facade: ToolServer,
settings: list[dict[str, Any]] | None,
*,
normalize_path: Callable[..., str],
uris: ModuleType,
) -> None:
"""Populate the facade's current workspace dictionary in place."""
if not settings:
key = normalize_path(
os.getcwd(), resolve_symlinks=facade.config.resolve_symlinks
)
facade.workspace_settings[key] = _settings.get_fallback_settings(
key, uris.from_fs_path(key), facade.get_global_defaults()
)
return

for setting in settings:
workspace_path = uris.to_fs_path(setting["workspace"])
# Virtual workspace roots, such as "pico:", have no local
# filesystem path, so they cannot be registered here.
if workspace_path is None:
continue

key = normalize_path(
workspace_path,
resolve_symlinks=facade.config.resolve_symlinks,
)
facade.workspace_settings[key] = _settings.get_workspace_settings(
key, facade.get_global_defaults(), setting
)


def get_settings_by_path(
facade: ToolServer,
file_path: pathlib.Path,
*,
normalize_path: Callable[..., str],
uris: ModuleType,
) -> dict[str, Any]:
"""Select workspace settings, falling back to CWD or the first workspace."""
if not facade.workspace_settings:
cwd = normalize_path(
os.getcwd(), resolve_symlinks=facade.config.resolve_symlinks
)
return _settings.get_fallback_settings(
cwd, uris.from_fs_path(cwd), facade.get_global_defaults()
)

workspaces = {s["workspaceFS"] for s in facade.workspace_settings.values()}

while file_path != file_path.parent:
str_file_path = normalize_path(
str(file_path), resolve_symlinks=facade.config.resolve_symlinks
)
if str_file_path in workspaces:
return facade.workspace_settings[str_file_path]
file_path = file_path.parent

return list(facade.workspace_settings.values())[0]


def get_document_key(
facade: ToolServer,
document: TextDocument,
*,
normalize_path: Callable[..., str],
) -> str | None:
"""Find the nearest workspace key without a first-workspace fallback."""
if facade.workspace_settings:
document_workspace = pathlib.Path(document.path)
workspaces = {s["workspaceFS"] for s in facade.workspace_settings.values()}

while document_workspace != document_workspace.parent:
norm_path = normalize_path(
str(document_workspace),
resolve_symlinks=facade.config.resolve_symlinks,
)
if norm_path in workspaces:
return norm_path
document_workspace = document_workspace.parent

return None


def get_settings_by_document(
facade: ToolServer,
document: TextDocument | None,
*,
normalize_path: Callable[..., str],
uris: ModuleType,
) -> dict[str, Any]:
"""Select settings, retaining the distinct absent/outside-document fallbacks."""
if document is None or document.path is None:
if not facade.workspace_settings:
cwd = normalize_path(
os.getcwd(), resolve_symlinks=facade.config.resolve_symlinks
)
return _settings.get_fallback_settings(
cwd, uris.from_fs_path(cwd), facade.get_global_defaults()
)
return list(facade.workspace_settings.values())[0]

key = facade.get_document_key(document)
if key is not None:
return facade.workspace_settings[key]

key = normalize_path(
str(pathlib.Path(document.path).parent),
resolve_symlinks=facade.config.resolve_symlinks,
)
return _settings.get_fallback_settings(
key, uris.from_fs_path(key), facade.get_global_defaults()
)
87 changes: 10 additions & 77 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 _settings, jsonrpc
from . import _routing, _settings, jsonrpc
from .context import substitute_attr
from .paths import normalize_path
from .runner import RunResult, run_module, run_path
Expand Down Expand Up @@ -122,91 +122,24 @@ def get_global_defaults(self) -> dict[str, Any]:

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] = _settings.get_fallback_settings(
key, uris.from_fs_path(key), self.get_global_defaults()
)
return

for setting in settings:
workspace_path = uris.to_fs_path(setting["workspace"])
# Virtual workspace roots, such as "pico:", have no local
# filesystem path, so they cannot be registered here.
if workspace_path is None:
continue

key = normalize_path(
workspace_path,
resolve_symlinks=self.config.resolve_symlinks,
)
self.workspace_settings[key] = _settings.get_workspace_settings(
key, self.get_global_defaults(), setting
)
_routing.update_workspace_settings(
self, settings, normalize_path=normalize_path, uris=uris
)

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 _settings.get_fallback_settings(
cwd, uris.from_fs_path(cwd), self.get_global_defaults()
)

workspaces = {s["workspaceFS"] for s in self.workspace_settings.values()}

while file_path != file_path.parent:
str_file_path = normalize_path(
str(file_path), resolve_symlinks=self.config.resolve_symlinks
)
if str_file_path in workspaces:
return self.workspace_settings[str_file_path]
file_path = file_path.parent

return list(self.workspace_settings.values())[0]
return _routing.get_settings_by_path(
self, file_path, normalize_path=normalize_path, uris=uris
)

def get_document_key(self, document: TextDocument) -> str | None:
"""Return the workspace key for the given document, or ``None``."""
if self.workspace_settings:
document_workspace = pathlib.Path(document.path)
workspaces = {s["workspaceFS"] for s in self.workspace_settings.values()}

while document_workspace != document_workspace.parent:
norm_path = normalize_path(
str(document_workspace),
resolve_symlinks=self.config.resolve_symlinks,
)
if norm_path in workspaces:
return norm_path
document_workspace = document_workspace.parent

return None
return _routing.get_document_key(self, document, normalize_path=normalize_path)

def get_settings_by_document(self, document: TextDocument | None) -> dict[str, Any]:
"""Return workspace settings for the given document."""
if document is None or document.path is None:
if not self.workspace_settings:
cwd = normalize_path(
os.getcwd(), resolve_symlinks=self.config.resolve_symlinks
)
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)
if key is not None:
return self.workspace_settings[key]

key = normalize_path(
str(pathlib.Path(document.path).parent),
resolve_symlinks=self.config.resolve_symlinks,
)
return _settings.get_fallback_settings(
key, uris.from_fs_path(key), self.get_global_defaults()
return _routing.get_settings_by_document(
self, document, normalize_path=normalize_path, uris=uris
)

# -----------------------------------------------------------------
Expand Down
Loading