Convert cnfvar names to lowercase on json import
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 31 Jan 2019 13:10:20 +0000 (14:10 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 7 Feb 2019 15:10:53 +0000 (16:10 +0100)
read_cnf already converts all variable names to lower case. Do the same for
read_cnf_json to get consistent behaviour. SimpleCnf already relies on this.

src/cnfvar.py

index 483a96f..ffd967d 100644 (file)
@@ -267,6 +267,27 @@ def count_vars (root):
 
 # the easy part: JSON reader for get_cnf -j
 
+def make_varname_lowercase(cnfvar):
+    """
+    Custom hook for json decoder: convert variable name to lowercase.
+
+    Since variable names are case insensitive, :py:func:`read_cnf` converts
+    them all to lower case. Downstream users of :py:func:`read_cnf_json` (e.g.
+    :py:class:`simple_cnf.SimpleCnf`) rely on lowercase variable names.
+
+    :param dict cnfvar: JSON "object" converted into a dict
+    :returns: same as input but if field `varname` is present, its value is
+              converted to lower case
+    :rtype: dict with str keys
+    """
+    try:
+        cnfvar['varname'] = cnfvar['varname'].lower()
+    except KeyError:      # there is no "varname" field
+        pass
+    except AttributeError:   # cnfvar['varname'] is not a string
+        pass
+    return cnfvar
+
 
 def read_cnf_json(cnfdata):
     """
@@ -280,7 +301,7 @@ def read_cnf_json(cnfdata):
         of Python 3 so we handle the decoding ourselves.
     """
     cnfdata = cnfdata.decode('iso-8859-1')
-    cnf_json = json.loads(cnfdata)
+    cnf_json = json.loads(cnfdata, object_hook=make_varname_lowercase)
     if is_cnf(cnf_json) is False:
         raise TypeError("Invalid CNF_VAR.")
     return cnf_json