| 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
# |
| 3 |
# This source code is licensed under the MIT license found in the |
| 4 |
# LICENSE file in the root directory of this source tree. |
| 5 |
|
| 6 |
import os |
| 7 |
import select |
| 8 |
import subprocess |
| 9 |
import sys |
| 10 |
|
| 11 |
from .envfuncs import Env |
| 12 |
from .platform import is_windows |
| 13 |
|
| 14 |
|
| 15 |
try: |
| 16 |
from shlex import quote as shellquote |
| 17 |
except ImportError: |
| 18 |
from pipes import quote as shellquote |
| 19 |
|
| 20 |
|
| 21 |
class RunCommandError(Exception): |
| 22 |
pass |
| 23 |
|
| 24 |
|
| 25 |
def _print_env_diff(env, log_fn) -> None: |
| 26 |
current_keys = set(os.environ.keys()) |
| 27 |
wanted_env = set(env.keys()) |
| 28 |
|
| 29 |
unset_keys = current_keys.difference(wanted_env) |
| 30 |
for k in sorted(unset_keys): |
| 31 |
log_fn("+ unset %s\n" % k) |
| 32 |
|
| 33 |
added_keys = wanted_env.difference(current_keys) |
| 34 |
for k in wanted_env.intersection(current_keys): |
| 35 |
if os.environ[k] != env[k]: |
| 36 |
added_keys.add(k) |
| 37 |
|
| 38 |
for k in sorted(added_keys): |
| 39 |
if ("PATH" in k) and (os.pathsep in env[k]): |
| 40 |
log_fn("+ %s=\\\n" % k) |
| 41 |
for elem in env[k].split(os.pathsep): |
| 42 |
log_fn("+ %s%s\\\n" % (shellquote(elem), os.pathsep)) |
| 43 |
else: |
| 44 |
log_fn("+ %s=%s \\\n" % (k, shellquote(env[k]))) |
| 45 |
|
| 46 |
|
| 47 |
def run_cmd(cmd, env=None, cwd=None, allow_fail: bool = False, log_file=None) -> int: |
| 48 |
def log_to_stdout(msg): |
| 49 |
sys.stdout.buffer.write(msg.encode(errors="surrogateescape")) |
| 50 |
|
| 51 |
if log_file is not None: |
| 52 |
with open(log_file, "a", encoding="utf-8", errors="surrogateescape") as log: |
| 53 |
|
| 54 |
def log_function(msg): |
| 55 |
log.write(msg) |
| 56 |
log_to_stdout(msg) |
| 57 |
|
| 58 |
return _run_cmd( |
| 59 |
cmd, env=env, cwd=cwd, allow_fail=allow_fail, log_fn=log_function |
| 60 |
) |
| 61 |
else: |
| 62 |
return _run_cmd( |
| 63 |
cmd, env=env, cwd=cwd, allow_fail=allow_fail, log_fn=log_to_stdout |
| 64 |
) |
| 65 |
|
| 66 |
|
| 67 |
def _run_cmd(cmd, env, cwd, allow_fail, log_fn) -> int: |
| 68 |
log_fn("---\n") |
| 69 |
try: |
| 70 |
cmd_str = " \\\n+ ".join(shellquote(arg) for arg in cmd) |
| 71 |
except TypeError: |
| 72 |
# eg: one of the elements is None |
| 73 |
raise RunCommandError("problem quoting cmd: %r" % cmd) |
| 74 |
|
| 75 |
if env: |
| 76 |
assert isinstance(env, Env) |
| 77 |
_print_env_diff(env, log_fn) |
| 78 |
|
| 79 |
# Convert from our Env type to a regular dict. |
| 80 |
# This is needed because python3 looks up b'PATH' and 'PATH' |
| 81 |
# and emits an error if both are present. In our Env type |
| 82 |
# we'll return the same value for both requests, but we don't |
| 83 |
# have duplicate potentially conflicting values which is the |
| 84 |
# spirit of the check. |
| 85 |
env = dict(env.items()) |
| 86 |
|
| 87 |
if cwd: |
| 88 |
log_fn("+ cd %s && \\\n" % shellquote(cwd)) |
| 89 |
# Our long path escape sequence may confuse cmd.exe, so if the cwd |
| 90 |
# is short enough, strip that off. |
| 91 |
if is_windows() and (len(cwd) < 250) and cwd.startswith("\\\\?\\"): |
| 92 |
cwd = cwd[4:] |
| 93 |
|
| 94 |
log_fn("+ %s\n" % cmd_str) |
| 95 |
|
| 96 |
isinteractive = os.isatty(sys.stdout.fileno()) |
| 97 |
if isinteractive: |
| 98 |
stdout = None |
| 99 |
sys.stdout.buffer.flush() |
| 100 |
else: |
| 101 |
stdout = subprocess.PIPE |
| 102 |
|
| 103 |
try: |
| 104 |
p = subprocess.Popen( |
| 105 |
cmd, env=env, cwd=cwd, stdout=stdout, stderr=subprocess.STDOUT |
| 106 |
) |
| 107 |
except (TypeError, ValueError, OSError) as exc: |
| 108 |
log_fn("error running `%s`: %s" % (cmd_str, exc)) |
| 109 |
raise RunCommandError( |
| 110 |
"%s while running `%s` with env=%r\nos.environ=%r" |
| 111 |
% (str(exc), cmd_str, env, os.environ) |
| 112 |
) |
| 113 |
|
| 114 |
if not isinteractive: |
| 115 |
_pipe_output(p, log_fn) |
| 116 |
|
| 117 |
p.wait() |
| 118 |
if p.returncode != 0 and not allow_fail: |
| 119 |
raise subprocess.CalledProcessError(p.returncode, cmd) |
| 120 |
|
| 121 |
return p.returncode |
| 122 |
|
| 123 |
|
| 124 |
if hasattr(select, "poll"): |
| 125 |
|
| 126 |
def _pipe_output(p, log_fn): |
| 127 |
"""Read output from p.stdout and call log_fn() with each chunk of data as it |
| 128 |
becomes available.""" |
| 129 |
# Perform non-blocking reads |
| 130 |
import fcntl |
| 131 |
|
| 132 |
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) |
| 133 |
poll = select.poll() |
| 134 |
poll.register(p.stdout.fileno(), select.POLLIN) |
| 135 |
|
| 136 |
buffer_size = 4096 |
| 137 |
while True: |
| 138 |
poll.poll() |
| 139 |
data = p.stdout.read(buffer_size) |
| 140 |
if not data: |
| 141 |
break |
| 142 |
# log_fn() accepts arguments as str (binary in Python 2, unicode in |
| 143 |
# Python 3). In Python 3 the subprocess output will be plain bytes, |
| 144 |
# and need to be decoded. |
| 145 |
if not isinstance(data, str): |
| 146 |
data = data.decode("utf-8", errors="surrogateescape") |
| 147 |
log_fn(data) |
| 148 |
|
| 149 |
else: |
| 150 |
|
| 151 |
def _pipe_output(p, log_fn): |
| 152 |
"""Read output from p.stdout and call log_fn() with each chunk of data as it |
| 153 |
becomes available.""" |
| 154 |
# Perform blocking reads. Use a smaller buffer size to avoid blocking |
| 155 |
# for very long when data is available. |
| 156 |
buffer_size = 64 |
| 157 |
while True: |
| 158 |
data = p.stdout.read(buffer_size) |
| 159 |
if not data: |
| 160 |
break |
| 161 |
# log_fn() accepts arguments as str (binary in Python 2, unicode in |
| 162 |
# Python 3). In Python 3 the subprocess output will be plain bytes, |
| 163 |
# and need to be decoded. |
| 164 |
if not isinstance(data, str): |
| 165 |
data = data.decode("utf-8", errors="surrogateescape") |
| 166 |
log_fn(data) |