Skip to content

Commit

Permalink
chore: Update code to adhere to Ruff rules
Browse files Browse the repository at this point in the history
Take care of all the errors reported by Ruff with the current
rules that are in place. This also takes care of percent-string
formatting and replaces it with PyFormat.

Signed-off-by: Freya Gustavsson <[email protected]>
  • Loading branch information
Venefilyn committed Sep 24, 2024
1 parent dfd5207 commit 3b13167
Show file tree
Hide file tree
Showing 101 changed files with 628 additions and 618 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Below are a list of things to keep in mind when developing and submitting
contributions to this repository.

1. All python code must be compatible with versions 2.7/3.6.
2. The code should follow linting from pylint.
2. The code should follow linting from ruff.
3. All commits should have passed the pre-commit checks.
4. Don't change code that is not related to your issue/ticket, open a new
issue/ticket if that's the case.
Expand Down
37 changes: 20 additions & 17 deletions convert2rhel/actions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ class Action:
# @property
# @abc.abstractmethod
# def id(self):
@abc.abstractproperty # pylint: disable=deprecated-decorator
@abc.abstractproperty
def id(self):
"""
This should be replaced by a simple class attribute.
Expand Down Expand Up @@ -203,7 +203,7 @@ def run(self):
instead.
"""
if self._has_run:
raise ActionError("Action %s has already run" % self.id)
raise ActionError("Action {} has already run".format(self.id))

self._has_run = True

Expand Down Expand Up @@ -324,7 +324,7 @@ def __hash__(self):
return hash((self.level, self.id, self.title, self.description, self.diagnosis, self.remediations))

