Skip to content

Commit e62ef52

Browse files
authored
Pyright type fixes (partial) (#4411)
1 parent 2e5af42 commit e62ef52

File tree

12 files changed

+57
-48
lines changed

12 files changed

+57
-48
lines changed

plugins/modules/fake_module.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
def main() -> None:
1818
"""Return the module instance."""
19-
return AnsibleModule(
19+
AnsibleModule(
2020
argument_spec={
2121
"data": {"default": None},
2222
"path": {"default": None},

src/ansiblelint/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from typing import TYPE_CHECKING, Any, TextIO
3434

3535
from ansible_compat.prerun import get_cache_dir
36-
from filelock import FileLock, Timeout
36+
from filelock import BaseFileLock, FileLock, Timeout
3737
from rich.markup import escape
3838

3939
from ansiblelint.constants import RC, SKIP_SCHEMA_UPDATE
@@ -119,7 +119,7 @@ def initialize_logger(level: int = 0) -> None:
119119
_logger.debug("Logging initialized to level %s", logging_level)
120120

121121

122-
def initialize_options(arguments: list[str] | None = None) -> None | FileLock:
122+
def initialize_options(arguments: list[str] | None = None) -> None | BaseFileLock:
123123
"""Load config options and store them inside options module."""
124124
cache_dir_lock = None
125125
new_options = cli.get_config(arguments or [])

src/ansiblelint/formatters/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from pathlib import Path
99
from typing import TYPE_CHECKING, Any, Generic, TypeVar
1010

11-
import rich
11+
from rich.markup import escape
1212

1313
from ansiblelint.config import options
1414
from ansiblelint.version import __version__
@@ -58,7 +58,7 @@ def apply(self, match: MatchError) -> str:
5858
@staticmethod
5959
def escape(text: str) -> str:
6060
"""Escapes a string to avoid processing it as markup."""
61-
return rich.markup.escape(text)
61+
return escape(text)
6262

6363

6464
class Formatter(BaseFormatter): # type: ignore[type-arg]

src/ansiblelint/rules/no_tabs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,4 @@ def test_no_tabs_rule(default_rules_collection: RulesCollection) -> None:
8585
assert len(results) >= i + 1
8686
assert results[i].lineno == expected[0]
8787
assert results[i].message == expected[1]
88-
assert len(results) == len(expected), results
88+
assert len(results) == len(expected_results), results

src/ansiblelint/rules/var_naming.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,10 +329,12 @@ def matchyaml(self, file: Lintable) -> list[MatchError]:
329329
"""Return matches for variables defined in vars files."""
330330
results: list[MatchError] = []
331331
raw_results: list[MatchError] = []
332-
meta_data: dict[AnsibleUnicode, Any] = {}
333332

334333
if str(file.kind) == "vars" and file.data:
335334
meta_data = parse_yaml_from_file(str(file.path))
335+
if not isinstance(meta_data, dict):
336+
msg = f"Content if vars file {file} is not a dictionary."
337+
raise TypeError(msg)
336338
for key in meta_data:
337339
prefix = Prefix(file.role) if file.role else Prefix()
338340
match_error = self.get_var_naming_matcherror(

src/ansiblelint/runner.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,12 @@
3030
from ansiblelint.app import App, get_app
3131
from ansiblelint.constants import States
3232
from ansiblelint.errors import LintWarning, MatchError, WarnSource
33-
from ansiblelint.file_utils import Lintable, expand_dirs_in_lintables
33+
from ansiblelint.file_utils import (
34+
Lintable,
35+
expand_dirs_in_lintables,
36+
expand_paths_vars,
37+
normpath,
38+
)
3439
from ansiblelint.logger import timed_info
3540
from ansiblelint.rules.syntax_check import OUTPUT_PATTERNS
3641
from ansiblelint.text import strip_ansi_escape
@@ -111,7 +116,7 @@ def __init__(
111116
def _update_exclude_paths(self, exclude_paths: list[str]) -> None:
112117
if exclude_paths:
113118
# These will be (potentially) relative paths
114-
paths = ansiblelint.file_utils.expand_paths_vars(exclude_paths)
119+
paths = expand_paths_vars(exclude_paths)
115120
# Since ansiblelint.utils.find_children returns absolute paths,
116121
# and the list of files we create in `Runner.run` can contain both
117122
# relative and absolute paths, we need to cover both bases.
@@ -169,7 +174,6 @@ def run(self) -> list[MatchError]:
169174
if warn.category is DeprecationWarning:
170175
continue
171176
if warn.category is LintWarning:
172-
filename: None | Lintable = None
173177
if isinstance(warn.source, WarnSource):
174178
match = MatchError(
175179
message=warn.source.message or warn.category.__name__,
@@ -179,13 +183,12 @@ def run(self) -> list[MatchError]:
179183
lineno=warn.source.lineno,
180184
)
181185
else:
182-
filename = warn.source
183186
match = MatchError(
184187
message=(
185188
warn.message if isinstance(warn.message, str) else "?"
186189
),
187190
rule=self.rules["warning"],
188-
lintable=Lintable(str(filename)),
191+
lintable=Lintable(str(warn.source)),
189192
)
190193
matches.append(match)
191194
continue
@@ -277,7 +280,7 @@ def worker(lintable: Lintable) -> list[MatchError]:
277280
continue
278281
_logger.debug(
279282
"Examining %s of type %s",
280-
ansiblelint.file_utils.normpath(file.path),
283+
normpath(file.path),
281284
file.kind,
282285
)
283286

src/ansiblelint/schemas/__main__.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from http.client import HTTPException
1212
from pathlib import Path
1313
from typing import Any
14+
from urllib.error import HTTPError
1415
from urllib.request import Request
1516

1617
_logger = logging.getLogger(__package__)
@@ -94,10 +95,7 @@ def refresh_schemas(min_age_seconds: int = 3600 * 24) -> int:
9495
if kind in _schema_cache: # pragma: no cover
9596
del _schema_cache[kind]
9697
except (ConnectionError, OSError, HTTPException) as exc:
97-
if (
98-
isinstance(exc, urllib.error.HTTPError)
99-
and getattr(exc, "code", None) == 304
100-
):
98+
if isinstance(exc, HTTPError) and getattr(exc, "code", None) == 304:
10199
_logger.debug("Schema %s is not modified", url)
102100
continue
103101
# In case of networking issues, we just stop and use last-known good

src/ansiblelint/schemas/main.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
import logging
77
import re
88
import typing
9-
from typing import TYPE_CHECKING
9+
from typing import TYPE_CHECKING, Any
1010

11-
import jsonschema
1211
import yaml
1312
from jsonschema.exceptions import ValidationError
13+
from jsonschema.validators import validator_for
1414

1515
from ansiblelint.loaders import yaml_load_safe
1616
from ansiblelint.schemas.__main__ import JSON_SCHEMAS, _schema_cache
@@ -22,13 +22,13 @@
2222

2323

2424
def find_best_deep_match(
25-
errors: jsonschema.ValidationError,
26-
) -> jsonschema.ValidationError:
25+
errors: ValidationError,
26+
) -> ValidationError:
2727
"""Return the deepest schema validation error."""
2828

2929
def iter_validation_error(
30-
err: jsonschema.ValidationError,
31-
) -> typing.Iterator[jsonschema.ValidationError]:
30+
err: ValidationError,
31+
) -> typing.Iterator[ValidationError]:
3232
if err.context:
3333
for e in err.context:
3434
yield e
@@ -39,7 +39,7 @@ def iter_validation_error(
3939

4040
def validate_file_schema(file: Lintable) -> list[str]:
4141
"""Return list of JSON validation errors found."""
42-
schema = {}
42+
schema: dict[Any, Any] = {}
4343
if file.kind not in JSON_SCHEMAS:
4444
return [f"Unable to find JSON Schema '{file.kind}' for '{file.path}' file."]
4545
try:
@@ -48,7 +48,7 @@ def validate_file_schema(file: Lintable) -> list[str]:
4848
json_data = json.loads(json.dumps(yaml_data))
4949
schema = _schema_cache[file.kind]
5050

51-
validator = jsonschema.validators.validator_for(schema)
51+
validator = validator_for(schema)
5252
v = validator(schema)
5353
try:
5454
error = next(v.iter_errors(json_data))
@@ -57,6 +57,9 @@ def validate_file_schema(file: Lintable) -> list[str]:
5757
if error.context:
5858
error = find_best_deep_match(error)
5959
# determine if we want to use our own messages embedded into schemas inside title/markdownDescription fields
60+
if not hasattr(error, "schema") or not isinstance(error.schema, dict):
61+
msg = "error object does not have schema attribute"
62+
raise TypeError(msg)
6063
if "not" in error.schema and len(error.schema["not"]) == 0:
6164
message = error.schema["title"]
6265
schema = error.schema
@@ -106,7 +109,7 @@ def validate_file_schema(file: Lintable) -> list[str]:
106109
return [message]
107110

108111

109-
def _deep_match_relevance(error: jsonschema.ValidationError) -> tuple[bool | int, ...]:
112+
def _deep_match_relevance(error: ValidationError) -> tuple[bool | int, ...]:
110113
validator = error.validator
111114
return (
112115
validator not in ("anyOf", "oneOf"), # type: ignore[comparison-overlap]

src/ansiblelint/utils.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,7 @@ def task_to_str(task: dict[str, Any]) -> str:
729729
return f"{action['__ansible_module__']} {' '.join(args)}"
730730

731731

732+
# pylint: disable=too-many-nested-blocks
732733
def extract_from_list(
733734
blocks: AnsibleBaseYAMLObject,
734735
candidates: list[str],
@@ -737,23 +738,24 @@ def extract_from_list(
737738
) -> list[Any]:
738739
"""Get action tasks from block structures."""
739740
results = []
740-
for block in blocks:
741-
for candidate in candidates:
742-
if isinstance(block, dict) and candidate in block:
743-
if isinstance(block[candidate], list):
744-
subresults = add_action_type(block[candidate], candidate)
745-
if recursive:
746-
subresults.extend(
747-
extract_from_list(
748-
subresults,
749-
candidates,
750-
recursive=recursive,
751-
),
752-
)
753-
results.extend(subresults)
754-
elif block[candidate] is not None:
755-
msg = f"Key '{candidate}' defined, but bad value: '{block[candidate]!s}'"
756-
raise RuntimeError(msg)
741+
if isinstance(blocks, Iterable):
742+
for block in blocks:
743+
for candidate in candidates:
744+
if isinstance(block, dict) and candidate in block:
745+
if isinstance(block[candidate], list):
746+
subresults = add_action_type(block[candidate], candidate)
747+
if recursive:
748+
subresults.extend(
749+
extract_from_list(
750+
subresults,
751+
candidates,
752+
recursive=recursive,
753+
),
754+
)
755+
results.extend(subresults)
756+
elif block[candidate] is not None:
757+
msg = f"Key '{candidate}' defined, but bad value: '{block[candidate]!s}'"
758+
raise RuntimeError(msg)
757759
return results
758760

759761

src/ansiblelint/yaml_utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
if TYPE_CHECKING:
3737
# noinspection PyProtectedMember
3838
from ruamel.yaml.comments import LineCol
39-
from ruamel.yaml.compat import StreamTextType
4039
from ruamel.yaml.nodes import ScalarNode
4140
from ruamel.yaml.representer import RoundTripRepresenter
4241
from ruamel.yaml.tokens import CommentToken
@@ -1026,7 +1025,7 @@ def version(self, value: tuple[int, int] | None) -> None:
10261025
self._yaml_version = self._yaml_version_default
10271026
# We do nothing if the object did not have a previous default version defined
10281027

1029-
def load(self, stream: Path | StreamTextType) -> Any:
1028+
def load(self, stream: Path | Any) -> Any:
10301029
"""Load YAML content from a string while avoiding known ruamel.yaml issues."""
10311030
if not isinstance(stream, str):
10321031
msg = f"expected a str but got {type(stream)}"

0 commit comments

Comments
 (0)