Skip to content

Commit

Permalink
Merge pull request #203 from daizutabi/ruff
Browse files Browse the repository at this point in the history
Update ruff rules
  • Loading branch information
daizutabi authored Sep 21, 2024
2 parents 397b2e1 + 4a69199 commit 0bc428e
Show file tree
Hide file tree
Showing 25 changed files with 136 additions and 162 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ jobs:
run: pip install uv
- name: Install the project
run: uv sync
- name: Ruff check
run: uv run ruff check .
- name: Run test
run: uv run pytest -n 8 --junitxml=junit.xml
- name: Upload Codecov Results
Expand Down
14 changes: 7 additions & 7 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,28 @@
from mkapi.plugin import MkApiPlugin


def before_on_config(config: MkDocsConfig, plugin: MkApiPlugin) -> None: # noqa: ARG001
def before_on_config(config: MkDocsConfig, plugin: MkApiPlugin) -> None:
"""Called before `on_config` event of MkAPI plugin."""
if "." not in sys.path:
sys.path.insert(0, ".")


def after_on_config(config: MkDocsConfig, plugin: MkApiPlugin) -> None: # noqa: ARG001
def after_on_config(config: MkDocsConfig, plugin: MkApiPlugin) -> None:
"""Called after `on_config` event of MkAPI plugin."""


def page_title(name: str, depth: int) -> str: # noqa: ARG001
def page_title(name: str, depth: int) -> str:
"""Return a page title."""
return name
# return ".".join(name.split(".")[depth:])
# return ".".join(name.split(".")[depth:]) # noqa: ERA001


def section_title(name: str, depth: int) -> str: # noqa: ARG001
def section_title(name: str, depth: int) -> str:
"""Return a section title."""
return name
# return ".".join(name.split(".")[depth:])
# return ".".join(name.split(".")[depth:]) # noqa: ERA001


def toc_title(name: str, depth: int) -> str: # noqa: ARG001
def toc_title(name: str, depth: int) -> str:
"""Return a toc title."""
return name.split(".")[-1] # Remove prefix.
23 changes: 19 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,24 @@ exclude_lines = [

[tool.ruff]
line-length = 88
target-version = "py312"
exclude = ["google.py", "numpy.py"]
target-version = "py310"
exclude = ["tests/examples/*.py", "example/*.py"]

[tool.ruff.lint]
select = ["E", "W", "F", "I"]
unfixable = ["F401", "RUF100"]
select = ["ALL"]
ignore = [
"ANN002",
"ANN003",
"ARG001",
"ARG002",
"D",
"FBT001",
"FBT002",
"PERF401",
"PGH003",
"PLR2004",
"SIM102",
]

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["ANN", "ARG", "PLR", "RUF", "S"]
10 changes: 7 additions & 3 deletions src/mkapi/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class definitions, assignments, and decorators.
Raise,
)
from dataclasses import dataclass
from inspect import Parameter as P
from inspect import Parameter as P # noqa: N817
from inspect import cleandoc
from typing import TYPE_CHECKING, TypeGuard

Expand Down Expand Up @@ -72,7 +72,8 @@ def iter_child_nodes(node: AST) -> Iterator[AST]:

for child in it:
if isinstance(
child, Import | ImportFrom | ClassDef | FunctionDef | AsyncFunctionDef
child,
Import | ImportFrom | ClassDef | FunctionDef | AsyncFunctionDef,
):
yield child

Expand Down Expand Up @@ -637,7 +638,10 @@ def iter_identifiers(node: AST) -> Iterator[str]:


def _unparse(
node: AST, callback: Callable[[str], str], *, is_type: bool = True
node: AST,
callback: Callable[[str], str],
*,
is_type: bool = True,
) -> Iterator[str]:
trans = StringTransformer() if is_type else Transformer()
source = trans.unparse(node)
Expand Down
4 changes: 2 additions & 2 deletions src/mkapi/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class MkApiConfig(Config):
_config: MkApiConfig = MkApiConfig() # type: ignore


def set_config(config: MkApiConfig):
global _config
def set_config(config: MkApiConfig) -> None:
global _config # noqa: PLW0603
_config = config


