Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update extension to latest extension template #199

Merged
merged 3 commits into from
Mar 28, 2023
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
3 changes: 2 additions & 1 deletion .vscodeignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ noxfile.py
.pylintrc
.flake8
**/requirements.txt
**/requirements.in
**/requirements.in
**/tool/_debug_server.py
2 changes: 1 addition & 1 deletion bundled/tool/lsp_jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ def __init__(self):
self._lock = threading.Lock()
self._thread_pool = ThreadPoolExecutor(10)

@atexit.register
def stop_all_processes(self):
"""Send exit command to all processes and shutdown transport."""
for i in self._rpc.values():
Expand Down Expand Up @@ -175,6 +174,7 @@ def get_json_rpc(self, workspace: str) -> JsonRpc:


_process_manager = ProcessManager()
atexit.register(_process_manager.stop_all_processes)


def _get_json_rpc(workspace: str) -> Union[JsonRpc, None]:
Expand Down
90 changes: 56 additions & 34 deletions bundled/tool/lsp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import pathlib
import sys
import traceback
from typing import Any, Dict, List, Sequence, Union
from typing import Any, Dict, List, Optional, Sequence, Union


# **********************************************************
Expand Down Expand Up @@ -38,9 +38,10 @@ def update_sys_path(path_to_add: str, strategy: str) -> None:
import lsp_jsonrpc as jsonrpc
import lsp_utils as utils
import lsprotocol.types as lsp
from pygls import protocol, server, uris, workspace
from pygls import server, uris, workspace

WORKSPACE_SETTINGS = {}
GLOBAL_SETTINGS = {}
RUNNER = pathlib.Path(__file__).parent / "lsp_runner.py"

MAX_WORKERS = 5
Expand Down Expand Up @@ -185,33 +186,35 @@ def initialize(params: lsp.InitializeParams) -> None:
"""LSP handler for initialize request."""
log_to_output(f"CWD Server: {os.getcwd()}")

paths = "\r\n ".join(sys.path)
log_to_output(f"sys.path used to run Server:\r\n {paths}")
GLOBAL_SETTINGS.update(**params.initialization_options.get("globalSettings", {}))

settings = params.initialization_options["settings"]
_update_workspace_settings(settings)
log_to_output(
f"Settings used to run Server:\r\n{json.dumps(settings, indent=4, ensure_ascii=False)}\r\n"
)
log_to_output(
f"Global settings:\r\n{json.dumps(GLOBAL_SETTINGS, indent=4, ensure_ascii=False)}\r\n"
)

paths = "\r\n ".join(sys.path)
log_to_output(f"sys.path used to run Server:\r\n {paths}")

if isinstance(LSP_SERVER.lsp, protocol.LanguageServerProtocol):
if any(setting["logLevel"] == "debug" for setting in settings):
LSP_SERVER.lsp.trace = lsp.TraceValues.Verbose
elif any(
setting["logLevel"] in ["error", "warn", "info"] for setting in settings
):
LSP_SERVER.lsp.trace = lsp.TraceValues.Messages
else:
LSP_SERVER.lsp.trace = lsp.TraceValues.Off
_log_version_info()


@LSP_SERVER.feature(lsp.EXIT)
def on_exit():
def on_exit(_params: Optional[Any] = None) -> None:
"""Handle clean up on exit."""
jsonrpc.shutdown_json_rpc()


@LSP_SERVER.feature(lsp.SHUTDOWN)
def on_shutdown(_params: Optional[Any] = None) -> None:
"""Handle clean up on shutdown."""
jsonrpc.shutdown_json_rpc()


def _log_version_info() -> None:
for value in WORKSPACE_SETTINGS.values():
try:
Expand Down Expand Up @@ -261,18 +264,24 @@ def _log_version_info() -> None:
# *****************************************************
# Internal functional and settings management APIs.
# *****************************************************
def _get_global_defaults():
return {
"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", "off"),
}


def _update_workspace_settings(settings):
if not settings:
key = os.getcwd()
WORKSPACE_SETTINGS[key] = {
"cwd": key,
"workspaceFS": key,
"workspace": uris.from_fs_path(key),
"logLevel": "error",
"path": [],
"interpreter": [sys.executable],
"args": [],
"importStrategy": "useBundled",
"showNotifications": "off",
**_get_global_defaults(),
}
return

Expand All @@ -284,14 +293,30 @@ def _update_workspace_settings(settings):
}


def _get_document_key(document: workspace.Document):
document_workspace = pathlib.Path(document.path)
def _get_settings_by_path(file_path: pathlib.Path):
workspaces = {s["workspaceFS"] for s in WORKSPACE_SETTINGS.values()}

while document_workspace != document_workspace.parent:
if str(document_workspace) in workspaces:
return str(document_workspace)
document_workspace = document_workspace.parent
while file_path != file_path.parent:
str_file_path = str(file_path)
if str_file_path in workspaces:
return WORKSPACE_SETTINGS[str_file_path]
file_path = file_path.parent

setting_values = list(WORKSPACE_SETTINGS.values())
return setting_values[0]


def _get_document_key(document: workspace.Document):
if WORKSPACE_SETTINGS:
document_workspace = pathlib.Path(document.path)
workspaces = {s["workspaceFS"] for s in WORKSPACE_SETTINGS.values()}

# Find workspace settings for the given file.
while document_workspace != document_workspace.parent:
if str(document_workspace) in workspaces:
return str(document_workspace)
document_workspace = document_workspace.parent

return None


Expand All @@ -301,16 +326,13 @@ def _get_settings_by_document(document: workspace.Document | None):

key = _get_document_key(document)
if key is None:
# This is either a non-workspace file or there is no workspace.
key = os.fspath(pathlib.Path(document.path).parent)
return {
"cwd": key,
"workspaceFS": key,
"workspace": uris.from_fs_path(key),
"logLevel": "error",
"path": [],
"interpreter": [sys.executable],
"args": [],
"importStrategy": "useBundled",
"showNotifications": "off",
**_get_global_defaults(),
}

return WORKSPACE_SETTINGS[str(key)]
Expand Down Expand Up @@ -342,7 +364,7 @@ def _run_tool_on_document(
settings = copy.deepcopy(_get_settings_by_document(document))

code_workspace = settings["workspaceFS"]
cwd = settings["workspaceFS"]
cwd = settings["cwd"]

use_path = False
use_rpc = False
Expand Down Expand Up @@ -422,7 +444,7 @@ def _run_tool_on_document(
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
"""Runs tool."""
code_workspace = settings["workspaceFS"]
cwd = settings["workspaceFS"]
cwd = settings["cwd"]

use_path = False
use_rpc = False
Expand Down
Loading