config.py 4.32 KB
Newer Older
1 2
"""Config functions"""
#-----------------------------------------------------------------------------
3
#  Copyright (C) PyZMQ Developers
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#
#  This file is part of pyzmq, copied and adapted from h5py.
#  h5py source used under the New BSD license
#
#  h5py: <http://code.google.com/p/h5py/>
#
#  Distributed under the terms of the New BSD License.  The full license is in
#  the file COPYING.BSD, distributed as part of this software.
#-----------------------------------------------------------------------------

import sys
import os
import json

try:
    from configparser import ConfigParser
except:
    from ConfigParser import ConfigParser

pjoin = os.path.join
from .msg import debug, fatal, warn

#-----------------------------------------------------------------------------
# Utility functions (adapted from h5py: http://h5py.googlecode.com)
#-----------------------------------------------------------------------------


31
def load_config(name, base='conf'):
32
    """Load config dict from JSON"""
33
    fname = pjoin(base, name + '.json')
34
    if not os.path.exists(fname):
35
        return {}
36 37 38 39 40
    try:
        with open(fname) as f:
            cfg = json.load(f)
    except Exception as e:
        warn("Couldn't load %s: %s" % (fname, e))
41
        cfg = {}
42 43 44
    return cfg


45
def save_config(name, data, base='conf'):
46
    """Save config dict to JSON"""
47 48 49
    if not os.path.exists(base):
        os.mkdir(base)
    fname = pjoin(base, name+'.json')
50 51 52 53 54 55 56 57
    with open(fname, 'w') as f:
        json.dump(data, f, indent=2)


def v_str(v_tuple):
    """turn (2,0,1) into '2.0.1'."""
    return ".".join(str(x) for x in v_tuple)

58
def get_env_args():
59 60 61 62
    """ Look for options in environment vars """

    settings = {}

63 64 65 66
    zmq = os.environ.get("ZMQ_PREFIX", None)
    if zmq is not None:
        debug("Found environ var ZMQ_PREFIX=%s" % zmq)
        settings['zmq_prefix'] = zmq
67 68 69

    return settings

70 71 72 73 74 75 76 77 78 79
def cfg2dict(cfg):
    """turn a ConfigParser into a nested dict
    
    because ConfigParser objects are dumb.
    """
    d = {}
    for section in cfg.sections():
        d[section] = dict(cfg.items(section))
    return d

80 81 82 83
def get_cfg_args():
    """ Look for options in setup.cfg """

    if not os.path.exists('setup.cfg'):
84
        return {}
85 86
    cfg = ConfigParser()
    cfg.read('setup.cfg')
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    cfg = cfg2dict(cfg)

    g = cfg.setdefault('global', {})
    # boolean keys:
    for key in ['libzmq_extension',
                'bundle_libzmq_dylib',
                'no_libzmq_extension',
                'have_sys_un_h',
                'skip_check_zmq',
                ]:
        if key in g:
            g[key] = eval(g[key])

    # globals go to top level
    cfg.update(cfg.pop('global'))
    return cfg
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
def config_from_prefix(prefix):
    """Get config from zmq prefix"""
    settings = {}
    if prefix.lower() in ('default', 'auto', ''):
        settings['zmq_prefix'] = ''
        settings['libzmq_extension'] = False
        settings['no_libzmq_extension'] = False
    elif prefix.lower() in ('bundled', 'extension'):
        settings['zmq_prefix'] = ''
        settings['libzmq_extension'] = True
        settings['no_libzmq_extension'] = False
    else:
        settings['zmq_prefix'] = prefix
        settings['libzmq_extension'] = False
        settings['no_libzmq_extension'] = True
119
        settings['allow_legacy_libzmq'] = True # explicit zmq prefix allows legacy
120 121
    return settings

122 123 124 125 126 127 128 129 130
def merge(into, d):
    """merge two containers
    
    into is updated, d has priority
    """
    if isinstance(into, dict):
        for key in d.keys():
            if key not in into:
                into[key] = d[key]
131
            else:
132 133 134 135 136 137 138 139
                into[key] = merge(into[key], d[key])
        return into
    elif isinstance(into, list):
        return into + d
    else:
        return d

def discover_settings(conf_base=None):
140
    """ Discover custom settings for ZMQ path"""
141 142 143 144 145
    settings = {
        'zmq_prefix': '',
        'libzmq_extension': False,
        'no_libzmq_extension': False,
        'skip_check_zmq': False,
146
        'allow_legacy_libzmq': False,
147 148 149 150 151 152 153 154 155 156
        'build_ext': {},
        'bdist_egg': {},
    }
    if sys.platform.startswith('win'):
        settings['have_sys_un_h'] = False
    
    if conf_base:
        # lowest priority
        merge(settings, load_config('config', conf_base))
    merge(settings, get_cfg_args())
157
    merge(settings, get_env_args())
158 159
    
    return settings