Skip to content

Commit

Permalink
tests: ruff: enforce UP032 (f-string) rule
Browse files Browse the repository at this point in the history
  • Loading branch information
KKoukiou committed Jun 27, 2024
1 parent c2c7e87 commit d839e12
Show file tree
Hide file tree
Showing 128 changed files with 305 additions and 400 deletions.
4 changes: 2 additions & 2 deletions pyanaconda/argument_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,8 @@ def __call__(self, parser, namespace, values, _option_string=None):
name, rest = values.split(',', maxsplit=1)
except ValueError:
raise ValueError(
"The addrepo option has incorrect format ('{}'). "
"Use: inst.addrepo=<name>,<url>".format(values)
f"The addrepo option has incorrect format ('{values}'). "
"Use: inst.addrepo=<name>,<url>"
) from None

items = getattr(namespace, self.dest, self.default)
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/configuration/anaconda.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def _set_from_profile(self, loader, profile_id):
if not loader.check_profile(profile_id):
raise ConfigurationError(
"Unable to find any suitable configuration files "
"for the '{}' profile.".format(profile_id)
f"for the '{profile_id}' profile."
)

# Read the configuration files of the profile.
Expand Down
8 changes: 4 additions & 4 deletions pyanaconda/core/configuration/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def __init__(self, msg, filename):
self._filename = filename

def __str__(self):
return "The following error has occurred while handling the configuration file '{}': " \
"{}".format(self._filename, super().__str__())
return f"The following error has occurred while handling the configuration file '{self._filename}': " \
f"{super().__str__()}"


class ConfigurationDataError(ConfigurationError):
Expand All @@ -47,8 +47,8 @@ def __init__(self, msg, section, option):
self._option = option

def __str__(self):
return "The following error has occurred while handling the option '{}' in the section " \
"'{}': {}".format(self._option, self._section, super().__str__())
return f"The following error has occurred while handling the option '{self._option}' in the section " \
f"'{self._section}': {super().__str__()}"


def create_parser():
Expand Down
4 changes: 2 additions & 2 deletions pyanaconda/core/configuration/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def default_source(self):
value = self._get_option("default_source", str)

if value not in (SOURCE_TYPE_CLOSEST_MIRROR, SOURCE_TYPE_CDN):
raise ValueError("Invalid value: {}".format(value))
raise ValueError(f"Invalid value: {value}")

return value

Expand All @@ -122,7 +122,7 @@ def _convert_flatpak_remote(cls, value):
"""Convert flatpak remote from string to tuple."""
value = value.split()
if len(value) != 2:
raise ValueError("Flatpak remote needs to be in format 'name URL': {}".format(value))
raise ValueError(f"Flatpak remote needs to be in format 'name URL': {value}")

return tuple(value)

Expand Down
10 changes: 5 additions & 5 deletions pyanaconda/core/configuration/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def load_profile(self, config_path):
profile_id = data.profile_id

if profile_id in self._profiles:
raise ConfigurationError("The '{}' profile was already loaded.".format(profile_id))
raise ConfigurationError(f"The '{profile_id}' profile was already loaded.")

# Add the profile.
log.info("Found the '%s' profile at %s.", profile_id, config_path)
Expand Down Expand Up @@ -250,14 +250,14 @@ def _get_profile_bases(self, profile_id):
while current_id:
if current_id not in self._profiles:
raise ConfigurationError(
"Dependencies of the '{}' profile cannot be resolved "
"due to an unknown '{}' profile.".format(profile_id, current_id)
f"Dependencies of the '{profile_id}' profile cannot be resolved "
f"due to an unknown '{current_id}' profile."
)

if current_id in visited:
raise ConfigurationError(
"Dependencies of the '{}' profile cannot be resolved "
"due to a conflict with '{}'.".format(profile_id, current_id)
f"Dependencies of the '{profile_id}' profile cannot be resolved "
f"due to a conflict with '{current_id}'."
)

visited.add(current_id)
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/configuration/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ def selinux(self):
value = self._get_option("selinux", int)

if value not in (-1, 0, 1):
raise ValueError("Invalid value: {}".format(value))
raise ValueError(f"Invalid value: {value}")

