Replace linter (#37)

This commit is contained in:
Regen
2021-03-28 22:23:57 +09:00
committed by GitHub
parent 6e839f7675
commit 4d120a6a98
17 changed files with 563 additions and 578 deletions

View File

@@ -25,7 +25,7 @@ class API(object):
_uuid: uuid.UUID
_builtin_commands: Dict[str, str]
_builtin_variables: Dict[str, str]
_builtin_variable_template: Dict[Pattern, str]
_builtin_variable_template: Dict[Pattern[str], str]
_builtin_modules: Dict[str, str]
_targets: List[str]
_cached_variables: Dict[str, str]
@@ -45,11 +45,11 @@ class API(object):
self._generated_list_parsed = False
def query(self) -> bool:
""" Use CMake's file API to get JSON information about the build tree
"""Use CMake's file API to get JSON information about the build tree
Generates a JSON request file for the current build tree and runs
CMake on the build tree. Deletes the request file immediately
after.
Generates a JSON request file for the current build tree and runs
CMake on the build tree. Deletes the request file immediately
after.
"""
if not self.cmake_cache.exists():
return False
@@ -83,10 +83,10 @@ class API(object):
return True
def read_reply(self) -> bool:
""" Reads the CMake file API reply file and updates internal state
"""Reads the CMake file API reply file and updates internal state
Reads the result of the previous query file and updates
the targets, the cache entries and the cmake files.
Reads the result of the previous query file and updates
the targets, the cache entries and the cmake files.
"""
reply = self._build / ".cmake" / "api" / "v1" / "reply"
indices = sorted(reply.glob("index-*.json"))
@@ -112,13 +112,13 @@ class API(object):
return True
def _read_codemodel(self, codemodelpath: Path):
def _read_codemodel(self, codemodelpath: Path) -> None:
with (codemodelpath).open() as fp:
codemodel = json.load(fp)
config = codemodel["configurations"][0]
self._targets[:] = [x["name"] for x in config["targets"]]
def _read_cache(self, cachepath: Path):
def _read_cache(self, cachepath: Path) -> None:
with cachepath.open() as fp:
cache = json.load(fp)
self._cached_variables.clear()
@@ -134,7 +134,7 @@ class API(object):
doc.append(f"`{value}`")
self._cached_variables[name] = "\n\n".join(doc)
def _read_cmake_files(self, jsonpath: Path):
def _read_cmake_files(self, jsonpath: Path) -> None:
"""inspect CMake list files that are used during build generation"""
if not self._builtin_variables or self._generated_list_parsed:
@@ -214,10 +214,10 @@ endforeach()
self._parse_modules()
def _parse_commands(self) -> None:
""" Load docs for builtin cmake functions
"""Load docs for builtin cmake functions
Loads the documentation for builtin cmake functions from the result
of `$ cmake --help-commands`.
Loads the documentation for builtin cmake functions from the result
of `$ cmake --help-commands`.
"""
p = subprocess.run(
[self._cmake, "--help-commands"],
@@ -247,10 +247,10 @@ endforeach()
self._builtin_commands[command] = "```cmake\n" + signature + "\n```"
def _parse_variables(self) -> None:
""" Load docs for builtin cmake variables
"""Load docs for builtin cmake variables
Loads the documentation for builtin cmake variables from
the result of `$ cmake --help-variables`.
Loads the documentation for builtin cmake variables from
the result of `$ cmake --help-variables`.
"""
p = subprocess.run(
[self._cmake, "--help-variables"],
@@ -286,10 +286,10 @@ endforeach()
self._builtin_variables[variable] = doc
def _parse_modules(self) -> None:
""" Loads docs for all modules in the cmake distribution
"""Loads docs for all modules in the cmake distribution
Loads the documentation for cmake modules included in the
distribution from the result of `$ cmake --help-modules`.
Loads the documentation for cmake modules included in the
distribution from the result of `$ cmake --help-modules`.
"""
p = subprocess.run(
[self._cmake, "--help-modules"],
@@ -316,7 +316,7 @@ endforeach()
module = match.group("module")
header = match.group("header")
doc = _tidy_doc(match.group("doc"))
if header is not None and header != "Overview":
if header != "Overview":
doc = ""
self._builtin_modules[module] = doc

View File

@@ -1,4 +1,4 @@
from typing import List
from typing import List, Optional
from .parser import TokenList
@@ -7,7 +7,7 @@ class Formatter(object):
indent: str
lower_identifier: bool
def __init__(self, indent=" ", lower_identifier=True):
def __init__(self, indent: str = " ", lower_identifier: bool = True):
self.indent = indent
self.lower_identifier = lower_identifier
@@ -94,7 +94,7 @@ class Formatter(object):
return ret
def main(args: List[str] = None):
def main(argss: Optional[List[str]] = None) -> None:
import sys
from argparse import ArgumentParser
from difflib import unified_diff
@@ -117,7 +117,7 @@ def main(args: List[str] = None):
"--version", action="version", version=f"%(prog)s {__version__}"
)
args = parser.parse_args(args)
args = parser.parse_args(argss)
if not args.lists and args.inplace:
print("error: cannot use -i when no arguments are specified.", file=sys.stderr)

View File

@@ -10,7 +10,7 @@ TokenList = List[TokenType]
class ListParser(object):
_parser: pp.ParserElement
def __init__(self):
def __init__(self) -> None:
newline = "\n"
space_plus = pp.Regex("[ \t]+")
space_star = pp.Optional(space_plus)
@@ -20,7 +20,7 @@ class ListParser(object):
bracket_content = pp.Forward()
def action_bracket_open(tokens: pp.ParseResults):
def action_bracket_open(tokens: pp.ParseResults) -> None:
nonlocal bracket_content
marker = "]" + "=" * (len(tokens[0]) - 2) + "]"
bracket_content <<= pp.SkipTo(marker, include=True)

View File

@@ -1,7 +1,7 @@
import logging
import re
from pathlib import Path
from typing import List, Optional, Tuple
from typing import Any, Callable, List, Optional, Tuple
from pygls.features import (
COMPLETION,
@@ -36,18 +36,18 @@ from .parser import ListParser
logger = logging.getLogger(__name__)
class CMakeLanguageServer(LanguageServer):
class CMakeLanguageServer(LanguageServer): # type: ignore
_parser: ListParser
_api: API
_api: Optional[API]
def __init__(self, *args):
def __init__(self, *args: Any) -> None:
super().__init__(*args)
self._parser = ListParser()
self._api = None
@self.feature(INITIALIZE)
def initialize(params: InitializeParams):
def initialize(params: InitializeParams) -> None:
opts = params.initializationOptions
cmake = getattr(opts, "cmakeExecutable", "cmake")
@@ -60,7 +60,9 @@ class CMakeLanguageServer(LanguageServer):
trigger_characters = ["{", "("]
@self.feature(COMPLETION, trigger_characters=trigger_characters)
def completions(params: CompletionParams):
def completions(params: CompletionParams) -> CompletionList:
assert self._api is not None
if (
hasattr(params, "context")
and params.context.triggerKind == CompletionTriggerKind.TriggerCharacter
@@ -143,7 +145,7 @@ class CMakeLanguageServer(LanguageServer):
return CompletionList(False, items)
@self.feature(FORMATTING)
def formatting(params: DocumentFormattingParams):
def formatting(params: DocumentFormattingParams) -> Optional[List[TextEdit]]:
doc = self.workspace.get_document(params.textDocument.uri)
content = doc.source
tokens, remain = self._parser.parse(content)
@@ -156,16 +158,19 @@ class CMakeLanguageServer(LanguageServer):
return [TextEdit(Range(Position(0, 0), Position(lines + 1, 0)), formatted)]
@self.feature(HOVER)
def hover(params: TextDocumentPositionParams):
def hover(params: TextDocumentPositionParams) -> Optional[Hover]:
assert self._api is not None
api = self._api
word = self._cursor_word(params.textDocument.uri, params.position, True)
if not word:
return None
candidates = [
lambda x: self._api.get_command_doc(x.lower()),
lambda x: self._api.get_variable_doc(x),
lambda x: self._api.get_module_doc(x, False),
lambda x: self._api.get_module_doc(x, True),
candidates: List[Callable[[str], Optional[str]]] = [
lambda x: api.get_command_doc(x.lower()),
lambda x: api.get_variable_doc(x),
lambda x: api.get_module_doc(x, False),
lambda x: api.get_module_doc(x, True),
]
for c in candidates:
doc = c(word[0])
@@ -177,7 +182,9 @@ class CMakeLanguageServer(LanguageServer):
@self.thread()
@self.feature(TEXT_DOCUMENT_DID_SAVE, includeText=False)
@self.feature(INITIALIZED)
def run_cmake(*args):
def run_cmake(*args: Any) -> None:
assert self._api is not None
if self._api.query():
self._api.read_reply()
@@ -192,7 +199,7 @@ class CMakeLanguageServer(LanguageServer):
doc = self.workspace.get_document(uri)
content = doc.source
line = content.split("\n")[position.line]
return line
return str(line)
def _cursor_word(
self, uri: str, position: Position, include_all: bool = True
@@ -212,7 +219,7 @@ class CMakeLanguageServer(LanguageServer):
return None
def main(args=None):
def main() -> None:
from argparse import ArgumentParser
from . import __version__
@@ -221,7 +228,7 @@ def main(args=None):
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
)
args = parser.parse_args(args)
parser.parse_args()
logging.basicConfig(level=logging.INFO)
logging.getLogger("pygls").setLevel(logging.WARNING)