]> www.average.org Git - loctrkd.git/blobdiff - loctrkd/termconfig.py
abstract protocol selection in `common`
[loctrkd.git] / loctrkd / termconfig.py
index b1ea80ae691bb1b93174c50b5d58d8150d9065fd..4968e28ee86cee6e6a46cd5a4fa8a2068d29457d 100644 (file)
@@ -1,9 +1,10 @@
 """ For when responding to the terminal is not trivial """
 
-from configparser import ConfigParser
+from configparser import ConfigParser, SectionProxy
 from datetime import datetime, timezone
 from logging import getLogger
 from struct import pack
+from typing import Any, Dict, List, Union
 import zmq
 
 from . import common
@@ -14,6 +15,34 @@ from .zmsg import Bcast, Resp, topic
 log = getLogger("loctrkd/termconfig")
 
 
+def normconf(section: SectionProxy) -> Dict[str, Any]:
+    result: Dict[str, Any] = {}
+    for key, val in section.items():
+        vals = val.split("\n")
+        if len(vals) > 1 and vals[0] == "":
+            vals = vals[1:]
+        lst: List[Union[str, int]] = []
+        for el in vals:
+            try:
+                lst.append(int(el, 0))
+            except ValueError:
+                if el[0] == '"' and el[-1] == '"':
+                    el = el.strip('"').rstrip('"')
+                lst.append(el)
+        if not (
+            all([isinstance(x, int) for x in lst])
+            or all([isinstance(x, str) for x in lst])
+        ):
+            raise ValueError(
+                "Values of %s - %s are of different type", key, vals
+            )
+        if len(lst) == 1:
+            result[key] = lst[0]
+        else:
+            result[key] = lst
+    return result
+
+
 def runserver(conf: ConfigParser) -> None:
     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
     zctx = zmq.Context()  # type: ignore
@@ -44,9 +73,9 @@ def runserver(conf: ConfigParser) -> None:
                     "%s does not expect externally provided response", msg
                 )
             if zmsg.imei is not None and conf.has_section(zmsg.imei):
-                termconfig = common.normconf(conf[zmsg.imei])
+                termconfig = normconf(conf[zmsg.imei])
             elif conf.has_section("termconfig"):
-                termconfig = common.normconf(conf["termconfig"])
+                termconfig = normconf(conf["termconfig"])
             else:
                 termconfig = {}
             kwargs = {}