Make mypy pass.

This commit is contained in:
Felix Fontein 2025-10-17 13:50:21 +02:00
parent c4e0215db9
commit 4cb8babb81
13 changed files with 51 additions and 34 deletions

View File

@ -12,8 +12,10 @@
from __future__ import annotations from __future__ import annotations
import traceback import traceback
import typing as t
REQUESTS_IMPORT_ERROR: str | None # pylint: disable=invalid-name
try: try:
from requests import Session # noqa: F401, pylint: disable=unused-import from requests import Session # noqa: F401, pylint: disable=unused-import
from requests.adapters import ( # noqa: F401, pylint: disable=unused-import from requests.adapters import ( # noqa: F401, pylint: disable=unused-import
@ -26,28 +28,29 @@ try:
except ImportError: except ImportError:
REQUESTS_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name REQUESTS_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name
class Session: class Session: # type: ignore
__attrs__ = [] __attrs__: list[t.Never] = []
class HTTPAdapter: class HTTPAdapter: # type: ignore
__attrs__ = [] __attrs__: list[t.Never] = []
class HTTPError(Exception): class HTTPError(Exception): # type: ignore
pass pass
class InvalidSchema(Exception): class InvalidSchema(Exception): # type: ignore
pass pass
else: else:
REQUESTS_IMPORT_ERROR = None # pylint: disable=invalid-name REQUESTS_IMPORT_ERROR = None # pylint: disable=invalid-name
URLLIB3_IMPORT_ERROR = None # pylint: disable=invalid-name URLLIB3_IMPORT_ERROR: str | None = None # pylint: disable=invalid-name
try: try:
from requests.packages import urllib3 # pylint: disable=unused-import from requests.packages import urllib3 # pylint: disable=unused-import
# pylint: disable-next=unused-import from requests.packages.urllib3 import ( # type: ignore # pylint: disable=unused-import # isort: skip
from requests.packages.urllib3 import connection as urllib3_connection connection as urllib3_connection,
)
except ImportError: except ImportError:
try: try:
import urllib3 # pylint: disable=unused-import import urllib3 # pylint: disable=unused-import

View File

@ -17,6 +17,7 @@ import time
import traceback import traceback
PYWIN32_IMPORT_ERROR: str | None # pylint: disable=invalid-name
try: try:
import pywintypes import pywintypes
import win32api import win32api

View File

@ -25,6 +25,7 @@ from .._import_helper import HTTPAdapter, urllib3, urllib3_connection
from .basehttpadapter import BaseHTTPAdapter from .basehttpadapter import BaseHTTPAdapter
PARAMIKO_IMPORT_ERROR: str | None # pylint: disable=invalid-name
try: try:
import paramiko import paramiko
except ImportError: except ImportError:

View File

@ -28,7 +28,7 @@ import re
__all__ = ["fnmatch", "fnmatchcase", "translate"] __all__ = ["fnmatch", "fnmatchcase", "translate"]
_cache = {} _cache: dict[str, re.Pattern] = {}
_MAXCACHE = 100 _MAXCACHE = 100

View File

