From cecd6946ff61b776d7ceca01c1d43b9441e5470e Mon Sep 17 00:00:00 2001 From: "Gerd v. Egidy" Date: Sun, 22 May 2022 15:49:10 +0200 Subject: [PATCH] sysrescue-autorun: improve type casting for booleans The recently implemented type casting code doesn't work intuitively for booleans: for example it treats a string "0" as False and doesn't show an error message for it. So the user might be unaware of this. So add a dedicated conversion function for booleans. Also add checks for conversions from dicts and lists, forbid to cast them to strings because that is most probably not what the user wants. --- .../etc/systemd/scripts/sysrescue-autorun | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/airootfs/etc/systemd/scripts/sysrescue-autorun b/airootfs/etc/systemd/scripts/sysrescue-autorun index 4fea826..960d0af 100755 --- a/airootfs/etc/systemd/scripts/sysrescue-autorun +++ b/airootfs/etc/systemd/scripts/sysrescue-autorun @@ -124,12 +124,36 @@ def search_autoruns(dirname, suffixes, copyfilefct): found+=1 return found +def strtobool (val): + """Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + + Function adapted from Pythons distutils.util.py because it will be deprecated soon + Copyright (c) Python Software Foundation; All Rights Reserved + """ + val = str(val).lower() + if val in ('y', 'yes', 't', 'true', 'on', '1'): + return True + elif val in ('n', 'no', 'f', 'false', 'off', '0'): + return False + else: + raise ValueError("invalid truth value %r" % (val,)) + def read_cfg_value(name, defaultval): if name in config: + chkval = config[name] try: - val = type(defaultval)(config[name]) + if isinstance(chkval, list) or isinstance(chkval, dict): + raise TypeError(f"must be a {type(defaultval)}, not a {type(chkval)}") + elif isinstance(defaultval, bool) and not isinstance(chkval, bool): + val = strtobool(chkval) + else: + val = type(defaultval)(chkval) except (TypeError, ValueError) as e: - writemsg(f"{name} with {config[name]} is not the same type as defaultval: {e}") + writemsg(f"config['{name}'] with {chkval} is not the same type as defaultval: {e}") val = defaultval else: val = defaultval