-
Notifications
You must be signed in to change notification settings - Fork 326
/
rex.py
1448 lines (1129 loc) · 45.1 KB
/
rex.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
import os
import sys
import re
import traceback
from fnmatch import fnmatch
from enum import Enum
from contextlib import contextmanager
from string import Formatter
from collections.abc import MutableMapping
from rez.system import system
from rez.config import config
from rez.exceptions import RexError, RexUndefinedVariableError, \
RezSystemError, _NeverError
from rez.util import shlex_join, is_non_string_iterable
from rez.utils import reraise
from rez.utils.execution import Popen
from rez.utils.sourcecode import SourceCode, SourceCodeError
from rez.utils.data_utils import AttrDictWrapper
from rez.utils.formatting import expandvars
from rez.utils.platform_ import platform_
#===============================================================================
# Actions
#===============================================================================
class Action(object):
_registry = []
def __init__(self, *args):
self.args = args
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,
', '.join(repr(x) for x in self.args))
def __eq__(self, other):
return (self.name == other.name) and (self.args == other.args)
@classmethod
def register_command_type(cls, name, klass):
cls._registry.append((name, klass))
@classmethod
def register(cls):
cls.register_command_type(cls.name, cls)
@classmethod
def get_command_types(cls):
return tuple(cls._registry)
class EnvAction(Action):
@property
def key(self):
return self.args[0]
@property
def value(self):
if len(self.args) == 2:
return self.args[1]
class Unsetenv(EnvAction):
name = 'unsetenv'
class Setenv(EnvAction):
name = 'setenv'
def pre_exec(self, interpreter):
key, value = self.args
if isinstance(value, (list, tuple)):
value = interpreter._env_sep(key).join(value)
self.args = key, value
def post_exec(self, interpreter, result):
interpreter._environ.add(self.key)
return result
class Resetenv(EnvAction):
name = 'resetenv'
@property
def friends(self):
if len(self.args) == 3:
return self.args[2]
def pre_exec(self, interpreter):
key, value, friends = self.args
if isinstance(value, (list, tuple)):
value = interpreter._env_sep(key).join(value)
self.args = key, value, friends
def post_exec(self, interpreter, result):
interpreter._environ.add(self.key)
return result
class Prependenv(Setenv):
name = 'prependenv'
class Appendenv(Setenv):
name = 'appendenv'
class Alias(Action):
name = 'alias'
class Info(Action):
name = 'info'
class Error(Action):
name = 'error'
class Stop(Action):
name = 'stop'
class Command(Action):
name = 'command'
class Comment(Action):
name = 'comment'
class Source(Action):
name = 'source'
class Shebang(Action):
name = 'shebang'
Unsetenv.register()
Setenv.register()
Resetenv.register()
Prependenv.register()
Appendenv.register()
Alias.register()
Info.register()
Error.register()
Stop.register()
Command.register()
Comment.register()
Source.register()
Shebang.register()
#===============================================================================
# Action Manager
#===============================================================================
class OutputStyle(Enum):
""" Enum to represent the style of code output when using Rex.
"""
file = ("Code as it would appear in a script file.", )
eval = ("Code in a form that can be evaluated.", )
class ActionManager(object):
"""Handles the execution book-keeping. Tracks env variable values, and
triggers the callbacks of the `ActionInterpreter`.
"""
def __init__(self, interpreter, parent_environ=None, parent_variables=None,
formatter=None, verbose=False, env_sep_map=None):
'''
interpreter: string or `ActionInterpreter`
the interpreter to use when executing rex actions
parent_environ: environment to execute the actions within. If None,
defaults to the current environment.
parent_variables: List of variables to append/prepend to, rather than
overwriting on first reference. If this is set to True instead of a
list, all variables are treated as parent variables.
formatter: func or None
function to use for formatting string values
verbose : bool or list of str
if True, causes commands to print additional feedback (using info()).
can also be set to a list of strings matching command names to add
verbosity to only those commands.
'''
self.interpreter = interpreter
self.verbose = verbose
self.parent_environ = os.environ if parent_environ is None else parent_environ
self.parent_variables = True if parent_variables is True \
else set(parent_variables or [])
self.environ = {}
self.formatter = formatter or str
self.actions = []
self._env_sep_map = env_sep_map if env_sep_map is not None \
else config.env_var_separators
def get_action_methods(self):
"""
return a list of methods on this class for executing actions.
methods are return as a list of (name, func) tuples
"""
return [(name, getattr(self, name))
for name, _ in Action.get_command_types()]
def get_public_methods(self):
"""
return a list of methods on this class which should be exposed in the rex
API.
"""
return self.get_action_methods() + [
('getenv', self.getenv),
('expandvars', self.expandvars),
('defined', self.defined),
('undefined', self.undefined)]
def _env_sep(self, name):
return self._env_sep_map.get(name, self.interpreter.pathsep)
def _is_verbose(self, command):
if isinstance(self.verbose, (list, tuple)):
return command in self.verbose
else:
return bool(self.verbose)
def _format(self, value):
# It would be unexpected to get var expansion on the str repr of an
# object, so don't do that.
#
if not isinstance(value, (str, EscapedString)):
return str(value)
# Perform expansion on non-literal parts of the string. If any
# expansion fails, just return unformatted string.
#
try:
return EscapedString.promote(value).formatted(self.formatter)
except (KeyError, ValueError):
return value
def _expand(self, value):
def _fn(str_):
str_ = expandvars(str_, self.environ)
str_ = expandvars(str_, self.parent_environ)
return os.path.expanduser(str_)
return EscapedString.promote(value).formatted(_fn)
def _key(self, key):
# returns (unexpanded, expanded) forms of key
unexpanded_key = str(self._format(key))
expanded_key = str(self._expand(unexpanded_key))
return unexpanded_key, expanded_key
def _value(self, value):
# returns (unexpanded, expanded) forms of value
unexpanded_value = self._format(value)
expanded_value = self._expand(unexpanded_value)
return unexpanded_value, expanded_value
def get_output(self, style=OutputStyle.file):
return self.interpreter.get_output(style=style)
# -- Commands
def undefined(self, key):
_, expanded_key = self._key(key)
return (
expanded_key not in self.environ
and expanded_key not in self.parent_environ
)
def defined(self, key):
return not self.undefined(key)
def expandvars(self, value, format=True):
if format:
value = str(self._format(value))
return str(self._expand(value))
def getenv(self, key):
_, expanded_key = self._key(key)
try:
return self.environ[expanded_key] if expanded_key in self.environ \
else self.parent_environ[expanded_key]
except KeyError:
raise RexUndefinedVariableError(
"Referenced undefined environment variable: %s" % expanded_key)
def setenv(self, key, value):
unexpanded_key, expanded_key = self._key(key)
unexpanded_value, expanded_value = self._value(value)
# TODO: check if value has already been set by another package
self.actions.append(Setenv(unexpanded_key, unexpanded_value))
self.environ[expanded_key] = str(expanded_value)
if self.interpreter.expand_env_vars:
key, value = expanded_key, expanded_value
else:
key, value = unexpanded_key, unexpanded_value
self.interpreter.setenv(key, value)
def unsetenv(self, key):
unexpanded_key, expanded_key = self._key(key)
self.actions.append(Unsetenv(unexpanded_key))
if expanded_key in self.environ:
del self.environ[expanded_key]
if self.interpreter.expand_env_vars:
key = expanded_key
else:
key = unexpanded_key
self.interpreter.unsetenv(key)
def resetenv(self, key, value, friends=None):
unexpanded_key, expanded_key = self._key(key)
unexpanded_value, expanded_value = self._value(value)
action = Resetenv(unexpanded_key, unexpanded_value, friends)
self.actions.append(action)
self.environ[expanded_key] = str(expanded_value)
if self.interpreter.expand_env_vars:
key, value = expanded_key, expanded_value
else:
key, value = unexpanded_key, unexpanded_value
self.interpreter.resetenv(key, value)
def _pendenv(self, key, value, action, interpfunc, addfunc):
unexpanded_key, expanded_key = self._key(key)
unexpanded_value, expanded_value = self._value(value)
# expose env-vars from parent env if explicitly told to do so
if (expanded_key not in self.environ) and \
((self.parent_variables is True) or (expanded_key in self.parent_variables)):
self.environ[expanded_key] = self.parent_environ.get(expanded_key, '')
if self.interpreter.expand_env_vars:
key_ = expanded_key
else:
key_ = unexpanded_key
self.interpreter._saferefenv(key_)
# *pend or setenv depending on whether this is first reference to the var
if expanded_key in self.environ:
env_sep = self._env_sep(expanded_key)
self.actions.append(action(unexpanded_key, unexpanded_value))
values = addfunc(unexpanded_value, [self._keytoken(expanded_key)])
unexpanded_values = EscapedString.join(env_sep, values)
parts = self.environ[expanded_key].split(env_sep)
values = addfunc(expanded_value, parts)
expanded_values = EscapedString.join(env_sep, values)
self.environ[expanded_key] = \
env_sep.join(addfunc(str(expanded_value), parts))
else:
self.actions.append(Setenv(unexpanded_key, unexpanded_value))
self.environ[expanded_key] = str(expanded_value)
unexpanded_values = unexpanded_value
expanded_values = expanded_value
interpfunc = None
applied = False
if interpfunc:
if self.interpreter.expand_env_vars:
key, value = expanded_key, expanded_value
else:
key, value = unexpanded_key, unexpanded_value
try:
interpfunc(key, value)
applied = True
except NotImplementedError:
pass
if not applied:
if self.interpreter.expand_env_vars:
key, value = expanded_key, expanded_values
else:
key, value = unexpanded_key, unexpanded_values
self.interpreter.setenv(key, value)
def prependenv(self, key, value):
self._pendenv(key, value, Prependenv, self.interpreter.prependenv,
lambda x, y: [x] + y)
def appendenv(self, key, value):
self._pendenv(key, value, Appendenv, self.interpreter.appendenv,
lambda x, y: y + [x])
def alias(self, key, value):
key = str(self._format(key))
value = str(self._format(value))
self.actions.append(Alias(key, value))
self.interpreter.alias(key, value)
def info(self, value=''):
value = self._format(value)
self.actions.append(Info(value))
self.interpreter.info(value)
def error(self, value):
value = self._format(value)
self.actions.append(Error(value))
self.interpreter.error(value)
def stop(self, msg, *nargs):
from rez.exceptions import RexStopError
raise RexStopError(msg % nargs)
def command(self, value):
# Note: Value is deliberately not formatted in commands
self.actions.append(Command(value))
self.interpreter.command(value)
def comment(self, value):
value = str(self._format(value))
self.actions.append(Comment(value))
self.interpreter.comment(value)
def source(self, value):
value = str(self._format(value))
self.actions.append(Source(value))
self.interpreter.source(value)
def shebang(self):
self.actions.append(Shebang())
self.interpreter.shebang()
def _keytoken(self, key):
return self.interpreter.get_key_token(key)
#===============================================================================
# Interpreters
#===============================================================================
class ActionInterpreter(object):
"""
Abstract base class that provides callbacks for rex Actions. This class
should not be used directly. Its methods are called by the
`ActionManager` in response to actions issued by user code written using
the rex python API.
Sub-classes should override the `get_output` method to return
implementation-specific data structure. For example, an interpreter for a
shell language like bash would return a string of shell code. An interpreter
for an active python session might return a dictionary of the modified
environment.
Sub-classes can override the `expand_env_vars` class variable to instruct
the `ActionManager` whether or not to expand the value of environment
variables which reference other variables (e.g. "this-${THAT}").
"""
expand_env_vars = False
# Path separator. There are cases (eg gitbash - git for windows) where the
# path separator does not match the system (ie os.pathsep)
#
pathsep = os.pathsep
# RegEx that captures environment variables (generic form).
# Extend/override to regex formats that can capture environment formats
# in other interpreters like shells if needed
ENV_VAR_REGEX = re.compile(
"|".join([
"\\${([^\\{\\}]+?)}", # ${ENVVAR}
"\\$([a-zA-Z_]+[a-zA-Z0-9_]*?)", # $ENVVAR
])
)
def get_output(self, style=OutputStyle.file):
"""Returns any implementation specific data.
Args:
style (`OutputStyle`): Style affecting output format.
Returns:
Depends on implementation, but usually a code string.
"""
raise NotImplementedError
# --- commands
def setenv(self, key, value):
raise NotImplementedError
def unsetenv(self, key):
raise NotImplementedError
def resetenv(self, key, value, friends=None):
raise NotImplementedError
def prependenv(self, key, value):
"""This is optional, but if it is not implemented, you must
implement setenv."""
raise NotImplementedError
def appendenv(self, key, value):
"""This is optional, but if it is not implemented, you must
implement setenv."""
raise NotImplementedError
def alias(self, key, value):
raise NotImplementedError
def info(self, value):
raise NotImplementedError
def error(self, value):
raise NotImplementedError
def command(self, value):
raise NotImplementedError
def comment(self, value):
raise NotImplementedError
def source(self, value):
raise NotImplementedError
def shebang(self):
raise NotImplementedError
# --- other
def escape_string(self, value, is_path=False):
"""Escape a string.
Escape the given string so that special characters (such as quotes and
whitespace) are treated properly. If `value` is a string, assume that
this is an expandable string in this interpreter.
Note that `is_path` provided because of the special case where a
path-like envvar is set. In this case, path normalization, if it needs
to occur, has to be part of the string escaping process.
Note:
This default implementation returns the string with no escaping
applied.
Args:
value (str or `EscapedString`): String to escape.
is_path (bool): True if the value is path-like.
Returns:
str: The escaped string.
"""
return str(value)
@classmethod
def _is_pathed_key(cls, key):
return any(fnmatch(key, x) for x in config.pathed_env_vars)
def normalize_path(self, path):
"""Normalize a path.
Change `path` to a valid filepath representation for this interpreter.
IMPORTANT: Because var references like ${THIS} might be passed to funcs
like appendvar, `path` might be in this form. You need to take that
into account (ie, ensure normalization doesn't break such a var reference).
Args:
path (str): A filepath which may be in posix format, or windows
format, or some combination of the two. For eg, a string like
`{root}/bin` on windows will evaluate to `C:\\.../bin` - in this
case, the `cmd` shell would want to normalize this and convert
to all forward slashes.
Returns:
str: The normalized path.
"""
return path
def normalize_paths(self, value):
"""Normalize value if it's a path(s).
Note that `value` may be more than one pathsep-delimited paths.
"""
paths = value.split(self.pathsep)
paths = [self.normalize_path(x) for x in paths]
return self.pathsep.join(paths)
# --- internal commands, not exposed to public rex API
def _saferefenv(self, key):
'''
make the var safe to reference, even if it does not yet exist. This is
needed because of different behaviours in shells - eg, tcsh will fail
on ref to undefined var, but sh will expand to the empty string.
'''
raise NotImplementedError
# --- internal functions
def _bind_interactive_rez(self):
'''
apply changes to the env needed to expose rez in an interactive shell,
for eg prompt change, sourcing completion scripts etc. Do NOT add rez
to PATH, this is done elsewhere.
'''
raise NotImplementedError
class Python(ActionInterpreter):
'''Execute commands in the current python session'''
expand_env_vars = True
def __init__(self, target_environ=None, passive=False):
'''
target_environ: dict
If target_environ is None or os.environ, interpreted actions are
applied to the current python interpreter. Otherwise, changes are
only applied to target_environ. In either case you must call
`apply_environ` to flush all changes to the target environ dict.
passive: bool
If True, commands that do not update the environment (such as info)
are skipped.
'''
self.passive = passive
self.manager = None
if (target_environ is None) or (target_environ is os.environ):
self.target_environ = os.environ
self.update_session = True
else:
self.target_environ = target_environ
self.update_session = False
def set_manager(self, manager):
self.manager = manager
def apply_environ(self):
"""Apply changes to target environ.
"""
if self.manager is None:
raise RezSystemError("You must call 'set_manager' on a Python rex "
"interpreter before using it.")
self.target_environ.update(self.manager.environ)
self.adjust_env_for_platform(self.target_environ)
def get_output(self, style=OutputStyle.file):
self.apply_environ()
return self.manager.environ
def setenv(self, key, value):
if self.update_session:
if key == 'PYTHONPATH':
value = self.escape_string(value)
sys.path = value.split(self.pathsep)
def unsetenv(self, key):
pass
def resetenv(self, key, value, friends=None):
pass
def prependenv(self, key, value):
if self.update_session:
if key == 'PYTHONPATH':
value = self.escape_string(value)
sys.path.insert(0, value)
def appendenv(self, key, value):
if self.update_session:
if key == 'PYTHONPATH':
value = self.escape_string(value)
sys.path.append(value)
def info(self, value):
if not self.passive:
value = self.escape_string(value)
print(value)
def error(self, value):
if not self.passive:
value = self.escape_string(value)
print(value, file=sys.stderr)
def subprocess(self, args, **subproc_kwargs):
if self.manager:
self.target_environ.update(self.manager.environ)
self.adjust_env_for_platform(self.target_environ)
shell_mode = isinstance(args, str)
return Popen(args,
shell=shell_mode,
env=self.target_environ,
**subproc_kwargs)
def command(self, value):
if self.passive:
return
if is_non_string_iterable(value):
it = iter(value)
cmd = EscapedString.disallow(next(it))
value = [cmd] + [self.escape_string(x) for x in it]
else:
value = EscapedString.disallow(value)
value = self.escape_string(value)
try:
p = self.subprocess(value)
p.communicate()
except Exception as e:
cmd = shlex_join(value)
raise RexError('Error executing command: %s\n%s' % (cmd, str(e)))
def comment(self, value):
pass
def source(self, value):
pass
def alias(self, key, value):
pass
def _bind_interactive_rez(self):
pass
def _saferefenv(self, key):
pass
def shebang(self):
pass
def get_key_token(self, key):
# Not sure if this actually needs to be returned here. Prior to the
# Windows refactor this is the value this interpretter was receiving,
# but the concept doesn't really feel applicable to Python. It's just
# here because the API requires it.
return "${%s}" % key
def adjust_env_for_platform(self, env):
""" Make required platform-specific adjustments to env.
"""
if platform_.name == "windows":
self._add_systemroot_to_env_win32(env)
def _add_systemroot_to_env_win32(self, env):
r""" Sets ``%SYSTEMROOT%`` environment variable, if not present
in :py:attr:`target_environ` .
Args:
env (dict): desired environment variables
Notes:
on windows, python-3.6 startup fails within an environment
where it ``%PATH%`` includes python3, but ``%SYSTEMROOT%`` is not
present.
for example.
.. code-block:: python
from subprocess import Popen
cmds = ['python', '--version']
# successful
Popen(cmds)
Popen(cmds, env={'PATH': 'C:\\Python-3.6.5',
'SYSTEMROOT': 'C:\Windows'})
# failure
Popen(cmds, env={'PATH': 'C:\\Python-3.6.5'})
#> Fatal Python Error: failed to get random numbers to initialize Python
"""
# 'SYSTEMROOT' unecessary unless 'PATH' is set.
if env is None:
return
# leave SYSTEMROOT alone if set by user
if 'SYSTEMROOT' in env:
return
# not enough info to set SYSTEMROOT
if 'SYSTEMROOT' not in os.environ:
return
env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
#===============================================================================
# String manipulation
#===============================================================================
class EscapedString(object):
"""Class for constructing literal or expandable strings, or a combination
of both.
This determines how a string is escaped in an interpreter. For example,
the following rex commands may result in the bash code shown:
>>> env.FOO = literal('oh "noes"')
>>> env.BAH = expandable('oh "noes"')
export FOO='oh "noes"'
export BAH="oh \"noes\""
You do not need to use `expandable` - a string by default is interpreted as
expandable. However you can mix literals and expandables together, like so:
>>> env.FOO = literal("hello").expandable(" ${DUDE}")
export FOO='hello'" ${DUDE}"
Shorthand methods `e` and `l` are also supplied, for better readability:
>>> env.FOO = literal("hello").e(" ${DUDE}").l(", and welcome!")
export FOO='hello'" ${DUDE}"', and welcome!'
Note:
you can use the `literal` and `expandable` free functions, rather than
constructing a class instance directly.
"""
def __init__(self, value, is_literal=False):
self.strings = [(is_literal, value)]
def copy(self):
other = EscapedString.__new__(EscapedString)
other.strings = self.strings[:]
return other
def literal(self, value):
self._add(value, True)
return self
def expandable(self, value):
self._add(value, False)
return self
def l(self, value): # noqa
return self.literal(value)
def e(self, value):
return self.expandable(value)
def _add(self, value, is_literal):
last = self.strings[-1]
if last[0] == is_literal:
self.strings[-1] = (last[0], last[1] + value)
else:
self.strings.append((is_literal, value))
def __str__(self):
"""Return the string unescaped."""
return ''.join(x[1] for x in self.strings)
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.strings)
def __eq__(self, other):
if isinstance(other, str):
return (str(self) == str(other))
else:
return (
isinstance(other, EscapedString)
and other.strings == self.strings
)
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
"""Join two escaped strings together.
Returns:
`EscapedString` object.
"""
result = self.copy()
other = EscapedString.promote(other)
for is_literal, value in other.strings:
result._add(value, is_literal)
return result
def expanduser(self):
"""Analogous to os.path.expanduser.
Returns:
`EscapedString` object with expanded '~' references.
"""
return self.formatted(os.path.expanduser)
def formatted(self, func):
"""Return the string with non-literal parts formatted.
Args:
func (typing.Callable): Callable that translates a string into a
formatted string.
Returns:
`EscapedString` object.
"""
other = EscapedString.__new__(EscapedString)
other.strings = []
for is_literal, value in self.strings:
if not is_literal:
value = func(value)
other.strings.append((is_literal, value))
return other
def split(self, delimiter=None):
"""Same as string.split(), but retains literal/expandable structure.
Returns:
List of `EscapedString`.
"""
result = []
strings = self.strings[:]
current = None
while strings:
is_literal, value = strings[0]
parts = value.split(delimiter, 1)
if len(parts) > 1:
value1, value2 = parts
strings[0] = (is_literal, value2)
out = EscapedString(value1, is_literal)
push = True
else:
strings = strings[1:]
out = EscapedString(value, is_literal)
push = False
if current is None:
current = out
else:
current = current + out
if push:
result.append(current)
current = None
if current:
result.append(current)
return result
@classmethod
def join(cls, sep, values):
if not values:
return EscapedString('')
it = iter(values)
result = EscapedString.promote(next(it))
for value in it:
result = result + sep
result = result + value
return result
@classmethod
def promote(cls, value):
if isinstance(value, cls):
return value
else:
return cls(value)
@classmethod
def demote(cls, value):
if isinstance(value, cls):
return str(value)
else:
return value
@classmethod
def disallow(cls, value):
if isinstance(value, cls):
raise RexError("The command does not accept use of 'literal' or 'expandable'")
return value
def literal(value):
"""Creates a literal string."""
return EscapedString(value, True)
def expandable(value):
"""Creates an expandable string."""
return EscapedString(value, False)
def optionvars(name, default=None):
"""Access arbitrary data from rez config setting 'optionvars'.
Args:
name (str): Name of the optionvar. Use dot notation for values in
nested dicts.
default (object): Default value if setting is missing.
"""