def __repr__(self):
return "%s(level=%s, id=%s, title=%s, description=%s, diagnosis=%s, remediations=%s, variables=%s)" % (
return "{}(level={}, id={}, title={}, description={}, diagnosis={}, remediations={}, variables={})".format(
self.__class__.__name__,
_STATUS_NAME_FROM_CODE[self.level],
self.id,
Expand Down Expand Up @@ -364,7 +364,7 @@ def __init__(self, level="", id="", title="", description="", diagnosis="", reme
# None of the result status codes are legal as a message. So we error if any
# of them were given here.
if not (STATUS_CODE["SUCCESS"] < STATUS_CODE[level] < STATUS_CODE["SKIP"]):
raise InvalidMessageError("Invalid level '%s', set for a non-result message" % level)
raise InvalidMessageError("Invalid level '{}', set for a non-result message".format(level))

super(ActionMessage, self).__init__(level, id, title, description, diagnosis, remediations, variables)

Expand Down Expand Up @@ -392,7 +392,7 @@ def __init__(

elif STATUS_CODE["SUCCESS"] < STATUS_CODE[level] < STATUS_CODE["SKIP"]:
raise InvalidMessageError(
"Invalid level '%s', the level for result must be SKIP or more fatal or SUCCESS." % level
"Invalid level '{}', the level for result must be SKIP or more fatal or SUCCESS.".format(level)
)

super(ActionResult, self).__init__(level, id, title, description, diagnosis, remediations, variables)
Expand Down Expand Up @@ -520,10 +520,10 @@ def run(self, successes=None, failures=None, skips=None):
running is WARNING or better (WARNING or SUCCESS) and
failure as worse than WARNING (OVERRIDABLE, ERROR)
"""
logger.task("Prepare: %s" % self.task_header)
logger.task("Prepare: {}".format(self.task_header))

if self._has_run:
raise ActionError("Stage %s has already run." % self.stage_name)
raise ActionError("Stage {} has already run.".format(self.stage_name))
self._has_run = True

# Make a mutable copy of these parameters so we don't overwrite the caller's data.
Expand All @@ -548,7 +548,7 @@ def run(self, successes=None, failures=None, skips=None):
to_be = "was"
if len(failed_deps) > 1:
to_be = "were"
diagnosis = "Skipped because %s %s not successful" % (
diagnosis = "Skipped because {} {} not successful".format(
utils.format_sequence_as_message(failed_deps),
to_be,
)
Expand All @@ -559,12 +559,13 @@ def run(self, successes=None, failures=None, skips=None):
title="Skipped action",
description="This action was skipped due to another action failing.",
diagnosis=diagnosis,
remediations="Please ensure that the %s check passes so that this Action can evaluate your system"
% utils.format_sequence_as_message(failed_deps),
remediations="Please ensure that the {} check passes so that this Action can evaluate your system".format(
utils.format_sequence_as_message(failed_deps)
),
)
skips.append(action)
failed_action_ids.add(action.id)
logger.error("Skipped %s. %s" % (action.id, diagnosis))
logger.error("Skipped {}. {}".format(action.id, diagnosis))
continue

# Run the Action
Expand All @@ -574,18 +575,18 @@ def run(self, successes=None, failures=None, skips=None):
# Uncaught exceptions are handled by constructing a generic
# failure message here that should be reported
description = (
"Unhandled exception was caught: %s\n"
"Unhandled exception was caught: {}\n"
"Please file a bug at https://issues.redhat.com/ to have this"
" fixed or a specific error message added.\n"
"Traceback: %s" % (e, traceback.format_exc())
"Traceback: {}".format(e, traceback.format_exc())
)
action.set_result(
level="ERROR", id="UNEXPECTED_ERROR", title="Unhandled exception caught", description=description
)

# Categorize the results
if action.result.level <= STATUS_CODE["WARNING"]:
logger.info("%s has succeeded" % action.id)
logger.info("{} has succeeded".format(action.id))
successes.append(action)

if action.result.level > STATUS_CODE["WARNING"]:
Expand Down Expand Up @@ -687,7 +688,9 @@ def resolve_action_order(potential_actions, previously_resolved_actions=None):
# that there is a circular dependency that needs to be broken.
if previous_number_of_unresolved_actions != 0:
raise DependencyError(
"Unsatisfied dependencies in these actions: %s" % ", ".join(action.id for action in unresolved_actions)
"Unsatisfied dependencies in these actions: {}".format(
", ".join(action.id for action in unresolved_actions)
)
)


Expand Down Expand Up @@ -749,7 +752,7 @@ def run_pre_actions():
except DependencyError as e:
# We want to fail early if dependencies are not properly set. This
# way we should fail in testing before release.
logger.critical("Some dependencies were set on Actions but not present in convert2rhel: %s" % e)
logger.critical("Some dependencies were set on Actions but not present in convert2rhel: {}".format(e))

# Run the Actions in system_checks and all subsequent Stages.
results = system_checks.run()
Expand Down Expand Up @@ -778,7 +781,7 @@ def run_post_actions():
except DependencyError as e:
# We want to fail early if dependencies are not properly set. This
# way we should fail in testing before release.
logger.critical("Some dependencies were set on Actions but not present in convert2rhel: %s" % e)
logger.critical("Some dependencies were set on Actions but not present in convert2rhel: {}".format(e))

# Run the Actions in conversion and all subsequent Stages.
results = conversion.run()
Expand Down
9 changes: 5 additions & 4 deletions convert2rhel/actions/conversion/lock_releasever.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ def run(self):
)
return
loggerinst.info(
"Updating /etc/yum.repos.d/rehat.repo to point to RHEL %s instead of the default latest minor version."
% system_info.releasever
"Updating /etc/yum.repos.d/rehat.repo to point to RHEL {} instead of the default latest minor version.".format(
system_info.releasever
)
)
cmd = [
"subscription-manager",
"release",
"--set=%s" % system_info.releasever,
"--set={}".format(system_info.releasever),
]
_, ret_code = utils.run_subprocess(cmd, print_output=False)
if ret_code != 0:
loggerinst.warning("Locking RHEL repositories failed.")
return
loggerinst.info("RHEL repositories locked to the %s minor version." % system_info.releasever)
loggerinst.info("RHEL repositories locked to the {} minor version.".format(system_info.releasever))
20 changes: 10 additions & 10 deletions convert2rhel/actions/conversion/preserve_only_rhel_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def run(self):

# Solution for RHELC-1707
# Update is needed in the UpdateKernel action
global _kernel_update_needed # pylint: disable=global-statement
global _kernel_update_needed

loggerinst.info("Installing RHEL kernel ...")
output, ret_code = pkgmanager.call_yum_cmd(command="install", args=["kernel"])
Expand Down Expand Up @@ -85,7 +85,7 @@ def run(self):
"We will try to install a lower version of the package,\n"
"remove the conflicting kernel and then update to the latest security patched version."
)
loggerinst.info("\n%s" % info_message)
loggerinst.info("\n{}".format(info_message))
pkghandler.handle_no_newer_rhel_kernel_available()
_kernel_update_needed = True

Expand All @@ -102,10 +102,10 @@ def run(self):
("non-RHEL kernel", non_rhel_kernels)
)
loggerinst.debug(
"Latest installed kernel version from the original vendor: %s" % latest_installed_non_rhel_kernel
"Latest installed kernel version from the original vendor: {}".format(latest_installed_non_rhel_kernel)
)
latest_installed_rhel_kernel = pkghandler.get_highest_package_version(("RHEL kernel", rhel_kernels))
loggerinst.debug("Latest installed RHEL kernel version: %s" % latest_installed_rhel_kernel)
loggerinst.debug("Latest installed RHEL kernel version: {}".format(latest_installed_rhel_kernel))
is_rhel_kernel_higher = pkghandler.compare_package_versions(
latest_installed_rhel_kernel, latest_installed_non_rhel_kernel
)
Expand Down Expand Up @@ -180,7 +180,7 @@ def run(self):
for entry in boot_entries:
# The boot loader entries in /boot/loader/entries/<machine-id>-<kernel-version>.conf
if machine_id not in os.path.basename(entry):
loggerinst.debug("Removing boot entry %s" % entry)
loggerinst.debug("Removing boot entry {}".format(entry))
os.remove(entry)

# Removing a boot entry that used to be the default makes grubby to choose a different entry as default,
Expand All @@ -189,7 +189,7 @@ def run(self):
if ret_code:
# Not setting the default entry shouldn't be a deal breaker and the reason to stop the conversions,
# grub should pick one entry in any case.
description = "Couldn't get the default GRUB2 boot loader entry:\n%s" % output
description = "Couldn't get the default GRUB2 boot loader entry:\n{}".format(output)
loggerinst.warning(description)
self.add_message(
level="WARNING",
Expand All @@ -198,10 +198,10 @@ def run(self):
description=description,
)
return
loggerinst.debug("Setting RHEL kernel %s as the default boot loader entry." % output.strip())
loggerinst.debug("Setting RHEL kernel {} as the default boot loader entry.".format(output.strip()))
output, ret_code = utils.run_subprocess(["/usr/sbin/grubby", "--set-default", output.strip()])
if ret_code:
description = "Couldn't set the default GRUB2 boot loader entry:\n%s" % output
description = "Couldn't set the default GRUB2 boot loader entry:\n{}".format(output)
loggerinst.warning(description)
self.add_message(
level="WARNING",
Expand Down Expand Up @@ -246,7 +246,7 @@ def run(self):

kernel_sys_cfg = kernel_sys_cfg.replace("DEFAULTKERNEL=" + kernel_to_change, new_kernel_str)
utils.store_content_to_file("/etc/sysconfig/kernel", kernel_sys_cfg)
loggerinst.info("Boot kernel %s was changed to %s" % (kernel_to_change, new_kernel_str))
loggerinst.info("Boot kernel {} was changed to {}".format(kernel_to_change, new_kernel_str))
else:
loggerinst.debug("Boot kernel validated.")

Expand Down Expand Up @@ -288,7 +288,7 @@ def install_additional_rhel_kernel_pkgs(self, additional_pkgs):
pkg_names = [p.nevra.name.replace(ol_kernel_ext, "", 1) for p in additional_pkgs]
for name in set(pkg_names):
if name != "kernel":
loggerinst.info("Installing RHEL %s" % name)
loggerinst.info("Installing RHEL {}".format(name))
pkgmanager.call_yum_cmd("install", args=[name])


Expand Down
27 changes: 15 additions & 12 deletions convert2rhel/actions/conversion/set_efi_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ def run(self):
for filename in grub.DEFAULT_INSTALLED_EFIBIN_FILENAMES:
efi_path = os.path.join(RHEL_EFIDIR_CANONICAL_PATH, filename)
if os.path.exists(efi_path):
logger.info("UEFI binary found: %s" % efi_path)
logger.info("UEFI binary found: {}".format(efi_path))
new_default_efibin = efi_path
break
logger.debug("UEFI binary %s not found. Checking next possibility..." % efi_path)
logger.debug("UEFI binary {} not found. Checking next possibility...".format(efi_path))
missing_binaries.append(efi_path)
if not new_default_efibin:
self.set_result(
Expand All @@ -65,9 +65,9 @@ def run(self):
remediations=(
"Verify the bootloader configuration as follows and reboot the system."
" Ensure that `grubenv` and `grub.cfg` files"
" are present in the %s directory. Verify that `efibootmgr -v`"
" are present in the {} directory. Verify that `efibootmgr -v`"
" shows a bootloader entry for Red Hat Enterprise Linux"
" that points to to '\\EFI\\redhat\\shimx64.efi'." % grub.RHEL_EFIDIR_CANONICAL_PATH
" that points to to '\\EFI\\redhat\\shimx64.efi'.".format(grub.RHEL_EFIDIR_CANONICAL_PATH)
),
)

Expand Down Expand Up @@ -125,7 +125,7 @@ def run(self):
# TODO(pstodulk): check behaviour for efibin from a different dir or with a different name for the possibility of
# the different grub content...
# E.g. if the efibin is located in a different directory, are these two files valid?
logger.info("Moving GRUB2 configuration files to the new UEFI directory %s." % RHEL_EFIDIR_CANONICAL_PATH)
logger.info("Moving GRUB2 configuration files to the new UEFI directory {}.".format(RHEL_EFIDIR_CANONICAL_PATH))
src_files = [
os.path.join(CENTOS_EFIDIR_CANONICAL_PATH, filename) for filename in ["grubenv", "grub.cfg", "user.cfg"]
]
Expand Down Expand Up @@ -154,20 +154,22 @@ def run(self):
# Skip non-existing file in destination directory
if not os.path.exists(src_file):
logger.debug(
"The %s file does not exist in %s folder. Moving skipped."
% (os.path.basename(src_file), CENTOS_EFIDIR_CANONICAL_PATH)
"The {} file does not exist in {} folder. Moving skipped.".format(
os.path.basename(src_file), CENTOS_EFIDIR_CANONICAL_PATH
)
)
continue
# Skip already existing file in destination directory
dst_file = os.path.join(RHEL_EFIDIR_CANONICAL_PATH, os.path.basename(src_file))
if os.path.exists(dst_file):
logger.debug(
"The %s file already exists in %s folder. Moving skipped."
% (os.path.basename(src_file), RHEL_EFIDIR_CANONICAL_PATH)
"The {} file already exists in {} folder. Moving skipped.".format(
os.path.basename(src_file), RHEL_EFIDIR_CANONICAL_PATH
)
)
continue

logger.info("Moving '%s' to '%s'" % (src_file, dst_file))
logger.info("Moving '{}' to '{}'".format(src_file, dst_file))

try:
shutil.move(src_file, dst_file)
Expand All @@ -178,8 +180,9 @@ def run(self):
id="GRUB_FILES_NOT_MOVED_TO_BOOT_DIRECTORY",
title="GRUB files have not been moved to boot directory",
description=(
"I/O error(%s): '%s'. Some GRUB files have not been moved to /boot/efi/EFI/redhat."
% (err.errno, err.strerror)
"I/O error({}): '{}'. Some GRUB files have not been moved to /boot/efi/EFI/redhat.".format(
err.errno, err.strerror
)
),
)

Expand Down
6 changes: 3 additions & 3 deletions convert2rhel/actions/post_conversion/hostmetering.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def _check_env_var(self):
return False

if self.env_var not in ("force", "auto"):
logger.debug("Value for environment variable not recognized: %s" % self.env_var)
logger.debug("Value for environment variable not recognized: {}".format(self.env_var))
self.add_message(
level="WARNING",
id="UNRECOGNIZED_OPTION_CONFIGURE_HOST_METERING",
Expand Down Expand Up @@ -221,7 +221,7 @@ def _enable_host_metering_service(self):
command = ["systemctl", "enable", "host-metering.service"]
output, ret_enable = run_subprocess(command)
if output:
logger.debug("Output of systemctl call: %s" % output)
logger.debug("Output of systemctl call: {}".format(output))
if ret_enable:
logger.warning("Failed to enable host-metering service.")
return " ".join(command), output
Expand All @@ -230,7 +230,7 @@ def _enable_host_metering_service(self):
command = ["systemctl", "start", "host-metering.service"]
output, ret_start = run_subprocess(command)
if output:
logger.debug("Output of systemctl call: %s" % output)
logger.debug("Output of systemctl call: {}".format(output))
if ret_start:
logger.warning("Failed to start host-metering service.")
return " ".join(command), output
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,15 @@ def run(self):

if modified_rpm_files_diff:
logger.info(
"Comparison of modified rpm files from before and after the conversion:\n%s" % modified_rpm_files_diff
"Comparison of modified rpm files from before and after the conversion:\n{}".format(
modified_rpm_files_diff
)
)
self.add_message(
level="INFO",
id="FOUND_MODIFIED_RPM_FILES",
title="Modified rpm files from before and after the conversion were found.",
description="Comparison of modified rpm files from before and after "
"the conversion: \n%s" % modified_rpm_files_diff,
description="Comparison of modified rpm files from before and after " "the conversion: \n{}".format(
modified_rpm_files_diff
),
)
Loading

0 comments on commit 3b13167

Please sign in to comment.