changeset 138:b883f4ef1967

Indirectly map extensions to configuration file styles
author Franz Glasner <hg@dom66.de>
date Fri, 06 Apr 2018 09:42:17 +0200
parents e84870359e1a
children c87b0dc54e1d
files configmix/__init__.py
diffstat 1 files changed, 35 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/configmix/__init__.py	Thu Apr 05 09:42:23 2018 +0200
+++ b/configmix/__init__.py	Fri Apr 06 09:42:17 2018 +0200
@@ -58,21 +58,43 @@
         return Configuration(ex)
 
 
+def _load_yaml(filename):
+    from . import yaml
+    with open(filename, "rb") as yf:
+        return yaml.safe_load(yf)
+
+
+def _load_json(filename):
+    from . import json
+    return json.load(filename)
+
+
+def _load_py(filename):
+    from . import py
+    return py.load(filename)
+
+
+def _load_ini(filename):
+    from . import ini
+    return ini.load(filename)
+
+
+_loaders = {
+    ".yml": _load_yaml,
+    ".yaml": _load_yaml,
+    ".json": _load_json,
+    ".py": _load_py,
+    ".ini": _load_ini
+}
+
+
 def _load_cfg_from_file(filename):
     fnl = filename.lower()
-    if fnl.endswith(".yml") or fnl.endswith("yaml"):
-        from . import yaml
-        with open(filename, "rb") as yf:
-            return yaml.safe_load(yf)
-    elif fnl.endswith(".json"):
-        from . import json
-        return json.load(filename)
-    elif fnl.endswith(".py"):
-        from . import py
-        return py.load(filename)
-    elif fnl.endswith(".ini"):
-        from . import ini
-        return ini.load(filename)
+    extensions = list(_loaders.keys())
+    extensions.sort(key=lambda x: len(x), reverse=True)
+    for ext in extensions:
+        if fnl.endswith(ext):
+            return _loaders[ext](filename)
     else:
         raise ValueError("Unknown configuration file type for filename "
                          "%r" % filename)