return value
4 changes: 2 additions & 2 deletions pyanaconda/core/configuration/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def from_name(cls, value):
except KeyError:
pass

raise ValueError("'{}' is not a valid partitioning scheme".format(value))
raise ValueError(f"'{value}' is not a valid partitioning scheme")


class StorageSection(Section):
Expand Down Expand Up @@ -145,7 +145,7 @@ def luks_version(self):
value = self._get_option("luks_version", str)

if value not in ("luks1", "luks2"):
raise ValueError("Invalid value: {}".format(value))
raise ValueError(f"Invalid value: {value}")

return value

Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/configuration/storage_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def from_name(cls, value):
except KeyError:
pass

raise ValueError("'{}' is not a valid device typ".format(value))
raise ValueError(f"'{value}' is not a valid device typ")


class StorageConstraints(Section):
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def items_raw(self):
"""
for key, val in self._data.items():
if key in self._args_with_prefix:
yield ("{}{}".format(BOOT_ARG_PREFIX, key), val)
yield (f"{BOOT_ARG_PREFIX}{key}", val)
continue

yield (key, val)
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/live_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def get_live_user():
home_dir = passwd_entry.pw_dir
env_prune = ("GDK_BACKEND",)
env_add = {
"XDG_RUNTIME_DIR": "/run/user/{}".format(uid),
"XDG_RUNTIME_DIR": f"/run/user/{uid}",
"USER": username,
"HOME": home_dir,
}
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def set_system_root(path):
rc = execWithRedirect("mount", ["--rbind", path, sysroot])

if rc != 0:
raise OSError("Failed to mount sysroot to {}.".format(path))
raise OSError(f"Failed to mount sysroot to {path}.")


def make_directories(directory):
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def split_protocol(url):
ret = url.split("://")

if len(ret) > 2:
raise ValueError("Invalid url to split protocol '{}'".format(url))
raise ValueError(f"Invalid url to split protocol '{url}'")

if len(ret) == 2:
# return back part removed when splitting
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/core/startup/dbus_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _start_dbus_session(self):
self.DBUS_LAUNCH_BIN,
'--print-address',
"--syslog",
"--config-file={}".format(ANACONDA_BUS_CONF_FILE)
f"--config-file={ANACONDA_BUS_CONF_FILE}"
]

def dbus_preexec():
Expand Down
4 changes: 2 additions & 2 deletions pyanaconda/core/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,8 @@ def _reown_homedir(root, homedir, username):
gid = int(pwent[3])

# Change owner UID and GID where matching
from_ids = "--from={}:{}".format(orig_uid, orig_gid)
to_ids = "{}:{}".format(uid, gid)
from_ids = f"--from={orig_uid}:{orig_gid}"
to_ids = f"{uid}:{gid}"
util.execWithRedirect("chown", ["--recursive", "--no-dereference",
from_ids, to_ids, root + homedir])

Expand Down
4 changes: 2 additions & 2 deletions pyanaconda/input_checking.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def secret_type(self, new_type):
# this does no blow up later on once we try to access the status/error message
# corresponding to the secret type.
if new_type not in constants.SecretType:
raise RuntimeError("Unknown secret type: {}".format(new_type))
raise RuntimeError(f"Unknown secret type: {new_type}")
self._secret_type = new_type


Expand Down Expand Up @@ -714,7 +714,7 @@ def secret_type(self, new_type):
# this does no blow up later on once we try to access the status/error message
# corresponding to the secret type.
if new_type not in constants.SecretType:
raise RuntimeError("Unknown secret type: {}".format(new_type))
raise RuntimeError(f"Unknown secret type: {new_type}")
self._secret_type = new_type

def add_check(self, check_instance):
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _writeKS(ksdata):

# Make it so only root can read - could have passwords
with open_with_perm(path, "w", 0o600) as f:
f.write("# Generated by Anaconda {}\n".format(util.get_anaconda_version_string()))
f.write(f"# Generated by Anaconda {util.get_anaconda_version_string()}\n")
f.write(str(ksdata))

class RunInstallationTask(InstallationTask):
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def raise_on_invalid_locale(arg):
:raise: InvalidLocaleSpec
"""
if not is_valid_langcode(arg):
raise InvalidLocaleSpec("'{}' is not a valid locale".format(arg))
raise InvalidLocaleSpec(f"'{arg}' is not a valid locale")


