diff --git a/.pylintrc b/.pylintrc index 145d25d9..3a1f0480 100644 --- a/.pylintrc +++ b/.pylintrc @@ -384,7 +384,6 @@ disable=raw-checker-failed, consider-using-with, fixme, import-error, # TODO figure out why pylint cannot find the module - no-else-return, no-member, no-name-in-module, # TODO figure out why pylint cannot find the module not-an-iterable, # TODO: needs better typing info diff --git a/plugins/connection/docker.py b/plugins/connection/docker.py index 5895bdfd..7d1aba90 100644 --- a/plugins/connection/docker.py +++ b/plugins/connection/docker.py @@ -349,21 +349,19 @@ class Connection(ConnectionBase): ) >= LooseVersion("1.7"): # Support for specifying the exec user was added in docker 1.7 return self.remote_user - else: - self.remote_user = None - actual_user = self._get_docker_remote_user() - if actual_user != self.get_option("remote_user"): - display.warning( - f'docker {self.docker_version} does not support remote_user, using container default: {actual_user or "?"}' - ) - return actual_user - elif self._display.verbosity > 2: + self.remote_user = None + actual_user = self._get_docker_remote_user() + if actual_user != self.get_option("remote_user"): + display.warning( + f'docker {self.docker_version} does not support remote_user, using container default: {actual_user or "?"}' + ) + return actual_user + if self._display.verbosity > 2: # Since we are not setting the actual_user, look it up so we have it for logging later # Only do this if display verbosity is high enough that we'll need the value # This saves overhead from calling into docker when we do not need to. return self._get_docker_remote_user() - else: - return None + return None def _connect(self, port=None): """Connect to the container. Nothing to do""" @@ -487,10 +485,9 @@ class Connection(ConnectionBase): import ntpath return ntpath.normpath(remote_path) - else: - if not remote_path.startswith(os.path.sep): - remote_path = os.path.join(os.path.sep, remote_path) - return os.path.normpath(remote_path) + if not remote_path.startswith(os.path.sep): + remote_path = os.path.join(os.path.sep, remote_path) + return os.path.normpath(remote_path) def put_file(self, in_path, out_path): """Transfer a file from local to docker container""" diff --git a/plugins/connection/docker_api.py b/plugins/connection/docker_api.py index 32da8516..cd9da076 100644 --- a/plugins/connection/docker_api.py +++ b/plugins/connection/docker_api.py @@ -369,10 +369,9 @@ class Connection(ConnectionBase): import ntpath return ntpath.normpath(remote_path) - else: - if not remote_path.startswith(os.path.sep): - remote_path = os.path.join(os.path.sep, remote_path) - return os.path.normpath(remote_path) + if not remote_path.startswith(os.path.sep): + remote_path = os.path.join(os.path.sep, remote_path) + return os.path.normpath(remote_path) def put_file(self, in_path, out_path): """Transfer a file from local to docker container""" diff --git a/plugins/inventory/docker_machine.py b/plugins/inventory/docker_machine.py index ea3601c7..d4eae1dd 100644 --- a/plugins/inventory/docker_machine.py +++ b/plugins/inventory/docker_machine.py @@ -217,11 +217,11 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): if daemon_env == "require": display.warning(f"{warning_prefix}: host will be skipped") return True - else: # 'optional', 'optional-silently' - if daemon_env == "optional": - display.warning( - f"{warning_prefix}: host will lack dm_DOCKER_xxx variables" - ) + if daemon_env == "optional": + display.warning( + f"{warning_prefix}: host will lack dm_DOCKER_xxx variables" + ) + # daemon_env is 'optional-silently' return False def _populate(self): diff --git a/plugins/module_utils/_api/api/client.py b/plugins/module_utils/_api/api/client.py index 9dd0a38c..ff127e8b 100644 --- a/plugins/module_utils/_api/api/client.py +++ b/plugins/module_utils/_api/api/client.py @@ -278,8 +278,7 @@ class APIClient(_Session, DaemonApiMixin): if kwargs.get("versioned_api", True): return f"{self.base_url}/v{self._version}{pathfmt.format(*args)}" - else: - return f"{self.base_url}{pathfmt.format(*args)}" + return f"{self.base_url}{pathfmt.format(*args)}" def _raise_for_status(self, response): """Raises stored :class:`APIError`, if one occurred.""" @@ -427,12 +426,11 @@ class APIClient(_Session, DaemonApiMixin): if stream: return gen - else: - try: - # Wait for all the frames, concatenate them, and return the result - return consume_socket_output(gen, demux=demux) - finally: - response.close() + try: + # Wait for all the frames, concatenate them, and return the result + return consume_socket_output(gen, demux=demux) + finally: + response.close() def _disable_socket_timeout(self, socket): """Depending on the combination of python version and whether we are @@ -484,8 +482,7 @@ class APIClient(_Session, DaemonApiMixin): sep = b"" if stream: return self._multiplexed_response_stream_helper(res) - else: - return sep.join(list(self._multiplexed_buffer_helper(res))) + return sep.join(list(self._multiplexed_buffer_helper(res))) def _unmount(self, *args): for proto in args: @@ -497,8 +494,7 @@ class APIClient(_Session, DaemonApiMixin): except _InvalidSchema as e: if self._custom_adapter: return self._custom_adapter - else: - raise e + raise e @property def api_version(self): diff --git a/plugins/module_utils/_api/utils/config.py b/plugins/module_utils/_api/utils/config.py index 47bf29a0..934f2dfc 100644 --- a/plugins/module_utils/_api/utils/config.py +++ b/plugins/module_utils/_api/utils/config.py @@ -68,8 +68,7 @@ def home_dir(): """ if IS_WINDOWS_PLATFORM: return os.environ.get("USERPROFILE", "") - else: - return os.path.expanduser("~") + return os.path.expanduser("~") def load_general_config(config_path=None): diff --git a/plugins/module_utils/_api/utils/ports.py b/plugins/module_utils/_api/utils/ports.py index 4d67fc04..11a350e6 100644 --- a/plugins/module_utils/_api/utils/ports.py +++ b/plugins/module_utils/_api/utils/ports.py @@ -90,9 +90,8 @@ def split_port(port): if external is not None and len(internal) != len(external): raise ValueError("Port ranges don't match in length") return internal, external - else: - if not external: - external = [None] * len(internal) - elif len(internal) != len(external): - raise ValueError("Port ranges don't match in length") - return internal, [(host, ext_port) for ext_port in external] + if not external: + external = [None] * len(internal) + elif len(internal) != len(external): + raise ValueError("Port ranges don't match in length") + return internal, [(host, ext_port) for ext_port in external] diff --git a/plugins/module_utils/_api/utils/socket.py b/plugins/module_utils/_api/utils/socket.py index 95ff3de1..615018ad 100644 --- a/plugins/module_utils/_api/utils/socket.py +++ b/plugins/module_utils/_api/utils/socket.py @@ -111,8 +111,7 @@ def frames_iter(socket, tty): """ if tty: return ((STDOUT, frame) for frame in frames_iter_tty(socket)) - else: - return frames_iter_no_tty(socket) + return frames_iter_no_tty(socket) def frames_iter_no_tty(socket): @@ -194,7 +193,6 @@ def demux_adaptor(stream_id, data): """ if stream_id == STDOUT: return (data, None) - elif stream_id == STDERR: + if stream_id == STDERR: return (None, data) - else: - raise ValueError(f"{stream_id} is not a valid stream") + raise ValueError(f"{stream_id} is not a valid stream") diff --git a/plugins/module_utils/_api/utils/utils.py b/plugins/module_utils/_api/utils/utils.py index 27a5bfab..e54f6eef 100644 --- a/plugins/module_utils/_api/utils/utils.py +++ b/plugins/module_utils/_api/utils/utils.py @@ -75,10 +75,9 @@ def compare_version(v1, v2): s2 = StrictVersion(v2) if s1 == s2: return 0 - elif s1 > s2: + if s1 > s2: return -1 - else: - return 1 + return 1 def version_lt(v1, v2): diff --git a/plugins/module_utils/_logfmt.py b/plugins/module_utils/_logfmt.py index a6b9f4b0..362ae4ff 100644 --- a/plugins/module_utils/_logfmt.py +++ b/plugins/module_utils/_logfmt.py @@ -133,38 +133,35 @@ def parse_line(line, logrus_mode=False): key.append(cur) parser.next() return _Mode.KEY - elif cur == "=": + if cur == "=": parser.next() return _Mode.EQUAL - else: - if logrus_mode: - raise InvalidLogFmt('Key must always be followed by "=" in logrus mode') - handle_kv(has_no_value=True) - parser.next() - return _Mode.GARBAGE + if logrus_mode: + raise InvalidLogFmt('Key must always be followed by "=" in logrus mode') + handle_kv(has_no_value=True) + parser.next() + return _Mode.GARBAGE def parse_equal(cur): if _is_ident(cur): value.append(cur) parser.next() return _Mode.IDENT_VALUE - elif cur == '"': + if cur == '"': parser.next() return _Mode.QUOTED_VALUE - else: - handle_kv() - parser.next() - return _Mode.GARBAGE + handle_kv() + parser.next() + return _Mode.GARBAGE def parse_ident_value(cur): if _is_ident(cur): value.append(cur) parser.next() return _Mode.IDENT_VALUE - else: - handle_kv() - parser.next() - return _Mode.GARBAGE + handle_kv() + parser.next() + return _Mode.GARBAGE def parse_quoted_value(cur): if cur == "\\": @@ -182,16 +179,15 @@ def parse_line(line, logrus_mode=False): value.append(parser.parse_unicode_sequence()) parser.next() return _Mode.QUOTED_VALUE - elif cur == '"': + if cur == '"': handle_kv() parser.next() return _Mode.GARBAGE - elif cur < " ": + if cur < " ": raise InvalidLogFmt("Control characters in quoted string are not allowed") - else: - value.append(cur) - parser.next() - return _Mode.QUOTED_VALUE + value.append(cur) + parser.next() + return _Mode.QUOTED_VALUE parsers = { _Mode.GARBAGE: parse_garbage, diff --git a/plugins/module_utils/_module_container/base.py b/plugins/module_utils/_module_container/base.py index 3deb3d71..ca4c80ef 100644 --- a/plugins/module_utils/_module_container/base.py +++ b/plugins/module_utils/_module_container/base.py @@ -436,11 +436,10 @@ def _parse_port_range(range_or_port, module): if end < start: module.fail_json(msg=f'Invalid port range: "{range_or_port}"') return list(range(start, end + 1)) - else: - try: - return [int(range_or_port)] - except ValueError: - module.fail_json(msg=f'Invalid port: "{range_or_port}"') + try: + return [int(range_or_port)] + except ValueError: + module.fail_json(msg=f'Invalid port: "{range_or_port}"') def _split_colon_ipv6(text, module): diff --git a/plugins/module_utils/_module_container/docker_api.py b/plugins/module_utils/_module_container/docker_api.py index 1b5b20ea..95b286c8 100644 --- a/plugins/module_utils/_module_container/docker_api.py +++ b/plugins/module_utils/_module_container/docker_api.py @@ -347,8 +347,7 @@ class DockerAPIEngineDriver(EngineDriver): ) output = client._get_result_tty(False, res, config["Config"]["Tty"]) return output, True - else: - return f"Result logged using `{logging_driver}` driver", False + return f"Result logged using `{logging_driver}` driver", False def update_container(self, client, container_id, update_parameters): result = client.post_json_to_json( diff --git a/plugins/module_utils/_socket_handler.py b/plugins/module_utils/_socket_handler.py index 60bae997..315af0cf 100644 --- a/plugins/module_utils/_socket_handler.py +++ b/plugins/module_utils/_socket_handler.py @@ -85,8 +85,7 @@ class DockerSocketHandlerBase: if "OpenSSL.SSL.ZeroReturnError" in str(type(e)): self._eof = True return - else: - raise + raise elif isinstance(self._sock, getattr(pysocket, "SocketIO")): data = self._sock.read() else: diff --git a/plugins/module_utils/_socket_helper.py b/plugins/module_utils/_socket_helper.py index abd95800..defaf252 100644 --- a/plugins/module_utils/_socket_helper.py +++ b/plugins/module_utils/_socket_helper.py @@ -67,7 +67,6 @@ def write_to_socket(sock, data): # WrappedSocket (urllib3/contrib/pyopenssl) does not have `send`, but # only `sendall`, which uses `_send_until_done` under the hood. return sock._send_until_done(data) - elif hasattr(sock, "send"): + if hasattr(sock, "send"): return sock.send(data) - else: - return os.write(sock.fileno(), data) + return os.write(sock.fileno(), data) diff --git a/plugins/module_utils/_swarm.py b/plugins/module_utils/_swarm.py index d5c0c0db..93b08d5d 100644 --- a/plugins/module_utils/_swarm.py +++ b/plugins/module_utils/_swarm.py @@ -74,22 +74,18 @@ class AnsibleDockerSwarmClient(AnsibleDockerClient): swarm_info = json.loads(json_str) if swarm_info["Swarm"]["NodeID"]: return True - if swarm_info["Swarm"]["LocalNodeState"] in ( + return swarm_info["Swarm"]["LocalNodeState"] in ( "active", "pending", "locked", - ): - return True + ) return False - else: - try: - node_info = self.get_node_inspect(node_id=node_id) - except APIError: - return + try: + node_info = self.get_node_inspect(node_id=node_id) + except APIError: + return - if node_info["ID"] is not None: - return True - return False + return node_info["ID"] is not None def check_if_swarm_manager(self): """ diff --git a/plugins/module_utils/_util.py b/plugins/module_utils/_util.py index 262ec7f5..ec01a299 100644 --- a/plugins/module_utils/_util.py +++ b/plugins/module_utils/_util.py @@ -98,10 +98,9 @@ def sanitize_result(data): """ if isinstance(data, dict): return dict((k, sanitize_result(v)) for k, v in data.items()) - elif isinstance(data, (list, tuple)): + if isinstance(data, (list, tuple)): return [sanitize_result(v) for v in data] - else: - return data + return data def log_debug(msg, pretty_print=False): @@ -194,31 +193,28 @@ def compare_generic(a, b, method, datatype): # Do proper comparison (both objects not None) if datatype == "value": return a == b - elif datatype == "list": + if datatype == "list": if method == "strict": return a == b - else: - i = 0 - for v in a: - while i < len(b) and b[i] != v: - i += 1 - if i == len(b): - return False + i = 0 + for v in a: + while i < len(b) and b[i] != v: i += 1 - return True - elif datatype == "dict": + if i == len(b): + return False + i += 1 + return True + if datatype == "dict": if method == "strict": return a == b - else: - return compare_dict_allow_more_present(a, b) - elif datatype == "set": + return compare_dict_allow_more_present(a, b) + if datatype == "set": set_a = set(a) set_b = set(b) if method == "strict": return set_a == set_b - else: - return set_b >= set_a - elif datatype == "set(dict)": + return set_b >= set_a + if datatype == "set(dict)": for av in a: found = False for bv in b: @@ -335,10 +331,9 @@ def clean_dict_booleans_for_docker_api(data, allow_sequences=False): def sanitize(value): if value is True: return "true" - elif value is False: + if value is False: return "false" - else: - return str(value) + return str(value) result = dict() if data is not None: diff --git a/plugins/modules/docker_container_copy_into.py b/plugins/modules/docker_container_copy_into.py index bfdbf8f3..f2f9d49c 100644 --- a/plugins/modules/docker_container_copy_into.py +++ b/plugins/modules/docker_container_copy_into.py @@ -343,31 +343,31 @@ def retrieve_diff( diff["before_header"] = container_path diff["before"] = "(directory)" return - elif regular_stat["mode"] & (1 << (32 - 4)) != 0: + if regular_stat["mode"] & (1 << (32 - 4)) != 0: diff["before_header"] = container_path diff["before"] = "(temporary file)" return - elif regular_stat["mode"] & (1 << (32 - 5)) != 0: + if regular_stat["mode"] & (1 << (32 - 5)) != 0: diff["before_header"] = container_path diff["before"] = link_target return - elif regular_stat["mode"] & (1 << (32 - 6)) != 0: + if regular_stat["mode"] & (1 << (32 - 6)) != 0: diff["before_header"] = container_path diff["before"] = "(device)" return - elif regular_stat["mode"] & (1 << (32 - 7)) != 0: + if regular_stat["mode"] & (1 << (32 - 7)) != 0: diff["before_header"] = container_path diff["before"] = "(named pipe)" return - elif regular_stat["mode"] & (1 << (32 - 8)) != 0: + if regular_stat["mode"] & (1 << (32 - 8)) != 0: diff["before_header"] = container_path diff["before"] = "(socket)" return - elif regular_stat["mode"] & (1 << (32 - 11)) != 0: + if regular_stat["mode"] & (1 << (32 - 11)) != 0: diff["before_header"] = container_path diff["before"] = "(character device)" return - elif regular_stat["mode"] & (1 << (32 - 13)) != 0: + if regular_stat["mode"] & (1 << (32 - 13)) != 0: diff["before_header"] = container_path diff["before"] = "(unknown filesystem object)" return diff --git a/plugins/modules/docker_host_info.py b/plugins/modules/docker_host_info.py index 746bbd20..8bd12f30 100644 --- a/plugins/modules/docker_host_info.py +++ b/plugins/modules/docker_host_info.py @@ -271,8 +271,7 @@ class DockerHostManager(DockerBaseClass): try: if self.verbose_output: return self.client.df() - else: - return dict(LayersSize=self.client.df()["LayersSize"]) + return dict(LayersSize=self.client.df()["LayersSize"]) except APIError as exc: self.client.fail(f"Error inspecting docker host: {exc}") diff --git a/plugins/modules/docker_image.py b/plugins/modules/docker_image.py index 63c27081..b7ee1131 100644 --- a/plugins/modules/docker_image.py +++ b/plugins/modules/docker_image.py @@ -656,17 +656,16 @@ class ImageManager(DockerBaseClass): if archived is None: return build_msg("since none present") - elif ( + if ( current_image_id == api_image_id(archived.image_id) and [current_image_name] == archived.repo_tags ): return None - else: - name = ", ".join(archived.repo_tags) + name = ", ".join(archived.repo_tags) - return build_msg( - f"overwriting archive with image {archived.image_id} named {name}" - ) + return build_msg( + f"overwriting archive with image {archived.image_id} named {name}" + ) def archive_image(self, name, tag): """ @@ -1076,8 +1075,7 @@ class ImageManager(DockerBaseClass): if is_image_name_id(self.name): return self.client.find_image_by_id(self.name, accept_missing_image=True) - else: - return self.client.find_image(self.name, self.tag) + return self.client.find_image(self.name, self.tag) def main(): diff --git a/plugins/modules/docker_network.py b/plugins/modules/docker_network.py index 8f988ba4..34edb46a 100644 --- a/plugins/modules/docker_network.py +++ b/plugins/modules/docker_network.py @@ -359,7 +359,7 @@ def validate_cidr(cidr): """ if CIDR_IPV4.match(cidr): return "ipv4" - elif CIDR_IPV6.match(cidr): + if CIDR_IPV6.match(cidr): return "ipv6" raise ValueError(f'"{cidr}" is not a valid CIDR') diff --git a/plugins/modules/docker_stack.py b/plugins/modules/docker_stack.py index 07da50c9..06fdef48 100644 --- a/plugins/modules/docker_stack.py +++ b/plugins/modules/docker_stack.py @@ -196,9 +196,8 @@ def docker_service_inspect(client, service_name): rc, out, err = client.call_cli("service", "inspect", service_name) if rc != 0: return None - else: - ret = json.loads(out)[0]["Spec"] - return ret + ret = json.loads(out)[0]["Spec"] + return ret def docker_stack_deploy(client, stack_name, compose_files): diff --git a/plugins/modules/docker_swarm_service.py b/plugins/modules/docker_swarm_service.py index bde82590..754b750f 100644 --- a/plugins/modules/docker_swarm_service.py +++ b/plugins/modules/docker_swarm_service.py @@ -932,8 +932,7 @@ def get_docker_environment(env, env_files): if not env_list: if env is not None or env_files is not None: return [] - else: - return None + return None return sorted(env_list) @@ -992,17 +991,16 @@ def get_docker_networks(networks, network_ids): def get_nanoseconds_from_raw_option(name, value): if value is None: return None - elif isinstance(value, int): + if isinstance(value, int): return value - elif isinstance(value, str): + if isinstance(value, str): try: return int(value) except ValueError: return convert_duration_to_nanosecond(value) - else: - raise ValueError( - f"Invalid type for {name} {value} ({type(value)}). Only string or int allowed." - ) + raise ValueError( + f"Invalid type for {name} {value} ({type(value)}). Only string or int allowed." + ) def get_value(key, values, default=None): @@ -1080,8 +1078,7 @@ def has_list_changed(new_list, old_list, sort_lists=True, sort_key=None): old_item_casted = new_item_type(old_item) if new_item != old_item_casted: return True - else: - continue + continue except UnicodeEncodeError: # Fallback to assuming the strings are different return True diff --git a/plugins/plugin_utils/_unsafe.py b/plugins/plugin_utils/_unsafe.py index c70959d6..29576dce 100644 --- a/plugins/plugin_utils/_unsafe.py +++ b/plugins/plugin_utils/_unsafe.py @@ -27,15 +27,15 @@ def make_unsafe(value): if isinstance(value, Mapping): return dict((make_unsafe(key), make_unsafe(val)) for key, val in value.items()) - elif isinstance(value, Set): + if isinstance(value, Set): return set(make_unsafe(elt) for elt in value) - elif is_sequence(value): + if is_sequence(value): return type(value)(make_unsafe(elt) for elt in value) - elif isinstance(value, bytes): + if isinstance(value, bytes): if _RE_TEMPLATE_CHARS_BYTES.search(value): value = _make_unsafe(value) return value - elif isinstance(value, str): + if isinstance(value, str): if _RE_TEMPLATE_CHARS.search(value): value = _make_unsafe(value) return value diff --git a/tests/unit/plugins/module_utils/_api/api/test_client.py b/tests/unit/plugins/module_utils/_api/api/test_client.py index b6797a97..918d4686 100644 --- a/tests/unit/plugins/module_utils/_api/api/test_client.py +++ b/tests/unit/plugins/module_utils/_api/api/test_client.py @@ -500,15 +500,14 @@ class TCPSocketStreamTest(unittest.TestCase): path = self.path.split("/")[-1] if path == "tty": return stdout_data + stderr_data - elif path == "no-tty": + if path == "no-tty": data = b"" data += self.frame_header(1, stdout_data) data += stdout_data data += self.frame_header(2, stderr_data) data += stderr_data return data - else: - raise NotImplementedError(f"Unknown path {path}") + raise NotImplementedError(f"Unknown path {path}") @staticmethod def frame_header(stream, data):