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

lint(ruff): Enable newer annotation style #59

Merged
merged 2 commits into from
Dec 31, 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
14 changes: 8 additions & 6 deletions .github/scripts/summary.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# ruff: noqa:D100,D101,D102,D103,D105
from __future__ import annotations

import argparse
import logging
from dataclasses import InitVar, dataclass, field
from typing import Any, List, Literal, Optional
from typing import Any, Literal
from xml.etree import ElementTree

from tabulate import tabulate
Expand All @@ -16,10 +18,10 @@ class TestCase:
name: str
time: float
state: Literal["success", "failure", "error", "skipped"]
summary: Optional[str]
summary: str | None

@classmethod
def from_junit(cls, tree: ElementTree.Element) -> "TestCase":
def from_junit(cls, tree: ElementTree.Element) -> TestCase:
children = tree.getchildren()
assert len(children) <= 1

Expand Down Expand Up @@ -67,13 +69,13 @@ class TestSuite:
failures: int
skipped: int
time: float
tests: List[TestCase]
tests: list[TestCase]

def __post_init__(self, total: int) -> None:
self.successes = total - self.errors - self.failures - self.skipped

@classmethod
def from_junit(cls, tree: ElementTree.Element) -> "TestSuite":
def from_junit(cls, tree: ElementTree.Element) -> TestSuite:
attrs = tree.attrib

tests = [
Expand All @@ -97,7 +99,7 @@ def __lt__(self, other: Any) -> bool:
return (self.time, self.name) < (other.time, other.name)


def get_failures_and_errors(testsuites: List[TestSuite]) -> str:
def get_failures_and_errors(testsuites: list[TestSuite]) -> str:
reports = []

for testsuite in testsuites:
Expand Down
17 changes: 10 additions & 7 deletions docs/_extensions/cleanup_signatures.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from typing import Any, Dict, Optional, Tuple
from __future__ import annotations

from sphinx.application import Sphinx
from sphinx.ext.autodoc import Options
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.ext.autodoc import Options


# ruff: noqa: ARG001
Expand All @@ -11,17 +14,17 @@ def cleanup_signatures( # pylint: disable=unused-argument
name: str,
obj: Any,
options: Options,
signature: Optional[str],
return_annotation: Optional[str],
) -> Optional[Tuple[str, Optional[str]]]:
signature: str | None,
return_annotation: str | None,
) -> tuple[str, str | None] | None:
if name == "dwas.StepRunner":
# Hide the __init__ signature for dwas.StepRunner, it's meant to be
# private
return ("()", return_annotation)
return None


def setup(app: Sphinx) -> Dict[str, Any]:
def setup(app: Sphinx) -> dict[str, Any]:
app.connect("autodoc-process-signature", cleanup_signatures)

return {
Expand Down
14 changes: 9 additions & 5 deletions docs/_extensions/execute.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
from __future__ import annotations

import os
import shlex
import subprocess
from typing import Any, Dict, List
from typing import TYPE_CHECKING, Any

from docutils import nodes
from docutils.parsers import rst
from docutils.parsers.rst.directives import nonnegative_int, unchanged
from sphinx.addnodes import document
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError

if TYPE_CHECKING:
from sphinx.addnodes import document
from sphinx.application import Sphinx


class execute(nodes.Element): # pylint: disable=invalid-name # noqa: N801
pass
Expand All @@ -25,7 +29,7 @@ class ExecuteDirective(rst.Directive):
"cwd": unchanged,
}

def run(self) -> List[nodes.Element]:
def run(self) -> list[nodes.Element]:
env = self.state.document.settings.env

node = execute()
Expand Down Expand Up @@ -77,7 +81,7 @@ def run_programs(
node.replace_self(new_node)


def setup(app: Sphinx) -> Dict[str, Any]:
def setup(app: Sphinx) -> dict[str, Any]:
app.add_directive("command-output", ExecuteDirective)
app.connect("doctree-read", run_programs)
return {"parallel_read_safe": True}
5 changes: 0 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,6 @@ ignore = [
"S603",
# We want to be able tor rely on PATH and not hardcode binaries
"S607",

# FIXME: re-enable future annotations
"FA100",
# FIXME: re-enable upgrade rules
"UP",
]

flake8-pytest-style.parametrize-values-type = "tuple"
Expand Down
24 changes: 14 additions & 10 deletions src/dwas/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# ruff: noqa:D100,D101,D102,D103
from __future__ import annotations

import importlib.util
import logging
import os
Expand All @@ -14,13 +16,15 @@
)
from contextvars import copy_context
from importlib.metadata import version
from typing import Any, Dict, List, Optional
from typing import TYPE_CHECKING, Any

from . import _io, _pipeline
from ._config import Config
from ._exceptions import BaseDwasException, FailedPipelineException
from ._logging import setup_logging
from ._steps.handlers import BaseStepHandler

if TYPE_CHECKING:
from ._steps.handlers import BaseStepHandler

LOGGER = logging.getLogger(__name__)

Expand All @@ -31,7 +35,7 @@ def __call__(
parser: ArgumentParser, # noqa:ARG002
namespace: Namespace,
values: Any,
option_string: Optional[str] = None, # noqa:ARG002
option_string: str | None = None, # noqa:ARG002
) -> None:
items = getattr(namespace, self.dest, None)
if items is None:
Expand All @@ -52,7 +56,7 @@ def __call__(
parser: ArgumentParser, # noqa:ARG002
namespace: Namespace,
values: Any, # noqa:ARG002
option_string: Optional[str] = None,
option_string: str | None = None,
) -> None:
assert option_string is not None