@ -36,6 +36,9 @@ from ansible_collections.community.docker.plugins.module_utils._version import (
HAS_DOCKER_PY_2 = False # pylint: disable=invalid-name HAS_DOCKER_PY_2 = False # pylint: disable=invalid-name
HAS_DOCKER_PY_3 = False # pylint: disable=invalid-name HAS_DOCKER_PY_3 = False # pylint: disable=invalid-name
HAS_DOCKER_ERROR: None | str # pylint: disable=invalid-name
HAS_DOCKER_TRACEBACK: None | str # pylint: disable=invalid-name
docker_version: str | None # pylint: disable=invalid-name
try: try:
from docker import __version__ as docker_version from docker import __version__ as docker_version
@ -51,12 +54,13 @@ try:
HAS_DOCKER_PY_2 = True # pylint: disable=invalid-name HAS_DOCKER_PY_2 = True # pylint: disable=invalid-name
from docker import APIClient as Client from docker import APIClient as Client
else: else:
from docker import Client from docker import Client # type: ignore
except ImportError as exc: except ImportError as exc:
HAS_DOCKER_ERROR = str(exc) # pylint: disable=invalid-name HAS_DOCKER_ERROR = str(exc) # pylint: disable=invalid-name
HAS_DOCKER_TRACEBACK = traceback.format_exc() # pylint: disable=invalid-name HAS_DOCKER_TRACEBACK = traceback.format_exc() # pylint: disable=invalid-name
HAS_DOCKER_PY = False # pylint: disable=invalid-name HAS_DOCKER_PY = False # pylint: disable=invalid-name
docker_version = None # pylint: disable=invalid-name
else: else:
HAS_DOCKER_PY = True # pylint: disable=invalid-name HAS_DOCKER_PY = True # pylint: disable=invalid-name
HAS_DOCKER_ERROR = None # pylint: disable=invalid-name HAS_DOCKER_ERROR = None # pylint: disable=invalid-name
@ -71,7 +75,7 @@ except ImportError:
# Either Docker SDK for Python is no longer using requests, or Docker SDK for Python is not around either, # Either Docker SDK for Python is no longer using requests, or Docker SDK for Python is not around either,
# or Docker SDK for Python's dependency requests is missing. In any case, define an exception # or Docker SDK for Python's dependency requests is missing. In any case, define an exception
# class RequestException so that our code does not break. # class RequestException so that our code does not break.
class RequestException(Exception): class RequestException(Exception): # type: ignore
pass pass
@ -79,18 +83,16 @@ MIN_DOCKER_VERSION = "2.0.0"
if not HAS_DOCKER_PY: if not HAS_DOCKER_PY:
docker_version = None # pylint: disable=invalid-name
# No Docker SDK for Python. Create a place holder client to allow # No Docker SDK for Python. Create a place holder client to allow
# instantiation of AnsibleModule and proper error handing # instantiation of AnsibleModule and proper error handing
class Client: # noqa: F811, pylint: disable=function-redefined class Client: # type: ignore # noqa: F811, pylint: disable=function-redefined
def __init__(self, **kwargs): def __init__(self, **kwargs):
pass pass
class APIError(Exception): # noqa: F811, pylint: disable=function-redefined class APIError(Exception): # type: ignore # noqa: F811, pylint: disable=function-redefined
pass pass
class NotFound(Exception): # noqa: F811, pylint: disable=function-redefined class NotFound(Exception): # type: ignore # noqa: F811, pylint: disable=function-redefined
pass pass

View File

@ -28,7 +28,7 @@ try:
) )
except ImportError: except ImportError:
# Define an exception class RequestException so that our code does not break. # Define an exception class RequestException so that our code does not break.
class RequestException(Exception): class RequestException(Exception): # type: ignore
pass pass

View File

