Skip to content

Commit

Permalink
Enable pylint check C0209 (#1267)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shrews authored Jul 12, 2023
1 parent b2b8a83 commit aef73cf
Show file tree
Hide file tree
Showing 16 changed files with 94 additions and 97 deletions.
3 changes: 1 addition & 2 deletions .yamllint
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
extends: default

ignore: |
.tox
ignore-from-file: .gitignore

rules:
braces:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ disable = [
]

enable = [
"C0209", # consider-using-f-string
"W0102", # dangerous-default-value
]
10 changes: 5 additions & 5 deletions src/ansible_runner/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@
dict(
default=DEFAULT_RUNNER_BINARY,
help="specifies the full path pointing to the Ansible binaries "
"(default={})".format(DEFAULT_RUNNER_BINARY)
f"(default={DEFAULT_RUNNER_BINARY})"
),
),
(
Expand All @@ -158,7 +158,7 @@
default=DEFAULT_UUID,
help="an identifier that will be used when generating the artifacts "
"directory and can be used to uniquely identify a playbook run "
"(default={})".format(DEFAULT_UUID)
f"(default={DEFAULT_UUID})"
),
),
(
Expand Down Expand Up @@ -432,18 +432,18 @@ def role_manager(vargs):

playbook = dump_artifact(json.dumps(play), project_path, filename)
kwargs.playbook = playbook
output.debug('using playbook file %s' % playbook)
output.debug(f"using playbook file {playbook}")

if vargs.get('inventory'):
inventory_file = os.path.join(vargs.get('private_data_dir'), 'inventory', vargs.get('inventory'))
if not os.path.exists(inventory_file):
raise AnsibleRunnerException('location specified by --inventory does not exist')
kwargs.inventory = inventory_file
output.debug('using inventory file %s' % inventory_file)
output.debug(f"using inventory file {inventory_file}")

roles_path = vargs.get('roles_path') or os.path.join(vargs.get('private_data_dir'), 'roles')
roles_path = os.path.abspath(roles_path)
output.debug('setting ANSIBLE_ROLES_PATH to %s' % roles_path)
output.debug(f"setting ANSIBLE_ROLES_PATH to {roles_path}")

envvars = {}
if envvars_exists:
Expand Down
42 changes: 21 additions & 21 deletions src/ansible_runner/config/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ def __init__(self,
if ident is None:
self.ident = str(uuid4())
else:
self.ident = ident
self.ident = str(ident)

self.artifact_dir = os.path.join(artifact_dir, "{}".format(self.ident))
self.artifact_dir = os.path.join(artifact_dir, self.ident)

if not project_dir:
self.project_dir = os.path.join(self.private_data_dir, 'project')
Expand Down Expand Up @@ -174,7 +174,7 @@ def _prepare_env(self, runner_mode='pexpect'):
for pattern, password in iteritems(self.passwords)
}
except Exception as e:
debug('Failed to compile RE from passwords: {}'.format(e))
debug(f'Failed to compile RE from passwords: {e}')

self.expect_passwords[pexpect.TIMEOUT] = None
self.expect_passwords[pexpect.EOF] = None
Expand Down Expand Up @@ -207,7 +207,7 @@ def _prepare_env(self, runner_mode='pexpect'):
raise ConfigurationError(
f'container_image required when specifying process_isolation_executable={self.process_isolation_executable}'
)
self.container_name = "ansible_runner_{}".format(sanitize_container_name(self.ident))
self.container_name = f"ansible_runner_{sanitize_container_name(self.ident)}"
self.env = {}

if self.process_isolation_executable == 'podman':
Expand All @@ -221,7 +221,7 @@ def _prepare_env(self, runner_mode='pexpect'):
# https://issues.redhat.com/browse/AAP-476
self.env['ANSIBLE_UNSAFE_WRITES'] = '1'

artifact_dir = os.path.join("/runner/artifacts", "{}".format(self.ident))
artifact_dir = os.path.join("/runner/artifacts", self.ident)
self.env['AWX_ISOLATED_DATA_DIR'] = artifact_dir
if self.fact_cache_type == 'jsonfile':
self.env['ANSIBLE_CACHE_PLUGIN_CONNECTION'] = os.path.join(artifact_dir, 'fact_cache')
Expand Down Expand Up @@ -273,7 +273,7 @@ def _prepare_env(self, runner_mode='pexpect'):
shutil.rmtree(callback_dir)
shutil.copytree(get_callback_dir(), callback_dir)

container_callback_dir = os.path.join("/runner/artifacts", "{}".format(self.ident), "callback")
container_callback_dir = os.path.join("/runner/artifacts", self.ident, "callback")
self.env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(filter(None, (self.env.get('ANSIBLE_CALLBACK_PLUGINS'), container_callback_dir)))
else:
callback_dir = self.env.get('AWX_LIB_DIRECTORY', os.getenv('AWX_LIB_DIRECTORY'))
Expand Down Expand Up @@ -370,7 +370,7 @@ def _update_volume_mount_paths(
):

if src_mount_path is None or not os.path.exists(src_mount_path):
logger.debug("Source volume mount path does not exit {0}".format(src_mount_path))
logger.debug(f"Source volume mount path does not exist: {src_mount_path}")
return

# ensure source is abs
Expand Down Expand Up @@ -403,7 +403,7 @@ def _update_volume_mount_paths(
self._ensure_path_safe_to_mount(dst_dir)

# format the src dest str
volume_mount_path = "{}:{}".format(src_dir, dst_dir)
volume_mount_path = f"{src_dir}:{dst_dir}"

# add labels as needed
if labels:
Expand Down Expand Up @@ -504,7 +504,7 @@ def wrap_args_for_containerization(self, args, execution_mode, cmdline_args):

# runtime commands need artifacts mounted to output data
self._update_volume_mount_paths(new_args,
"{}/artifacts".format(self.private_data_dir),
f"{self.private_data_dir}/artifacts",
dst_mount_path="/runner/artifacts",
labels=":Z")

Expand All @@ -515,16 +515,16 @@ def wrap_args_for_containerization(self, args, execution_mode, cmdline_args):

# Mount the entire private_data_dir
# custom show paths inside private_data_dir do not make sense
self._update_volume_mount_paths(new_args, "{}".format(self.private_data_dir), dst_mount_path="/runner", labels=":Z")
self._update_volume_mount_paths(new_args, self.private_data_dir, dst_mount_path="/runner", labels=":Z")

if self.container_auth_data:
# Pull in the necessary registry auth info, if there is a container cred
self.registry_auth_path, registry_auth_conf_file = self._generate_container_auth_dir(self.container_auth_data)
if 'podman' in self.process_isolation_executable:
new_args.extend(["--authfile={}".format(self.registry_auth_path)])
new_args.extend([f"--authfile={self.registry_auth_path}"])
else:
docker_idx = new_args.index(self.process_isolation_executable)
new_args.insert(docker_idx + 1, "--config={}".format(self.registry_auth_path))
new_args.insert(docker_idx + 1, f"--config={self.registry_auth_path}")
if registry_auth_conf_file is not None:
# Podman >= 3.1.0
self.env['CONTAINERS_REGISTRIES_CONF'] = registry_auth_conf_file
Expand All @@ -537,7 +537,7 @@ def wrap_args_for_containerization(self, args, execution_mode, cmdline_args):
self._ensure_path_safe_to_mount(volume_mounts[0])
labels = None
if len(volume_mounts) == 3:
labels = ":%s" % volume_mounts[2]
labels = f":{volume_mounts[2]}"
self._update_volume_mount_paths(new_args, volume_mounts[0], dst_mount_path=volume_mounts[1], labels=labels)

# Reference the file with list of keys to pass into container
Expand All @@ -564,10 +564,10 @@ def wrap_args_for_containerization(self, args, execution_mode, cmdline_args):

def _generate_container_auth_dir(self, auth_data):
host = auth_data.get('host')
token = "{}:{}".format(auth_data.get('username'), auth_data.get('password'))
token = f"{auth_data.get('username')}:{auth_data.get('password')}"
encoded_container_auth_data = {'auths': {host: {'auth': b64encode(token.encode('UTF-8')).decode('UTF-8')}}}
# Create a new temp file with container auth data
path = tempfile.mkdtemp(prefix='%s%s_' % (registry_auth_prefix, self.ident))
path = tempfile.mkdtemp(prefix=f'{registry_auth_prefix}{self.ident}_')
register_for_cleanup(path)

if self.process_isolation_executable == 'docker':
Expand All @@ -588,7 +588,7 @@ def _generate_container_auth_dir(self, auth_data):

lines = [
'[[registry]]',
'location = "{}"'.format(host),
f'location = "{host}"',
'insecure = true',
]

Expand All @@ -605,14 +605,14 @@ def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silen
necessary calls to ``ssh-agent``
"""
if self.containerized:
artifact_dir = os.path.join("/runner/artifacts", "{}".format(self.ident))
artifact_dir = os.path.join("/runner/artifacts", self.ident)
ssh_key_path = os.path.join(artifact_dir, "ssh_key_data")

if ssh_key_path:
ssh_add_command = args2cmdline('ssh-add', ssh_key_path)
if silence_ssh_add:
ssh_add_command = ' '.join([ssh_add_command, '2>/dev/null'])
ssh_key_cleanup_command = 'rm -f {}'.format(ssh_key_path)
ssh_key_cleanup_command = f'rm -f {ssh_key_path}'
# The trap ensures the fifo is cleaned up even if the call to ssh-add fails.
# This prevents getting into certain scenarios where subsequent reads will
# hang forever.
Expand All @@ -634,15 +634,15 @@ def _handle_automounts(self, new_args):

if os.path.exists(os.environ[env]):
if os.environ[env].startswith(os.environ['HOME']):
dest_path = '/home/runner/{}'.format(os.environ[env].lstrip(os.environ['HOME']))
dest_path = f"/home/runner/{os.environ[env].lstrip(os.environ['HOME'])}"
elif os.environ[env].startswith('~'):
dest_path = '/home/runner/{}'.format(os.environ[env].lstrip('~/'))
dest_path = f"/home/runner/{os.environ[env].lstrip('~/')}"
else:
dest_path = os.environ[env]

self._update_volume_mount_paths(new_args, os.environ[env], dst_mount_path=dest_path)

new_args.extend(["-e", "{}={}".format(env, dest_path)])
new_args.extend(["-e", f"{env}={dest_path}"])

for paths in cli_automount['PATHS']:
if os.path.exists(paths['src']):
Expand Down
4 changes: 2 additions & 2 deletions src/ansible_runner/config/ansible_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self, runner_mode=None, **kwargs):
# runner params
self.runner_mode = runner_mode if runner_mode else 'subprocess'
if self.runner_mode not in ['pexpect', 'subprocess']:
raise ConfigurationError("Invalid runner mode {0}, valid value is either 'pexpect' or 'subprocess'".format(self.runner_mode))
raise ConfigurationError(f"Invalid runner mode {self.runner_mode}, valid value is either 'pexpect' or 'subprocess'")

if kwargs.get("process_isolation"):
self._ansible_config_exec_path = "ansible-config"
Expand All @@ -62,7 +62,7 @@ def __init__(self, runner_mode=None, **kwargs):
def prepare_ansible_config_command(self, action, config_file=None, only_changed=None):

if action not in AnsibleCfgConfig._supported_actions:
raise ConfigurationError("Invalid action {0}, valid value is one of either {1}".format(action, ", ".join(AnsibleCfgConfig._supported_actions)))
raise ConfigurationError(f'Invalid action {action}, valid value is one of either {", ".join(AnsibleCfgConfig._supported_actions)}')

if action != 'dump' and only_changed:
raise ConfigurationError("only_changed is applicable for action 'dump'")
Expand Down
2 changes: 1 addition & 1 deletion src/ansible_runner/config/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(self, input_fd=None, output_fd=None, error_fd=None, runner_mode=Non
raise ConfigurationError("input_fd is applicable only with 'subprocess' runner mode")

if runner_mode and runner_mode not in ['pexpect', 'subprocess']:
raise ConfigurationError("Invalid runner mode {0}, valid value is either 'pexpect' or 'subprocess'".format(runner_mode))
raise ConfigurationError(f"Invalid runner mode {runner_mode}, valid value is either 'pexpect' or 'subprocess'")

# runner params
self.runner_mode = runner_mode
Expand Down
12 changes: 6 additions & 6 deletions src/ansible_runner/config/doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self, runner_mode=None, **kwargs):
# runner params
self.runner_mode = runner_mode if runner_mode else 'subprocess'
if self.runner_mode not in ['pexpect', 'subprocess']:
raise ConfigurationError("Invalid runner mode {0}, valid value is either 'pexpect' or 'subprocess'".format(self.runner_mode))
raise ConfigurationError(f"Invalid runner mode {self.runner_mode}, valid value is either 'pexpect' or 'subprocess'")

if kwargs.get("process_isolation"):
self._ansible_doc_exec_path = "ansible-doc"
Expand All @@ -63,11 +63,11 @@ def prepare_plugin_docs_command(self, plugin_names, plugin_type=None, response_f
snippet=False, playbook_dir=None, module_path=None):

if response_format and response_format not in DocConfig._supported_response_formats:
raise ConfigurationError("Invalid response_format {0}, valid value is one of either {1}".format(response_format,
", ".join(DocConfig._supported_response_formats)))
raise ConfigurationError(f'Invalid response_format {response_format}, '
f'valid value is one of either {", ".join(DocConfig._supported_response_formats)}')

if not isinstance(plugin_names, list):
raise ConfigurationError("plugin_names should be of type list, instead received {0} of type {1}".format(plugin_names, type(plugin_names)))
raise ConfigurationError(f"plugin_names should be of type list, instead received {plugin_names} of type {type(plugin_names)}")

self._prepare_env(runner_mode=self.runner_mode)
self.cmdline_args = []
Expand Down Expand Up @@ -96,8 +96,8 @@ def prepare_plugin_list_command(self, list_files=None, response_format=None, plu
playbook_dir=None, module_path=None):

if response_format and response_format not in DocConfig._supported_response_formats:
raise ConfigurationError("Invalid response_format {0}, valid value is one of either {1}".format(response_format,
", ".join(DocConfig._supported_response_formats)))
raise ConfigurationError(f"Invalid response_format {response_format}, "
f'valid value is one of either {", ".join(DocConfig._supported_response_formats)}')

self._prepare_env(runner_mode=self.runner_mode)
self.cmdline_args = []
Expand Down
14 changes: 7 additions & 7 deletions src/ansible_runner/config/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, runner_mode=None, **kwargs):
# runner params
self.runner_mode = runner_mode if runner_mode else 'subprocess'
if self.runner_mode not in ['pexpect', 'subprocess']:
raise ConfigurationError("Invalid runner mode {0}, valid value is either 'pexpect' or 'subprocess'".format(self.runner_mode))
raise ConfigurationError(f"Invalid runner mode {self.runner_mode}, valid value is either 'pexpect' or 'subprocess'")

if kwargs.get("process_isolation"):
self._ansible_inventory_exec_path = "ansible-inventory"
Expand All @@ -64,14 +64,14 @@ def prepare_inventory_command(self, action, inventories, response_format=None, h
output_file=None, export=None):

if action not in InventoryConfig._supported_actions:
raise ConfigurationError("Invalid action {0}, valid value is one of either {1}".format(action, ", ".join(InventoryConfig._supported_actions)))
raise ConfigurationError(f'Invalid action {action}, valid value is one of either {", ".join(InventoryConfig._supported_actions)}')

if response_format and response_format not in InventoryConfig._supported_response_formats:
raise ConfigurationError("Invalid response_format {0}, valid value is one of "
"either {1}".format(response_format, ", ".join(InventoryConfig._supported_response_formats)))
raise ConfigurationError(f"Invalid response_format {response_format}, valid value is one of "
f"either {', '.join(InventoryConfig._supported_response_formats)}")

if not isinstance(inventories, list):
raise ConfigurationError("inventories should be of type list, instead received {0} of type {1}".format(inventories, type(inventories)))
raise ConfigurationError(f"inventories should be of type list, instead received {inventories} of type {type(inventories)}")

if action == "host" and host is None:
raise ConfigurationError("Value of host parameter is required when action in 'host'")
Expand All @@ -82,15 +82,15 @@ def prepare_inventory_command(self, action, inventories, response_format=None, h
self._prepare_env(runner_mode=self.runner_mode)
self.cmdline_args = []

self.cmdline_args.append('--{0}'.format(action))
self.cmdline_args.append(f'--{action}')
if action == 'host':
self.cmdline_args.append(host)

for inv in inventories:
self.cmdline_args.extend(['-i', inv])

if response_format in ['yaml', 'toml']:
self.cmdline_args.append('--{0}'.format(response_format))
self.cmdline_args.append(f'--{response_format}')

if playbook_dir:
self.cmdline_args.extend(['--playbook-dir', playbook_dir])
Expand Down
Loading

0 comments on commit aef73cf

Please sign in to comment.