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.
This commit is contained in:
Gerd v. Egidy 2022-05-22 15:49:10 +02:00
parent afb77e30c5
commit cecd6946ff

View file

@ -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