summaryrefslogtreecommitdiff
path: root/iniherit/parser.py
blob: 85344a546fb2d0143170d27bf95621de75b35850 (plain)
1
2
3
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# file: $Id$
# auth: Philip J Grabner <grabner@cadit.com>
# date: 2013/08/20
# copy: (C) Copyright 2013 Cadit Health Inc., All Rights Reserved.
#------------------------------------------------------------------------------

import io
import os.path
import warnings

import six
from six.moves import configparser as CP
from six.moves import urllib
try:
  from collections import OrderedDict
except ImportError:
  OrderedDict = dict

# TODO: PY3 added a `ConfigParser.read_dict` that should probably
#       be overridden as well...
# TODO: should `ConfigParser.set()` be checked for option==INHERITTAG?...

from . import interpolation

__all__ = (
  'Loader', 'IniheritMixin', 'RawConfigParser',
  'ConfigParser', 'SafeConfigParser',
  'DEFAULT_INHERITTAG',
)

#------------------------------------------------------------------------------

_real_RawConfigParser  = CP.RawConfigParser
_real_ConfigParser     = CP.ConfigParser
_real_SafeConfigParser = CP.SafeConfigParser

DEFAULT_INHERITTAG = '%inherit'

#------------------------------------------------------------------------------
class Loader(object):
  def load(self, name, encoding=None):
    # todo: these fp are leaked... need to use "contextlib.closing" somehow...
    if encoding is None:
      return open(name)
    return open(name, encoding=encoding)


#------------------------------------------------------------------------------
# TODO: this would probably be *much* simpler with meta-classes...

