|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# @Author: José Sánchez-Gallego (gallegoj@uw.edu) |
| 5 | +# @Date: 2019-05-08 |
| 6 | +# @Filename: configuration.py |
| 7 | +# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) |
| 8 | +# |
| 9 | +# @Last modified by: José Sánchez-Gallego (gallegoj@uw.edu) |
| 10 | +# @Last modified time: 2019-05-09 10:44:49 |
| 11 | + |
| 12 | +import os |
| 13 | + |
| 14 | +import yaml |
| 15 | +from pkg_resources import parse_version |
| 16 | + |
| 17 | + |
| 18 | +__all__ = ['get_config'] |
| 19 | + |
| 20 | + |
| 21 | +def merge_config(user, default): |
| 22 | + """Merges a user configuration with the default one.""" |
| 23 | + |
| 24 | + if isinstance(user, dict) and isinstance(default, dict): |
| 25 | + for kk, vv in default.items(): |
| 26 | + if kk not in user: |
| 27 | + user[kk] = vv |
| 28 | + else: |
| 29 | + user[kk] = merge_config(user[kk], vv) |
| 30 | + |
| 31 | + return user |
| 32 | + |
| 33 | + |
| 34 | +def get_config(name, allow_user=True, user_path=None, config_envvar=None, |
| 35 | + merge_mode='update'): |
| 36 | + """Returns a configuration dictionary. |
| 37 | +
|
| 38 | + The configuration dictionary is created by merging the default |
| 39 | + configuration file that is part of the library (in ``etc/<name>.yml``) |
| 40 | + with a user configuration file. The path to the user configuration file |
| 41 | + can be defined as an environment variable to be passed to this function |
| 42 | + in ``config_envvar`` or as a path in ``user_path``. The environment |
| 43 | + variable, if exists, always takes precedence. |
| 44 | +
|
| 45 | + Parameters |
| 46 | + ---------- |
| 47 | + name : str |
| 48 | + The name of the package. |
| 49 | + allow_user : bool |
| 50 | + If `True`, looks for an user configuration file and merges is to the |
| 51 | + default configuration. Otherwise it returns just the default |
| 52 | + configuration. |
| 53 | + user_path : str |
| 54 | + The path to the user configuration file. Defaults to |
| 55 | + ``~/.config/<name>/<name>.yml``. Ignored if the file does not exist. |
| 56 | + config_envvar : str |
| 57 | + The environment variable that contains the path to the user |
| 58 | + configuration file. Defaults to ``<name>_CONFIG_PATH``. If the |
| 59 | + environment variable exists, the ``user_path`` is ignored. |
| 60 | + merge_mode : str |
| 61 | + Defines how the default and user dictionaries will be merged. If |
| 62 | + ``update``, the user dictionary will be used to update the default |
| 63 | + configuration. If ``replace``, only the user configuration will be |
| 64 | + returned. |
| 65 | +
|
| 66 | + Returns |
| 67 | + ------- |
| 68 | + config : dict |
| 69 | + A dictionary containing the configuration. |
| 70 | +
|
| 71 | + """ |
| 72 | + |
| 73 | + assert merge_mode in ['update', 'replace'], 'invalid merge mode.' |
| 74 | + |
| 75 | + yaml_kwds = dict() |
| 76 | + if parse_version(yaml.__version__) >= parse_version('5.1'): |
| 77 | + yaml_kwds.update(Loader=yaml.FullLoader) |
| 78 | + |
| 79 | + # Loads config |
| 80 | + config_path = os.path.join(os.path.dirname(__file__), '../etc/{0}.yml'.format(name)) |
| 81 | + with open(config_path, 'r') as fp: |
| 82 | + config = yaml.load(fp, **yaml_kwds) |
| 83 | + |
| 84 | + if allow_user is False: |
| 85 | + return config |
| 86 | + |
| 87 | + config_envvar = config_envvar or '{}_CONFIG_PATH'.format(name.upper()) |
| 88 | + |
| 89 | + if user_path is not None: |
| 90 | + user_path = os.path.expanduser(os.path.expandvars(user_path)) |
| 91 | + else: |
| 92 | + user_path = os.path.expanduser('~/.config/{0}/{0}.yml'.format(name)) |
| 93 | + |
| 94 | + if config_envvar in os.environ: |
| 95 | + custom_config_fn = os.environ[config_envvar] |
| 96 | + elif os.path.exists(user_path): |
| 97 | + custom_config_fn = user_path |
| 98 | + else: |
| 99 | + return config |
| 100 | + |
| 101 | + with open(custom_config_fn, 'r') as fp: |
| 102 | + user_config = yaml.load(fp, **yaml_kwds) |
| 103 | + |
| 104 | + if merge_mode == 'update': |
| 105 | + return merge_config(user_config, config) |
| 106 | + else: |
| 107 | + return user_config |
0 commit comments