From c3f126eaa6515be3b5c4c5cba619c1b354e48113 Mon Sep 17 00:00:00 2001 From: Yann Dirson Date: Wed, 4 Oct 2023 14:48:31 +0200 Subject: [PATCH] findXenSourceBackups: refactor and log reason for ignoring Previous code structure was that of 2 nested if's, with nominal code path being in the positive branch of each if. Adding another condition will bring a need for logging the reason to ignore a backup, but doing that by converting inner `if` to an `elif` chain (arguably the simplest modification) would bring the nominal code path to switch to the negative/last branch of the inner `elif` chain. At the same time, the outer `if` would not seem special enough to deserve it special place (and the cyclomatic complexity). This commit leverages the existing `try:except:` block to switch to an "error out the loop" pattern, where the nominal code path is just linear. Using `StopIteration` may feel like an abuse, but: - it is the only standard `Exception` that is not a `StandardError` or a `Warning`, and defining a new one could seem overkill - the closest alternative would be a `while True` loop and breaking out in both exceptional code paths and at the end of nominal path, where the `break` statements would "stop the iteration" as well Signed-off-by: Yann Dirson --- product.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/product.py b/product.py index 61eb0c99..0a919365 100644 --- a/product.py +++ b/product.py @@ -534,12 +534,25 @@ def findXenSourceBackups(): b = None try: b = util.TempMount(p, 'backup-', ['ro'], 'ext3') - if os.path.exists(os.path.join(b.mount_point, '.xen-backup-partition')): - backup = XenServerBackup(p, b.mount_point) - logger.log("Found a backup: %s" % (repr(backup),)) - if backup.version >= XENSERVER_MIN_VERSION and \ - backup.version <= THIS_PLATFORM_VERSION: - backups.append(backup) + if not os.path.exists(os.path.join(b.mount_point, '.xen-backup-partition')): + raise StopIteration() + + backup = XenServerBackup(p, b.mount_point) + logger.log("Found a backup: %s" % (repr(backup),)) + + if backup.version < XENSERVER_MIN_VERSION: + logger.log("findXenSourceBackups: ignoring, platform too old: %s < %s" % + (backup.version, XENSERVER_MIN_VERSION)) + raise StopIteration() + if backup.version > THIS_PLATFORM_VERSION: + logger.log("findXenSourceBackups: ignoring later platform: %s > %s" % + (backup.version, THIS_PLATFORM_VERSION)) + raise StopIteration() + + backups.append(backup) + + except StopIteration: + pass except Exception as ex: logger.log("findXenSourceBackups caught exception for partition %s: %s" % (p, ex)) pass