add '--config-yaml' option

(#8)
pull/13/head
Mike Fährmann 8 years ago
parent 379125746a
commit 0cfe51dc78
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88

@ -70,6 +70,11 @@ def build_cmdline_parser():
metavar="CFG", dest="cfgfiles", action="append", metavar="CFG", dest="cfgfiles", action="append",
help="additional configuration files", help="additional configuration files",
) )
parser.add_argument(
"--config-yaml",
metavar="CFG", dest="yamlfiles", action="append",
help="additional configuration files (YAML format)",
)
parser.add_argument( parser.add_argument(
"-o", "--option", "-o", "--option",
metavar="OPT", action="append", default=[], metavar="OPT", action="append", default=[],
@ -139,6 +144,8 @@ def main():
if args.cfgfiles: if args.cfgfiles:
config.load(*args.cfgfiles, strict=True) config.load(*args.cfgfiles, strict=True)
if args.yamlfiles:
config.load(*args.yamlfiles, format="yaml", strict=True)
if args.dest: if args.dest:
config.set(("base-directory",), args.dest) config.set(("base-directory",), args.dest)

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright 2015, 2016 Mike Fährmann # Copyright 2015-2017 Mike Fährmann
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as # it under the terms of the GNU General Public License version 2 as
@ -11,27 +11,42 @@
import sys import sys
import json import json
import os.path import os.path
import logging
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# public interface # public interface
def load(*files, strict=False): def load(*files, format="json", strict=False):
"""Load JSON configuration files""" """Load JSON configuration files"""
log = logging.getLogger("config")
configfiles = files or _default_configs configfiles = files or _default_configs
if format == "yaml":
try:
import yaml
parsefunc = yaml.safe_load
except ImportError:
log.error("Could not import 'yaml' module")
return
else:
parsefunc = json.load
for conf in configfiles: for conf in configfiles:
try: try:
path = os.path.expanduser(os.path.expandvars(conf)) path = os.path.expanduser(os.path.expandvars(conf))
with open(path) as file: with open(path) as file:
confdict = json.load(file) confdict = parsefunc(file)
_config.update(confdict) _config.update(confdict)
except FileNotFoundError: except FileNotFoundError:
if strict: if strict:
raise log.error("Configuration file '%s' not found", path)
continue sys.exit(1)
except ValueError as exception: except Exception as exception:
print("Error while loading '", path, "':", sep="", file=sys.stderr) log.warning("Could not parse '%s'", path)
print(exception, file=sys.stderr) log.warning(exception)
if strict:
sys.exit(2)
def clear(): def clear():

Loading…
Cancel
Save