-
Notifications
You must be signed in to change notification settings - Fork 337
/
powershell_base.py
313 lines (251 loc) · 9.91 KB
/
powershell_base.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
import os
import re
from subprocess import PIPE, list2cmdline
from rez.backport.shutilwhich import which
from rez.config import config
from rez.rex import RexExecutor, OutputStyle, EscapedString
from rez.shells import Shell
from rez.system import system
from rez.utils.platform_ import platform_
from rez.utils.execution import Popen
class PowerShellBase(Shell):
"""
Abstract base class for PowerShell-like shells.
"""
expand_env_vars = True
syspaths = None
# Make sure that the $Env:VAR formats come before the $VAR formats since
# PowerShell Environment variables are ambiguous with Unix paths.
ENV_VAR_REGEX = re.compile(
"|".join([
"\\$[Ee][Nn][Vv]:([a-zA-Z_]+[a-zA-Z0-9_]*?)", # $Env:ENVVAR
"\\${[Ee][Nn][Vv]:([a-zA-Z_]+[a-zA-Z0-9_]*?)}", # ${Env:ENVVAR}
Shell.ENV_VAR_REGEX.pattern, # Generic form
])
)
@staticmethod
def _escape_quotes(s):
return s.replace('"', '`"').replace("'", "`'")
@staticmethod
def _escape_vars(s):
return s.replace('$', '`$')
@classmethod
def startup_capabilities(cls,
rcfile=False,
norc=False,
stdin=False,
command=False):
cls._unsupported_option('rcfile', rcfile)
cls._unsupported_option('norc', norc)
cls._unsupported_option('stdin', stdin)
rcfile = False
norc = False
stdin = False
return (rcfile, norc, stdin, command)
@classmethod
def get_startup_sequence(cls, rcfile, norc, stdin, command):
rcfile, norc, stdin, command = \
cls.startup_capabilities(rcfile, norc, stdin, command)
return dict(stdin=stdin,
command=command,
do_rcfile=False,
envvar=None,
files=[],
bind_files=[],
source_bind_files=(not norc))
@classmethod
def get_syspaths(cls):
if cls.syspaths is not None:
return cls.syspaths
if config.standard_system_paths:
cls.syspaths = config.standard_system_paths
return cls.syspaths
# detect system paths using registry
def gen_expected_regex(parts):
whitespace = r"[\s]+"
return whitespace.join(parts)
# TODO: Research if there is an easier way to pull system PATH from
# registry in powershell
paths = []
cmd = [
"REG", "QUERY",
("HKLM\\SYSTEM\\CurrentControlSet\\"
"Control\\Session Manager\\Environment"), "/v", "PATH"
]
expected = gen_expected_regex([
("HKEY_LOCAL_MACHINE\\\\SYSTEM\\\\CurrentControlSet\\\\"
"Control\\\\Session Manager\\\\Environment"), "PATH",
"REG_(EXPAND_)?SZ", "(.*)"
])
p = Popen(cmd, stdout=PIPE, stderr=PIPE,
shell=True, text=True)
out_, _ = p.communicate()
out_ = out_.strip()
if p.returncode == 0:
match = re.match(expected, out_)
if match:
paths.extend(match.group(2).split(os.pathsep))
cmd = ["REG", "QUERY", "HKCU\\Environment", "/v", "PATH"]
expected = gen_expected_regex([
"HKEY_CURRENT_USER\\\\Environment", "PATH", "REG_(EXPAND_)?SZ",
"(.*)"
])
p = Popen(cmd, stdout=PIPE, stderr=PIPE,
shell=True, text=True)
out_, _ = p.communicate()
out_ = out_.strip()
if p.returncode == 0:
match = re.match(expected, out_)
if match:
paths.extend(match.group(2).split(os.pathsep))
cls.syspaths = list(set([x for x in paths if x]))
return cls.syspaths
def _bind_interactive_rez(self):
if config.set_prompt and self.settings.prompt:
self._addline('Function prompt {"%s"}' % self.settings.prompt)
def _additional_commands(self, executor):
# Make .py launch within shell without extension.
# For PowerShell this will also execute in the same window, so that
# stdout can be captured.
if platform_.name == "windows" and self.settings.additional_pathext:
# Ensures that the PATHEXT does not append duplicates.
executor.command(
'$Env:PATHEXT = ((($Env:PATHEXT + ";{}") -split ";") | Select-Object -Unique) -join ";"'.format(
";".join(self.settings.additional_pathext)
))
def spawn_shell(self,
context_file,
tmpdir,
rcfile=None,
norc=False,
stdin=False,
command=None,
env=None,
quiet=False,
pre_command=None,
add_rez=True,
**Popen_args):
startup_sequence = self.get_startup_sequence(rcfile, norc, bool(stdin),
command)
shell_command = None
def _record_shell(ex, files, bind_rez=True, print_msg=False):
ex.source(context_file)
if startup_sequence["envvar"]:
ex.unsetenv(startup_sequence["envvar"])
if add_rez and bind_rez:
ex.interpreter._bind_interactive_rez()
if print_msg and add_rez and not quiet:
ex.info('')
ex.info('You are now in a rez-configured environment.')
ex.info('')
if system.is_production_rez_install:
ex.command("rezolve context")
executor = RexExecutor(interpreter=self.new_shell(),
parent_environ={},
add_default_namespaces=False)
if startup_sequence["command"] is not None:
_record_shell(executor, files=startup_sequence["files"])
shell_command = startup_sequence["command"]
else:
_record_shell(executor,
files=startup_sequence["files"],
print_msg=(not quiet))
self._additional_commands(executor)
if shell_command:
executor.command(shell_command)
# Forward exit call to parent PowerShell process
executor.command("exit $LastExitCode")
code = executor.get_output()
target_file = os.path.join(tmpdir,
"rez-shell.%s" % self.file_extension())
with open(target_file, 'w') as f:
f.write(code)
cmd = []
if pre_command:
cmd = pre_command
if not isinstance(cmd, (tuple, list)):
cmd = pre_command.rstrip().split()
cmd += [self.executable]
# Suppresses copyright message of PowerShell and pwsh
cmd += ["-NoLogo"]
# Generic form of sourcing that works in powershell and pwsh
cmd += ["-File", target_file]
if shell_command is None:
cmd.insert(1, "-NoExit")
p = Popen(cmd, env=env, **Popen_args)
return p
def get_output(self, style=OutputStyle.file):
if style == OutputStyle.file:
script = '\n'.join(self._lines) + '\n'
else:
lines = []
for line in self._lines:
if line.startswith('#'):
continue
line = line.rstrip()
lines.append(line)
script = '&& '.join(lines)
return script
def escape_string(self, value):
value = EscapedString.promote(value)
value = value.expanduser()
result = ''
for is_literal, txt in value.strings:
if is_literal:
txt = self._escape_quotes(self._escape_vars(txt))
else:
txt = self._escape_quotes(txt)
result += txt
return result
def _saferefenv(self, key):
pass
def shebang(self):
pass
def setenv(self, key, value):
value = self.escape_string(value)
self._addline('$Env:{0} = "{1}"'.format(key, value))
def appendenv(self, key, value):
value = self.escape_string(value)
# Be careful about ambiguous case in pwsh on Linux where pathsep is :
# so that the ${ENV:VAR} form has to be used to not collide.
self._addline(
'$Env:{0} = "${{Env:{0}}}{1}{2}"'.format(key, os.path.pathsep, value)
)
def unsetenv(self, key):
self._addline(r"Remove-Item Env:\%s" % key)
def resetenv(self, key, value, friends=None):
self._addline(self.setenv(key, value))
def alias(self, key, value):
value = EscapedString.disallow(value)
# TODO: Find a way to properly escape paths in alias() calls that also
# contain args
cmd = "function {key}() {{ {value} $args }}"
self._addline(cmd.format(key=key, value=value))
def comment(self, value):
for line in value.split('\n'):
self._addline('# %s' % line)
def info(self, value):
for line in value.split('\n'):
line = self.escape_string(line)
line = self.convert_tokens(line)
self._addline('Write-Host %s' % line)
def error(self, value):
for line in value.split('\n'):
line = self.escape_string(line)
line = self.convert_tokens(line)
self._addline('Write-Error "%s"' % line)
def source(self, value):
self._addline(". \"%s\"" % value)
def command(self, value):
self._addline(value)
@classmethod
def get_all_key_tokens(cls, key):
return ["${Env:%s}" % key, "$Env:%s" % key]
@classmethod
def join(cls, command):
# TODO: This may disappear in future [1]
# [1] https://bugs.python.org/issue10838
return list2cmdline(command)
@classmethod
def line_terminator(cls):
return "\n"