Unify the cnf reading API to bytes argument and returned str
authorPlamen Dimitrov <pdimitrov@pevogam.com>
Fri, 15 Jun 2018 18:02:44 +0000 (01:02 +0700)
committerPlamen Dimitrov <pdimitrov@pevogam.com>
Tue, 23 Oct 2018 07:22:19 +0000 (15:22 +0800)
Also fix byte usage in config preparation with the above assumption.

src/cnfvar.py

index 02ec34e..6b7c267 100644 (file)
@@ -263,6 +263,17 @@ def is_cnf(root):
 
 
 def read_cnf_json(cnfdata):
+    """
+    Read json data from cnf data bytes.
+
+    :param bytes cnfdata: config data
+    :return: the parsed json data
+    :rtype: str
+
+    .. note:: The JSON module does not decode data for all versions
+        of Python 3 so we handle the decoding ourselves.
+    """
+    cnfdata = cnfdata.decode('iso-8859-1')
     cnf_json = json.loads(cnfdata)
     if is_cnf(cnf_json) is False:
         raise TypeError("Invalid CNF_VAR.")
@@ -290,7 +301,7 @@ def advance(cns):
 
 def prepare(raw):
     """
-    :type raw: str
+    :type raw: bytes
     :rtype: (str * str option * str list) option
     """
     lines = raw.splitlines()
@@ -306,7 +317,7 @@ def prepare(raw):
         second = None
 
     first = first.strip()
-    if first == "":
+    if first == b"":
         return advance((first, second, lines))
 
     return (first, second, lines)
@@ -386,7 +397,7 @@ base_line_pattern = re.compile(b"""
 def read_base_line(line):
     if len(line.strip()) == 0:
         return None  # ignore empty lines
-    if line[0] == "#":
+    if line[0] == b"#":
         return None  # ignore comments
 
     match = re.match(base_line_pattern, line)
@@ -503,6 +514,13 @@ def parse_cnf_root(state):
 
 
 def read_cnf(data):
+    """
+    Read cnf data from data bytes.
+
+    :param bytes data: raw data
+    :return: the parsed cnf data
+    :rtype: {str, {str, str or int}}
+    """
     state = prepare(data)
     if state is None:
         raise InvalidCNF("Empty input string.")