#------------------------------------------------------------------------------
class IniheritMixin(object):

  IM_INHERITTAG  = DEFAULT_INHERITTAG
  IM_DEFAULTSECT = CP.DEFAULTSECT

  #----------------------------------------------------------------------------
  def __init__(self, *args, **kw):
    self.loader = kw.get('loader', None) or Loader()
    self.inherit = True
    self.IM_INHERITTAG  = DEFAULT_INHERITTAG
    self.IM_DEFAULTSECT = getattr(self, 'default_section', CP.DEFAULTSECT)

  #----------------------------------------------------------------------------
  def read(self, filenames, encoding=None):
    if isinstance(filenames, six.string_types):
      filenames = [filenames]
    read_ok = []
    for filename in filenames:
      try:
        fp = self._load(filename, encoding=encoding)
      except IOError:
        continue
      self._read(fp, filename, encoding=encoding)
      fp.close()
      read_ok.append(filename)
    return read_ok

  #----------------------------------------------------------------------------
  def _load(self, filename, encoding=None):
    if not getattr(self, 'loader', None):
      self.loader = Loader()
    return self.loader.load(filename, encoding=encoding)

  #----------------------------------------------------------------------------
  def _read(self, fp, fpname, encoding=None):
    if getattr(self, 'inherit', True) or not hasattr(self, '_iniherit__read'):
      raw = self._readRecursive(fp, fpname, encoding=encoding)
      self._apply(raw, self)
    else:
      self._iniherit__read(fp, fpname)

  #----------------------------------------------------------------------------
  def _makeParser(self):
    ret = _real_RawConfigParser()
    ret.inherit = False
    ## TODO: any other configurations that need to be copied into `ret`??...
    ret.optionxform = self.optionxform
    return ret

  #----------------------------------------------------------------------------
  def _interpolate_inherit(self, parser, section, option, value):
    ## TODO: ugh. this just doesn't feel "right"...
    vars = dict(parser.items(section))
    return self._interpolate(section, option, value, vars)

  #----------------------------------------------------------------------------
  def _readRecursive(self, fp, fpname, encoding=None):
    ret = self._makeParser()
    src = self._makeParser()
    src.readfp(fp, fpname)
    dirname = os.path.dirname(fpname)
    if src.has_option(self.IM_DEFAULTSECT, self.IM_INHERITTAG):
      inilist = src.get(self.IM_DEFAULTSECT, self.IM_INHERITTAG)
      src.remove_option(self.IM_DEFAULTSECT, self.IM_INHERITTAG)
      inilist = self._interpolate_inherit(src, self.IM_DEFAULTSECT, self.IM_INHERITTAG, inilist)
      for curname in inilist.split():
        optional = curname.startswith('?')
        if optional:
          curname = curname[1:]
        curname = os.path.join(dirname, urllib.parse.unquote(curname))
        try:
          curfp = self._load(curname, encoding=encoding)
        except IOError:
          if optional:
            continue
          raise
        self._apply(self._readRecursive(curfp, curname, encoding=encoding), ret)
    for section in src.sections():
      if not src.has_option(section, self.IM_INHERITTAG):
        continue
      inilist = src.get(section, self.IM_INHERITTAG)
      src.remove_option(section, self.IM_INHERITTAG)
      inilist = self._interpolate_inherit(src, section, self.IM_INHERITTAG, inilist)
      for curname in inilist.split():
        optional = curname.startswith('?')
        if optional:
          curname = curname[1:]
        fromsect = section
        if '[' in curname and curname.endswith(']'):
          curname, fromsect = curname.split('[', 1)
          fromsect = urllib.parse.unquote(fromsect[:-1])
        curname = os.path.join(dirname, urllib.parse.unquote(curname))
        try:
          curfp = self._load(curname, encoding=encoding)
        except IOError:
          if optional:
            continue
          raise
        self._apply(self._readRecursive(curfp, curname, encoding=encoding), ret,
                    sections={fromsect: section})
    self._apply(src, ret)
    return ret

  #----------------------------------------------------------------------------
  def _apply(self, src, dst, sections=None):
    # todo: this does not detect the case that a section overrides
    #       the default section with the exact same value... ugh.
    if sections is None:
      for option, value in src.items(self.IM_DEFAULTSECT):
        value = interpolation.interpolate_super(
          self, src, dst, self.IM_DEFAULTSECT, option, value)
        self._im_setraw(dst, self.IM_DEFAULTSECT, option, value)
    if sections is None:
      sections = OrderedDict([(s, s) for s in src.sections()])
    for srcsect, dstsect in sections.items():
      if not dst.has_section(dstsect):
        dst.add_section(dstsect)
      for option, value in src.items(srcsect):
        # todo: this is a *terrible* way of detecting if this option is
        #       defaulting...
        if src.has_option(self.IM_DEFAULTSECT, option) \
            and value == src.get(self.IM_DEFAULTSECT, option):
          continue
        value = interpolation.interpolate_super(
          self, src, dst, dstsect, option, value)
        self._im_setraw(dst, dstsect, option, value)

  #----------------------------------------------------------------------------
  def _im_setraw(self, parser, section, option, value):
    if six.PY3 and hasattr(parser, '_interpolation'):
      # todo: don't do this for systems that have
      #       http://bugs.python.org/issue21265 fixed
      try:
        tmp = parser._interpolation.before_set
        parser._interpolation.before_set = lambda self,s,o,v,*a,**k: v
        _real_RawConfigParser.set(parser, section, option, value)
      finally:
        parser._interpolation.before_set = tmp
    else:
      _real_RawConfigParser.set(parser, section, option, value)

  #----------------------------------------------------------------------------
  # todo: yikes! overriding a private method!...
  def _interpolate(self, section, option, rawval, vars):
    base_interpolate = getattr(_real_ConfigParser, '_iniherit__interpolate', None)
    if not base_interpolate:
      base_interpolate = getattr(_real_ConfigParser, '_interpolate', None)
    return interpolation.interpolate(
      self, base_interpolate, section, option, rawval, vars)
  if not hasattr(_real_ConfigParser, '_interpolate') and not six.PY3:
    warnings.warn(
      'ConfigParser did not have a "_interpolate" method'
      ' -- iniherit may be broken on this platform',
      RuntimeWarning)


#------------------------------------------------------------------------------
# todo: i'm a little worried about the diamond inheritance here...
class RawConfigParser(IniheritMixin, _real_RawConfigParser):
  _DEFAULT_INTERPOLATION = interpolation.IniheritInterpolation()
  def __init__(self, *args, **kw):
    loader = kw.pop('loader', None)
    IniheritMixin.__init__(self, loader=loader)
    _real_RawConfigParser.__init__(self, *args, **kw)
class ConfigParser(RawConfigParser, _real_ConfigParser):
  def __init__(self, *args, **kw):
    loader = kw.pop('loader', None)
    RawConfigParser.__init__(self, loader=loader)
    _real_ConfigParser.__init__(self, *args, **kw)
class SafeConfigParser(ConfigParser, _real_SafeConfigParser):
  def __init__(self, *args, **kw):
    loader = kw.pop('loader', None)
    ConfigParser.__init__(self, loader=loader)
    _real_SafeConfigParser.__init__(self, *args, **kw)


#------------------------------------------------------------------------------
# end of $Id$
# $ChangeLog$
#------------------------------------------------------------------------------