diff options
author | Aaron LI <aaronly.me@outlook.com> | 2016-10-15 12:48:31 +0800 |
---|---|---|
committer | Aaron LI <aaronly.me@outlook.com> | 2016-10-15 12:48:31 +0800 |
commit | b73527b90b51c659cfa665b268b67d4eb6a776d4 (patch) | |
tree | ac425da9dfcdc8a7ba4b4fe7d2e37701bd9e0123 | |
parent | 1ea04bfcbf6e4fcb1fe63dfc26f90a4ae8468d28 (diff) | |
download | fg21sim-b73527b90b51c659cfa665b268b67d4eb6a776d4.tar.bz2 |
configs: Switch to use `pkg_resources` to access config specs
After this switch to `pkg_resources`, this package can also be installed
as an EGG (a zip archive), which is more generic.
References:
* http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access
* http://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
-rw-r--r-- | fg21sim/configs/manager.py | 29 |
1 files changed, 19 insertions, 10 deletions
diff --git a/fg21sim/configs/manager.py b/fg21sim/configs/manager.py index 0250591..a446057 100644 --- a/fg21sim/configs/manager.py +++ b/fg21sim/configs/manager.py @@ -11,9 +11,9 @@ Configuration manager. import os import sys -from glob import glob import logging from functools import reduce +import pkg_resources from configobj import ConfigObj, ConfigObjError, flatten_errors from validate import Validator @@ -21,10 +21,25 @@ from validate import Validator from ..errors import ConfigError -CONFIGS_PATH = os.path.dirname(__file__) logger = logging.getLogger(__name__) +def _get_configspec(): + """Found and read all the configuration specifications""" + files = sorted(pkg_resources.resource_listdir(__name__, "")) + specfiles = filter(lambda fn: fn.endswith(".conf.spec"), files) + if os.environ.get("DEBUG_FG21SIM"): + print("DEBUG: Found config specifications: %s" % ", ".join(specfiles), + file=sys.stderr) + # NOTE: + # `resource_string()` returns the resource in *binary/bytes* string + configspec = "\n".join([ + pkg_resources.resource_string(__name__, fn).decode("utf-8") + for fn in specfiles + ]).split("\n") + return configspec + + class ConfigManager: """Manager the configurations""" def __init__(self, configs=None): @@ -36,18 +51,12 @@ class ConfigManager: configs: list (of config files) (optional) list of user config files to be merged """ - configs_spec = sorted(glob(os.path.join(CONFIGS_PATH, "*.conf.spec"))) - if os.environ.get("DEBUG_FG21SIM"): - print("Found config specifications: %s" % ", ".join(configs_spec), - file=sys.stderr) - spec = "\n".join([open(f).read() for f in configs_spec]).split("\n") - self._configspec = ConfigObj(spec, interpolation=False, + configspec = _get_configspec() + self._configspec = ConfigObj(configspec, interpolation=False, list_values=False, _inspec=True) configs_default = ConfigObj(interpolation=False, configspec=self._configspec) self._config = self._validate(configs_default) - logger.info("Loaded default configs with specification: {0}".format( - ", ".join(configs_spec))) if configs: for config in configs: self.read_config(config) |