Expand Down
9 changes: 3 additions & 6 deletions src/mkapi/doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def _split_sections(text: str, style: Style) -> Iterator[str]:
# In Numpy style, if a section is indented, then a section break is
# created by resuming unindented text.
def _subsplit(text: str, style: Style) -> list[str]:
if style == "google" or len(lines := text.splitlines()) < 3: # noqa: PLR2004
if style == "google" or len(lines := text.splitlines()) < 3:
return [text]

if not lines[2].startswith(" "): # 2 == after '----' line.
Expand Down Expand Up @@ -455,7 +455,7 @@ def split_section(text: str, style: Style) -> tuple[str, str]:
('Returns', 'str: The output string.')
"""
lines = text.splitlines()
if len(lines) < 2: # noqa: PLR2004
if len(lines) < 2:
return "", text

if style == "google" and re.match(r"^([A-Za-z0-9][^:]*):$", lines[0]):
Expand Down Expand Up @@ -722,10 +722,7 @@ def create_doc(text: str | None, style: Style | None = None) -> Doc:
return Doc("Doc", "", "", [])

style = style or get_style(text)

text = mkapi.markdown.convert_code_block(text)
# text = mkapi.markdown.replace(text, ["<", ">"], ["&lt;", "&gt;"])

sections = list(iter_sections(text, style))

if sections and not sections[0].name:
Expand Down Expand Up @@ -897,7 +894,7 @@ def merge_sections(a: Section, b: Section) -> Section:
return Section(a.name, type_, text, list(items))


def iter_merged_sections(a: list[Section], b: list[Section]) -> Iterator[Section]:
def iter_merged_sections(a: list[Section], b: list[Section]) -> Iterator[Section]: # noqa: C901
"""Yield merged `Section` instances from two lists of `Section`.
Take two lists of `Section` instances and yield merged
Expand Down
34 changes: 24 additions & 10 deletions src/mkapi/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@


