prettyconf 2.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prettyconf/__init__.py +4 -0
- prettyconf/casts.py +117 -0
- prettyconf/configuration.py +60 -0
- prettyconf/exceptions.py +22 -0
- prettyconf/loaders.py +382 -0
- prettyconf/parsers.py +193 -0
- prettyconf-2.3.0.dist-info/METADATA +61 -0
- prettyconf-2.3.0.dist-info/RECORD +12 -0
- prettyconf-2.3.0.dist-info/WHEEL +5 -0
- prettyconf-2.3.0.dist-info/licenses/AUTHORS.md +11 -0
- prettyconf-2.3.0.dist-info/licenses/LICENSE.txt +22 -0
- prettyconf-2.3.0.dist-info/top_level.txt +1 -0
prettyconf/__init__.py
ADDED
prettyconf/casts.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from .exceptions import InvalidConfiguration
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AbstractCast:
|
|
7
|
+
def __call__(self, value):
|
|
8
|
+
raise NotImplementedError() # pragma: no cover
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Boolean(AbstractCast):
|
|
12
|
+
default_values = {
|
|
13
|
+
'1': True,
|
|
14
|
+
'true': True,
|
|
15
|
+
'yes': True,
|
|
16
|
+
'y': True,
|
|
17
|
+
'on': True,
|
|
18
|
+
't': True,
|
|
19
|
+
'0': False,
|
|
20
|
+
'false': False,
|
|
21
|
+
'no': False,
|
|
22
|
+
'n': False,
|
|
23
|
+
'off': False,
|
|
24
|
+
'f': False,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
def __init__(self, values=None):
|
|
28
|
+
self.values = self.default_values
|
|
29
|
+
if isinstance(values, dict):
|
|
30
|
+
self.values.update(values)
|
|
31
|
+
|
|
32
|
+
def __call__(self, value):
|
|
33
|
+
try:
|
|
34
|
+
return self.values[str(value).lower()]
|
|
35
|
+
except KeyError as ex:
|
|
36
|
+
raise InvalidConfiguration(f'Error casting value {value!r} to boolean') from ex
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class List(AbstractCast):
|
|
40
|
+
def __init__(self, delimiter=',', quotes='"\''):
|
|
41
|
+
self.delimiter = delimiter
|
|
42
|
+
self.quotes = quotes
|
|
43
|
+
|
|
44
|
+
def _parse(self, string):
|
|
45
|
+
elements = []
|
|
46
|
+
element = []
|
|
47
|
+
quote = ''
|
|
48
|
+
for char in string:
|
|
49
|
+
# open quote
|
|
50
|
+
if char in self.quotes and not quote:
|
|
51
|
+
quote = char
|
|
52
|
+
element.append(char)
|
|
53
|
+
continue
|
|
54
|
+
|
|
55
|
+
# close quote
|
|
56
|
+
if char in self.quotes and char == quote:
|
|
57
|
+
quote = ''
|
|
58
|
+
element.append(char)
|
|
59
|
+
continue
|
|
60
|
+
|
|
61
|
+
if quote:
|
|
62
|
+
element.append(char)
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
if char == self.delimiter:
|
|
66
|
+
elements.append(''.join(element))
|
|
67
|
+
element = []
|
|
68
|
+
continue
|
|
69
|
+
|
|
70
|
+
element.append(char)
|
|
71
|
+
|
|
72
|
+
# remaining element
|
|
73
|
+
if element:
|
|
74
|
+
elements.append(''.join(element))
|
|
75
|
+
|
|
76
|
+
return self.cast(e.strip() for e in elements)
|
|
77
|
+
|
|
78
|
+
def cast(self, sequence):
|
|
79
|
+
return list(sequence)
|
|
80
|
+
|
|
81
|
+
def __call__(self, value):
|
|
82
|
+
return self._parse(value)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Tuple(List):
|
|
86
|
+
def cast(self, sequence):
|
|
87
|
+
return tuple(sequence)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Option(AbstractCast):
|
|
91
|
+
"""
|
|
92
|
+
Example::
|
|
93
|
+
_INSTALLED_APPS = ("foo", "bar")
|
|
94
|
+
INSTALLED_APPS = config("ENVIRONMENT", default="production", cast=Option({
|
|
95
|
+
"production": _INSTALLED_APPS,
|
|
96
|
+
"local": _INSTALLED_APPS + ("baz",)
|
|
97
|
+
}))
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(self, options):
|
|
101
|
+
self.options = options
|
|
102
|
+
|
|
103
|
+
def __call__(self, value):
|
|
104
|
+
try:
|
|
105
|
+
return self.options[value]
|
|
106
|
+
except KeyError as ex:
|
|
107
|
+
raise InvalidConfiguration(f'Invalid option {value!r}') from ex
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class JSON(AbstractCast):
|
|
111
|
+
def __call__(self, value):
|
|
112
|
+
try:
|
|
113
|
+
return json.loads(value)
|
|
114
|
+
except json.JSONDecodeError as ex:
|
|
115
|
+
raise InvalidConfiguration(f'Invalid option {value!r}') from ex
|
|
116
|
+
except TypeError:
|
|
117
|
+
return value
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from .casts import JSON, Boolean, List, Option, Tuple
|
|
6
|
+
from .exceptions import UnknownConfiguration
|
|
7
|
+
from .loaders import Environment, RecursiveSearch
|
|
8
|
+
|
|
9
|
+
MAGIC_FRAME_DEPTH = 2
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _caller_path():
|
|
13
|
+
# MAGIC! Get the caller's module path.
|
|
14
|
+
# noinspection PyProtectedMember
|
|
15
|
+
frame = sys._getframe(MAGIC_FRAME_DEPTH)
|
|
16
|
+
path = os.path.dirname(os.path.abspath(frame.f_code.co_filename))
|
|
17
|
+
return path
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Configuration:
|
|
21
|
+
# Shortcut for standard casts
|
|
22
|
+
boolean = Boolean()
|
|
23
|
+
list = List()
|
|
24
|
+
tuple = Tuple()
|
|
25
|
+
option = Option
|
|
26
|
+
eval = staticmethod(ast.literal_eval)
|
|
27
|
+
json = JSON()
|
|
28
|
+
|
|
29
|
+
def __init__(self, loaders=None):
|
|
30
|
+
self._recursive_search = None
|
|
31
|
+
if loaders is None:
|
|
32
|
+
self._recursive_search = RecursiveSearch()
|
|
33
|
+
loaders = [
|
|
34
|
+
Environment(),
|
|
35
|
+
self._recursive_search,
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
self.loaders = loaders
|
|
39
|
+
|
|
40
|
+
def __repr__(self):
|
|
41
|
+
loaders = ', '.join([repr(loader) for loader in self.loaders])
|
|
42
|
+
return f'{self.__class__.__name__}(loaders=[{loaders}])'
|
|
43
|
+
|
|
44
|
+
def __call__(self, item, cast=lambda v: v, **kwargs):
|
|
45
|
+
if not callable(cast):
|
|
46
|
+
raise TypeError('Cast must be callable')
|
|
47
|
+
|
|
48
|
+
if self._recursive_search:
|
|
49
|
+
self._recursive_search.starting_path = _caller_path()
|
|
50
|
+
|
|
51
|
+
for loader in self.loaders:
|
|
52
|
+
try:
|
|
53
|
+
return cast(loader[item])
|
|
54
|
+
except KeyError:
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
if 'default' not in kwargs:
|
|
58
|
+
raise UnknownConfiguration(f"Configuration '{item}' not found")
|
|
59
|
+
|
|
60
|
+
return cast(kwargs['default'])
|
prettyconf/exceptions.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
class ConfigurationException(Exception):
|
|
2
|
+
pass
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class InvalidConfigurationFile(ConfigurationException):
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MissingSettingsSection(InvalidConfigurationFile):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InvalidPath(ConfigurationException):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UnknownConfiguration(ConfigurationException):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InvalidConfiguration(ConfigurationException):
|
|
22
|
+
pass
|
prettyconf/loaders.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from configparser import ConfigParser, MissingSectionHeaderError, NoOptionError
|
|
3
|
+
from glob import glob
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import boto3
|
|
7
|
+
import botocore
|
|
8
|
+
except ImportError:
|
|
9
|
+
boto3 = None
|
|
10
|
+
|
|
11
|
+
from .exceptions import InvalidConfigurationFile, InvalidPath, MissingSettingsSection
|
|
12
|
+
from .parsers import EnvFileParser
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NotSet(str):
|
|
16
|
+
"""
|
|
17
|
+
A special type that behaves as a replacement for None.
|
|
18
|
+
We have to put a new default value to know if a variable has been set by
|
|
19
|
+
the user explicitly. This is useful for the ``CommandLine`` loader, when
|
|
20
|
+
CLI parsers force you to set a default value, and thus, break the discovery
|
|
21
|
+
chain.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
NOT_SET = NotSet()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_args(parser):
|
|
31
|
+
"""
|
|
32
|
+
Converts arguments extracted from a parser to a dict,
|
|
33
|
+
and will dismiss arguments which default to NOT_SET.
|
|
34
|
+
|
|
35
|
+
:param parser: an ``argparse.ArgumentParser`` instance.
|
|
36
|
+
:type parser: argparse.ArgumentParser
|
|
37
|
+
:return: Dictionary with the configs found in the parsed CLI arguments.
|
|
38
|
+
:rtype: dict
|
|
39
|
+
"""
|
|
40
|
+
args = vars(parser.parse_args()).items()
|
|
41
|
+
return {key: val for key, val in args if not isinstance(val, NotSet)}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AbstractConfigurationLoader:
|
|
45
|
+
def __repr__(self):
|
|
46
|
+
raise NotImplementedError() # pragma: no cover
|
|
47
|
+
|
|
48
|
+
def __contains__(self, item):
|
|
49
|
+
raise NotImplementedError() # pragma: no cover
|
|
50
|
+
|
|
51
|
+
def __getitem__(self, item):
|
|
52
|
+
raise NotImplementedError() # pragma: no cover
|
|
53
|
+
|
|
54
|
+
def check(self):
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# noinspection PyAbstractClass
|
|
59
|
+
class AbstractConfigurationFileLoader(AbstractConfigurationLoader):
|
|
60
|
+
file_filters = ()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class CommandLine(AbstractConfigurationLoader):
|
|
64
|
+
"""
|
|
65
|
+
Extract configuration from an ``argparse`` parser.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
# noinspection PyShadowingNames
|
|
69
|
+
def __init__(self, parser, get_args=get_args):
|
|
70
|
+
"""
|
|
71
|
+
:param parser: An `argparse` parser instance to extract variables from.
|
|
72
|
+
:param function get_args: A function to extract args from the parser.
|
|
73
|
+
:type parser: argparse.ArgumentParser
|
|
74
|
+
"""
|
|
75
|
+
self.parser = parser
|
|
76
|
+
self.configs = get_args(self.parser)
|
|
77
|
+
|
|
78
|
+
def __repr__(self):
|
|
79
|
+
return f'CommandLine(parser={self.parser})'
|
|
80
|
+
|
|
81
|
+
def __contains__(self, item):
|
|
82
|
+
return item in self.configs
|
|
83
|
+
|
|
84
|
+
def __getitem__(self, item):
|
|
85
|
+
return self.configs[item]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class IniFile(AbstractConfigurationFileLoader):
|
|
89
|
+
file_extensions = ('*.ini', '*.cfg')
|
|
90
|
+
|
|
91
|
+
def __init__(self, filename, section='settings', var_format=lambda x: x):
|
|
92
|
+
"""
|
|
93
|
+
:param str filename: Path to the ``.ini/.cfg`` file.
|
|
94
|
+
:param str section: Section name inside the config file.
|
|
95
|
+
:param function var_format: A function to pre-format variable names.
|
|
96
|
+
"""
|
|
97
|
+
self.filename = filename
|
|
98
|
+
self.section = section
|
|
99
|
+
self.var_format = var_format
|
|
100
|
+
self.parser = ConfigParser(allow_no_value=True)
|
|
101
|
+
self._initialized = False
|
|
102
|
+
|
|
103
|
+
def __repr__(self):
|
|
104
|
+
return f'IniFile("{self.filename}")'
|
|
105
|
+
|
|
106
|
+
def _parse(self):
|
|
107
|
+
if self._initialized:
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
with open(self.filename) as inifile:
|
|
111
|
+
try:
|
|
112
|
+
self.parser.read_file(inifile)
|
|
113
|
+
except (UnicodeDecodeError, MissingSectionHeaderError) as ex:
|
|
114
|
+
raise InvalidConfigurationFile() from ex
|
|
115
|
+
|
|
116
|
+
if not self.parser.has_section(self.section):
|
|
117
|
+
raise MissingSettingsSection(f'Missing [{self.section}] section in {self.filename}')
|
|
118
|
+
|
|
119
|
+
self._initialized = True
|
|
120
|
+
|
|
121
|
+
def check(self):
|
|
122
|
+
try:
|
|
123
|
+
self._parse()
|
|
124
|
+
except (FileNotFoundError, InvalidConfigurationFile, MissingSettingsSection):
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
return super().check()
|
|
128
|
+
|
|
129
|
+
def __contains__(self, item):
|
|
130
|
+
if not self.check():
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
return self.parser.has_option(self.section, self.var_format(item))
|
|
134
|
+
|
|
135
|
+
def __getitem__(self, item):
|
|
136
|
+
if not self.check():
|
|
137
|
+
raise KeyError(f'{item!r}')
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
return self.parser.get(self.section, self.var_format(item))
|
|
141
|
+
except NoOptionError as ex:
|
|
142
|
+
raise KeyError(f'{item!r}') from ex
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Environment(AbstractConfigurationLoader):
|
|
146
|
+
"""
|
|
147
|
+
Get's configuration from the environment, by inspecting ``os.environ``.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
def __init__(self, var_format=str.upper):
|
|
151
|
+
"""
|
|
152
|
+
:param function var_format: A function to pre-format variable names.
|
|
153
|
+
"""
|
|
154
|
+
self.var_format = var_format
|
|
155
|
+
|
|
156
|
+
def __repr__(self):
|
|
157
|
+
return f'Environment(var_format={self.var_format})'
|
|
158
|
+
|
|
159
|
+
def __contains__(self, item):
|
|
160
|
+
return self.var_format(item) in os.environ
|
|
161
|
+
|
|
162
|
+
def __getitem__(self, item):
|
|
163
|
+
# Uses `os.environ` because it raises an exception if the environmental
|
|
164
|
+
# variable does not exist, whilst `os.getenv` doesn't.
|
|
165
|
+
return os.environ[self.var_format(item)]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class EnvFile(AbstractConfigurationFileLoader):
|
|
169
|
+
file_extensions = ('.env',)
|
|
170
|
+
|
|
171
|
+
def __init__(self, filename='.env', var_format=str.upper):
|
|
172
|
+
"""
|
|
173
|
+
:param str filename: Path to the ``.env`` file.
|
|
174
|
+
:param function var_format: A function to pre-format variable names.
|
|
175
|
+
"""
|
|
176
|
+
self.filename = filename
|
|
177
|
+
self.var_format = var_format
|
|
178
|
+
self.configs = None
|
|
179
|
+
|
|
180
|
+
def __repr__(self):
|
|
181
|
+
return f'EnvFile("{self.filename}")'
|
|
182
|
+
|
|
183
|
+
def _parse(self):
|
|
184
|
+
if self.configs is not None:
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
self.configs = {}
|
|
188
|
+
with open(self.filename) as envfile:
|
|
189
|
+
self.configs.update(EnvFileParser(envfile).parse_config())
|
|
190
|
+
|
|
191
|
+
def check(self):
|
|
192
|
+
if not os.path.isfile(self.filename):
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
self._parse()
|
|
197
|
+
except FileNotFoundError:
|
|
198
|
+
return False
|
|
199
|
+
|
|
200
|
+
return super().check()
|
|
201
|
+
|
|
202
|
+
def __contains__(self, item):
|
|
203
|
+
if not self.check():
|
|
204
|
+
return False
|
|
205
|
+
|
|
206
|
+
return self.var_format(item) in self.configs
|
|
207
|
+
|
|
208
|
+
def __getitem__(self, item):
|
|
209
|
+
if not self.check():
|
|
210
|
+
raise KeyError(f'{item!r}')
|
|
211
|
+
|
|
212
|
+
return self.configs[self.var_format(item)]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class RecursiveSearch(AbstractConfigurationLoader):
|
|
216
|
+
def __init__(self, starting_path=None, filetypes=(('.env', EnvFile), (('*.ini', '*.cfg'), IniFile)), root_path='/'):
|
|
217
|
+
"""
|
|
218
|
+
:param str starting_path: The path to begin looking for configuration files.
|
|
219
|
+
:param tuple filetypes: tuple of tuples with configuration loaders, order matters.
|
|
220
|
+
Defaults to
|
|
221
|
+
``(('*.env', EnvFile), (('*.ini', *.cfg',), IniFile)``
|
|
222
|
+
:param str root_path: Configuration lookup will stop at the given path. Defaults to
|
|
223
|
+
the current user directory
|
|
224
|
+
"""
|
|
225
|
+
self.root_path = os.path.realpath(root_path)
|
|
226
|
+
self._starting_path = self.root_path
|
|
227
|
+
|
|
228
|
+
if starting_path:
|
|
229
|
+
self.starting_path = starting_path
|
|
230
|
+
|
|
231
|
+
self.filetypes = filetypes
|
|
232
|
+
self._config_files = None
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def starting_path(self):
|
|
236
|
+
return self._starting_path
|
|
237
|
+
|
|
238
|
+
@starting_path.setter
|
|
239
|
+
def starting_path(self, path):
|
|
240
|
+
if not path:
|
|
241
|
+
raise InvalidPath('Invalid starting path')
|
|
242
|
+
|
|
243
|
+
path = os.path.realpath(os.path.abspath(path))
|
|
244
|
+
if not path.startswith(self.root_path):
|
|
245
|
+
raise InvalidPath('Invalid root path given')
|
|
246
|
+
self._starting_path = path
|
|
247
|
+
|
|
248
|
+
@staticmethod
|
|
249
|
+
def get_filenames(path, patterns):
|
|
250
|
+
filenames = []
|
|
251
|
+
if isinstance(patterns, str):
|
|
252
|
+
patterns = (patterns,)
|
|
253
|
+
|
|
254
|
+
for pattern in patterns:
|
|
255
|
+
filenames += glob(os.path.join(path, pattern))
|
|
256
|
+
return filenames
|
|
257
|
+
|
|
258
|
+
def _scan_path(self, path):
|
|
259
|
+
config_files = []
|
|
260
|
+
|
|
261
|
+
for patterns, Loader in self.filetypes:
|
|
262
|
+
for filename in self.get_filenames(path, patterns):
|
|
263
|
+
try:
|
|
264
|
+
loader = Loader(filename=filename)
|
|
265
|
+
if not loader.check():
|
|
266
|
+
continue
|
|
267
|
+
config_files.append(loader)
|
|
268
|
+
except InvalidConfigurationFile:
|
|
269
|
+
continue
|
|
270
|
+
|
|
271
|
+
return config_files
|
|
272
|
+
|
|
273
|
+
def _discover(self):
|
|
274
|
+
self._config_files = []
|
|
275
|
+
|
|
276
|
+
path = self.starting_path
|
|
277
|
+
while True:
|
|
278
|
+
if os.path.isdir(path):
|
|
279
|
+
self._config_files += self._scan_path(path)
|
|
280
|
+
|
|
281
|
+
if path == self.root_path:
|
|
282
|
+
break
|
|
283
|
+
|
|
284
|
+
path = os.path.dirname(path)
|
|
285
|
+
|
|
286
|
+
@property
|
|
287
|
+
def config_files(self):
|
|
288
|
+
if self._config_files is None:
|
|
289
|
+
self._discover()
|
|
290
|
+
|
|
291
|
+
return self._config_files
|
|
292
|
+
|
|
293
|
+
def __repr__(self):
|
|
294
|
+
return f'RecursiveSearch(starting_path={self.starting_path})'
|
|
295
|
+
|
|
296
|
+
def __contains__(self, item):
|
|
297
|
+
for config_file in self.config_files:
|
|
298
|
+
if item in config_file:
|
|
299
|
+
return True
|
|
300
|
+
return False
|
|
301
|
+
|
|
302
|
+
def __getitem__(self, item):
|
|
303
|
+
for config_file in self.config_files:
|
|
304
|
+
try:
|
|
305
|
+
return config_file[item]
|
|
306
|
+
except KeyError:
|
|
307
|
+
continue
|
|
308
|
+
else:
|
|
309
|
+
raise KeyError(f'{item!r}')
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class AwsParameterStore(AbstractConfigurationLoader):
|
|
313
|
+
def __init__(
|
|
314
|
+
self,
|
|
315
|
+
path='/',
|
|
316
|
+
aws_access_key_id=None,
|
|
317
|
+
aws_secret_access_key=None,
|
|
318
|
+
region_name='us-east-1',
|
|
319
|
+
endpoint_url=None,
|
|
320
|
+
):
|
|
321
|
+
if not boto3:
|
|
322
|
+
raise RuntimeError(
|
|
323
|
+
'AwsParameterStore requires [aws] feature. Please install it: "pip install prettyconf[aws]"'
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
self.path = path
|
|
327
|
+
self.aws_access_key_id = aws_access_key_id
|
|
328
|
+
self.aws_secret_access_key = aws_secret_access_key
|
|
329
|
+
self.region_name = region_name
|
|
330
|
+
self.endpoint_url = endpoint_url
|
|
331
|
+
self._fetched = False
|
|
332
|
+
self._parameters = {}
|
|
333
|
+
|
|
334
|
+
def _store_parameters(self, parameters):
|
|
335
|
+
for parameter in parameters:
|
|
336
|
+
self._parameters[parameter['Name'].split('/')[-1]] = parameter['Value']
|
|
337
|
+
|
|
338
|
+
def _fetch_parameters(self):
|
|
339
|
+
if self._fetched:
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
client = boto3.client(
|
|
343
|
+
service_name='ssm',
|
|
344
|
+
aws_access_key_id=self.aws_access_key_id,
|
|
345
|
+
aws_secret_access_key=self.aws_secret_access_key,
|
|
346
|
+
region_name=self.region_name,
|
|
347
|
+
endpoint_url=self.endpoint_url,
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
response = client.get_parameters_by_path(Path=self.path)
|
|
351
|
+
next_token = response.get('NextToken')
|
|
352
|
+
self._store_parameters(response['Parameters'])
|
|
353
|
+
|
|
354
|
+
while next_token:
|
|
355
|
+
response = client.get_parameters_by_path(Path=self.path, NextToken=next_token)
|
|
356
|
+
next_token = response.get('NextToken')
|
|
357
|
+
self._store_parameters(response['Parameters'])
|
|
358
|
+
|
|
359
|
+
self._fetched = True
|
|
360
|
+
|
|
361
|
+
def check(self):
|
|
362
|
+
try:
|
|
363
|
+
self._fetch_parameters()
|
|
364
|
+
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError):
|
|
365
|
+
return False
|
|
366
|
+
|
|
367
|
+
return super().check()
|
|
368
|
+
|
|
369
|
+
def __repr__(self):
|
|
370
|
+
return f'AwsParameterStore(path={self.path} region={self.region_name})'
|
|
371
|
+
|
|
372
|
+
def __contains__(self, item):
|
|
373
|
+
if not self.check():
|
|
374
|
+
return False
|
|
375
|
+
|
|
376
|
+
return item in self._parameters
|
|
377
|
+
|
|
378
|
+
def __getitem__(self, item):
|
|
379
|
+
if not self.check():
|
|
380
|
+
raise KeyError(f'{item!r}')
|
|
381
|
+
|
|
382
|
+
return self._parameters[item]
|
prettyconf/parsers.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
from typing import Union
|
|
3
|
+
|
|
4
|
+
STATE_INITIAL = 'initial'
|
|
5
|
+
STATE_PARSING_KEY = 'parsing_key'
|
|
6
|
+
STATE_PARSING_VALUE = 'parsing_value'
|
|
7
|
+
STATE_PARSING_VALUE_ESCAPE = 'parsing_value_escape'
|
|
8
|
+
STATE_PARSING_COMMENT = 'parsing_comment'
|
|
9
|
+
|
|
10
|
+
COMMENT = '#'
|
|
11
|
+
END_OF_LINE = '\n'
|
|
12
|
+
ESCAPE_CHAR = '\\'
|
|
13
|
+
SPACES = set(' \n')
|
|
14
|
+
QUOTES = set('\'"')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BufferedStreamReader:
|
|
18
|
+
BUFFER_SIZE = 1024
|
|
19
|
+
|
|
20
|
+
def __init__(self, stream):
|
|
21
|
+
self.stream = stream
|
|
22
|
+
self.buffer = stream.read(self.BUFFER_SIZE)
|
|
23
|
+
self.position = 0
|
|
24
|
+
|
|
25
|
+
def read_char(self):
|
|
26
|
+
if self._is_buffer_depleted():
|
|
27
|
+
self._fill_buffer()
|
|
28
|
+
if not self.buffer:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
char = self.buffer[self.position]
|
|
32
|
+
self.position += 1
|
|
33
|
+
return char
|
|
34
|
+
|
|
35
|
+
def _is_buffer_depleted(self):
|
|
36
|
+
return self.position >= len(self.buffer)
|
|
37
|
+
|
|
38
|
+
def _fill_buffer(self):
|
|
39
|
+
self.buffer = self.stream.read(self.BUFFER_SIZE)
|
|
40
|
+
self.position = 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class EnvFileParser:
|
|
44
|
+
def __init__(self, stream):
|
|
45
|
+
self.state = STATE_INITIAL
|
|
46
|
+
self._stream = BufferedStreamReader(stream)
|
|
47
|
+
|
|
48
|
+
self._current_key = []
|
|
49
|
+
self._current_value = []
|
|
50
|
+
self._current_quote = ''
|
|
51
|
+
self._key_parsed = False
|
|
52
|
+
|
|
53
|
+
def parse_config(self) -> Iterator[tuple[str, str]]:
|
|
54
|
+
key = self._current_key
|
|
55
|
+
value = self._current_value
|
|
56
|
+
|
|
57
|
+
while True:
|
|
58
|
+
char = self._stream.read_char()
|
|
59
|
+
if not char:
|
|
60
|
+
if key or value:
|
|
61
|
+
yield self._return_current_config()
|
|
62
|
+
break
|
|
63
|
+
|
|
64
|
+
if self._process_initial(char):
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
if self._process_quotes(char):
|
|
68
|
+
continue
|
|
69
|
+
|
|
70
|
+
if self._start_comment(char):
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
parsed_value = self._finish_comment(char)
|
|
74
|
+
if parsed_value:
|
|
75
|
+
if isinstance(parsed_value, tuple):
|
|
76
|
+
yield parsed_value
|
|
77
|
+
continue
|
|
78
|
+
|
|
79
|
+
if self._parse_key(char):
|
|
80
|
+
continue
|
|
81
|
+
|
|
82
|
+
parsed_value = self._parse_value(char)
|
|
83
|
+
if parsed_value:
|
|
84
|
+
if isinstance(parsed_value, tuple):
|
|
85
|
+
yield parsed_value
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
if self._parse_escaped_value(char):
|
|
89
|
+
continue
|
|
90
|
+
|
|
91
|
+
def _start_comment(self, char):
|
|
92
|
+
if char == COMMENT and (not self._current_quote or self.state == STATE_INITIAL):
|
|
93
|
+
self.state = STATE_PARSING_COMMENT
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
def _finish_comment(self, char) -> Union[bool, tuple[str, str]]:
|
|
99
|
+
if not (self.state == STATE_PARSING_COMMENT and char == END_OF_LINE):
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
if not (self._current_key or self._current_value) or not self._key_parsed:
|
|
103
|
+
# Key started with a comment
|
|
104
|
+
self._reset_state()
|
|
105
|
+
return True
|
|
106
|
+
|
|
107
|
+
return self._return_current_config()
|
|
108
|
+
|
|
109
|
+
def _process_quotes(self, char):
|
|
110
|
+
if char not in QUOTES:
|
|
111
|
+
return False
|
|
112
|
+
if not self._current_quote:
|
|
113
|
+
self._current_quote = char
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
if self._current_quote == char:
|
|
117
|
+
self._current_quote = ''
|
|
118
|
+
return True
|
|
119
|
+
|
|
120
|
+
self._current_value.append(char)
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
def _process_initial(self, char):
|
|
124
|
+
if self.state != STATE_INITIAL:
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
if self._start_comment(char):
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
if char in SPACES:
|
|
131
|
+
return True
|
|
132
|
+
|
|
133
|
+
self._current_key.append(char)
|
|
134
|
+
self.state = STATE_PARSING_KEY
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
def _parse_key(self, char):
|
|
138
|
+
if self.state != STATE_PARSING_KEY:
|
|
139
|
+
return False
|
|
140
|
+
|
|
141
|
+
if char == '=':
|
|
142
|
+
self.state = STATE_PARSING_VALUE
|
|
143
|
+
self._key_parsed = True
|
|
144
|
+
return True
|
|
145
|
+
|
|
146
|
+
if char == END_OF_LINE:
|
|
147
|
+
self._reset_state()
|
|
148
|
+
return True
|
|
149
|
+
|
|
150
|
+
self._current_key.append(char)
|
|
151
|
+
return True
|
|
152
|
+
|
|
153
|
+
def _parse_value(self, char) -> Union[bool, tuple[str, str]]:
|
|
154
|
+
if self.state != STATE_PARSING_VALUE:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
if char == ESCAPE_CHAR:
|
|
158
|
+
self.state = STATE_PARSING_VALUE_ESCAPE
|
|
159
|
+
return True
|
|
160
|
+
|
|
161
|
+
if char == ' ' and not (self._current_value or self._current_quote):
|
|
162
|
+
return True
|
|
163
|
+
|
|
164
|
+
if char == END_OF_LINE:
|
|
165
|
+
return self._return_current_config()
|
|
166
|
+
|
|
167
|
+
self._current_value.append(char)
|
|
168
|
+
return True
|
|
169
|
+
|
|
170
|
+
def _parse_escaped_value(self, char):
|
|
171
|
+
if self.state != STATE_PARSING_VALUE_ESCAPE:
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
if char == END_OF_LINE:
|
|
175
|
+
# resume value parsing on the next line
|
|
176
|
+
self.state = STATE_PARSING_VALUE
|
|
177
|
+
return True
|
|
178
|
+
|
|
179
|
+
# That was a literal \
|
|
180
|
+
self.state = STATE_PARSING_VALUE
|
|
181
|
+
self._current_value.extend([ESCAPE_CHAR, char])
|
|
182
|
+
return True
|
|
183
|
+
|
|
184
|
+
def _return_current_config(self) -> tuple[str, str]:
|
|
185
|
+
key, value = ''.join(self._current_key), ''.join(self._current_value)
|
|
186
|
+
self._reset_state()
|
|
187
|
+
return key.rstrip(), value.rstrip()
|
|
188
|
+
|
|
189
|
+
def _reset_state(self):
|
|
190
|
+
self.state = STATE_INITIAL
|
|
191
|
+
self._current_key.clear()
|
|
192
|
+
self._current_value.clear()
|
|
193
|
+
self._key_parsed = False
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: prettyconf
|
|
3
|
+
Version: 2.3.0
|
|
4
|
+
Summary: Separation of settings from code.
|
|
5
|
+
Author-email: Osvaldo Santana Neto <prettyconf@osantana.me>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Source, https://github.com/osantana/prettyconf
|
|
8
|
+
Project-URL: Download, https://github.com/osantana/prettyconf/releases
|
|
9
|
+
Keywords: asyncio,dispatcher,message,microservices,tasks
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Framework :: Django
|
|
12
|
+
Classifier: Framework :: Flask
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
23
|
+
Classifier: Programming Language :: Python
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/x-rst
|
|
27
|
+
License-File: LICENSE.txt
|
|
28
|
+
License-File: AUTHORS.md
|
|
29
|
+
Provides-Extra: aws
|
|
30
|
+
Requires-Dist: boto3<2.0.0,>=1.28.0; extra == "aws"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
prettyconf
|
|
34
|
+
==========
|
|
35
|
+
|
|
36
|
+
|Coverage Status| |Docs| |Codacy|
|
|
37
|
+
|
|
38
|
+
Pretty Conf is a Python library created to make easy the separation of
|
|
39
|
+
configuration and code following the recomendations of `12 Factor`_'s topic
|
|
40
|
+
about configs.
|
|
41
|
+
|
|
42
|
+
It is strongly inspired in `python-decouple`_ and both provides a similar
|
|
43
|
+
API.
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
Documentation
|
|
47
|
+
-------------
|
|
48
|
+
|
|
49
|
+
You can find ``prettyconf`` documentation at `Read the Docs`_ website.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
.. _`12 Factor`: http://12factor.net/
|
|
53
|
+
.. _`Read the Docs`: http://prettyconf.readthedocs.org/
|
|
54
|
+
.. _`python-decouple`: https://github.com/henriquebastos/python-decouple
|
|
55
|
+
|
|
56
|
+
.. |Coverage Status| image:: https://coveralls.io/repos/osantana/prettyconf/badge.svg?branch=main
|
|
57
|
+
:target: https://coveralls.io/r/osantana/prettyconf?branch=main
|
|
58
|
+
.. |Docs| image:: https://readthedocs.org/projects/prettyconf/badge/?version=latest
|
|
59
|
+
:target: https://readthedocs.org/projects/prettyconf/?badge=latest
|
|
60
|
+
.. |Codacy| image:: https://app.codacy.com/project/badge/Grade/e5caa8df7068427b829fb1f9760de3bc
|
|
61
|
+
:target: https://app.codacy.com/gh/osantana/prettyconf/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
prettyconf/__init__.py,sha256=dICa2QqBEIiqw2mPxkBDENsDZoQtDHNYjnI7GCe0T5U,104
|
|
2
|
+
prettyconf/casts.py,sha256=osKQQJy4mVNffJyx84m6xUpZcQr3YEgJaPkGR0HywFo,2895
|
|
3
|
+
prettyconf/configuration.py,sha256=5n5YYGuwbtwqVq_hSD5lqXoVp19SUbLgDyOnjFXaqGk,1647
|
|
4
|
+
prettyconf/exceptions.py,sha256=riMLqVIVFJT6uf3dO4KCbH20YwxZF3Yr6bULR7cbY0Y,364
|
|
5
|
+
prettyconf/loaders.py,sha256=CHAy4t-i8jUJCKhR_W9CtWeTxizjWoG6nhCVjGnthgM,11344
|
|
6
|
+
prettyconf/parsers.py,sha256=Huz4XuR6rXf5JSll3AQlaGjmKgRlnSFE1r9QkG1kfMs,5294
|
|
7
|
+
prettyconf-2.3.0.dist-info/licenses/AUTHORS.md,sha256=Mhx21Dn3hA7MVIvDHOxfS-DQrM9sHFTSBC8xyjpcEHM,484
|
|
8
|
+
prettyconf-2.3.0.dist-info/licenses/LICENSE.txt,sha256=R0-VTg7WwPj9ceEcFnOjSwM3IGiR9UXRJykx90_fepg,1088
|
|
9
|
+
prettyconf-2.3.0.dist-info/METADATA,sha256=3EUfWVcxu7dQuMmlp-31fmpw-N8FsUpz2R_7NOEiVrQ,2422
|
|
10
|
+
prettyconf-2.3.0.dist-info/WHEEL,sha256=DK49LOLCYiurdXXOXwGJm6U4DkHkg4lcxjhqwRa0CP4,91
|
|
11
|
+
prettyconf-2.3.0.dist-info/top_level.txt,sha256=8Yw7VWVi8HNxM8fZ5xuuJynwq11_taSQT0J1fdWSuzU,11
|
|
12
|
+
prettyconf-2.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Authors and Contributors
|
|
2
|
+
|
|
3
|
+
- [Christofer Bertonha](https://github.com/bertonha)
|
|
4
|
+
- [Erick Wilder](https://github.com/erickwilder)
|
|
5
|
+
- [George Kussumoto](https://github.com/georgeyk)
|
|
6
|
+
- [@hernantz](https://github.com/hernantz)
|
|
7
|
+
- [Jayson Santos](https://github.com/jaysonsantos)
|
|
8
|
+
- [Osvaldo Santana Neto](https://github.com/osantana)
|
|
9
|
+
- [Roel Adriaans](https://github.com/RoelAdriaans)
|
|
10
|
+
- [Ronaldo Duarte](https://github.com/ronaldotd)
|
|
11
|
+
- [Christian Hartung](https://github.com/hartungstenio)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2015 Osvaldo Santana Neto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
prettyconf
|