mirror of
https://github.com/ansible-collections/community.docker.git
synced 2026-07-29 11:55:04 +00:00
Python code modernization, 4/n (#1162)
* Address attribute-defined-outside-init. * Address broad-exception-raised. * Address broad-exception-caught. * Address consider-iterating-dictionary. * Address consider-using-dict-comprehension. * Address consider-using-f-string. * Address consider-using-in. * Address consider-using-max-builtin. * Address some consider-using-with. * Address invalid-name. * Address keyword-arg-before-vararg. * Address line-too-long. * Address no-else-continue. * Address no-else-raise. * Address no-else-return. * Remove broken dead code. * Make consider-using-f-string changes compatible with older Python versions. * Python 3.11 and earlier apparently do not like multi-line f-strings.
This commit is contained in:
@@ -58,7 +58,7 @@ def _get_ansible_type(value_type):
|
||||
if value_type == "set":
|
||||
return "list"
|
||||
if value_type not in ("list", "dict", "bool", "int", "float", "str"):
|
||||
raise Exception(f'Invalid type "{value_type}"')
|
||||
raise ValueError(f'Invalid type "{value_type}"')
|
||||
return value_type
|
||||
|
||||
|
||||
@@ -87,13 +87,13 @@ class Option:
|
||||
needs_elements = self.value_type in ("list", "set")
|
||||
needs_ansible_elements = self.ansible_type in ("list",)
|
||||
if elements is not None and not needs_elements:
|
||||
raise Exception("elements only allowed for lists/sets")
|
||||
raise ValueError("elements only allowed for lists/sets")
|
||||
if elements is None and needs_elements:
|
||||
raise Exception("elements required for lists/sets")
|
||||
raise ValueError("elements required for lists/sets")
|
||||
if ansible_elements is not None and not needs_ansible_elements:
|
||||
raise Exception("Ansible elements only allowed for Ansible lists")
|
||||
raise ValueError("Ansible elements only allowed for Ansible lists")
|
||||
if (elements is None and ansible_elements is None) and needs_ansible_elements:
|
||||
raise Exception("Ansible elements required for Ansible lists")
|
||||
raise ValueError("Ansible elements required for Ansible lists")
|
||||
self.elements = elements if needs_elements else None
|
||||
self.ansible_elements = (
|
||||
(ansible_elements or _get_ansible_type(elements))
|
||||
@@ -104,7 +104,7 @@ class Option:
|
||||
self.ansible_type == "list" and self.ansible_elements == "dict"
|
||||
) or (self.ansible_type == "dict")
|
||||
if ansible_suboptions is not None and not needs_suboptions:
|
||||
raise Exception(
|
||||
raise ValueError(
|
||||
"suboptions only allowed for Ansible lists with dicts, or Ansible dicts"
|
||||
)
|
||||
if (
|
||||
@@ -113,7 +113,7 @@ class Option:
|
||||
and not needs_no_suboptions
|
||||
and not not_an_ansible_option
|
||||
):
|
||||
raise Exception(
|
||||
raise ValueError(
|
||||
"suboptions required for Ansible lists with dicts, or Ansible dicts"
|
||||
)
|
||||
self.ansible_suboptions = ansible_suboptions if needs_suboptions else None
|
||||
@@ -431,16 +431,15 @@ def _parse_port_range(range_or_port, module):
|
||||
if "-" in range_or_port:
|
||||
try:
|
||||
start, end = [int(port) for port in range_or_port.split("-")]
|
||||
except Exception:
|
||||
except ValueError:
|
||||
module.fail_json(msg=f'Invalid port range: "{range_or_port}"')
|
||||
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 Exception:
|
||||
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):
|
||||
@@ -707,7 +706,7 @@ def _preprocess_mounts(module, values):
|
||||
if mount_dict["tmpfs_mode"] is not None:
|
||||
try:
|
||||
mount_dict["tmpfs_mode"] = int(mount_dict["tmpfs_mode"], 8)
|
||||
except Exception:
|
||||
except ValueError:
|
||||
module.fail_json(
|
||||
msg=f'tmp_fs mode of mount "{target}" is not an octal string!'
|
||||
)
|
||||
@@ -747,7 +746,7 @@ def _preprocess_mounts(module, values):
|
||||
check_collision(container, "volumes")
|
||||
new_vols.append(f"{host}:{container}:{mode}")
|
||||
continue
|
||||
elif len(parts) == 2:
|
||||
if len(parts) == 2:
|
||||
if not _is_volume_permissions(parts[1]) and re.match(
|
||||
r"[.~]", parts[0]
|
||||
):
|
||||
|
||||
@@ -124,7 +124,7 @@ def _get_ansible_type(our_type):
|
||||
if our_type == "set":
|
||||
return "list"
|
||||
if our_type not in ("list", "dict", "bool", "int", "float", "str"):
|
||||
raise Exception(f'Invalid type "{our_type}"')
|
||||
raise ValueError(f'Invalid type "{our_type}"')
|
||||
return our_type
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
# Ensure driver_opts values are strings
|
||||
for key, val in value.items():
|
||||
if not isinstance(val, str):
|
||||
raise Exception(
|
||||
raise ValueError(
|
||||
f"driver_opts values must be strings, got {type(val).__name__} for key '{key}'"
|
||||
)
|
||||
params[dest_para] = value
|
||||
@@ -278,7 +278,7 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
params[dest_para] = value
|
||||
if parameters:
|
||||
ups = ", ".join([f'"{p}"' for p in sorted(parameters)])
|
||||
raise Exception(
|
||||
raise ValueError(
|
||||
f"Unknown parameter(s) for connect_container_to_network for Docker API driver: {ups}"
|
||||
)
|
||||
ipam_config = {}
|
||||
@@ -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(
|
||||
@@ -399,13 +398,13 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
# New docker daemon versions do not allow containers to be removed
|
||||
# if they are paused. Make sure we do not end up in an infinite loop.
|
||||
if count == 3:
|
||||
raise Exception(f"{exc} [tried to unpause three times]")
|
||||
raise RuntimeError(f"{exc} [tried to unpause three times]")
|
||||
count += 1
|
||||
# Unpause
|
||||
try:
|
||||
self.unpause_container(client, container_id)
|
||||
except Exception as exc2:
|
||||
raise Exception(f"{exc2} [while unpausing]")
|
||||
raise RuntimeError(f"{exc2} [while unpausing]")
|
||||
# Now try again
|
||||
continue
|
||||
raise
|
||||
@@ -430,13 +429,13 @@ class DockerAPIEngineDriver(EngineDriver):
|
||||
# New docker daemon versions do not allow containers to be removed
|
||||
# if they are paused. Make sure we do not end up in an infinite loop.
|
||||
if count == 3:
|
||||
raise Exception(f"{exc} [tried to unpause three times]")
|
||||
raise RuntimeError(f"{exc} [tried to unpause three times]")
|
||||
count += 1
|
||||
# Unpause
|
||||
try:
|
||||
self.unpause_container(client, container_id)
|
||||
except Exception as exc2:
|
||||
raise Exception(f"{exc2} [while unpausing]")
|
||||
raise RuntimeError(f"{exc2} [while unpausing]")
|
||||
# Now try again
|
||||
continue
|
||||
if (
|
||||
@@ -1060,7 +1059,7 @@ def _get_network_id(module, client, network_name):
|
||||
network_id = network["Id"]
|
||||
break
|
||||
return network_id
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
client.fail(f"Error getting network id for {network_name} - {exc}")
|
||||
|
||||
|
||||
|
||||
@@ -134,6 +134,7 @@ class ContainerManager(DockerBaseClass):
|
||||
"The value of default_host_ip must be an empty string, an IPv4 address, "
|
||||
f'or an IPv6 address. Got "{self.param_default_host_ip}" instead.'
|
||||
)
|
||||
self.parameters = None
|
||||
|
||||
def _collect_all_options(self, active_options):
|
||||
all_options = {}
|
||||
@@ -480,7 +481,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.unpause_container(
|
||||
self.client, container.id
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(
|
||||
f"Error {'pausing' if self.param_paused else 'unpausing'} container {container.id}: {exc}"
|
||||
)
|
||||
@@ -567,13 +568,13 @@ class ContainerManager(DockerBaseClass):
|
||||
if not image or self.param_pull == "always":
|
||||
if not self.check_mode:
|
||||
self.log("Pull the image.")
|
||||
image, alreadyToLatest = self.engine_driver.pull_image(
|
||||
image, already_to_latest = self.engine_driver.pull_image(
|
||||
self.client,
|
||||
repository,
|
||||
tag,
|
||||
image_platform=self.module.params["platform"],
|
||||
)
|
||||
if alreadyToLatest:
|
||||
if already_to_latest:
|
||||
self.results["changed"] = False
|
||||
self.results["actions"].append(
|
||||
dict(pulled_image=f"{repository}:{tag}", changed=False)
|
||||
@@ -950,7 +951,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.disconnect_container_from_network(
|
||||
self.client, container.id, diff["parameter"]["id"]
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(
|
||||
f"Error disconnecting container from network {diff['parameter']['name']} - {exc}"
|
||||
)
|
||||
@@ -975,7 +976,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.connect_container_to_network(
|
||||
self.client, container.id, diff["parameter"]["id"], params
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(
|
||||
f"Error connecting container to network {diff['parameter']['name']} - {exc}"
|
||||
)
|
||||
@@ -989,7 +990,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.disconnect_container_from_network(
|
||||
self.client, container.id, network["name"]
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(
|
||||
f"Error disconnecting container from network {network['name']} - {exc}"
|
||||
)
|
||||
@@ -1027,7 +1028,7 @@ class ContainerManager(DockerBaseClass):
|
||||
container_id = self.engine_driver.create_container(
|
||||
self.client, self.param_name, create_parameters, networks=networks
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error creating container: {exc}")
|
||||
return self._get_container(container_id)
|
||||
return new_container
|
||||
@@ -1039,7 +1040,7 @@ class ContainerManager(DockerBaseClass):
|
||||
if not self.check_mode:
|
||||
try:
|
||||
self.engine_driver.start_container(self.client, container_id)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error starting container {container_id}: {exc}")
|
||||
|
||||
if self.module.params["detach"] is False:
|
||||
@@ -1096,7 +1097,7 @@ class ContainerManager(DockerBaseClass):
|
||||
link=link,
|
||||
force=force,
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.client.fail(f"Error removing container {container_id}: {exc}")
|
||||
|
||||
def container_update(self, container_id, update_parameters):
|
||||
@@ -1112,7 +1113,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.update_container(
|
||||
self.client, container_id, update_parameters
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error updating container {container_id}: {exc}")
|
||||
return self._get_container(container_id)
|
||||
|
||||
@@ -1126,7 +1127,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.kill_container(
|
||||
self.client, container_id, kill_signal=self.param_kill_signal
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error killing container {container_id}: {exc}")
|
||||
|
||||
def container_restart(self, container_id):
|
||||
@@ -1139,7 +1140,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.restart_container(
|
||||
self.client, container_id, self.module.params["stop_timeout"] or 10
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error restarting container {container_id}: {exc}")
|
||||
return self._get_container(container_id)
|
||||
|
||||
@@ -1156,7 +1157,7 @@ class ContainerManager(DockerBaseClass):
|
||||
self.engine_driver.stop_container(
|
||||
self.client, container_id, self.module.params["stop_timeout"]
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||
self.fail(f"Error stopping container {container_id}: {exc}")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user