-
Notifications
You must be signed in to change notification settings - Fork 9
/
expandvars.py
469 lines (363 loc) · 12.6 KB
/
expandvars.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# -*- coding: utf-8 -*-
import os
from io import TextIOWrapper
__author__ = "Arijit Basu"
__email__ = "sayanarijit@gmail.com"
__homepage__ = "https://github.com/sayanarijit/expandvars"
__description__ = "Expand system variables Unix style"
__version__ = "v0.12.0"
__license__ = "MIT"
__all__ = [
"BadSubstitution",
"ExpandvarsException",
"MissingClosingBrace",
"MissingExcapedChar",
"NegativeSubStringExpression",
"OperandExpected",
"ParameterNullOrNotSet",
"UnboundVariable",
"expand",
"expandvars",
]
ESCAPE_CHAR = "\\"
# Set EXPANDVARS_RECOVER_NULL="foo" if you want variables with
# `${VAR:?}` syntax to fallback to "foo" if it's not defined.
# Also works works with nounset=True.
#
# This helps with certain use cases where you need to temporarily
# disable strict parsing of critical env vars. e.g. in testing
# environment.
#
# See tests/test_recover_null.py for examples.
#
# WARNING: Try to avoid `export EXPANDVARS_RECOVER_NULL` as it
# will permanently disable strict parsing until you log out.
RECOVER_NULL = os.environ.get("EXPANDVARS_RECOVER_NULL", None)
class ExpandvarsException(Exception):
"""The base exception for all the handleable exceptions."""
pass
class MissingClosingBrace(ExpandvarsException, SyntaxError):
def __init__(self, param):
super().__init__("{0}: missing '}}'".format(param))
class MissingExcapedChar(ExpandvarsException, SyntaxError):
def __init__(self, param):
super().__init__("{0}: missing escaped character".format(param))
class OperandExpected(ExpandvarsException, SyntaxError):
def __init__(self, param, operand):
super().__init__(
"{0}: operand expected (error token is {1})".format(param, repr(operand))
)
class NegativeSubStringExpression(ExpandvarsException, IndexError):
def __init__(self, param, expr):
super().__init__("{0}: {1}: substring expression < 0".format(param, expr))
class BadSubstitution(ExpandvarsException, SyntaxError):
def __init__(self, param):
super().__init__("{0}: bad substitution".format(param))
class ParameterNullOrNotSet(ExpandvarsException, KeyError):
def __init__(self, param, msg=None):
if msg is None:
msg = "parameter null or not set"
super().__init__("{0}: {1}".format(param, msg))
class UnboundVariable(ExpandvarsException, KeyError):
def __init__(self, param):
super().__init__("{0}: unbound variable".format(param))
def _valid_char(char):
return char.isalnum() or char == "_"
def _isint(val):
try:
int(val)
return True
except ValueError:
return False
def getenv(var, nounset, indirect, environ, default=None):
"""Get value from environment variable.
When nounset is True, it behaves like bash's "set -o nounset" or "set -u"
and raises UnboundVariable exception.
When indirect is True, it will use the value of the resolved variable as
the name of the final variable.
"""
val = environ.get(var)
if val is not None and indirect:
val = environ.get(val)
if val:
return val
if default is not None:
return default
if nounset:
if RECOVER_NULL is not None:
return RECOVER_NULL
raise UnboundVariable(var)
return ""
def escape(vars_, nounset, environ, var_symbol):
"""Escape the first character."""
if len(vars_) == 0:
raise MissingExcapedChar(vars_)
if len(vars_) == 1:
return vars_[0]
if vars_[0] == var_symbol:
return vars_[0] + expand(vars_[1:], environ=environ, var_symbol=var_symbol)
if vars_[0] == ESCAPE_CHAR:
if vars_[1] == var_symbol:
return ESCAPE_CHAR + expand(
vars_[1:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
if vars_[1] == ESCAPE_CHAR:
return ESCAPE_CHAR + escape(
vars_[2:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
return (
ESCAPE_CHAR
+ vars_[0]
+ expand(vars_[1:], nounset=nounset, environ=environ, var_symbol=var_symbol)
)
def expand_var(vars_, nounset, environ, var_symbol):
"""Expand a single variable."""
if len(vars_) == 0:
return var_symbol
if vars_[0] == ESCAPE_CHAR:
return var_symbol + escape(
vars_[1:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
if vars_[0] == var_symbol:
return str(os.getpid()) + expand(
vars_[1:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
if vars_[0] == "{":
return expand_modifier_var(
vars_[1:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
buff = []
for c in vars_:
if _valid_char(c):
buff.append(c)
else:
n = len(buff)
return getenv(
"".join(buff), nounset=nounset, indirect=False, environ=environ
) + expand(
vars_[n:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
return getenv("".join(buff), nounset=nounset, indirect=False, environ=environ)
def expand_modifier_var(vars_, nounset, environ, var_symbol):
"""Expand variables with modifier."""
if len(vars_) <= 1:
raise BadSubstitution(vars_)
if vars_[0] == "!":
indirect = True
vars_ = vars_[1:]
else:
indirect = False
buff = []
for c in vars_:
if _valid_char(c):
buff.append(c)
elif c == "}":
n = len(buff) + 1
return getenv(
"".join(buff), nounset=nounset, indirect=indirect, environ=environ
) + expand(
vars_[n:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
else:
n = len(buff)
if c == ":":
n += 1
return expand_advanced(
"".join(buff),
vars_[n:],
nounset=nounset,
indirect=indirect,
environ=environ,
var_symbol=var_symbol,
)
raise MissingClosingBrace("".join(buff))
def expand_advanced(var, vars_, nounset, indirect, environ, var_symbol):
"""Expand substitution."""
if len(vars_) == 0:
raise MissingClosingBrace(var)
modifier = []
depth = 1
for c in vars_:
if c == "{":
depth += 1
modifier.append(c)
elif c == "}":
depth -= 1
if depth == 0:
break
else:
modifier.append(c)
else:
modifier.append(c)
if depth != 0:
raise MissingClosingBrace(var)
vars_ = vars_[len(modifier) + 1 :]
modifier = expand(
"".join(modifier), nounset=nounset, environ=environ, var_symbol=var_symbol
)
if not modifier:
raise BadSubstitution(var)
if modifier[0] == "-":
return expand_default(
var,
modifier=modifier[1:],
set_=False,
nounset=nounset,
indirect=indirect,
environ=environ,
) + expand(vars_, nounset=nounset, environ=environ, var_symbol=var_symbol)
if modifier[0] == "=":
return expand_default(
var,
modifier=modifier[1:],
set_=True,
nounset=nounset,
indirect=indirect,
environ=environ,
) + expand(vars_, nounset=nounset, environ=environ, var_symbol=var_symbol)
if modifier[0] == "+":
return expand_substitute(
var,
modifier=modifier[1:],
environ=environ,
) + expand(vars_, nounset=nounset, environ=environ, var_symbol=var_symbol)
if modifier[0] == "?":
return expand_strict(
var,
modifier=modifier[1:],
environ=environ,
) + expand(vars_, nounset=nounset, environ=environ, var_symbol=var_symbol)
return expand_offset(
var,
modifier=modifier,
nounset=nounset,
environ=environ,
) + expand(vars_, nounset=nounset, environ=environ, var_symbol=var_symbol)
def expand_strict(var, modifier, environ):
"""Expand variable that must be defined."""
val = environ.get(var, "")
if val:
return val
if RECOVER_NULL is not None:
return RECOVER_NULL
raise ParameterNullOrNotSet(var, modifier if modifier else None)
def expand_offset(var, modifier, nounset, environ):
"""Expand variable with offset."""
buff = []
for c in modifier:
if c == ":":
n = len(buff) + 1
offset_str = "".join(buff)
if not offset_str or not _isint(offset_str):
offset = 0
else:
offset = int(offset_str)
return expand_length(
var,
modifier=modifier[n:],
offset=offset,
nounset=nounset,
environ=environ,
)
buff.append(c)
n = len(buff) + 1
offset_str = "".join(buff).strip()
if not offset_str or not _isint(offset_str):
offset = 0
else:
offset = int(offset_str)
return getenv(var, nounset=nounset, indirect=False, environ=environ)[offset:]
def expand_length(var, modifier, offset, nounset, environ):
"""Expand variable with offset and length."""
length_str = modifier.strip()
if not length_str:
length = None
elif not _isint(length_str):
if not all(_valid_char(c) for c in length_str):
raise OperandExpected(var, length_str)
else:
length = None
else:
length = int(length_str)
if length < 0:
raise NegativeSubStringExpression(var, length_str)
if length is None:
width = 0
else:
width = offset + length
return getenv(var, nounset=nounset, indirect=False, environ=environ)[offset:width]
def expand_substitute(var, modifier, environ):
"""Expand or return substitute."""
if environ.get(var):
return modifier
return ""
def expand_default(var, modifier, set_, nounset, indirect, environ):
"""Expand var or return default."""
if set_ and not environ.get(var):
environ.update({var: modifier})
return getenv(
var,
nounset=nounset,
indirect=indirect,
default=modifier,
environ=environ,
)
def expand(vars_, nounset=False, environ=os.environ, var_symbol="$"):
"""Expand variables Unix style.
Params:
vars_ (str): Variables to expand.
nounset (bool): If True, enables strict parsing (similar to set -u / set -o nounset in bash).
environ (Mapping): Elements to consider during variable expansion. Defaults to os.environ
var_symbol (str): Character used to identify a variable. Defaults to $
Returns:
str: Expanded values.
Example usage: ::
from expandvars import expand
print(expand("%PATH:$HOME/bin:%{SOME_UNDEFINED_PATH:-/default/path}", environ={"PATH": "/example"}, var_symbol="%"))
# /example:$HOME/bin:/default/path
# Or
with open(somefile) as f:
print(expand(f))
"""
if isinstance(vars_, TextIOWrapper):
# This is a file. Read it.
vars_ = vars_.read().strip()
if len(vars_) == 0:
return ""
buff = []
try:
for c in vars_:
if c == var_symbol:
n = len(buff) + 1
return "".join(buff) + expand_var(
vars_[n:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
if c == ESCAPE_CHAR:
n = len(buff) + 1
return "".join(buff) + escape(
vars_[n:], nounset=nounset, environ=environ, var_symbol=var_symbol
)
buff.append(c)
return "".join(buff)
except MissingExcapedChar:
raise MissingExcapedChar(vars_)
except MissingClosingBrace:
raise MissingClosingBrace(vars_)
except BadSubstitution:
raise BadSubstitution(vars_)
def expandvars(vars_, nounset=False):
"""Expand system variables Unix style.
Params:
vars_ (str): System variables to expand.
nounset (bool): If True, enables strict parsing (similar to set -u / set -o nounset in bash).
Returns:
str: Expanded values.
Example usage: ::
from expandvars import expandvars
print(expandvars("$PATH:$HOME/bin:${SOME_UNDEFINED_PATH:-/default/path}"))
# /bin:/sbin:/usr/bin:/usr/sbin:/home/you/bin:/default/path
# Or
with open(somefile) as f:
print(expandvars(f))
"""
return expand(vars_, nounset=nounset)