-
Notifications
You must be signed in to change notification settings - Fork 337
/
cmd.py
374 lines (305 loc) · 12.2 KB
/
cmd.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
"""
Windows Command Prompt (DOS) shell.
"""
from rez.config import config
from rez.rex import RexExecutor, expandable, literal, OutputStyle, EscapedString
from rez.shells import Shell
from rez.system import system
from rez.utils.execution import Popen
from rez.utils.platform_ import platform_
from rez.vendor.six import six
from functools import partial
import os
import re
import subprocess
basestring = six.string_types[0]
class CMD(Shell):
# For reference, the ss64 web page provides useful documentation on builtin
# commands for the Windows Command Prompt (cmd). It can be found here :
# http://ss64.com/nt/cmd.html
syspaths = None
_doskey = None
expand_env_vars = True
_env_var_regex = re.compile("%([A-Za-z0-9_]+)%") # %ENVVAR%
# Regex to aid with escaping of Windows-specific special chars:
# http://ss64.com/nt/syntax-esc.html
_escape_re = re.compile(r'(?<!\^)[&<>]|(?<!\^)\^(?![&<>\^])|(\|)')
_escaper = partial(_escape_re.sub, lambda m: '^' + m.group(0))
@classmethod
def name(cls):
return 'cmd'
@classmethod
def file_extension(cls):
return 'bat'
@classmethod
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False,
command=False):
cls._unsupported_option('rcfile', rcfile)
rcfile = False
cls._unsupported_option('norc', norc)
norc = False
cls._unsupported_option('stdin', stdin)
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)
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=subprocess.PIPE,
stderr=subprocess.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=subprocess.PIPE,
stderr=subprocess.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 = [x for x in paths if x]
return cls.syspaths
def _bind_interactive_rez(self):
if config.set_prompt and self.settings.prompt:
stored_prompt = os.getenv("REZ_STORED_PROMPT_CMD")
curr_prompt = stored_prompt or os.getenv("PROMPT", "")
if not stored_prompt:
self.setenv("REZ_STORED_PROMPT_CMD", curr_prompt)
new_prompt = "%%REZ_ENV_PROMPT%%"
new_prompt = (new_prompt + " %s") if config.prefix_prompt \
else ("%s " + new_prompt)
new_prompt = new_prompt % curr_prompt
self._addline('set PROMPT=%s' % new_prompt)
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:
# previously this was called with the /K flag, however
# that would leave spawn_shell hung on a blocked call
# waiting for the user to type "exit" into the shell that
# was spawned to run the rez context printout
ex.command("cmd /Q /C rez context")
def _create_ex():
return RexExecutor(interpreter=self.new_shell(),
parent_environ={},
add_default_namespaces=False)
executor = _create_ex()
if self.settings.prompt:
executor.interpreter._saferefenv('REZ_ENV_PROMPT')
executor.env.REZ_ENV_PROMPT = \
expandable("%REZ_ENV_PROMPT%").literal(self.settings.prompt)
# Make .py launch within cmd without extension.
if self.settings.additional_pathext:
# Ensure that the PATHEXT does not append duplicates.
for pathext in self.settings.additional_pathext:
executor.command('echo %PATHEXT%|C:\\Windows\\System32\\findstr.exe /i /c:"{0}">nul || set PATHEXT=%PATHEXT%;{0}'.format(
pathext
))
# This resets the errorcode, which is tainted by the code above
executor.command("(call )")
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))
if shell_command:
# Launch the provided command in the configured shell and wait
# until it exits.
executor.command(shell_command)
# Test for None specifically because resolved_context.execute_rex_code
# passes '' and we do NOT want to keep a shell open during a rex code
# exec operation.
elif shell_command is None:
# Launch the configured shell itself and wait for user interaction
# to exit.
executor.command('cmd /Q /K')
# Exit the configured shell.
executor.command('exit %errorlevel%')
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)
if startup_sequence["stdin"] and stdin and (stdin is not True):
Popen_args["stdin"] = stdin
cmd = []
if pre_command:
if isinstance(pre_command, basestring):
cmd = pre_command.strip().split()
else:
cmd = pre_command
# Test for None specifically because resolved_context.execute_rex_code
# passes '' and we do NOT want to keep a shell open during a rex code
# exec operation.
if shell_command is None:
cmd_flags = ['/Q', '/K']
else:
cmd_flags = ['/Q', '/C']
cmd += [self.executable]
cmd += cmd_flags
cmd += ['call {}'.format(target_file)]
is_detached = (cmd[0] == 'START')
p = Popen(cmd, env=env, shell=is_detached, **Popen_args)
return p
def get_output(self, style=OutputStyle.file):
if style == OutputStyle.file:
script = '\n'.join(self._lines) + '\n'
else: # eval style
lines = []
for line in self._lines:
if not line.startswith('REM'): # strip comments
line = line.rstrip()
lines.append(line)
script = '&& '.join(lines)
return script
def escape_string(self, value):
"""Escape the <, >, ^, and & special characters reserved by Windows.
Args:
value (str/EscapedString): String or already escaped string.
Returns:
str: The value escaped for Windows.
"""
value = EscapedString.promote(value)
value = value.expanduser()
result = ''
for is_literal, txt in value.strings:
if is_literal:
txt = self._escaper(txt)
# Note that cmd uses ^% while batch files use %% to escape %
txt = self._env_var_regex.sub(r"%%\1%%", txt)
else:
txt = self._escaper(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('set %s=%s' % (key, value))
def unsetenv(self, key):
self._addline("set %s=" % key)
def resetenv(self, key, value, friends=None):
self._addline(self.setenv(key, value))
def alias(self, key, value):
# find doskey, falling back to system paths if not in $PATH. Fall back
# to unqualified 'doskey' if all else fails
if self._doskey is None:
try:
self.__class__._doskey = \
self.find_executable("doskey", check_syspaths=True)
except:
self._doskey = "doskey"
self._addline("%s %s=%s $*" % (self._doskey, key, value))
def comment(self, value):
for line in value.split('\n'):
self._addline('REM %s' % line)
def info(self, value):
for line in value.split('\n'):
line = self.escape_string(line)
line = self.convert_tokens(line)
if line:
self._addline('echo %s' % line)
else:
self._addline('echo.')
def error(self, value):
for line in value.split('\n'):
line = self.escape_string(line)
line = self.convert_tokens(line)
self._addline('echo "%s" 1>&2' % line)
def source(self, value):
self._addline("call %s" % value)
def command(self, value):
self._addline(value)
@classmethod
def get_all_key_tokens(cls, key):
return ["%{}%".format(key)]
@classmethod
def join(cls, command):
# TODO: This may disappear in future [1]
# [1] https://bugs.python.org/issue10838
return subprocess.list2cmdline(command)
@classmethod
def line_terminator(cls):
return "\r\n"
def register_plugin():
if platform_.name == "windows":
return CMD
# Copyright 2013-2016 Allan Johns.
#
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.