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

Sourcery refactored main branch #201

Merged
merged 3 commits into from
Feb 21, 2022
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
3 changes: 2 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ repos:
hooks:
- id: mypy
exclude: "^(docs|tests|.github)"
additional_dependencies: [types-all]

- repo: https://github.com/MarcoGorelli/absolufy-imports
rev: v0.3.1
Expand All @@ -31,7 +32,7 @@ repos:
rev: v2.31.0
hooks:
- id: pyupgrade
args: [--py36-plus]
args: [--py37-plus]
- repo: https://github.com/python/black
rev: 22.1.0
hooks:
Expand Down
19 changes: 6 additions & 13 deletions flake8_nb/__main__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Command-line implementation of flake8_nb."""
from __future__ import annotations

import sys
from typing import List
from typing import Optional

from flake8_nb import FLAKE8_VERSION_TUPLE
from flake8_nb.flake8_integration.cli import Flake8NbApplication


def main(argv: Optional[List[str]] = None) -> None:
def main(argv: list[str] | None = None) -> None:
"""Execute the main bit of the application.

This handles the creation of an instance of :class:`Application`, runs it,
Expand All @@ -16,18 +16,11 @@ def main(argv: Optional[List[str]] = None) -> None:

Parameters
----------
argv: List[str], optional
argv: list[str] | None
The arguments to be passed to the application for parsing.
"""
# TODO: remove compat after flake8>3.8.0 release
# tested with flake8-nightly, in test__main__.py,
# but not picked up by by coverage
if FLAKE8_VERSION_TUPLE > (3, 7, 9): # pragma: no cover
if argv is None:
argv = sys.argv[1:]
else:
argv = argv[1:]

if FLAKE8_VERSION_TUPLE > (3, 7, 9):
argv = sys.argv[1:] if argv is None else argv[1:]
s-weigand marked this conversation as resolved.
Show resolved Hide resolved
app = Flake8NbApplication()
app.run(argv)
app.exit()
43 changes: 20 additions & 23 deletions flake8_nb/flake8_integration/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@
``*.ipynb`` files and injecting the parsed files, during the loading
of the CLI argv and config of ``flake8``.
"""
from __future__ import annotations

import logging
import os
import sys
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple

from flake8 import __version__ as flake_version
from flake8 import defaults
Expand All @@ -33,35 +31,35 @@


def get_notebooks_from_args(
args: List[str], exclude: List[str] = ["*.tox/*", "*.ipynb_checkpoints*"]
) -> Tuple[List[str], List[str]]:
args: list[str], exclude: list[str] = ["*.tox/*", "*.ipynb_checkpoints*"]
) -> tuple[list[str], list[str]]:
"""Extract the absolute paths to notebooks.

The paths are relative to the current directory or
to the CLI passes files/folder and returned as list.

Parameters
----------
args : List[str]
args : list[str]
The left over arguments that were not parsed by :attr:`option_manager`
exclude : List[str], optional
exclude : list[str]
File-/Folderpatterns that should be excluded,
by default ["*.tox/*", "*.ipynb_checkpoints*"]

Returns
-------
Tuple[List[str],List[str]]
tuple[list[str], list[str]]
List of found notebooks absolute paths.
"""

def is_notebook(file_path: str, nb_list: List[str], root: str = ".") -> bool:
def is_notebook(file_path: str, nb_list: list[str], root: str = ".") -> bool:
"""Check if a file is a notebook and appends it to nb_list if it is.

Parameters
----------
file_path : str
File to check if it is a notebook
nb_list : List[str]
nb_list : list[str]
List of notebooks
root : str
Root directory, by default "."
Expand All @@ -77,7 +75,7 @@ def is_notebook(file_path: str, nb_list: List[str], root: str = ".") -> bool:
return True
return False

nb_list: List[str] = []
nb_list: list[str] = []
if not args:
args = [os.curdir]
for index, arg in list(enumerate(args))[::-1]:
Expand All @@ -102,12 +100,12 @@ def hack_option_manager_generate_versions(

Parameters
----------
generate_versions : Callable
generate_versions : Callable[..., str]
option_manager.generate_versions of flake8.options.manager.OptionManager

Returns
-------
Callable
Callable[..., str]
hacked_generate_versions
"""

