Source code for vdat.config.core

"""Manage configuration

    Mostly copied from vhc/libvhc/config.py

"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import os
import warnings
import yaml

from pyhetdex.tools import configuration as confp
from pyhetdex.tools import six_ext
from six.moves import ExtendedInterpolation

# Public interface
__all__ = ["load_yaml", "load_std_conf", "load_all_configs", "get_config",
           "ConfigurationError", "MissingConfigurationError",
           "MissingConfigurationSectionError"]

_config_dic = {}


# exceptions

[docs]class ConfigurationError(Exception): """Generic error raised by the configuration sub-package""" pass
[docs]class MissingConfigurationError(ConfigurationError, KeyError): """Raised when a configuration item does not exist""" pass
[docs]class MissingConfigurationSectionError(ConfigurationError, KeyError): """Raised when a configuration section does not exist""" pass # functions
[docs]def load_yaml(name, *fnames): """Load YAML configuration files. Skip non existing files. Parameters ---------- name : string name to associate to the configurations fnames : list of strings the filename(s) of the configuration files Returns ------- flist : list files successfully loaded """ yconf = {} flist = [] for fn in fnames: try: with open(fn) as f: yconf.update(yaml.safe_load(f)) flist.append(fn) except six_ext.FileOpenError: pass _config_dic[name] = yconf return flist
[docs]def load_std_conf(name, *fnames): """Load standard configuration files Parameters ---------- name : string name to associate to the configurations fnames : list of strings the filename(s) of the configuration files Returns ------- flist : list files successfully loaded """ conf = confp.ConfigParser(interpolation=ExtendedInterpolation(), defaults=default_dict()) flist = conf.read(*fnames) _config_dic[name] = conf return flist
def default_dict(): """Default values of the configuration object Returns ------- defaults : dict options-values pairs """ defaults = {} # Do the same to get the source dir defaults['vdat_source_dir'] = os.path.join(os.sep, *os.path.abspath(__file__).split(os.sep)[:-2]) # get the curebin directory from the environment as save in into # ``curebin_env`` try: defaults['curebin_env'] = os.environ['CUREBIN'] except KeyError: warnings.warn("'CUREBIN' environment variable is not set. If the" " 'curebin' option in the configuration file is set" " to interpolate from 'curebin_env', all the vdat" " commands requiring cure binaries will fail.") return defaults
[docs]def load_all_configs(vdat_conf_fname): """Convenience function to load the vdat configuration files. It loads: * ``"main"``: the standard configuration file ``vdat_conf_fname``; given from the command line * ``"tab"``: the yaml file(s) that instruct the gui how to display the files; the names are in the ``tab_config`` of the ``general`` section of the "default" configuration Parameters ---------- vdat_conf_fname : string name of the file with the vdat configuration name : string name under which the configuration object is saved """ if not load_std_conf('main', vdat_conf_fname): msg = "The file '{}' does not exist".format(vdat_conf_fname) raise ConfigurationError(msg) # get the ``general`` section of the configuration file conf = get_config('main') # load the tab and command interpreter yaml files for opt_name, name in zip(['tab_config', 'command_config', 'buttons_config'], ['tab', 'commands', 'buttons']): fnames = conf.get_list('general', opt_name) if not load_yaml(name, *fnames): msg = "The file(s) '{}' do not exist" msg = msg.format(', '.join(fnames)) raise ConfigurationError(msg)
[docs]def get_config(name, section=None): """Returns the configuration file with the specified name. Parameters ---------- name : string, optional name associated with the configuration object; by default returns the main configuration section : string, optional optionally returns only one section Returns ------- configuration object can be either a :class:`~pyhetdex.tools.configuration.ConfigParser` or a dictionary(-like) object """ try: conf = _config_dic[name] except KeyError: raise MissingConfigurationError("The configuration object '{}' does" " not exist".format(name)) if section: try: conf = conf[section] except KeyError: msg = ("The configuration object '{}' does not have the required" " section '{}".format(name, section)) raise MissingConfigurationSectionError(msg) return conf