From 52d428fa757778d631ba7951ee2f8d62facf8193 Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Tue, 12 Nov 2024 14:17:30 +0000 Subject: [PATCH] Remove type for self (#326) --- .pre-commit-config.yaml | 18 +++++---- pyproject.toml | 4 ++ src/ansible_creator/arg_parser.py | 38 +++++++++---------- src/ansible_creator/cli.py | 10 ++--- src/ansible_creator/config.py | 2 +- src/ansible_creator/exceptions.py | 6 +-- src/ansible_creator/output.py | 26 ++++++------- .../plugins/filter/hello_world.py.j2 | 2 +- src/ansible_creator/subcommands/add.py | 3 +- src/ansible_creator/subcommands/init.py | 10 +++-- src/ansible_creator/templar.py | 4 +- src/ansible_creator/utils.py | 4 +- .../testcol/plugins/filter/hello_world.py | 2 +- tests/units/test_init.py | 12 +++--- 14 files changed, 75 insertions(+), 66 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a0d1470e..74e6ddd0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -43,11 +43,6 @@ repos: - prettier-plugin-toml - prettier-plugin-sort-json - - repo: https://github.com/psf/black - rev: 24.10.0 - hooks: - - id: black - - repo: https://github.com/pappasam/toml-sort rev: v0.23.1 hooks: @@ -59,14 +54,23 @@ repos: - id: tox-ini-fmt - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.2 + rev: v0.7.3 hooks: - id: ruff args: + - --fix - --exit-non-zero-on-fix + types_or: [python, pyi] + - id: ruff-format # must be after ruff + types_or: [python, pyi] + + - repo: https://github.com/psf/black # must be after ruff + rev: 24.10.0 + hooks: + - id: black - repo: https://github.com/streetsidesoftware/cspell-cli - rev: v8.15.2 + rev: v8.16.0 hooks: - id: cspell name: Spell check with cspell diff --git a/pyproject.toml b/pyproject.toml index 8f19baa1..d1c67fc5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -342,6 +342,10 @@ line-length = 100 target-version = "py310" [tool.ruff.lint] +ignore = [ + "COM812", # conflicts with ISC001 on format + "ISC001" # conflicts with COM812 on format +] select = ["ALL"] [tool.ruff.lint.flake8-pytest-style] diff --git a/src/ansible_creator/arg_parser.py b/src/ansible_creator/arg_parser.py index c026da98..7483c8dd 100644 --- a/src/ansible_creator/arg_parser.py +++ b/src/ansible_creator/arg_parser.py @@ -46,12 +46,12 @@ class Parser: """A parser for the command line arguments.""" - def __init__(self: Parser) -> None: + def __init__(self) -> None: """Initialize the parser.""" self.args: argparse.Namespace self.pending_logs: list[Msg] = [] - def parse_args(self: Parser) -> tuple[argparse.Namespace, list[Msg]]: + def parse_args(self) -> tuple[argparse.Namespace, list[Msg]]: """Parse the root arguments. Returns: @@ -104,7 +104,7 @@ def parse_args(self: Parser) -> tuple[argparse.Namespace, list[Msg]]: return self.args, self.pending_logs - def _add(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add(self, subparser: SubParser[ArgumentParser]) -> None: """Add resources to an existing Ansible project. Args: @@ -217,7 +217,7 @@ def _add_args_plugin_common(self, parser: ArgumentParser) -> None: "current working directory.", ) - def _add_resource(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_resource(self, subparser: SubParser[ArgumentParser]) -> None: """Add resources to an existing Ansible project. Args: @@ -237,7 +237,7 @@ def _add_resource(self: Parser, subparser: SubParser[ArgumentParser]) -> None: self._add_resource_devfile(subparser=subparser) self._add_resource_role(subparser=subparser) - def _add_resource_devcontainer(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_resource_devcontainer(self, subparser: SubParser[ArgumentParser]) -> None: """Add devcontainer files to an existing Ansible project. Args: @@ -259,7 +259,7 @@ def _add_resource_devcontainer(self: Parser, subparser: SubParser[ArgumentParser self._add_args_common(parser) - def _add_resource_devfile(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_resource_devfile(self, subparser: SubParser[ArgumentParser]) -> None: """Add a devfile file to an existing Ansible project. Args: @@ -281,7 +281,7 @@ def _add_resource_devfile(self: Parser, subparser: SubParser[ArgumentParser]) -> self._add_overwrite(parser) self._add_args_common(parser) - def _add_resource_role(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_resource_role(self, subparser: SubParser[ArgumentParser]) -> None: """Add a role to an existing Ansible collection. Args: @@ -305,7 +305,7 @@ def _add_resource_role(self: Parser, subparser: SubParser[ArgumentParser]) -> No ) self._add_args_common(parser) - def _add_plugin(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_plugin(self, subparser: SubParser[ArgumentParser]) -> None: """Add a plugin to an Ansible project. Args: @@ -326,7 +326,7 @@ def _add_plugin(self: Parser, subparser: SubParser[ArgumentParser]) -> None: self._add_plugin_filter(subparser=subparser) self._add_plugin_lookup(subparser=subparser) - def _add_plugin_action(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_plugin_action(self, subparser: SubParser[ArgumentParser]) -> None: """Add an action plugin to an existing Ansible collection project. Args: @@ -340,7 +340,7 @@ def _add_plugin_action(self: Parser, subparser: SubParser[ArgumentParser]) -> No self._add_args_common(parser) self._add_args_plugin_common(parser) - def _add_plugin_filter(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_plugin_filter(self, subparser: SubParser[ArgumentParser]) -> None: """Add a filter plugin to an existing Ansible collection project. Args: @@ -354,7 +354,7 @@ def _add_plugin_filter(self: Parser, subparser: SubParser[ArgumentParser]) -> No self._add_args_common(parser) self._add_args_plugin_common(parser) - def _add_plugin_lookup(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _add_plugin_lookup(self, subparser: SubParser[ArgumentParser]) -> None: """Add a lookup plugin to an existing Ansible collection project. Args: @@ -391,7 +391,7 @@ def _add_overwrite(self, parser: ArgumentParser) -> None: help="Flag that restricts overwriting operation.", ) - def _init(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _init(self, subparser: SubParser[ArgumentParser]) -> None: """Initialize an Ansible project. Args: @@ -411,7 +411,7 @@ def _init(self: Parser, subparser: SubParser[ArgumentParser]) -> None: self._init_collection(subparser=subparser) self._init_playbook(subparser=subparser) - def _init_collection(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _init_collection(self, subparser: SubParser[ArgumentParser]) -> None: """Initialize an Ansible collection. Args: @@ -440,7 +440,7 @@ def _init_collection(self: Parser, subparser: SubParser[ArgumentParser]) -> None self._add_args_common(parser) self._add_args_init_common(parser) - def _init_playbook(self: Parser, subparser: SubParser[ArgumentParser]) -> None: + def _init_playbook(self, subparser: SubParser[ArgumentParser]) -> None: """Initialize an Ansible playbook. Args: @@ -498,7 +498,7 @@ def _valid_collection_name(self, collection: str) -> str: self.pending_logs.append(Msg(prefix=Level.CRITICAL, message=msg)) return collection - def handle_deprecations(self: Parser) -> bool: # noqa: C901 + def handle_deprecations(self) -> bool: # noqa: C901 """Start parsing args passed from Cli. Returns: @@ -560,7 +560,7 @@ class ArgumentParser(argparse.ArgumentParser): """A custom argument parser.""" def add_argument( # type: ignore[override] - self: ArgumentParser, + self, *args: Any, # noqa: ANN401 **kwargs: Any, # noqa: ANN401 ) -> None: @@ -578,7 +578,7 @@ def add_argument( # type: ignore[override] super().add_argument(*args, **kwargs) def add_argument_group( - self: ArgumentParser, + self, *args: Any, # noqa: ANN401 **kwargs: Any, # noqa: ANN401 ) -> argparse._ArgumentGroup: @@ -604,7 +604,7 @@ def add_argument_group( class CustomHelpFormatter(HelpFormatter): """A custom help formatter.""" - def __init__(self: CustomHelpFormatter, prog: str) -> None: + def __init__(self, prog: str) -> None: """Initialize the help formatter. Args: @@ -620,7 +620,7 @@ def __init__(self: CustomHelpFormatter, prog: str) -> None: ) def _format_action_invocation( - self: CustomHelpFormatter, + self, action: argparse.Action, ) -> str: """Format the action invocation. diff --git a/src/ansible_creator/cli.py b/src/ansible_creator/cli.py index cf5e7399..e61f3777 100644 --- a/src/ansible_creator/cli.py +++ b/src/ansible_creator/cli.py @@ -25,7 +25,7 @@ class Cli: """Class representing the ansible-creator Cli.""" - def __init__(self: Cli) -> None: + def __init__(self) -> None: """Initialize the Cli and parse Cli args.""" self.args: dict[str, Any] self.output: Output @@ -33,7 +33,7 @@ def __init__(self: Cli) -> None: self.term_features: TermFeatures self.parse_args() - def init_output(self: Cli) -> None: + def init_output(self) -> None: """Initialize the output object. In case the arg parsing exited early, set some sane default values. @@ -56,18 +56,18 @@ def init_output(self: Cli) -> None: display="json" if self.args.pop("json", None) else "text", ) - def parse_args(self: Cli) -> None: + def parse_args(self) -> None: """Start parsing args passed from Cli.""" args, pending_logs = Parser().parse_args() self.args = vars(args) self.pending_logs = pending_logs - def process_pending_logs(self: Cli) -> None: + def process_pending_logs(self) -> None: """Log any pending logs.""" for msg in self.pending_logs: getattr(self.output, msg.prefix.value.lower())(msg.message) - def run(self: Cli) -> None: + def run(self) -> None: """Dispatch work to correct subcommand class.""" self.output.debug(msg=f"parsed args {self.args!s}") subcommand = self.args["subcommand"] diff --git a/src/ansible_creator/config.py b/src/ansible_creator/config.py index cded3ec8..f0874baf 100644 --- a/src/ansible_creator/config.py +++ b/src/ansible_creator/config.py @@ -50,7 +50,7 @@ class Config: type: str = "" path: str = "" - def __post_init__(self: Config) -> None: + def __post_init__(self) -> None: """Post process config values.""" if self.project == "ansible-project": object.__setattr__(self, "project", "playbook") diff --git a/src/ansible_creator/exceptions.py b/src/ansible_creator/exceptions.py index 07eded6a..36a82704 100644 --- a/src/ansible_creator/exceptions.py +++ b/src/ansible_creator/exceptions.py @@ -6,7 +6,7 @@ class CreatorError(Exception): """Class representing exceptions raised from creator code.""" - def __init__(self: CreatorError, message: str) -> None: + def __init__(self, message: str) -> None: """Instantiate an object of this class. Args: @@ -16,7 +16,7 @@ def __init__(self: CreatorError, message: str) -> None: self._message = message @property - def message(self: CreatorError) -> str: + def message(self) -> str: """Craft and return the CreatorError message. Includes the 'cause' when raised from another exception. @@ -29,7 +29,7 @@ def message(self: CreatorError) -> str: msg += f"\n{self.__cause__!s}" return msg - def __str__(self: CreatorError) -> str: + def __str__(self) -> str: """Return a string representation of the exception. Returns: diff --git a/src/ansible_creator/output.py b/src/ansible_creator/output.py index f2d22f61..2703fe86 100644 --- a/src/ansible_creator/output.py +++ b/src/ansible_creator/output.py @@ -127,7 +127,7 @@ class Level(Enum): WARNING = "Warning" @property - def log_level(self: Level) -> int: + def log_level(self) -> int: """Return a log level. :returns: The log level @@ -161,7 +161,7 @@ def longest_formatted(cls) -> int: """ return max(len(str(member)) for member in cls) - def __str__(self: Level) -> str: + def __str__(self) -> str: """Return the exit message prefix as a string. Returns: @@ -183,7 +183,7 @@ class Msg: prefix: Level = Level.ERROR @property - def color(self: Msg) -> str: + def color(self) -> str: """Return a color for the prefix. :returns: The color for the prefix @@ -200,7 +200,7 @@ def color(self: Msg) -> str: return color_mapping[self.prefix] def to_lines( - self: Msg, + self, color: bool, # noqa: FBT001 width: int, with_prefix: bool, # noqa: FBT001 @@ -252,7 +252,7 @@ class Output: """Output functionality.""" def __init__( # noqa: PLR0913 # pylint: disable=too-many-positional-arguments - self: Output, + self, log_file: str, log_level: str, log_append: str, @@ -299,7 +299,7 @@ def __init__( # noqa: PLR0913 # pylint: disable=too-many-positional-arguments self.log_to_file = False self.display = display - def critical(self: Output, msg: str) -> None: + def critical(self, msg: str) -> None: """Print a critical message to the console. Args: @@ -309,7 +309,7 @@ def critical(self: Output, msg: str) -> None: self.log(msg, level=Level.CRITICAL) sys.exit(1) - def debug(self: Output, msg: str) -> None: + def debug(self, msg: str) -> None: """Print a debug message to the console. Args: @@ -318,7 +318,7 @@ def debug(self: Output, msg: str) -> None: self.call_count["debug"] += 1 self.log(msg, level=Level.DEBUG) - def error(self: Output, msg: str) -> None: + def error(self, msg: str) -> None: """Print an error message to the console. Args: @@ -327,7 +327,7 @@ def error(self: Output, msg: str) -> None: self.call_count["error"] += 1 self.log(msg, level=Level.ERROR) - def hint(self: Output, msg: str) -> None: + def hint(self, msg: str) -> None: """Print a hint message to the console. Args: @@ -336,7 +336,7 @@ def hint(self: Output, msg: str) -> None: self.call_count["hint"] += 1 self.log(msg, level=Level.HINT) - def info(self: Output, msg: str) -> None: + def info(self, msg: str) -> None: """Print a info message to the console. Args: @@ -345,7 +345,7 @@ def info(self: Output, msg: str) -> None: self.call_count["info"] += 1 self.log(msg, level=Level.INFO) - def note(self: Output, msg: str) -> None: + def note(self, msg: str) -> None: """Print a note message to the console. Args: @@ -354,7 +354,7 @@ def note(self: Output, msg: str) -> None: self.call_count["note"] += 1 self.log(msg, level=Level.NOTE) - def warning(self: Output, msg: str) -> None: + def warning(self, msg: str) -> None: """Print a warning message to the console. Args: @@ -363,7 +363,7 @@ def warning(self: Output, msg: str) -> None: self.call_count["warning"] += 1 self.log(msg, level=Level.WARNING) - def log(self: Output, msg: str, level: Level = Level.ERROR) -> None: + def log(self, msg: str, level: Level = Level.ERROR) -> None: """Print a message to the console. Args: diff --git a/src/ansible_creator/resources/collection_project/plugins/filter/hello_world.py.j2 b/src/ansible_creator/resources/collection_project/plugins/filter/hello_world.py.j2 index 0e44f875..04753508 100644 --- a/src/ansible_creator/resources/collection_project/plugins/filter/hello_world.py.j2 +++ b/src/ansible_creator/resources/collection_project/plugins/filter/hello_world.py.j2 @@ -49,7 +49,7 @@ def _hello_world(name: str) -> str: class FilterModule: """filter plugin.""" - def filters(self: FilterModule) -> dict[str, Callable[[str], str]]: + def filters(self) -> dict[str, Callable[[str], str]]: """Map filter plugin names to their functions. Returns: diff --git a/src/ansible_creator/subcommands/add.py b/src/ansible_creator/subcommands/add.py index 424c7415..b5f48b9e 100644 --- a/src/ansible_creator/subcommands/add.py +++ b/src/ansible_creator/subcommands/add.py @@ -22,7 +22,7 @@ class Add: """Class to handle the add subcommand.""" def __init__( - self: Add, + self, config: Config, ) -> None: """Initialize the add action. @@ -81,7 +81,6 @@ def _scaffold(self) -> None: template_data = self._get_devfile_template_data() else: - msg = f"Unsupported resource type: {self._resource_type}" raise CreatorError(msg) diff --git a/src/ansible_creator/subcommands/init.py b/src/ansible_creator/subcommands/init.py index 356b106e..c85a13a6 100644 --- a/src/ansible_creator/subcommands/init.py +++ b/src/ansible_creator/subcommands/init.py @@ -34,7 +34,7 @@ class Init: ) def __init__( - self: Init, + self, config: Config, ) -> None: """Initialize the init action. @@ -53,7 +53,7 @@ def __init__( self._templar = Templar() self.output: Output = config.output - def run(self: Init) -> None: + def run(self) -> None: """Start scaffolding skeleton.""" self._construct_init_path() self.output.debug(msg=f"final collection path set to {self._init_path}") @@ -64,7 +64,7 @@ def run(self: Init) -> None: self._scaffold() - def _construct_init_path(self: Init) -> None: + def _construct_init_path(self) -> None: """Construct the init path based on project type.""" if self._project == "playbook": return @@ -119,7 +119,9 @@ def _scaffold(self) -> None: CreatorError: When the destination directory contains files that will be overwritten and the user chooses not to proceed. """ - self.output.debug(msg=f"started copying {self._project} skeleton to destination") + self.output.debug( + msg=f"started copying {self._project} skeleton to destination", + ) template_data = TemplateData( namespace=self._namespace, collection_name=self._collection_name, diff --git a/src/ansible_creator/templar.py b/src/ansible_creator/templar.py index 76291f12..39557612 100644 --- a/src/ansible_creator/templar.py +++ b/src/ansible_creator/templar.py @@ -23,7 +23,7 @@ class Templar: """Class representing a Jinja2 template engine.""" - def __init__(self: Templar) -> None: + def __init__(self) -> None: """Instantiate the template engine. Raises: @@ -43,7 +43,7 @@ def __init__(self: Templar) -> None: ) self.env.filters["json"] = json.dumps - def render_from_content(self: Templar, template: str, data: TemplateData) -> str: + def render_from_content(self, template: str, data: TemplateData) -> str: """Render a template with provided data. Args: diff --git a/src/ansible_creator/utils.py b/src/ansible_creator/utils.py index 18996250..fca0d26f 100644 --- a/src/ansible_creator/utils.py +++ b/src/ansible_creator/utils.py @@ -43,7 +43,7 @@ class TermFeatures: color: bool links: bool - def any_enabled(self: TermFeatures) -> bool: + def any_enabled(self) -> bool: """Return True if any features are enabled. Returns: @@ -363,7 +363,7 @@ def _copy_file( with dest_path.dest.open("w", encoding="utf-8") as df_handle: df_handle.write(dest_path.content) - def copy_containers(self: Copier, paths: FileList) -> None: + def copy_containers(self, paths: FileList) -> None: """Copy multiple containers to destination. Args: diff --git a/tests/fixtures/collection/testorg/testcol/plugins/filter/hello_world.py b/tests/fixtures/collection/testorg/testcol/plugins/filter/hello_world.py index ca61280f..1733e637 100644 --- a/tests/fixtures/collection/testorg/testcol/plugins/filter/hello_world.py +++ b/tests/fixtures/collection/testorg/testcol/plugins/filter/hello_world.py @@ -49,7 +49,7 @@ def _hello_world(name: str) -> str: class FilterModule: """filter plugin.""" - def filters(self: FilterModule) -> dict[str, Callable[[str], str]]: + def filters(self) -> dict[str, Callable[[str], str]]: """Map filter plugin names to their functions. Returns: diff --git a/tests/units/test_init.py b/tests/units/test_init.py index 57fdeabd..be995423 100644 --- a/tests/units/test_init.py +++ b/tests/units/test_init.py @@ -110,9 +110,9 @@ def test_run_success_for_collection( ) # Mock the "unique_name_in_devfile" method - def mock_unique_name_in_devfile(self: Init) -> str: - coll_namespace = self._namespace - coll_name = self._collection_name + def mock_unique_name_in_devfile(init: Init) -> str: + coll_namespace = init._namespace + coll_name = init._collection_name return f"{coll_namespace}.{coll_name}" with pytest.MonkeyPatch.context() as mp: @@ -193,9 +193,9 @@ def test_run_success_ansible_project( ) # Mock the "unique_name_in_devfile" method - def mock_unique_name_in_devfile(self: Init) -> str: - coll_namespace = self._namespace - coll_name = self._collection_name + def mock_unique_name_in_devfile(init: Init) -> str: + coll_namespace = init._namespace + coll_name = init._collection_name return f"{coll_namespace}.{coll_name}" with pytest.MonkeyPatch.context() as mp: