Skip to content

Commit 598f11a

Browse files
committed
ref(bootstrap.py): add eprint function
just like `print` but for `stderr`
1 parent 5105b1e commit 598f11a

File tree

1 file changed

+41
-49
lines changed

1 file changed

+41
-49
lines changed

src/bootstrap/bootstrap.py

+41-49
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ def get_cpus():
4141
return 1
4242

4343

44+
def eprint(*args, **kwargs):
45+
kwargs["file"] = sys.stderr
46+
print(*args, **kwargs)
47+
4448

4549
def get(base, url, path, checksums, verbose=False):
4650
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
@@ -57,23 +61,23 @@ def get(base, url, path, checksums, verbose=False):
5761
if os.path.exists(path):
5862
if verify(path, sha256, False):
5963
if verbose:
60-
print("using already-download file", path, file=sys.stderr)
64+
eprint("using already-download file", path)
6165
return
6266
else:
6367
if verbose:
64-
print("ignoring already-download file",
65-
path, "due to failed verification", file=sys.stderr)
68+
eprint("ignoring already-download file",
69+
path, "due to failed verification")
6670
os.unlink(path)
6771
download(temp_path, "{}/{}".format(base, url), True, verbose)
6872
if not verify(temp_path, sha256, verbose):
6973
raise RuntimeError("failed verification")
7074
if verbose:
71-
print("moving {} to {}".format(temp_path, path), file=sys.stderr)
75+
eprint("moving {} to {}".format(temp_path, path))
7276
shutil.move(temp_path, path)
7377
finally:
7478
if os.path.isfile(temp_path):
7579
if verbose:
76-
print("removing", temp_path, file=sys.stderr)
80+
eprint("removing", temp_path)
7781
os.unlink(temp_path)
7882

7983

@@ -83,7 +87,7 @@ def download(path, url, probably_big, verbose):
8387
_download(path, url, probably_big, verbose, True)
8488
return
8589
except RuntimeError:
86-
print("\nspurious failure, trying again", file=sys.stderr)
90+
eprint("\nspurious failure, trying again")
8791
_download(path, url, probably_big, verbose, False)
8892

8993

@@ -94,7 +98,7 @@ def _download(path, url, probably_big, verbose, exception):
9498
# - If we are on win32 fallback to powershell
9599
# - Otherwise raise the error if appropriate
96100
if probably_big or verbose:
97-
print("downloading {}".format(url), file=sys.stderr)
101+
eprint("downloading {}".format(url))
98102

99103
try:
100104
if (probably_big or verbose) and "GITHUB_ACTIONS" not in os.environ:
@@ -129,20 +133,20 @@ def _download(path, url, probably_big, verbose, exception):
129133
def verify(path, expected, verbose):
130134
"""Check if the sha256 sum of the given path is valid"""
131135
if verbose:
132-
print("verifying", path, file=sys.stderr)
136+
eprint("verifying", path)
133137
with open(path, "rb") as source:
134138
found = hashlib.sha256(source.read()).hexdigest()
135139
verified = found == expected
136140
if not verified:
137-
print("invalid checksum:\n"
141+
eprint("invalid checksum:\n"
138142
" found: {}\n"
139-
" expected: {}".format(found, expected), file=sys.stderr)
143+
" expected: {}".format(found, expected))
140144
return verified
141145

142146

143147
def unpack(tarball, tarball_suffix, dst, verbose=False, match=None):
144148
"""Unpack the given tarball file"""
145-
print("extracting", tarball, file=sys.stderr)
149+
eprint("extracting", tarball)
146150
fname = os.path.basename(tarball).replace(tarball_suffix, "")
147151
with contextlib.closing(tarfile.open(tarball)) as tar:
148152
for member in tar.getnames():
@@ -155,7 +159,7 @@ def unpack(tarball, tarball_suffix, dst, verbose=False, match=None):
155159

156160
dst_path = os.path.join(dst, name)
157161
if verbose:
158-
print(" extracting", member, file=sys.stderr)
162+
eprint(" extracting", member)
159163
tar.extract(member, dst)
160164
src_path = os.path.join(dst, member)
161165
if os.path.isdir(src_path) and os.path.exists(dst_path):
@@ -167,7 +171,7 @@ def unpack(tarball, tarball_suffix, dst, verbose=False, match=None):
167171
def run(args, verbose=False, exception=False, is_bootstrap=False, **kwargs):
168172
"""Run a child program in a new process"""
169173
if verbose:
170-
print("running: " + ' '.join(args), file=sys.stderr)
174+
eprint("running: " + ' '.join(args))
171175
sys.stdout.flush()
172176
# Ensure that the .exe is used on Windows just in case a Linux ELF has been
173177
# compiled in the same directory.
@@ -207,8 +211,8 @@ def require(cmd, exit=True, exception=False):
207211
if exception:
208212
raise
209213
elif exit:
210-
print("error: unable to run `{}`: {}".format(' '.join(cmd), exc), file=sys.stderr)
211-
print("Please make sure it's installed and in the path.", file=sys.stderr)
214+
eprint("error: unable to run `{}`: {}".format(' '.join(cmd), exc))
215+
eprint("Please make sure it's installed and in the path.")
212216
sys.exit(1)
213217
return None
214218

@@ -239,14 +243,12 @@ def default_build_triple(verbose):
239243
host = next(x for x in version.split('\n') if x.startswith("host: "))
240244
triple = host.split("host: ")[1]
241245
if verbose:
242-
print("detected default triple {} from pre-installed rustc".format(triple),
243-
file=sys.stderr)
246+
eprint("detected default triple {} from pre-installed rustc".format(triple))
244247
return triple
245248
except Exception as e:
246249
if verbose:
247-
print("pre-installed rustc not detected: {}".format(e),
248-
file=sys.stderr)
249-
print("falling back to auto-detect", file=sys.stderr)
250+
eprint("pre-installed rustc not detected: {}".format(e))
251+
eprint("falling back to auto-detect")
250252

251253
required = not platform_is_win32()
252254
uname = require(["uname", "-smp"], exit=required)
@@ -672,15 +674,14 @@ def get_answer():
672674
if not is_nixos:
673675
in_nix_shell = os.getenv('IN_NIX_SHELL')
674676
if in_nix_shell:
675-
print("The IN_NIX_SHELL environment variable is `{}`;".format(in_nix_shell),
676-
"you may need to set `patch-binaries-for-nix=true` in config.toml",
677-
file=sys.stderr)
677+
eprint("The IN_NIX_SHELL environment variable is `{}`;".format(in_nix_shell),
678+
"you may need to set `patch-binaries-for-nix=true` in config.toml")
678679

679680
return is_nixos
680681

681682
answer = self._should_fix_bins_and_dylibs = get_answer()
682683
if answer:
683-
print("info: You seem to be using Nix.", file=sys.stderr)
684+
eprint("info: You seem to be using Nix.")
684685
return answer
685686

