Completed
Push — master ( bff2ab...5dc771 )
by Satoru
01:07
created

anyconfig.backend._parse()   C

Complexity

Conditions 7

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 7
dl 0
loc 21
rs 6.4705
1
#
2
# Copyright (C) 2011 - 2015 Satoru SATOH <ssato @ redhat.com>
3
# License: MIT
4
#
5
#  pylint: disable=unused-argument
6
"""INI or INI like config files backend.
7
8
.. versionchanged:: 0.3
9
   Introduce 'ac_parse_value' keyword option to switch behaviors, same as
10
   original configparser and rich backend parsing each parameter values.
11
12
- Format to support: INI or INI like ones
13
- Requirements: It should be available always.
14
15
  - ConfigParser in python 2 standard library:
16
    https://docs.python.org/2.7/library/configparser.html
17
18
  - configparser in python 3 standard library:
19
    https://docs.python.org/3/library/configparser.html
20
21
- Limitations: None obvious
22
- Special options:
23
24
  - Use 'ac_parse_value' boolean keyword option if you want to parse values by
25
    custom parser, anyconfig.backend.ini._parse.
26
"""
27
from __future__ import absolute_import
28
29
import anyconfig.backend.base
30
import anyconfig.parser as P
31
import anyconfig.utils
32
33
from anyconfig.compat import configparser, iteritems
34
from anyconfig.backend.base import mk_opt_args
35
36
37
_SEP = ','
38
39
40
def _noop(val, *args, **kwargs):
41
    """
42
    Parser does nothing.
43
    """
44
    # It means nothing but can suppress 'Unused argument' pylint warns.
45
    # (val, args, kwargs)[0]
46
    return val
47
48
49
def _parse(val_s, sep=_SEP):
50
    """
51
    FIXME: May be too naive implementation.
52
53
    :param val_s: A string represents some value to parse
54
    :param sep: separator between values
55
56
    >>> _parse(r'"foo string"')
57
    'foo string'
58
    >>> _parse("a, b, c")
59
    ['a', 'b', 'c']
60
    >>> _parse("aaa")
61
    'aaa'
62
    """
63
    if (val_s.startswith('"') and val_s.endswith('"')) or \
64
            (val_s.startswith("'") and val_s.endswith("'")):
65
        return val_s[1:-1]
66
    elif sep in val_s:
67
        return [P.parse(x) for x in P.parse_list(val_s)]
68
    else:
69
        return P.parse(val_s)
70
71
72
def _to_s(val, sep=", "):
73
    """Convert any to string.
74
75
    :param val: An object
76
    :param sep: separator between values
77
78
    >>> _to_s([1, 2, 3])
79
    '1, 2, 3'
80
    >>> _to_s("aaa")
81
    'aaa'
82
    """
83
    if anyconfig.utils.is_iterable(val):
84
        return sep.join(str(x) for x in val)
85
    else:
86
        return str(val)
87
88
89
def _load(stream, to_container=dict, sep=_SEP, **kwargs):
90
    """
91
    :param stream: File or file-like object provides ini-style conf
92
    :param to_container: any callable to make container
93
    :param sep: Seprator string
94
95
    :return: Dict or dict-like object represents config values
96
    """
97
    _parse_val = _parse if kwargs.get("ac_parse_value", False) else _noop
98
99
    # Optional arguements for configparser.SafeConfigParser{,readfp}
100
    kwargs_0 = mk_opt_args(("defaults", "dict_type", "allow_no_value"), kwargs)
101
    kwargs_1 = mk_opt_args(("filename", ), kwargs)
102
103
    try:
104
        parser = configparser.SafeConfigParser(**kwargs_0)
105
    except TypeError:
106
        # .. note::
107
        #    It seems ConfigPaser.*ConfigParser in python 2.6 does not support
108
        #    'allow_no_value' option parameter, and TypeError will be thrown.
109
        kwargs_0 = mk_opt_args(("defaults", "dict_type"), kwargs)
110
        parser = configparser.SafeConfigParser(**kwargs_0)
111
112
    cnf = to_container()
113
    parser.readfp(stream, **kwargs_1)
114
115
    # .. note:: Process DEFAULT config parameters as special ones.
116
    defaults = parser.defaults()
117
    if defaults:
118
        cnf["DEFAULT"] = to_container()
119
        for key, val in iteritems(defaults):
120
            cnf["DEFAULT"][key] = _parse_val(val, sep)
121
122
    for sect in parser.sections():
123
        cnf[sect] = to_container()
124
        for key, val in parser.items(sect):
125
            cnf[sect][key] = _parse_val(val, sep)
126
127
    return cnf
128
129
130
def _dumps_itr(cnf):
131
    """
132
    :param cnf: Configuration data to dump
133
    """
134
    dkey = "DEFAULT"
135
    for sect, params in iteritems(cnf):
136
        yield "[%s]" % sect
137
138
        for key, val in iteritems(params):
139
            if sect != dkey and dkey in cnf and cnf[dkey].get(key) == val:
140
                continue  # It should be in [DEFAULT] section.
141
142
            yield "%s = %s" % (key, _to_s(val))
143
144
        yield ''  # it will be a separator between each sections.
145
146
147
def _dumps(cnf, **kwargs):
148
    """
149
    :param cnf: Configuration data to dump
150
    :param kwargs: optional keyword parameters to be sanitized :: dict
151
152
    :return: String representation of `cnf` object in INI format
153
    """
154
    return '\n'.join(l for l in _dumps_itr(cnf))
155
156
157
class Parser(anyconfig.backend.base.FromStreamLoader,
158
             anyconfig.backend.base.ToStringDumper):
159
    """
160
    Ini config files parser.
161
    """
162
    _type = "ini"
163
    _extensions = ["ini"]
164
    _load_opts = ["defaults", "dict_type", "allow_no_value", "filename",
165
                  "ac_parse_value"]
166
167
    dump_to_string = anyconfig.backend.base.to_method(_dumps)
168
169
    def load_from_stream(self, stream, to_container, **options):
170
        """
171
        Load config from given file like object `stream`.
172
173
        :param stream:  Config file or file like object
174
        :param to_container: callble to make a container object
175
        :param options: optional keyword arguments
176
177
        :return: Dict-like object holding config parameters
178
        """
179
        return _load(stream, to_container=to_container, **options)
180
181
# vim:sw=4:ts=4:et:
182