def _iter(
pattern: re.Pattern, text: str, pos: int = 0, endpos: int | None = None
pattern: re.Pattern,
text: str,
pos: int = 0,
endpos: int | None = None,
) -> Iterator[re.Match[str] | tuple[int, int]]:
"""Iterate over matches of a regex pattern in the given text.
Expand Down Expand Up @@ -77,18 +80,20 @@ def _iter(
yield cursor, endpos


FENCED_CODE = re.compile(r"^(?P<pre> *[~`]{3,}).*?^(?P=pre)", re.M | re.S)
FENCED_CODE = re.compile(r"^(?P<pre> *[~`]{3,}).*?^(?P=pre)", re.MULTILINE | re.DOTALL)


def _iter_fenced_codes(
text: str, pos: int = 0, endpos: int | None = None
text: str,
pos: int = 0,
endpos: int | None = None,
) -> Iterator[re.Match[str] | tuple[int, int]]:
return _iter(FENCED_CODE, text, pos, endpos)


DOCTEST = re.compile(r" *#+ *doctest:.*$", re.M)
PROMPT_ONLY = re.compile(r"^(?P<pre> *\>\>\> *)$", re.M)
COMMENT_ONLY = re.compile(r"^(?P<pre> *\>\>\> )(?P<comment>#.*)$", re.M)
DOCTEST = re.compile(r" *#+ *doctest:.*$", re.MULTILINE)
PROMPT_ONLY = re.compile(r"^(?P<pre> *\>\>\> *)$", re.MULTILINE)
COMMENT_ONLY = re.compile(r"^(?P<pre> *\>\>\> )(?P<comment>#.*)$", re.MULTILINE)


def _add_example_escape(text: str) -> str:
Expand Down Expand Up @@ -283,8 +288,11 @@ def _convert_examples(examples: list[doctest.Example]) -> str:


_ = r"^(?P<suffix>(?P<pre> *)(?P<prev>\S.*)\n{2,})(?P=pre) {4}\S"
FOURINDENT = re.compile(_, re.M)
DIRECTIVE = re.compile(r"^(?P<pre> *)\.\. *(?P<name>[\w\-]+):: *(?P<attr>.*)$", re.M)
FOURINDENT = re.compile(_, re.MULTILINE)
DIRECTIVE = re.compile(
r"^(?P<pre> *)\.\. *(?P<name>[\w\-]+):: *(?P<attr>.*)$",
re.MULTILINE,
)


def _iter_literal_block(text: str) -> Iterator[str]:
Expand Down Expand Up @@ -496,7 +504,10 @@ def convert_code_block(text: str) -> str:


def _finditer(
pattern: re.Pattern, text: str, pos: int = 0, endpos: int | None = None
pattern: re.Pattern,
text: str,
pos: int = 0,
endpos: int | None = None,
) -> Iterator[re.Match[str] | tuple[int, int]]:
for match in _iter_fenced_codes(text, pos, endpos):
if isinstance(match, re.Match):
Expand All @@ -507,7 +518,10 @@ def _finditer(


def finditer(
pattern: re.Pattern, text: str, pos: int = 0, endpos: int | None = None
pattern: re.Pattern,
text: str,
pos: int = 0,
endpos: int | None = None,
) -> Iterator[re.Match[str]]:
"""Find all matches of a regex pattern in the provided text.
Expand Down
2 changes: 1 addition & 1 deletion src/mkapi/nav.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def update_apinav(
except StopIteration:
return
while True:
if is_section: # noqa: SIM108
if is_section:
value = section(name, depth) if section else name
else:
value = page(name, depth)
Expand Down
42 changes: 26 additions & 16 deletions src/mkapi/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ def get_child_nodes(node: AST, module: str) -> list[Definition | Assign | Import
else:
nodes = node_dict[child.name]
if not isinstance(nodes[-1], Definition) or not isinstance(
child, Definition
child,
Definition,
):
nodes.clear()

Expand Down Expand Up @@ -351,7 +352,8 @@ def iter_nodes(fullname: str) -> Iterator[Module | Definition | Assign | Import]

@cache
def parse_node(
node: AST, module: str
node: AST,
module: str,
) -> list[tuple[str, Module | Definition | Assign | Import]]:
"""Parse the given AST node and return a list of tuples.
Expand Down Expand Up @@ -402,7 +404,8 @@ def parse_module(

@cache
def get_node(
name: str, module: str | None = None
name: str,
module: str | None = None,
) -> Module | Definition | Assign | Import | None:
"""Retrieve a node corresponding to the given name and module.
Expand Down Expand Up @@ -521,15 +524,12 @@ def _is_private(name: str) -> bool:


def _is_special(name: str) -> bool:
for name_ in name.split("."):
if name_.startswith("__"):
return True

return False
return any(name_.startswith("__") for name_ in name.split("."))


def _iter_module_members(
module: str, child_only: bool = False
module: str,
child_only: bool = False,
) -> Iterator[tuple[str, Module | Definition]]:
members = parse_module(module)

Expand All @@ -552,7 +552,7 @@ def _get_module_member_from_module(name: str, module: str) -> str | None:
if name.startswith(f"{module}."):
return name.split(".")[1]

elif "." in name:
if "." in name:
return None

return name
Expand Down Expand Up @@ -580,7 +580,9 @@ def _iter_children_from_definition(


def iter_classes_from_module(
module: str, private: bool = False, special: bool = False
module: str,
private: bool = False,
special: bool = False,
) -> Iterator[str]:
"""Iterate over the classes in the given module.
Expand All @@ -600,7 +602,9 @@ def iter_classes_from_module(


def iter_functions_from_module(
module: str, private: bool = False, special: bool = False
module: str,
private: bool = False,
special: bool = False,
) -> Iterator[str]:
"""Iterate over the functions in the given module.
Expand All @@ -620,7 +624,9 @@ def iter_functions_from_module(


def iter_modules_from_module(
module: str, private: bool = False, special: bool = False
module: str,
private: bool = False,
special: bool = False,
) -> Iterator[str]:
"""Iterate over the modules in the given module.
Expand All @@ -639,7 +645,10 @@ def iter_modules_from_module(


def iter_methods_from_class(
name: str, module: str, private: bool = False, special: bool = False
name: str,
module: str,
private: bool = False,
special: bool = False,
) -> Iterator[str]:
"""Iterate over the methods in the given class.
Expand Down Expand Up @@ -679,8 +688,9 @@ def iter_methods_from_class(


@cache
def resolve(
name: str, module: str | None = None
def resolve( # noqa: C901, PLR0911, PLR0912
name: str,
module: str | None = None,
) -> tuple[str | None, str | None] | None:
"""Resolve the given name and return a tuple of the name and module.
Expand Down
Loading

0 comments on commit 0bc428e

Please sign in to comment.