@ -14,6 +14,7 @@ import re
import shutil import shutil
import tempfile import tempfile
import traceback import traceback
import typing as t
from collections import namedtuple from collections import namedtuple
from shlex import quote from shlex import quote
@ -34,6 +35,7 @@ from ansible_collections.community.docker.plugins.module_utils._version import (
) )
PYYAML_IMPORT_ERROR: None | str # pylint: disable=invalid-name
try: try:
import yaml import yaml
@ -41,7 +43,7 @@ try:
# use C version if possible for speedup # use C version if possible for speedup
from yaml import CSafeDumper as _SafeDumper from yaml import CSafeDumper as _SafeDumper
except ImportError: except ImportError:
from yaml import SafeDumper as _SafeDumper from yaml import SafeDumper as _SafeDumper # type: ignore
except ImportError: except ImportError:
HAS_PYYAML = False HAS_PYYAML = False
PYYAML_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name PYYAML_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name
@ -144,8 +146,7 @@ class ResourceType:
SERVICE = "service" SERVICE = "service"
@classmethod @classmethod
def from_docker_compose_event(cls, resource_type): def from_docker_compose_event(cls, resource_type: str) -> t.Any:
# type: (Type[ResourceType], Text) -> Any
return { return {
"Network": cls.NETWORK, "Network": cls.NETWORK,
"Image": cls.IMAGE, "Image": cls.IMAGE,

View File

@ -12,6 +12,7 @@ import abc
import os import os
import re import re
import shlex import shlex
import typing as t
from functools import partial from functools import partial
from ansible.module_utils.common.text.converters import to_text from ansible.module_utils.common.text.converters import to_text
@ -32,6 +33,12 @@ from ansible_collections.community.docker.plugins.module_utils._util import (
) )
if t.TYPE_CHECKING:
from ansible_collections.community.docker.plugins.module_utils._version import (
LooseVersion,
)
_DEFAULT_IP_REPLACEMENT_STRING = ( _DEFAULT_IP_REPLACEMENT_STRING = (
"[[DEFAULT_IP:iewahhaeB4Sae6Aen8IeShairoh4zeph7xaekoh8Geingunaesaeweiy3ooleiwi]]" "[[DEFAULT_IP:iewahhaeB4Sae6Aen8IeShairoh4zeph7xaekoh8Geingunaesaeweiy3ooleiwi]]"
) )
@ -207,9 +214,9 @@ class OptionGroup:
class Engine: class Engine:
min_api_version = None # string or None min_api_version: str | None = None
min_api_version_obj = None # LooseVersion object or None min_api_version_obj: LooseVersion | None = None
extra_option_minimal_versions = None # dict[str, dict[str, Any]] or None extra_option_minimal_versions: dict[str, dict[str, t.Any]] | None = None
@abc.abstractmethod @abc.abstractmethod
def get_value(self, module, container, api_version, options, image, host_info): def get_value(self, module, container, api_version, options, image, host_info):
@ -268,7 +275,7 @@ class Engine:
class EngineDriver: class EngineDriver:
name = None # string name: str
@abc.abstractmethod @abc.abstractmethod
def setup( def setup(

View File

@ -11,7 +11,7 @@ import fcntl
import os import os
import os.path import os.path
import socket as pysocket import socket as pysocket
import typing as t from collections.abc import Callable
def make_file_unblocking(file) -> None: def make_file_unblocking(file) -> None:
@ -43,7 +43,7 @@ def _empty_writer(msg: str) -> None:
pass pass
def shutdown_writing(sock, log: t.Callable[[str], None] = _empty_writer) -> None: def shutdown_writing(sock, log: Callable[[str], None] = _empty_writer) -> None:
# FIXME: This does **not work with SSLSocket**! Apparently SSLSocket does not allow to send # FIXME: This does **not work with SSLSocket**! Apparently SSLSocket does not allow to send
# a close_notify TLS alert without completely shutting down the connection. # a close_notify TLS alert without completely shutting down the connection.
# Calling sock.shutdown(pysocket.SHUT_WR) simply turns of TLS encryption and from that # Calling sock.shutdown(pysocket.SHUT_WR) simply turns of TLS encryption and from that
@ -63,7 +63,7 @@ def shutdown_writing(sock, log: t.Callable[[str], None] = _empty_writer) -> None
log("No idea how to signal end of writing") log("No idea how to signal end of writing")
def write_to_socket(sock, data: bytes) -> None: def write_to_socket(sock, data: bytes) -> int:
if hasattr(sock, "_send_until_done"): if hasattr(sock, "_send_until_done"):
# WrappedSocket (urllib3/contrib/pyopenssl) does not have `send`, but # WrappedSocket (urllib3/contrib/pyopenssl) does not have `send`, but
# only `sendall`, which uses `_send_until_done` under the hood. # only `sendall`, which uses `_send_until_done` under the hood.

View File

@ -69,9 +69,11 @@ DOCKER_COMMON_ARGS_VARS = {
if option_name != "debug" if option_name != "debug"
} }
DOCKER_MUTUALLY_EXCLUSIVE = [] DOCKER_MUTUALLY_EXCLUSIVE: list[tuple[str, ...] | list[str]] = []
DOCKER_REQUIRED_TOGETHER = [["client_cert", "client_key"]] DOCKER_REQUIRED_TOGETHER: list[tuple[str, ...] | list[str]] = [
["client_cert", "client_key"]
]
DEFAULT_DOCKER_REGISTRY = "https://index.docker.io/v1/" DEFAULT_DOCKER_REGISTRY = "https://index.docker.io/v1/"
BYTE_SUFFIXES = ["B", "KB", "MB", "GB", "TB", "PB"] BYTE_SUFFIXES = ["B", "KB", "MB", "GB", "TB", "PB"]

View File

@ -19,7 +19,7 @@ from ansible_collections.community.docker.plugins.module_utils._api.transport im
try: try:
from ssl import CertificateError, match_hostname from ssl import CertificateError, match_hostname # type: ignore
except ImportError: except ImportError:
HAS_MATCH_HOSTNAME = False # pylint: disable=invalid-name HAS_MATCH_HOSTNAME = False # pylint: disable=invalid-name
else: else:

View File

@ -12,8 +12,8 @@ import json
import os import os
import shutil import shutil
import tempfile import tempfile
import typing as t
import unittest import unittest
from collections.abc import Callable
from unittest import mock from unittest import mock
from pytest import fixture, mark from pytest import fixture, mark
@ -22,7 +22,7 @@ from ansible_collections.community.docker.plugins.module_utils._api.utils import
class FindConfigFileTest(unittest.TestCase): class FindConfigFileTest(unittest.TestCase):
mkdir: t.Callable[[str], os.PathLike[str]] mkdir: Callable[[str], os.PathLike[str]]
@fixture(autouse=True) @fixture(autouse=True)
def tmpdir(self, tmpdir): def tmpdir(self, tmpdir):

View File

@ -11,7 +11,7 @@ from ansible_collections.community.docker.plugins.module_utils._compose_v2 impor
) )
EVENT_TEST_CASES = [ EVENT_TEST_CASES: list[tuple[str, str, bool, bool, str, list[Event], list[Event]]] = [
# ####################################################################################################################### # #######################################################################################################################
# ## Docker Compose 2.18.1 ############################################################################################## # ## Docker Compose 2.18.1 ##############################################################################################
# ####################################################################################################################### # #######################################################################################################################