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

Bump pygls to 1.0 #285

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
1,541 changes: 824 additions & 717 deletions poetry.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ include = ["salt_lsp/data/states.pickle"]

[tool.poetry.dependencies]
# remove the compat code from salt_lsp/workspace.py once we drop python 3.8 support
python = "^3.8"
pygls = "^0.11.3"
python = "^3.8,<3.12"
pygls = "^1.0"
PyYAML = "^6"

[tool.poetry.dev-dependencies]
Expand All @@ -20,7 +20,7 @@ mypy = ">=0.812"
pylint = ">=2.7.4"
pyfakefs = ">=4.4.0"
salt = "^3005"
pytest-testinfra = "^6.7.0"
pytest-testinfra = ">=6.7.0"
types-PyYAML = "^6"

[tool.poetry.scripts]
Expand Down
5 changes: 5 additions & 0 deletions salt_lsp/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from importlib import metadata

__version__ = metadata.version(__package__)

del metadata # avoid polluting the main namespace
4 changes: 2 additions & 2 deletions salt_lsp/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def loglevel_from_str(level: str) -> int:
return LOG_LEVEL_DICT[level.lower()]


def add_arguments(parser):
def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.description = "salt state server"

parser.add_argument(
Expand Down Expand Up @@ -53,7 +53,7 @@ def add_arguments(parser):
)


def main():
def main() -> None:
parser = argparse.ArgumentParser()
add_arguments(parser)
args = parser.parse_args()
Expand Down
3 changes: 1 addition & 2 deletions salt_lsp/document_symbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import itertools
from typing import Callable, Dict, List, Sequence, TypedDict, cast

from pygls.lsp import types
from lsprotocol import types

