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

ruff: Address PGH #3380

Merged
merged 1 commit into from
Apr 27, 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
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,6 @@ ignore = [
"ARG002", # Unused method argument (currently in too many places)
"D",
"FBT",
"PGH",
"PLR",
"PTH",
"TRY",
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def emit(self, record: logging.LogRecord) -> None:
console_stderr.print(f"[dim]{msg}[/dim]", highlight=False)
except RecursionError: # See issue 36272
raise
except Exception: # pylint: disable=broad-exception-caught # noqa:BLE001
except Exception: # pylint: disable=broad-exception-caught # noqa: BLE001
self.handleError(record)


Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/_internal/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def getmatches(self, file: Lintable) -> list[MatchError]:
for method in [self.matchlines, self.matchtasks, self.matchyaml]:
try:
matches.extend(method(file))
except Exception as exc: # pylint: disable=broad-except # noqa:BLE001
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
_logger.warning(
"Ignored exception from %s.%s while processing %s: %s",
self.__class__.__name__,
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ def _rich_codeblock_custom_rich_console(
yield syntax


rich.markdown.CodeBlock.__rich_console__ = _rich_codeblock_custom_rich_console # type: ignore
rich.markdown.CodeBlock.__rich_console__ = _rich_codeblock_custom_rich_console # type: ignore[method-assign]
2 changes: 1 addition & 1 deletion src/ansiblelint/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def kind_from_path(path: Path, base: bool = False) -> FileType:
| wcmatch.pathlib.DOTGLOB
),
):
return str(k) # type: ignore
return str(k) # type: ignore[return-value]

if base:
# Unknown base file type is default
Expand Down
6 changes: 3 additions & 3 deletions src/ansiblelint/formatters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
if TYPE_CHECKING:
from ansiblelint.errors import MatchError

T = TypeVar("T", bound="BaseFormatter") # type: ignore
T = TypeVar("T", bound="BaseFormatter") # type: ignore[type-arg]


class BaseFormatter(Generic[T]):
Expand Down Expand Up @@ -53,7 +53,7 @@ def escape(text: str) -> str:
return rich.markup.escape(text)


class Formatter(BaseFormatter): # type: ignore
class Formatter(BaseFormatter): # type: ignore[type-arg]
"""Default output formatter of ansible-lint."""

def apply(self, match: MatchError) -> str:
Expand Down Expand Up @@ -98,7 +98,7 @@ def apply(self, match: MatchError) -> str:
return result


class AnnotationsFormatter(BaseFormatter): # type: ignore
class AnnotationsFormatter(BaseFormatter): # type: ignore[type-arg]
# https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-a-warning-message
"""Formatter for emitting violations as GitHub Workflow Commands.

Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from yaml import CFullLoader as FullLoader
from yaml import CSafeLoader as SafeLoader
except (ImportError, AttributeError):
from yaml import FullLoader, SafeLoader # type: ignore
from yaml import FullLoader, SafeLoader # type: ignore[assignment]

if TYPE_CHECKING:
from pathlib import Path
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/rules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def all_subclasses(cls: type) -> set[type]:
and rule.id not in rules
):
rules[rule.id] = rule()
for rule in rules.values(): # type: ignore
for rule in rules.values(): # type: ignore[assignment]
if isinstance(rule, AnsibleLintRule) and bool(rule.id):
yield rule

Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/rules/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class ValidationPassedError(Exception):
"""Exception to be raised when validation passes."""


class CustomAnsibleModule(basic.AnsibleModule): # type: ignore
class CustomAnsibleModule(basic.AnsibleModule): # type: ignore[misc]
"""Mock AnsibleModule class."""

def __init__(self, *args: str, **kwargs: str) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/rules/galaxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class GalaxyRule(AnsibleLintRule):

def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]:
"""Return matches found for a specific play (entry in playbook)."""
if file.kind != "galaxy": # type: ignore
if file.kind != "galaxy": # type: ignore[comparison-overlap]
return []

# Defined by Automation Hub Team and Partner Engineering
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/schemas/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
JSON_SCHEMAS = json.load(json_file)


class SchemaCacheDict(defaultdict): # type: ignore
class SchemaCacheDict(defaultdict): # type: ignore[type-arg]
"""Caching schema store."""

def __missing__(self, key: str) -> Any:
Expand Down
8 changes: 4 additions & 4 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,16 +233,16 @@ def tokenize(line: str) -> tuple[str, list[str], dict[str, str]]:
return (command, args, kwargs)


def _playbook_items(pb_data: AnsibleBaseYAMLObject) -> ItemsView: # type: ignore
def _playbook_items(pb_data: AnsibleBaseYAMLObject) -> ItemsView: # type: ignore[type-arg]
if isinstance(pb_data, dict):
return pb_data.items()
if not pb_data:
return [] # type: ignore
return [] # type: ignore[return-value]

# "if play" prevents failure if the play sequence contains None,
# which is weird but currently allowed by Ansible
# https://github.com/ansible/ansible-lint/issues/849
return [item for play in pb_data if play for item in play.items()] # type: ignore
return [item for play in pb_data if play for item in play.items()] # type: ignore[return-value]


def _set_collections_basedir(basedir: str) -> None:
Expand Down Expand Up @@ -1001,7 +1001,7 @@ def is_playbook(filename: str) -> bool:

try:
f = parse_yaml_from_file(filename)
except Exception as exc: # pylint: disable=broad-except # noqa:BLE001
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
_logger.warning(
"Failed to load %s with %s, assuming is not a playbook.",
filename,
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import pkg_resources

__version__ = pkg_resources.get_distribution("ansible-lint").version
except Exception: # pylint: disable=broad-except # noqa:BLE001
except Exception: # pylint: disable=broad-except # noqa: BLE001
# this is the fallback SemVer version picked by setuptools_scm when tag
# information is not available.
__version__ = "0.1.dev1"
Expand Down
2 changes: 1 addition & 1 deletion test/test_file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def test_expand_paths_vars(
) -> None:
"""Ensure that tilde and env vars are expanded in paths lists."""
monkeypatch.setenv("TEST_PATH", "/test/path")
assert expand_paths_vars([test_path]) == [expected] # type: ignore
assert expand_paths_vars([test_path]) == [expected] # type: ignore[list-item]


@pytest.mark.parametrize(
Expand Down
2 changes: 1 addition & 1 deletion test/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def test_dict_format_line() -> None:
match = MatchError(
message="xyz",
lineno=1,
details={"hello": "world"}, # type: ignore
details={"hello": "world"}, # type: ignore[arg-type]
lintable=Lintable("filename.yml", content=""),
rule=rule,
)
Expand Down
4 changes: 2 additions & 2 deletions test/test_formatter_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_base_formatter_when_base_dir(
) -> None:
"""Check that base formatter accepts relative pathlib and str."""
# Given
base_formatter = BaseFormatter(base_dir, relative_path) # type: ignore
base_formatter = BaseFormatter(base_dir, relative_path) # type: ignore[var-annotated]

# When
output_path = (
Expand Down Expand Up @@ -58,7 +58,7 @@ def test_base_formatter_when_base_dir_is_given_and_relative_is_true(
) -> None:
"""Check that the base formatter equally accepts pathlib and str."""
# Given
base_formatter = BaseFormatter(base_dir, True) # type: ignore
base_formatter = BaseFormatter(base_dir, True) # type: ignore[var-annotated]

# When
# pylint: disable=protected-access
Expand Down
2 changes: 1 addition & 1 deletion test/test_formatter_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def test_single_match(self) -> None:
"""Test negative case. Only lists are allowed. Otherwise a RuntimeError will be raised."""
assert isinstance(self.formatter, CodeclimateJSONFormatter)
with pytest.raises(RuntimeError):
self.formatter.format_result(self.matches[0]) # type: ignore
self.formatter.format_result(self.matches[0]) # type: ignore[arg-type]

def test_result_is_list(self) -> None:
"""Test if the return JSON contains a list with a length of 2."""
Expand Down
2 changes: 1 addition & 1 deletion test/test_formatter_sarif.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def test_single_match(self) -> None:
"""Test negative case. Only lists are allowed. Otherwise, a RuntimeError will be raised."""
assert isinstance(self.formatter, SarifFormatter)
with pytest.raises(RuntimeError):
self.formatter.format_result(self.matches[0]) # type: ignore
self.formatter.format_result(self.matches[0]) # type: ignore[arg-type]

def test_result_is_list(self) -> None:
"""Test if the return SARIF object contains the results with length of 2."""
Expand Down
10 changes: 5 additions & 5 deletions test/test_matcherrror.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ class DummySentinelTestObject:

def __eq__(self, other: object) -> bool:
"""Return sentinel as result of equality check w/ anything."""
return "EQ_SENTINEL" # type: ignore
return "EQ_SENTINEL" # type: ignore[return-value]

def __ne__(self, other: object) -> bool:
"""Return sentinel as result of inequality check w/ anything."""
return "NE_SENTINEL" # type: ignore
return "NE_SENTINEL" # type: ignore[return-value]

def __lt__(self, other: object) -> bool:
"""Return sentinel as result of less than check w/ anything."""
return "LT_SENTINEL" # type: ignore
return "LT_SENTINEL" # type: ignore[return-value]

def __gt__(self, other: object) -> bool:
"""Return sentinel as result of greater than chk w/ anything."""
return "GT_SENTINEL" # type: ignore
return "GT_SENTINEL" # type: ignore[return-value]


@pytest.mark.parametrize(
Expand Down Expand Up @@ -205,4 +205,4 @@ def test_matcherror_compare_with_dummy_sentinel(
# NOTE: This assertion abuses the CPython property to cache short string
# NOTE: objects because the identity check is more precise and we don't
# NOTE: want extra operator protocol methods to influence the test.
assert operation(MatchError("foo"), dummy_obj) is expected_value # type: ignore
assert operation(MatchError("foo"), dummy_obj) is expected_value # type: ignore[comparison-overlap]
2 changes: 1 addition & 1 deletion test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def test_extract_from_list() -> None:
test_list = utils.extract_from_list(blocks, ["block"])
test_none = utils.extract_from_list(blocks, ["test_none"])

assert list(block["block"]) == test_list # type: ignore
assert list(block["block"]) == test_list # type: ignore[arg-type]
assert not test_none
with pytest.raises(RuntimeError):
utils.extract_from_list(blocks, ["test_string"])
Expand Down