-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathpresets.py
344 lines (244 loc) · 9.57 KB
/
presets.py
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
"""
Swift preset parsing and handling functionality.
"""
from __future__ import absolute_import, unicode_literals
from collections import namedtuple
from contextlib import contextmanager
try:
# Python 2
import ConfigParser as configparser
from StringIO import StringIO
except ImportError:
import configparser
from io import StringIO
__all__ = [
'Error',
'DuplicatePresetError',
'DuplicateOptionError',
'InterpolationError',
'PresetNotFoundError',
'UnparsedFilesError',
'Preset',
'PresetParser',
]
# -----------------------------------------------------------------------------
_PRESET_PREFIX = 'preset: '
_Mixin = namedtuple('_Mixin', ['name'])
_Argument = namedtuple('_Argument', ['name', 'value'])
_RawPreset = namedtuple('_RawPreset', ['name', 'options'])
def _interpolate_string(string, values):
if string is None:
return string
return string % values
def _remove_prefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
return string
@contextmanager
def _catch_duplicate_option_error():
"""Shim context object used for catching and rethrowing configparser's
DuplicateOptionError, which was added in the Python 3 refactor.
"""
if hasattr(configparser, 'DuplicateOptionError'):
try:
yield
except configparser.DuplicateOptionError as e:
preset_name = _remove_prefix(e.section, _PRESET_PREFIX)
raise DuplicateOptionError(preset_name, e.option)
else:
yield
@contextmanager
def _catch_duplicate_section_error():
"""Shim context object used for catching and rethrowing configparser's
DuplicateSectionError.
"""
try:
yield
except configparser.DuplicateSectionError as e:
preset_name = _remove_prefix(e.section, _PRESET_PREFIX)
raise DuplicatePresetError(preset_name)
@contextmanager
def _convert_configparser_errors():
with _catch_duplicate_option_error(), _catch_duplicate_section_error():
yield
# -----------------------------------------------------------------------------
# Error classes
class Error(Exception):
"""Base class for preset errors.
"""
def __init__(self, message=''):
super(Error, self).__init__(self, message)
self.message = message
def __str__(self):
return self.message
__repr__ = __str__
class DuplicatePresetError(Error):
"""Raised when an existing preset would be overriden.
"""
def __init__(self, preset_name):
Error.__init__(self, '{} already exists'.format(preset_name))
self.preset_name = preset_name
class DuplicateOptionError(Error):
"""Raised when an option is repeated in a single preset.
"""
def __init__(self, preset_name, option):
Error.__init__(self, '{} already exists in preset {}'.format(
option, preset_name))
self.preset_name = preset_name
self.option = option
class InterpolationError(Error):
"""Raised when an error is encountered while interpolating use-provided
values in preset arguments.
"""
def __init__(self, preset_name, option, rawval, reference):
Error.__init__(self, 'no value found for {} in "{}"'.format(
reference, rawval))
self.preset_name = preset_name
self.option = option
self.rawval = rawval
self.reference = reference
class PresetNotFoundError(Error):
"""Raised when a requested preset cannot be found.
"""
def __init__(self, preset_name):
Error.__init__(self, '{} not found'.format(preset_name))
self.preset_name = preset_name
class UnparsedFilesError(Error):
"""Raised when an error was encountered parsing one or more preset files.
"""
def __init__(self, filenames):
Error.__init__(self, 'unable to parse files: {}'.format(filenames))
self.filenames = filenames
# -----------------------------------------------------------------------------
class Preset(namedtuple('Preset', ['name', 'args'])):
"""Container class used to wrap preset names and expanded argument lists.
"""
# Keeps memory costs low according to the docs
__slots__ = ()
def format_args(self):
"""Format argument pairs for use in the command line.
"""
args = []
for (name, value) in self.args:
if value is None:
args.append(name)
else:
args.append('{}={}'.format(name, value))
return args
class PresetParser(object):
"""Parser class used to read and manipulate Swift preset files.
"""
def __init__(self):
self._parser = configparser.RawConfigParser(allow_no_value=True)
self._presets = {}
def _parse_raw_preset(self, section):
preset_name = _remove_prefix(section, _PRESET_PREFIX)
try:
section_items = self._parser.items(section)
except configparser.InterpolationMissingOptionError as e:
raise InterpolationError(preset_name, e.option, e.rawval,
e.reference)
args = []
for (option, value) in section_items:
# Ignore the '--' separator, it's no longer necessary
if option == 'dash-dash':
continue
# Parse out mixin options
if option == 'mixin-preset':
lines = value.strip().splitlines()
args += [_Mixin(option.strip()) for option in lines]
continue
option = '--' + option # Format as a command-line option
args.append(_Argument(option, value))
return _RawPreset(preset_name, args)
def _parse_raw_presets(self):
for section in self._parser.sections():
# Skip all non-preset sections
if not section.startswith(_PRESET_PREFIX):
continue
raw_preset = self._parse_raw_preset(section)
self._presets[raw_preset.name] = raw_preset
def read(self, filenames):
"""Reads and parses preset files. Throws an UnparsedFilesError if any
of the files couldn't be read.
"""
with _convert_configparser_errors():
parsed_files = self._parser.read(filenames)
unparsed_files = set(filenames) - set(parsed_files)
if len(unparsed_files) > 0:
raise UnparsedFilesError(list(unparsed_files))
self._parse_raw_presets()
def read_file(self, file):
"""Reads and parses a single file.
"""
self.read([file])
def read_string(self, string):
"""Reads and parses a string containing preset definintions.
"""
fp = StringIO(string)
with _convert_configparser_errors():
# ConfigParser changes drastically from Python 2 to 3
if hasattr(self._parser, 'read_file'):
self._parser.read_file(fp)
else:
self._parser.readfp(fp)
self._parse_raw_presets()
def _get_preset(self, name):
preset = self._presets.get(name)
if preset is None:
raise PresetNotFoundError(name)
if isinstance(preset, _RawPreset):
preset = self._resolve_preset_mixins(preset)
# Cache resolved preset
self._presets[name] = preset
return preset
def _resolve_preset_mixins(self, raw_preset):
"""Resolve all mixins in a preset, fully expanding the arguments list.
"""
assert isinstance(raw_preset, _RawPreset)
# Expand mixin arguments
args = []
for option in raw_preset.options:
if isinstance(option, _Mixin):
args += self._get_preset(option.name).args
elif isinstance(option, _Argument):
args.append((option.name, option.value))
else:
# Should be unreachable
raise ValueError('invalid argument type: {}', option.__class__)
return Preset(raw_preset.name, args)
def _interpolate_preset_vars(self, preset, vars):
interpolated_args = []
for (name, value) in preset.args:
try:
value = _interpolate_string(value, vars)
except KeyError as e:
raise InterpolationError(preset.name, name, value, e.args[0])
interpolated_args.append((name, value))
return Preset(preset.name, interpolated_args)
def get_preset(self, name, raw=False, vars=None):
"""Returns the preset with the requested name or throws a
PresetNotFoundError.
If raw is False vars will be interpolated into the preset arguments.
Otherwise presets will be returned without interpolation.
Presets are retrieved using a dynamic caching algorithm that expands
only the requested preset and it's mixins recursively. Every expanded
preset is then cached. All subsequent expansions or calls to
`get_preset` for any pre-expanded presets will use the cached results.
"""
vars = vars or {}
preset = self._get_preset(name)
if not raw:
preset = self._interpolate_preset_vars(preset, vars)
return preset
def preset_names(self):
"""Returns a list of all parsed preset names.
"""
return self._presets.keys()