from salt_lsp.parser import (
AstNode,
Expand Down Expand Up @@ -197,7 +197,6 @@ def __call__(self, node: AstNode) -> bool:
def tree_to_document_symbols(
tree: Tree, state_completions: CompletionsDict
) -> List[types.DocumentSymbol]:

res = []

for elem in itertools.chain.from_iterable(
Expand Down
2 changes: 1 addition & 1 deletion salt_lsp/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from os.path import abspath, dirname, exists, isdir, join
from typing import Any, Callable, List, Optional, Sequence, Tuple, Union, cast

from pygls.lsp import types
from lsprotocol import types
import yaml
from yaml.tokens import BlockEndToken, ScalarToken

Expand Down
61 changes: 32 additions & 29 deletions salt_lsp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,28 @@
from os.path import basename
from typing import Dict, List, Optional, Sequence, Tuple, Union, cast

from pygls.lsp import types
from pygls.lsp.methods import (
COMPLETION,
from lsprotocol.types import (
TEXT_DOCUMENT_COMPLETION,
INITIALIZE,
TEXT_DOCUMENT_DID_OPEN,
DEFINITION,
DOCUMENT_SYMBOL,
)
from pygls.lsp.types import (
TEXT_DOCUMENT_DEFINITION,
TEXT_DOCUMENT_DOCUMENT_SYMBOL,
CompletionItem,
CompletionList,
CompletionOptions,
CompletionParams,
DeclarationParams,
DidOpenTextDocumentParams,
DocumentSymbol,
DocumentSymbolParams,
InitializeParams,
Location,
SymbolInformation,
TextDocumentItem,
)
from pygls.server import LanguageServer

from salt_lsp import __version__
from salt_lsp import utils
from salt_lsp.base_types import StateNameCompletion, SLS_LANGUAGE_ID
from salt_lsp.workspace import SaltLspProto, SlsFileWorkspace
Expand All @@ -41,7 +46,9 @@ class SaltServer(LanguageServer):
LINE_START_REGEX = re.compile(r"^(\s*)\b", re.MULTILINE)

def __init__(self) -> None:
super().__init__(protocol_cls=SaltLspProto)
super().__init__(
name="SaltServer", version=__version__, protocol_cls=SaltLspProto
)

self._state_name_completions: Dict[str, StateNameCompletion] = {}

Expand All @@ -59,7 +66,7 @@ def workspace(self) -> SlsFileWorkspace:
def post_init(
self,
state_name_completions: Dict[str, StateNameCompletion],
log_level=logging.DEBUG,
log_level: int = logging.DEBUG,
) -> None:
"""Further initialisation, called after
setup_salt_server_capabilities."""
Expand All @@ -69,7 +76,7 @@ def post_init(
self.logger.setLevel(log_level)

def complete_state_name(
self, params: types.CompletionParams
self, params: CompletionParams
) -> List[Tuple[str, Optional[str]]]:
"""Complete state name at current position"""
assert (
Expand Down Expand Up @@ -100,7 +107,7 @@ def complete_state_name(

def find_id_in_doc_and_includes(
self, id_to_find: str, starting_uri: str
) -> Optional[types.Location]:
) -> Optional[Location]:
"""Finds the first matching location of the given id in the document or
in its includes.

Expand Down Expand Up @@ -147,10 +154,7 @@ def find_id_in_doc_and_includes(
self.logger.debug(
"found match at '%s', '%s", lsp_range.start, lsp_range.end
)
return types.Location(
uri=str(uri),
range=lsp_range,
)
return Location(uri=str(uri), range=lsp_range)

return None

Expand All @@ -168,7 +172,8 @@ def initialize(params: InitializeParams) -> None:
server.logger.debug("Replaced workspace with SlsFileWorkspace")

@server.feature(
COMPLETION, CompletionOptions(trigger_characters=["-", "."])
TEXT_DOCUMENT_COMPLETION,
CompletionOptions(trigger_characters=["-", "."]),
)
def completions(
salt_server: SaltServer, params: CompletionParams
Expand Down Expand Up @@ -210,10 +215,10 @@ def completions(
)
return None

@server.feature(DEFINITION)
@server.feature(TEXT_DOCUMENT_DEFINITION)
def goto_definition(
salt_server: SaltServer, params: types.DeclarationParams
) -> Optional[types.Location]:
salt_server: SaltServer, params: DeclarationParams
) -> Optional[Location]:
uri = params.text_document.uri
if (tree := salt_server.workspace.trees.get(uri)) is None:
return None
Expand All @@ -223,15 +228,15 @@ def goto_definition(
if not isinstance(path[-1], RequisiteNode):
return None

if (id_to_find := cast(RequisiteNode, path[-1]).reference) is None:
if (id_to_find := path[-1].reference) is None:
return None

return salt_server.find_id_in_doc_and_includes(id_to_find, uri)

@server.feature(TEXT_DOCUMENT_DID_OPEN)
def did_open(
salt_server: SaltServer, params: types.DidOpenTextDocumentParams
) -> Optional[types.TextDocumentItem]:
salt_server: SaltServer, params: DidOpenTextDocumentParams
) -> Optional[TextDocumentItem]:
"""Text document did open notification.

This function registers the newly opened file with the salt server.
Expand All @@ -241,19 +246,17 @@ def did_open(
params.text_document.uri,
)
doc = salt_server.workspace.get_document(params.text_document.uri)
return types.TextDocumentItem(
return TextDocumentItem(
uri=params.text_document.uri,
language_id=SLS_LANGUAGE_ID,
text=params.text_document.text or "",
version=doc.version,
version=doc.version or 0,
)

@server.feature(DOCUMENT_SYMBOL)
@server.feature(TEXT_DOCUMENT_DOCUMENT_SYMBOL)
def document_symbol(
salt_server: SaltServer, params: types.DocumentSymbolParams
) -> Optional[
Union[List[types.DocumentSymbol], List[types.SymbolInformation]]
]:
salt_server: SaltServer, params: DocumentSymbolParams
) -> Optional[Union[List[DocumentSymbol], List[SymbolInformation]]]:
return salt_server.workspace.document_symbols.get(
params.text_document.uri, []
)
2 changes: 1 addition & 1 deletion salt_lsp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
)
from urllib.parse import urlparse, ParseResult

from pygls.lsp.types import Position, Range
from lsprotocol.types import Position, Range

from salt_lsp import parser
from salt_lsp.parser import AstNode, Tree
Expand Down
3 changes: 1 addition & 2 deletions salt_lsp/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sys
from typing import List, Optional, Union

from pygls.lsp import types
from lsprotocol import types
from pygls.protocol import LanguageServerProtocol
from pygls.workspace import Workspace

Expand Down Expand Up @@ -154,7 +154,6 @@ def _update_document(

def _get_workspace_of_document(self, uri: Union[str, FileUri]) -> FileUri:
for workspace_uri in self._folders:

if is_relative_to(
Path(FileUri(uri).path), Path(FileUri(workspace_uri).path)
):
Expand Down
21 changes: 11 additions & 10 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
from threading import Thread
import os

from pygls.lsp.methods import (
EXIT,
INITIALIZE,
TEXT_DOCUMENT_DID_OPEN,
SHUTDOWN,
)
from pygls.lsp.types import (
from lsprotocol.types import (
ClientCapabilities,
InitializeParams,
DidOpenTextDocumentParams,
InitializeResult,
TextDocumentItem,
EXIT,
INITIALIZE,
TEXT_DOCUMENT_DID_OPEN,
SHUTDOWN,
)
from pygls.server import LanguageServer
import pytest
Expand Down Expand Up @@ -497,7 +496,9 @@ def salt_client_server():
args=(os.fdopen(csr, "rb"), os.fdopen(scw, "wb")),
)
server_thread.daemon = True
client = LanguageServer(asyncio.new_event_loop())
client = LanguageServer(
loop=asyncio.new_event_loop(), version="0.0.1", name="test_server"
)
client_thread = Thread(
target=client.start_io,
args=(os.fdopen(scr, "rb"), os.fdopen(csw, "wb")),
Expand All @@ -509,7 +510,7 @@ def salt_client_server():

client_thread.start()

response = client.lsp.send_request(
response: InitializeResult = client.lsp.send_request(
INITIALIZE,
InitializeParams(
process_id=12345,
Expand All @@ -518,7 +519,7 @@ def salt_client_server():
),
).result(timeout=CALL_TIMEOUT)

assert "capabilities" in response
assert response.capabilities

yield client, server

Expand Down
6 changes: 5 additions & 1 deletion tests/test_completions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from types import SimpleNamespace

from conftest import MODULE_DOCS
from salt_lsp.base_types import SLS_LANGUAGE_ID


TEST_FILE = """saltmaster.packages:
Expand All @@ -23,7 +24,10 @@ def test_complete_of_file(salt_client_server, file_name_completer):
_, server = salt_client_server
txt_doc = {
"text_document": SimpleNamespace(
uri="foo.sls", text=TEST_FILE, version=0
uri="foo.sls",
text=TEST_FILE,
version=0,
language_id=SLS_LANGUAGE_ID,
),
}
server.workspace.put_document(txt_doc["text_document"])
Expand Down
2 changes: 1 addition & 1 deletion tests/test_document_symbols.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pygls.lsp import types
from lsprotocol import types

from salt_lsp.document_symbols import tree_to_document_symbols
from salt_lsp.parser import parse
Expand Down
2 changes: 1 addition & 1 deletion tests/test_find_ids.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pygls.lsp.types import (
from lsprotocol.types import (
Location,
Range,
Position,
Expand Down
4 changes: 1 addition & 3 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
)
from salt_lsp.utils import construct_path_to_position

from pygls.lsp.types import (
Position,
)
from lsprotocol.types import Position


MASTER_DOT_SLS = """saltmaster.packages:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os

import pytest
from pygls.lsp import types
from lsprotocol import types

from salt_lsp.utils import (
ast_node_to_range,
Expand Down