NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

reprconf.py (7030B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\cherrypy\lib\reprconf.py
      2 try:
      3     from configparser import ConfigParser
      4 except ImportError:
      5     from ConfigParser import ConfigParser
      6 
      7 try:
      8     set
      9 except NameError:
     10     from sets import Set as set
     11 
     12 import sys
     13 
     14 def as_dict(config):
     15     if isinstance(config, basestring):
     16         config = Parser().dict_from_file(config)
     17     elif hasattr(config, 'read'):
     18         config = Parser().dict_from_file(config)
     19     return config
     20 
     21 
     22 class NamespaceSet(dict):
     23 
     24     def __call__(self, config):
     25         ns_confs = {}
     26         for k in config:
     27             if '.' in k:
     28                 ns, name = k.split('.', 1)
     29                 bucket = ns_confs.setdefault(ns, {})
     30                 bucket[name] = config[k]
     31 
     32         for ns, handler in self.items():
     33             exit = getattr(handler, '__exit__', None)
     34             if exit:
     35                 callable = handler.__enter__()
     36                 no_exc = True
     37                 try:
     38                     for k, v in ns_confs.get(ns, {}).items():
     39                         callable(k, v)
     40 
     41                 except:
     42                     no_exc = False
     43                     if exit is None:
     44                         raise
     45                     if not exit(*sys.exc_info()):
     46                         raise
     47                 finally:
     48                     if no_exc and exit:
     49                         exit(None, None, None)
     50 
     51             else:
     52                 for k, v in ns_confs.get(ns, {}).items():
     53                     handler(k, v)
     54 
     55     def __repr__(self):
     56         return '%s.%s(%s)' % (self.__module__, self.__class__.__name__, dict.__repr__(self))
     57 
     58     def __copy__(self):
     59         newobj = self.__class__()
     60         newobj.update(self)
     61         return newobj
     62 
     63     copy = __copy__
     64 
     65 
     66 class Config(dict):
     67     defaults = {}
     68     environments = {}
     69     namespaces = NamespaceSet()
     70 
     71     def __init__(self, file = None, **kwargs):
     72         self.reset()
     73         if file is not None:
     74             self.update(file)
     75         if kwargs:
     76             self.update(kwargs)
     77 
     78     def reset(self):
     79         self.clear()
     80         dict.update(self, self.defaults)
     81 
     82     def update(self, config):
     83         if isinstance(config, basestring):
     84             config = Parser().dict_from_file(config)
     85         elif hasattr(config, 'read'):
     86             config = Parser().dict_from_file(config)
     87         else:
     88             config = config.copy()
     89         self._apply(config)
     90 
     91     def _apply(self, config):
     92         which_env = config.get('environment')
     93         if which_env:
     94             env = self.environments[which_env]
     95             for k in env:
     96                 if k not in config:
     97                     config[k] = env[k]
     98 
     99         dict.update(self, config)
    100         self.namespaces(config)
    101 
    102     def __setitem__(self, k, v):
    103         dict.__setitem__(self, k, v)
    104         self.namespaces({k: v})
    105 
    106 
    107 class Parser(ConfigParser):
    108 
    109     def optionxform(self, optionstr):
    110         return optionstr
    111 
    112     def read(self, filenames):
    113         if isinstance(filenames, basestring):
    114             filenames = [filenames]
    115         for filename in filenames:
    116             fp = open(filename)
    117             try:
    118                 self._read(fp, filename)
    119             finally:
    120                 fp.close()
    121 
    122     def as_dict(self, raw = False, vars = None):
    123         result = {}
    124         for section in self.sections():
    125             if section not in result:
    126                 result[section] = {}
    127             for option in self.options(section):
    128                 value = self.get(section, option, raw, vars)
    129                 try:
    130                     value = unrepr(value)
    131                 except Exception as x:
    132                     msg = 'Config error in section: %r, option: %r, value: %r. Config values must be valid Python.' % (section, option, value)
    133                     raise ValueError(msg, x.__class__.__name__, x.args)
    134 
    135                 result[section][option] = value
    136 
    137         return result
    138 
    139     def dict_from_file(self, file):
    140         if hasattr(file, 'read'):
    141             self.readfp(file)
    142         else:
    143             self.read(file)
    144         return self.as_dict()
    145 
    146 
    147 class _Builder:
    148 
    149     def build(self, o):
    150         m = getattr(self, 'build_' + o.__class__.__name__, None)
    151         if m is None:
    152             raise TypeError('unrepr does not recognize %s' % repr(o.__class__.__name__))
    153         return m(o)
    154 
    155     def build_Subscript(self, o):
    156         expr, flags, subs = o.getChildren()
    157         expr = self.build(expr)
    158         subs = self.build(subs)
    159         return expr[subs]
    160 
    161     def build_CallFunc(self, o):
    162         children = map(self.build, o.getChildren())
    163         callee = children.pop(0)
    164         kwargs = children.pop() or {}
    165         starargs = children.pop() or ()
    166         args = tuple(children) + tuple(starargs)
    167         return callee(*args, **kwargs)
    168 
    169     def build_List(self, o):
    170         return map(self.build, o.getChildren())
    171 
    172     def build_Const(self, o):
    173         return o.value
    174 
    175     def build_Dict(self, o):
    176         d = {}
    177         i = iter(map(self.build, o.getChildren()))
    178         for el in i:
    179             d[el] = i.next()
    180 
    181         return d
    182 
    183     def build_Tuple(self, o):
    184         return tuple(self.build_List(o))
    185 
    186     def build_Name(self, o):
    187         name = o.name
    188         if name == 'None':
    189             return
    190         if name == 'True':
    191             return True
    192         if name == 'False':
    193             return False
    194         try:
    195             return modules(name)
    196         except ImportError:
    197             pass
    198 
    199         try:
    200             import __builtin__
    201             return getattr(__builtin__, name)
    202         except AttributeError:
    203             pass
    204 
    205         raise TypeError('unrepr could not resolve the name %s' % repr(name))
    206 
    207     def build_Add(self, o):
    208         left, right = map(self.build, o.getChildren())
    209         return left + right
    210 
    211     def build_Getattr(self, o):
    212         parent = self.build(o.expr)
    213         return getattr(parent, o.attrname)
    214 
    215     def build_NoneType(self, o):
    216         return None
    217 
    218     def build_UnarySub(self, o):
    219         return -self.build(o.getChildren()[0])
    220 
    221     def build_UnaryAdd(self, o):
    222         return self.build(o.getChildren()[0])
    223 
    224 
    225 def _astnode(s):
    226     try:
    227         import compiler
    228     except ImportError:
    229         return eval(s)
    230 
    231     p = compiler.parse('__tempvalue__ = ' + s)
    232     return p.getChildren()[1].getChildren()[0].getChildren()[1]
    233 
    234 
    235 def unrepr(s):
    236     if not s:
    237         return s
    238     obj = _astnode(s)
    239     return _Builder().build(obj)
    240 
    241 
    242 def modules(modulePath):
    243     try:
    244         mod = sys.modules[modulePath]
    245         if mod is None:
    246             raise KeyError()
    247     except KeyError:
    248         mod = __import__(modulePath, globals(), locals(), [''])
    249 
    250     return mod
    251 
    252 
    253 def attributes(full_attribute_name):
    254     last_dot = full_attribute_name.rfind('.')
    255     attr_name = full_attribute_name[last_dot + 1:]
    256     mod_path = full_attribute_name[:last_dot]
    257     mod = modules(mod_path)
    258     try:
    259         attr = getattr(mod, attr_name)
    260     except AttributeError:
    261         raise AttributeError("'%s' object has no attribute '%s'" % (mod_path, attr_name))
    262 
    263     return attr