Expand All @@ -65,7 +69,7 @@ def format_usage(self) -> str:
return " | ".join(self.option_strings)


def _parse_args(args: Optional[List[str]] = None) -> Namespace:
def _parse_args(args: list[str] | None = None) -> Namespace:
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
epilog="""\
Expand Down Expand Up @@ -195,8 +199,8 @@ def _parse_args(args: Optional[List[str]] = None) -> Namespace:


def _parse_steps(
args: List[str], known_steps: Dict[str, BaseStepHandler]
) -> Optional[List[str]]:
args: list[str], known_steps: dict[str, BaseStepHandler]
) -> list[str] | None:
if not args:
return None

Expand Down Expand Up @@ -275,8 +279,8 @@ def _load_user_config(
def _execute_pipeline(
config: Config,
pipeline_config: str,
steps_parameters: List[str],
except_steps: Optional[List[str]],
steps_parameters: list[str],
except_steps: list[str] | None,
*,
only_selected_step: bool,
clean: bool,
Expand Down Expand Up @@ -314,7 +318,7 @@ def _execute_pipeline(


@_io.instrument_streams()
def main(sys_args: Optional[List[str]] = None) -> None:
def main(sys_args: list[str] | None = None) -> None:
if sys_args is None:
sys_args = sys.argv[1:]
if env_args := os.environ.get("DWAS_ADDOPTS"):
Expand Down
11 changes: 6 additions & 5 deletions src/dwas/_config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import annotations

import logging
import multiprocessing
import os
import random
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional

from ._exceptions import BaseDwasException

Expand Down Expand Up @@ -56,7 +57,7 @@ class Config:
- Finally, it will look if this is attached to a tty and enable colors if so.
"""

environ: Dict[str, str]
environ: dict[str, str]
"""
The environment to use when running commands.

Expand Down Expand Up @@ -123,9 +124,9 @@ class Config:
def __init__(
self,
cache_path: str,
log_path: Optional[str],
log_path: str | None,
verbosity: int,
colors: Optional[bool],
colors: bool | None,
n_jobs: int,
*,
skip_missing_interpreters: bool,
Expand Down Expand Up @@ -201,7 +202,7 @@ def __init__(
self.environ["PY_COLORS"] = "0"
self.environ["NO_COLOR"] = "0"

def _get_color_setting(self, colors: Optional[bool]) -> bool:
def _get_color_setting(self, colors: bool | None) -> bool:
# pylint: disable=too-many-return-statements
if colors is not None:
return colors
Expand Down
6 changes: 4 additions & 2 deletions src/dwas/_dependency_injection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import inspect
import logging
from typing import Any, Callable, Dict, TypeVar
from typing import Any, Callable, TypeVar

from ._exceptions import BaseDwasException
from ._inspect import get_location, get_name
Expand All @@ -10,7 +12,7 @@


def call_with_parameters(
func: Callable[..., T], parameters: Dict[str, Any]
func: Callable[..., T], parameters: dict[str, Any]
) -> T:
signature = inspect.signature(func)
kwargs = {}
Expand Down
6 changes: 3 additions & 3 deletions src/dwas/_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List
from __future__ import annotations


class BaseDwasException(Exception):
Expand Down Expand Up @@ -46,13 +46,13 @@ def _pluralize(self, n_jobs: int) -> str:


class UnknownStepsException(BaseDwasException):
def __init__(self, steps: List[str]) -> None:
def __init__(self, steps: list[str]) -> None:
message = f"Unknown steps: {', '.join(steps)}"
super().__init__(message)


class CyclicStepDependenciesException(BaseDwasException):
def __init__(self, cycle: List[str]) -> None:
def __init__(self, cycle: list[str]) -> None:
message = f"Cyclic dependencies between steps: {' --> '.join(cycle)}"
super().__init__(message)
self.cycle = cycle
Expand Down
12 changes: 8 additions & 4 deletions src/dwas/_frontend.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
from __future__ import annotations

import shutil
import sys
import time
from contextlib import contextmanager
from contextvars import copy_context
from datetime import timedelta
from threading import Event, Thread
from typing import Iterator, List
from typing import TYPE_CHECKING, Iterator

from colorama import Cursor, Fore, Style, ansi

from . import _io
from ._scheduler import Scheduler
from ._timing import format_timedelta

if TYPE_CHECKING:
from ._scheduler import Scheduler

ANSI_SHOW_CURSOR = f"{ansi.CSI}?25h"
ANSI_HIDE_CURSOR = f"{ansi.CSI}?25l"

Expand All @@ -25,7 +29,7 @@
def _counter(self, value: int, color: str) -> str:
return f"{color}{Style.BRIGHT}{value}{Style.NORMAL}{Fore.YELLOW}"

def lines(self) -> List[str]:
def lines(self) -> list[str]:
update_at = time.monotonic()

term_width = shutil.get_terminal_size().columns
Expand Down Expand Up @@ -55,7 +59,7 @@
"~",
)

additional_info: List[str] = []
additional_info: list[str] = []

Check warning on line 62 in src/dwas/_frontend.py

View check run for this annotation

Codecov / codecov/patch

src/dwas/_frontend.py#L62

Added line #L62 was not covered by tests
if self._scheduler.ready:
ready_line = (
f"[-:--:--] {Fore.YELLOW}{Style.BRIGHT}ready: "
Expand Down
Loading