Skip to content

Commit 6c025a0

Browse files
[3.14] Make printing log lines to the terminal a little cleaner when building WASI (GH-140772) (GH-140804)
Make printing log lines to the terminal a little cleaner when building WASI (GH-140772) (cherry picked from commit abd19ed) Co-authored-by: Brett Cannon <[email protected]>
1 parent 5954b5b commit 6c025a0

File tree

1 file changed

+48
-29
lines changed

1 file changed

+48
-29
lines changed

Tools/wasm/wasi/__main__.py

Lines changed: 48 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,30 @@
3737
WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}"
3838

3939

40+
def separator():
41+
"""Print a separator line across the terminal width."""
42+
try:
43+
tput_output = subprocess.check_output(
44+
["tput", "cols"], encoding="utf-8"
45+
)
46+
except subprocess.CalledProcessError:
47+
terminal_width = 80
48+
else:
49+
terminal_width = int(tput_output.strip())
50+
print("⎯" * terminal_width)
51+
52+
53+
def log(emoji, message, *, spacing=None):
54+
"""Print a notification with an emoji.
55+
56+
If 'spacing' is None, calculate the spacing based on the number of code points
57+
in the emoji as terminals "eat" a space when the emoji has multiple code points.
58+
"""
59+
if spacing is None:
60+
spacing = " " if len(emoji) == 1 else " "
61+
print("".join([emoji, spacing, message]))
62+
63+
4064
def updated_env(updates={}):
4165
"""Create a new dict representing the environment to use.
4266
@@ -60,9 +84,10 @@ def updated_env(updates={}):
6084
if os.environ.get(key) != value:
6185
env_diff[key] = value
6286

63-
print("🌎 Environment changes:")
64-
for key in sorted(env_diff.keys()):
65-
print(f" {key}={env_diff[key]}")
87+
env_vars = (
88+
f"\n {key}={item}" for key, item in sorted(env_diff.items())
89+
)
90+
log("🌎", f"Environment changes:{''.join(env_vars)}")
6691

6792
return environment
6893

@@ -77,22 +102,14 @@ def wrapper(context):
77102

78103
if callable(working_dir):
79104
working_dir = working_dir(context)
80-
try:
81-
tput_output = subprocess.check_output(
82-
["tput", "cols"], encoding="utf-8"
83-
)
84-
except subprocess.CalledProcessError:
85-
terminal_width = 80
86-
else:
87-
terminal_width = int(tput_output.strip())
88-
print("⎯" * terminal_width)
89-
print("📁", working_dir)
105+
separator()
106+
log("📁", os.fsdecode(working_dir))
90107
if (
91108
clean_ok
92109
and getattr(context, "clean", False)
93110
and working_dir.exists()
94111
):
95-
print("🚮 Deleting directory (--clean)...")
112+
log("🚮", "Deleting directory (--clean)...")
96113
shutil.rmtree(working_dir)
97114

98115
working_dir.mkdir(parents=True, exist_ok=True)
@@ -116,7 +133,7 @@ def call(command, *, context=None, quiet=False, logdir=None, **kwargs):
116133
elif quiet and logdir is None:
117134
raise ValueError("When quiet is True, logdir must be specified")
118135

119-
print("❯", " ".join(map(str, command)))
136+
log("❯", " ".join(map(str, command)), spacing=" ")
120137
if not quiet:
121138
stdout = None
122139
stderr = None
@@ -130,7 +147,7 @@ def call(command, *, context=None, quiet=False, logdir=None, **kwargs):
130147
suffix=".log",
131148
)
132149
stderr = subprocess.STDOUT
133-
print(f"📝 Logging output to {stdout.name} (--quiet)...")
150+
log("📝", f"Logging output to {stdout.name} (--quiet)...")
134151

135152
subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr)
136153

@@ -163,11 +180,11 @@ def configure_build_python(context, working_dir):
163180
"""Configure the build/host Python."""
164181
if LOCAL_SETUP.exists():
165182
if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
166-
print(f"👍 {LOCAL_SETUP} exists ...")
183+
log("👍", f"{LOCAL_SETUP} exists ...")
167184
else:
168-
print(f"⚠️ {LOCAL_SETUP} exists, but has unexpected contents")
185+
log("⚠️", f"{LOCAL_SETUP} exists, but has unexpected contents")
169186
else:
170-
print(f"📝 Creating {LOCAL_SETUP} ...")
187+
log("📝", f"Creating {LOCAL_SETUP} ...")
171188
LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER)
172189

173190
configure = [os.path.relpath(CHECKOUT / "configure", working_dir)]
@@ -191,7 +208,7 @@ def make_build_python(context, working_dir):
191208
]
192209
version = subprocess.check_output(cmd, encoding="utf-8").strip()
193210

194-
print(f"🎉 {binary} {version}")
211+
log("🎉", f"{binary} {version}")
195212

196213

197214
def find_wasi_sdk():
@@ -228,9 +245,10 @@ def find_wasi_sdk():
228245
# supported version is a prefix of the found version (e.g. `25` and `2567`).
229246
if not found_version.startswith(f"{WASI_SDK_VERSION}."):
230247
major_version = found_version.partition(".")[0]
231-
print(
232-
f"⚠️ Found WASI SDK {major_version}, "
233-
f"but WASI SDK {WASI_SDK_VERSION} is the supported version"
248+
log(
249+
"⚠️",
250+
f" Found WASI SDK {major_version}, "
251+
f"but WASI SDK {WASI_SDK_VERSION} is the supported version",
234252
)
235253

236254
return wasi_sdk_path
@@ -349,7 +367,7 @@ def configure_wasi_python(context, working_dir):
349367
with exec_script.open("w", encoding="utf-8") as file:
350368
file.write(f'#!/bin/sh\nexec {host_runner} {python_wasm} "$@"\n')
351369
exec_script.chmod(0o755)
352-
print(f"🏃‍♀️ Created {exec_script} (--host-runner)... ")
370+
log("🏃", f"Created {exec_script} (--host-runner)... ")
353371
sys.stdout.flush()
354372

355373

@@ -364,9 +382,10 @@ def make_wasi_python(context, working_dir):
364382

365383
exec_script = working_dir / "python.sh"
366384
call([exec_script, "--version"], quiet=False)
367-
print(
368-
f"🎉 Use `{exec_script.relative_to(context.init_dir)}` "
369-
"to run CPython w/ the WASI host specified by --host-runner"
385+
log(
386+
"🎉",
387+
f"Use `{exec_script.relative_to(context.init_dir)}` "
388+
"to run CPython w/ the WASI host specified by --host-runner",
370389
)
371390

372391

@@ -385,12 +404,12 @@ def build_all(context):
385404
def clean_contents(context):
386405
"""Delete all files created by this script."""
387406
if CROSS_BUILD_DIR.exists():
388-
print(f"🧹 Deleting {CROSS_BUILD_DIR} ...")
407+
log("🧹", f"Deleting {CROSS_BUILD_DIR} ...")
389408
shutil.rmtree(CROSS_BUILD_DIR)
390409

391410
if LOCAL_SETUP.exists():
392411
if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
393-
print(f"🧹 Deleting generated {LOCAL_SETUP} ...")
412+
log("🧹", f"Deleting generated {LOCAL_SETUP} ...")
394413

395414

396415
def main():

0 commit comments

Comments
 (0)