Make printing log lines to the terminal a little cleaner when building WASI (GH-140772)

This commit is contained in:
Brett Cannon
2025-10-30 10:35:53 -07:00
committed by GitHub
parent e4deefbb2f
commit abd19eddee

View File

@@ -37,6 +37,30 @@ WASMTIME_VAR_NAME = "WASMTIME"
WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}" WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}"
def separator():
"""Print a separator line across the terminal width."""
try:
tput_output = subprocess.check_output(
["tput", "cols"], encoding="utf-8"
)
except subprocess.CalledProcessError:
terminal_width = 80
else:
terminal_width = int(tput_output.strip())
print("" * terminal_width)
def log(emoji, message, *, spacing=None):
"""Print a notification with an emoji.
If 'spacing' is None, calculate the spacing based on the number of code points
in the emoji as terminals "eat" a space when the emoji has multiple code points.
"""
if spacing is None:
spacing = " " if len(emoji) == 1 else " "
print("".join([emoji, spacing, message]))
def updated_env(updates={}): def updated_env(updates={}):
"""Create a new dict representing the environment to use. """Create a new dict representing the environment to use.
@@ -60,9 +84,10 @@ def updated_env(updates={}):
if os.environ.get(key) != value: if os.environ.get(key) != value:
env_diff[key] = value env_diff[key] = value
print("🌎 Environment changes:") env_vars = (
for key in sorted(env_diff.keys()): f"\n {key}={item}" for key, item in sorted(env_diff.items())
print(f" {key}={env_diff[key]}") )
log("🌎", f"Environment changes:{''.join(env_vars)}")
return environment return environment
@@ -77,22 +102,14 @@ def subdir(working_dir, *, clean_ok=False):
if callable(working_dir): if callable(working_dir):
working_dir = working_dir(context) working_dir = working_dir(context)
try: separator()
tput_output = subprocess.check_output( log("📁", os.fsdecode(working_dir))
["tput", "cols"], encoding="utf-8"
)
except subprocess.CalledProcessError:
terminal_width = 80
else:
terminal_width = int(tput_output.strip())
print("" * terminal_width)
print("📁", working_dir)
if ( if (
clean_ok clean_ok
and getattr(context, "clean", False) and getattr(context, "clean", False)
and working_dir.exists() and working_dir.exists()
): ):
print("🚮 Deleting directory (--clean)...") log("🚮", "Deleting directory (--clean)...")
shutil.rmtree(working_dir) shutil.rmtree(working_dir)
working_dir.mkdir(parents=True, exist_ok=True) working_dir.mkdir(parents=True, exist_ok=True)
@@ -116,7 +133,7 @@ def call(command, *, context=None, quiet=False, logdir=None, **kwargs):
elif quiet and logdir is None: elif quiet and logdir is None:
raise ValueError("When quiet is True, logdir must be specified") raise ValueError("When quiet is True, logdir must be specified")
print("", " ".join(map(str, command))) log("", " ".join(map(str, command)), spacing=" ")
if not quiet: if not quiet:
stdout = None stdout = None
stderr = None stderr = None
@@ -130,7 +147,7 @@ def call(command, *, context=None, quiet=False, logdir=None, **kwargs):
suffix=".log", suffix=".log",
) )
stderr = subprocess.STDOUT stderr = subprocess.STDOUT
print(f"📝 Logging output to {stdout.name} (--quiet)...") log("📝", f"Logging output to {stdout.name} (--quiet)...")
subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr) subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr)
@@ -163,11 +180,11 @@ def configure_build_python(context, working_dir):
"""Configure the build/host Python.""" """Configure the build/host Python."""
if LOCAL_SETUP.exists(): if LOCAL_SETUP.exists():
if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER: if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
print(f"👍 {LOCAL_SETUP} exists ...") log("👍", f"{LOCAL_SETUP} exists ...")
else: else:
print(f"⚠️ {LOCAL_SETUP} exists, but has unexpected contents") log("⚠️", f"{LOCAL_SETUP} exists, but has unexpected contents")
else: else:
print(f"📝 Creating {LOCAL_SETUP} ...") log("📝", f"Creating {LOCAL_SETUP} ...")
LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER) LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER)
configure = [os.path.relpath(CHECKOUT / "configure", working_dir)] configure = [os.path.relpath(CHECKOUT / "configure", working_dir)]
@@ -191,7 +208,7 @@ def make_build_python(context, working_dir):
] ]
version = subprocess.check_output(cmd, encoding="utf-8").strip() version = subprocess.check_output(cmd, encoding="utf-8").strip()
print(f"🎉 {binary} {version}") log("🎉", f"{binary} {version}")
def find_wasi_sdk(): def find_wasi_sdk():
@@ -228,9 +245,10 @@ def find_wasi_sdk():
# supported version is a prefix of the found version (e.g. `25` and `2567`). # supported version is a prefix of the found version (e.g. `25` and `2567`).
if not found_version.startswith(f"{WASI_SDK_VERSION}."): if not found_version.startswith(f"{WASI_SDK_VERSION}."):
major_version = found_version.partition(".")[0] major_version = found_version.partition(".")[0]
print( log(
f"⚠️ Found WASI SDK {major_version}, " "⚠️",
f"but WASI SDK {WASI_SDK_VERSION} is the supported version" f" Found WASI SDK {major_version}, "
f"but WASI SDK {WASI_SDK_VERSION} is the supported version",
) )
return wasi_sdk_path return wasi_sdk_path
@@ -349,7 +367,7 @@ def configure_wasi_python(context, working_dir):
with exec_script.open("w", encoding="utf-8") as file: with exec_script.open("w", encoding="utf-8") as file:
file.write(f'#!/bin/sh\nexec {host_runner} {python_wasm} "$@"\n') file.write(f'#!/bin/sh\nexec {host_runner} {python_wasm} "$@"\n')
exec_script.chmod(0o755) exec_script.chmod(0o755)
print(f"🏃‍♀️ Created {exec_script} (--host-runner)... ") log("🏃", f"Created {exec_script} (--host-runner)... ")
sys.stdout.flush() sys.stdout.flush()
@@ -364,9 +382,10 @@ def make_wasi_python(context, working_dir):
exec_script = working_dir / "python.sh" exec_script = working_dir / "python.sh"
call([exec_script, "--version"], quiet=False) call([exec_script, "--version"], quiet=False)
print( log(
f"🎉 Use `{exec_script.relative_to(context.init_dir)}` " "🎉",
"to run CPython w/ the WASI host specified by --host-runner" f"Use `{exec_script.relative_to(context.init_dir)}` "
"to run CPython w/ the WASI host specified by --host-runner",
) )
@@ -385,12 +404,12 @@ def build_all(context):
def clean_contents(context): def clean_contents(context):
"""Delete all files created by this script.""" """Delete all files created by this script."""
if CROSS_BUILD_DIR.exists(): if CROSS_BUILD_DIR.exists():
print(f"🧹 Deleting {CROSS_BUILD_DIR} ...") log("🧹", f"Deleting {CROSS_BUILD_DIR} ...")
shutil.rmtree(CROSS_BUILD_DIR) shutil.rmtree(CROSS_BUILD_DIR)
if LOCAL_SETUP.exists(): if LOCAL_SETUP.exists():
if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER: if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
print(f"🧹 Deleting generated {LOCAL_SETUP} ...") log("🧹", f"Deleting generated {LOCAL_SETUP} ...")
def main(): def main():