Mercurial > hgrepos > Python > libs > ConfigMix
comparison configmix/__init__.py @ 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 | 21d92ff8cf31 |
| children | c87b0dc54e1d |
comparison
equal
deleted
inserted
replaced
| 137:e84870359e1a | 138:b883f4ef1967 |
|---|---|
| 56 for f in files[1:]: | 56 for f in files[1:]: |
| 57 ex = safe_merge(_load_cfg_from_file(f), ex) | 57 ex = safe_merge(_load_cfg_from_file(f), ex) |
| 58 return Configuration(ex) | 58 return Configuration(ex) |
| 59 | 59 |
| 60 | 60 |
| 61 def _load_yaml(filename): | |
| 62 from . import yaml | |
| 63 with open(filename, "rb") as yf: | |
| 64 return yaml.safe_load(yf) | |
| 65 | |
| 66 | |
| 67 def _load_json(filename): | |
| 68 from . import json | |
| 69 return json.load(filename) | |
| 70 | |
| 71 | |
| 72 def _load_py(filename): | |
| 73 from . import py | |
| 74 return py.load(filename) | |
| 75 | |
| 76 | |
| 77 def _load_ini(filename): | |
| 78 from . import ini | |
| 79 return ini.load(filename) | |
| 80 | |
| 81 | |
| 82 _loaders = { | |
| 83 ".yml": _load_yaml, | |
| 84 ".yaml": _load_yaml, | |
| 85 ".json": _load_json, | |
| 86 ".py": _load_py, | |
| 87 ".ini": _load_ini | |
| 88 } | |
| 89 | |
| 90 | |
| 61 def _load_cfg_from_file(filename): | 91 def _load_cfg_from_file(filename): |
| 62 fnl = filename.lower() | 92 fnl = filename.lower() |
| 63 if fnl.endswith(".yml") or fnl.endswith("yaml"): | 93 extensions = list(_loaders.keys()) |
| 64 from . import yaml | 94 extensions.sort(key=lambda x: len(x), reverse=True) |
| 65 with open(filename, "rb") as yf: | 95 for ext in extensions: |
| 66 return yaml.safe_load(yf) | 96 if fnl.endswith(ext): |
| 67 elif fnl.endswith(".json"): | 97 return _loaders[ext](filename) |
| 68 from . import json | |
| 69 return json.load(filename) | |
| 70 elif fnl.endswith(".py"): | |
| 71 from . import py | |
| 72 return py.load(filename) | |
| 73 elif fnl.endswith(".ini"): | |
| 74 from . import ini | |
| 75 return ini.load(filename) | |
| 76 else: | 98 else: |
| 77 raise ValueError("Unknown configuration file type for filename " | 99 raise ValueError("Unknown configuration file type for filename " |
| 78 "%r" % filename) | 100 "%r" % filename) |
| 79 | 101 |
| 80 | 102 |