686687
def fix_bin_or_dylib(self, fname):
@@ -693,7 +694,7 @@ def fix_bin_or_dylib(self, fname):
693694
Please see https://nixos.org/patchelf.html for more information
694695
"""
695696
assert self._should_fix_bins_and_dylibs is True
696-
print("attempting to patch", fname, file=sys.stderr)
697+
eprint("attempting to patch", fname)
697698

698699
# Only build `.nix-deps` once.
699700
nix_deps_dir = self.nix_deps_dir
@@ -726,7 +727,7 @@ def fix_bin_or_dylib(self, fname):
726727
"nix-build", "-E", nix_expr, "-o", nix_deps_dir,
727728
])
728729
except subprocess.CalledProcessError as reason:
729-
print("warning: failed to call nix-build:", reason, file=sys.stderr)
730+
eprint("warning: failed to call nix-build:", reason)
730731
return
731732
self.nix_deps_dir = nix_deps_dir
732733

@@ -746,7 +747,7 @@ def fix_bin_or_dylib(self, fname):
746747
try:
747748
subprocess.check_output([patchelf] + patchelf_args + [fname])
748749
except subprocess.CalledProcessError as reason:
749-
print("warning: failed to call patchelf:", reason, file=sys.stderr)
750+
eprint("warning: failed to call patchelf:", reason)
750751
return
751752

752753
def rustc_stamp(self):
@@ -888,7 +889,7 @@ def build_bootstrap(self):
888889
if "GITHUB_ACTIONS" in env:
889890
print("::group::Building bootstrap")
890891
else:
891-
print("Building bootstrap", file=sys.stderr)
892+
eprint("Building bootstrap")
892893

893894
args = self.build_bootstrap_cmd(env)
894895
# Run this from the source directory so cargo finds .cargo/config
@@ -997,12 +998,9 @@ def check_vendored_status(self):
997998
if 'SUDO_USER' in os.environ and not self.use_vendored_sources:
998999
if os.getuid() == 0:
9991000
self.use_vendored_sources = True
1000-
print('info: looks like you\'re trying to run this command as root',
1001-
file=sys.stderr)
1002-
print(' and so in order to preserve your $HOME this will now',
1003-
file=sys.stderr)
1004-
print(' use vendored sources by default.',
1005-
file=sys.stderr)
1001+
eprint('info: looks like you\'re trying to run this command as root')
1002+
eprint(' and so in order to preserve your $HOME this will now')
1003+
eprint(' use vendored sources by default.')
10061004

10071005
cargo_dir = os.path.join(self.rust_root, '.cargo')
10081006
if self.use_vendored_sources:
@@ -1012,18 +1010,14 @@ def check_vendored_status(self):
10121010
"--sync ./src/tools/rust-analyzer/Cargo.toml " \
10131011
"--sync ./compiler/rustc_codegen_cranelift/Cargo.toml " \
10141012
"--sync ./src/bootstrap/Cargo.toml "
1015-
print('error: vendoring required, but vendor directory does not exist.',
1016-
file=sys.stderr)
1017-
print(' Run `cargo vendor {}` to initialize the '
1018-
'vendor directory.'.format(sync_dirs),
1019-
file=sys.stderr)
1020-
print('Alternatively, use the pre-vendored `rustc-src` dist component.',
1021-
file=sys.stderr)
1013+
eprint('error: vendoring required, but vendor directory does not exist.')
1014+
eprint(' Run `cargo vendor {}` to initialize the '
1015+
'vendor directory.'.format(sync_dirs))
1016+
eprint('Alternatively, use the pre-vendored `rustc-src` dist component.')
10221017
raise Exception("{} not found".format(vendor_dir))
10231018

10241019
if not os.path.exists(cargo_dir):
1025-
print('error: vendoring required, but .cargo/config does not exist.',
1026-
file=sys.stderr)
1020+
eprint('error: vendoring required, but .cargo/config does not exist.')
10271021
raise Exception("{} not found".format(cargo_dir))
10281022
else:
10291023
if os.path.exists(cargo_dir):
@@ -1117,10 +1111,9 @@ def main():
11171111
# If the user is asking for help, let them know that the whole download-and-build
11181112
# process has to happen before anything is printed out.
11191113
if help_triggered:
1120-
print(
1114+
eprint(
11211115
"info: Downloading and building bootstrap before processing --help command.\n"
1122-
" See src/bootstrap/README.md for help with common commands."
1123-
, file=sys.stderr)
1116+
" See src/bootstrap/README.md for help with common commands.")
11241117

11251118
exit_code = 0
11261119
success_word = "successfully"
@@ -1131,12 +1124,11 @@ def main():
11311124
exit_code = error.code
11321125
else:
11331126
exit_code = 1
1134-
print(error, file=sys.stderr)
1127+
eprint(error)
11351128
success_word = "unsuccessfully"
11361129

11371130
if not help_triggered:
1138-
print("Build completed", success_word, "in", format_build_time(time() - start_time),
1139-
file=sys.stderr)
1131+
eprint("Build completed", success_word, "in", format_build_time(time() - start_time))
11401132
sys.exit(exit_code)
11411133

11421134

0 commit comments

Comments
 (0)