def get_language_id(locale):
Expand Down
3 changes: 1 addition & 2 deletions pyanaconda/modules/boss/kickstart_manager/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ def is_addon(self):
return self._type == self.KickstartElementType.ADDON

def __repr__(self):
return "KickstartElement(args={}, lines={}, lineno={}, filename={})".format(
self._args, self._lines, self._lineno, self._filename)
return f"KickstartElement(args={self._args}, lines={self._lines}, lineno={self._lineno}, filename={self._filename})"

def __str__(self):
return self.content
Expand Down
7 changes: 2 additions & 5 deletions pyanaconda/modules/boss/module_manager/module_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ def is_addon(self):
def proxy(self):
"""Returns a proxy of the remote object."""
if not self._is_service_available:
raise DBusObserverError("Service {} is not available."
.format(self._service_name))
raise DBusObserverError(f"Service {self._service_name} is not available.")

if not self._proxy:
self._proxy = self._message_bus.get_proxy(self._service_name,
Expand All @@ -71,6 +70,4 @@ def _disable_service(self):

def __repr__(self):
"""Returns a string representation."""
return "{}({},{})".format(self.__class__.__name__,
self._service_name,
self._object_path)
return f"{self.__class__.__name__}({self._service_name},{self._object_path})"
2 changes: 1 addition & 1 deletion pyanaconda/modules/boss/module_manager/start_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def _start_service_by_name_handler(self, call, observer):
returned = call()
except Exception as error: # pylint: disable=broad-except
raise UnavailableModuleError(
"Service {} has failed to start: {}".format(observer, error)
f"Service {observer} has failed to start: {error}"
) from error

if returned != DBUS_START_REPLY_SUCCESS:
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/modules/common/structures/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __repr__(self):
return super().__repr__()

# Don't list attributes if none of them are set.
return "{}()".format(self.__class__.__name__)
return f"{self.__class__.__name__}()"


class RepoConfigurationData(DBusData):
Expand Down
4 changes: 2 additions & 2 deletions pyanaconda/modules/common/structures/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def to_structure_dict(cls, objects) -> Dict[Str, Structure]:
"""
if not isinstance(objects, dict):
raise TypeError(
"Invalid type '{}'.".format(type(objects).__name__)
f"Invalid type '{type(objects).__name__}'."
)

return {k: PasswordPolicy.to_structure(v) for k, v in objects.items()}
Expand All @@ -133,7 +133,7 @@ def from_structure_dict(cls, structures: Dict[Str, Structure]):
"""
if not isinstance(structures, dict):
raise TypeError(
"Invalid type '{}'.".format(type(structures).__name__)
f"Invalid type '{type(structures).__name__}'."
)

return {k: PasswordPolicy.from_structure(v) for k, v in structures.items()}
6 changes: 1 addition & 5 deletions pyanaconda/modules/common/task/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,7 @@ def _generate_thread_name(cls):
"""Generate the name of the thread."""
cls._thread_counter += 1

return "{}-{}-{}".format(
THREAD_DBUS_TASK,
cls.__name__,
cls._thread_counter
)
return f"{THREAD_DBUS_TASK}-{cls.__name__}-{cls._thread_counter}"


class ValidationTask(Task):
Expand Down
8 changes: 4 additions & 4 deletions pyanaconda/modules/localization/installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ def _write_language_configuration(self, lang):
log.debug("Writing the '%s' locale to %s.", lang, fpath)

with open(fpath, "w") as fobj:
fobj.write('LANG="{}"\n'.format(lang))
fobj.write(f'LANG="{lang}"\n')

except OSError as e:
msg = "Cannot write language configuration file: {}".format(e.strerror)
msg = f"Cannot write language configuration file: {e.strerror}"
raise LanguageInstallationError(msg) from e


Expand Down Expand Up @@ -203,7 +203,7 @@ def write_x_configuration(localed_wrapper, x_layouts, switch_options, x_conf_dir
if not os.path.isdir(rooted_xconf_dir):
os.makedirs(rooted_xconf_dir)
except OSError:
errors.append("Cannot create directory {}".format(rooted_xconf_dir))
errors.append(f"Cannot create directory {rooted_xconf_dir}")

# Copy the file to the chroot.
xconf_file_path = os.path.normpath(x_conf_dir_path + "/" + X_CONF_FILE_NAME)
Expand Down Expand Up @@ -247,5 +247,5 @@ def write_vc_configuration(vc_keymap, root):
fobj.write('FONT="%s"\n' % vc_font)

except OSError as e:
msg = "Cannot write vconsole configuration file: {}".format(e.strerror)
msg = f"Cannot write vconsole configuration file: {e.strerror}"
raise KeyboardInstallationError(msg) from e
2 changes: 1 addition & 1 deletion pyanaconda/modules/network/config_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_config_files_content(root_path=""):
"""Get content of all network device config files."""
fragments = []
for file_path in get_config_files_paths(root_path):
fragments.append("{}:".format(file_path))
fragments.append(f"{file_path}:")
with open(file_path, "r") as f:
fragments.append(f.read().strip("\n"))
return "\n".join(fragments)
Expand Down
2 changes: 1 addition & 1 deletion pyanaconda/modules/network/device_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def __str__(self):
return str(self._device_configurations)

def __repr__(self):
return "DeviceConfigurations({})".format(self.nm_client)
return f"DeviceConfigurations({self.nm_client})"


def is_libvirt_device(iface):
Expand Down
12 changes: 5 additions & 7 deletions pyanaconda/modules/network/installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def name(self):
def run(self):
_write_config_file(
self._sysroot, self.HOSTNAME_CONF_FILE_PATH,
"{}\n".format(self._hostname),
f"{self._hostname}\n",
"Cannot write hostname configuration file",
self._overwrite
)
Expand All @@ -89,7 +89,7 @@ def _write_config_file(root, path, content, error_msg, overwrite):
with open(fpath, "w") as fobj:
fobj.write(content)
except OSError as e:
msg = "{}: {}".format(error_msg, e.strerror)
msg = f"{error_msg}: {e.strerror}"
raise NetworkInstallationError(msg) from e


Expand Down Expand Up @@ -166,8 +166,7 @@ def _write_sysconfig_network(self, root, overwrite):
"""
return _write_config_file(root, self.SYSCONF_NETWORK_FILE_PATH,
"# Created by anaconda\n",
"Cannot write {} configuration file".format(
self.SYSCONF_NETWORK_FILE_PATH),
f"Cannot write {self.SYSCONF_NETWORK_FILE_PATH} configuration file",
overwrite)

def _write_interface_rename_config(self, root, ifname_option_values, overwrite):
Expand All @@ -193,8 +192,7 @@ def _write_interface_rename_config(self, root, ifname_option_values, overwrite):
root,
config_file_path,
content,
"Cannot write {} configuration file for ifname={} option.".format(
config_file_path, ifname_value),
f"Cannot write {config_file_path} configuration file for ifname={ifname_value} option.",
overwrite
)

Expand All @@ -212,7 +210,7 @@ def _disable_ipv6_on_system(self, root):
f.write("net.ipv6.conf.default.disable_ipv6=1\n")

except OSError as e:
msg = "Cannot disable ipv6 on the system: {}".format(e.strerror)
msg = f"Cannot disable ipv6 on the system: {e.strerror}"
raise NetworkInstallationError(msg) from e

def _copy_file_to_root(self, root, config_file, overwrite=False, follow_symlinks=True):
Expand Down
3 changes: 1 addition & 2 deletions pyanaconda/modules/network/kickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def parse(self, args):
if retval.hostname:
(result, reason) = is_valid_hostname(retval.hostname)
if not result:
message = "Hostname '{}' given in network kickstart command is invalid: {}"\
.format(retval.hostname, reason)
message = f"Hostname '{retval.hostname}' given in network kickstart command is invalid: {reason}"
raise KickstartParseError(message, lineno=self.lineno)

return retval
Expand Down
Loading

0 comments on commit d839e12

Please sign in to comment.