Expand All @@ -128,12 +126,11 @@ def hacked_generate_versions(*args: Any, **kwargs: Any) -> str:
"""
original_output = generate_versions(*args, **kwargs)
format_str = "%(name)s: %(version)s"
join_on = ", "
additional_output = format_str % {
"name": "flake8",
"version": flake_version,
}
return f"{additional_output}{join_on}{original_output}"
return f"{additional_output}, {original_output}"

return hacked_generate_versions

Expand Down Expand Up @@ -257,7 +254,7 @@ def hack_options(self) -> None:
)

@staticmethod
def hack_args(args: List[str], exclude: List[str]) -> List[str]:
def hack_args(args: list[str], exclude: list[str]) -> list[str]:
r"""Update args with ``*.ipynb`` files.

Checks the passed args if ``*.ipynb`` can be found and
Expand All @@ -266,14 +263,14 @@ def hack_args(args: List[str], exclude: List[str]) -> List[str]:

Parameters
----------
args : List[str]
args : list[str]
List of commandline arguments provided to ``flake8_nb``
exclude : List[str]
exclude : list[str]
File-/Folderpatterns that should be excluded

Returns
-------
List[str]
list[str]
The original args + intermediate parsed ``*.ipynb`` files.
"""
args, nb_list = get_notebooks_from_args(args, exclude=exclude)
Expand All @@ -282,7 +279,7 @@ def hack_args(args: List[str], exclude: List[str]) -> List[str]:

def parse_configuration_and_cli_legacy(
self,
argv: Optional[List[str]] = None,
argv: list[str] | None = None,
) -> None:
"""Compat version of self.parse_configuration_and_cli to work with flake8 >=3.7.0,<= 3.7.9 .

Expand All @@ -292,7 +289,7 @@ def parse_configuration_and_cli_legacy(

Parameters
----------
argv: List[str]
argv: list[str] | None
Command-line arguments passed in directly.
"""
if self.options is None and self.args is None: # type: ignore # pragma: no branch
Expand All @@ -315,15 +312,15 @@ def parse_configuration_and_cli_legacy(
self.formatting_plugins.provide_options(self.option_manager, self.options, self.args)

def parse_configuration_and_cli(
self, config_finder: config.ConfigFileFinder, argv: List[str]
self, config_finder: config.ConfigFileFinder, argv: list[str]
) -> None:
"""Parse configuration files and the CLI options.

Parameters
----------
config_finder: config.ConfigFileFinder
The finder for finding and reading configuration files.
argv: List[str]
argv: list[str]
Command-line arguments passed in directly.
"""
self.options, self.args = aggregator.aggregate_options(
Expand Down
35 changes: 19 additions & 16 deletions flake8_nb/flake8_integration/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
original notebook and the cell the code in.
"""

from __future__ import annotations

import os
from typing import Tuple
from typing import Union
from typing import cast

from flake8.formatting.default import Default
from flake8.style_guide import Violation
Expand All @@ -15,7 +16,7 @@
from flake8_nb.parsers.notebook_parsers import map_intermediate_to_input


def map_notebook_error(violation: Violation, format_str: str) -> Union[Tuple[str, int], None]:
def map_notebook_error(violation: Violation, format_str: str) -> tuple[str, int] | None:
"""Map the violation caused in an intermediate file back to its cause.

The cause is resolved as the notebook, the input cell and
Expand All @@ -30,7 +31,7 @@ def map_notebook_error(violation: Violation, format_str: str) -> Union[Tuple[str

Returns
-------
Tuple[str, int]
tuple[str, int] | None
(filename, input_cell_line_number)
``filename`` being the name of the original notebook and
the input cell were the violation was reported.
Expand Down Expand Up @@ -69,7 +70,7 @@ def after_init(self) -> None:
if self.options.format.lower() != "default_notebook":
self.error_format = self.options.format

def format(self, violation: Violation) -> Union[str, None]:
def format(self, violation: Violation) -> str | None:
r"""Format the error detected by a flake8 checker.

Depending on if the violation was caused by a ``*.py`` file
Expand All @@ -82,7 +83,7 @@ def format(self, violation: Violation) -> Union[str, None]:

Returns
-------
str
str | None
Formatted error message, which will be displayed
in the terminal.
"""
Expand All @@ -91,13 +92,15 @@ def format(self, violation: Violation) -> Union[str, None]:
map_result = map_notebook_error(violation, self.options.notebook_cell_format)
if map_result:
filename, line_number = map_result
notebook_error: str = self.error_format % {
"code": violation.code,
"text": violation.text,
"path": filename,
"row": line_number,
"col": violation.column_number,
}
return notebook_error
default_error: Union[str, None] = super().format(violation)
return default_error
return cast(
str,
self.error_format
% {
"code": violation.code,
"text": violation.text,
"path": filename,
"row": line_number,
"col": violation.column_number,
},
)
return cast(str, super().format(violation))
Loading