mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 22:08:40 +00:00
Merge pull request #1378 from Diegobecker07/make-game-plain-log
make_game: a run without the LEONIDA board still writes <work>/logs/<stage>.log (MAKE-GAME-PLAIN-LOG)
This commit is contained in:
139
make_game.py
139
make_game.py
@ -43,14 +43,16 @@ Long steps log percent and a rough ETA (shader translation shards, asset exports
|
||||
weighted by module size, and overall weighted stage completion while they overlap).
|
||||
|
||||
On an interactive terminal, a LEONIDA setup screen asks for --jobs and whether to overlap stages, then a
|
||||
key-switchable per-stage log view (1-4 / Tab) keeps parallel output demuxed; full logs land in <work>/logs/.
|
||||
Pass --no-tui (or redirect stdout) for the plain interleaved console.
|
||||
key-switchable per-stage log view (1-4 / Tab) keeps parallel output demuxed. Pass --no-tui (or redirect stdout)
|
||||
for the plain interleaved console. Either way each build stage's full log lands in <work>/logs/<stage>.log.
|
||||
"""
|
||||
import argparse
|
||||
import codecs
|
||||
import functools
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import locale
|
||||
import ntpath
|
||||
import os
|
||||
import re
|
||||
@ -95,6 +97,114 @@ MODEL_ARCHIVES = [
|
||||
]
|
||||
|
||||
|
||||
class PlainStageLogs:
|
||||
"""The stage logs of a build without the LEONIDA board (--no-tui, or stdout redirected). The console keeps the
|
||||
plain interleaved output, and each stage's lines also go to <work>/logs/<stage>.log, the files the board writes:
|
||||
log() and fail() lines, and the output of the commands run() starts, one line per \\r- or \\n-ended piece as the
|
||||
board splits it. Active (module-level _plain_logs) while run_build_stages runs. A stage's file is opened with its
|
||||
first line; when the folder can't be written, one note goes to stderr and the build goes on without the logs.
|
||||
A command's output is decoded once, and the console and the log both get that text."""
|
||||
|
||||
def __init__(self, stages: list, log_dir: str):
|
||||
self.log_dir = log_dir
|
||||
self.stages = tuple(stages)
|
||||
self.consoles: dict = {}
|
||||
self._lock = threading.Lock()
|
||||
self._unwritable = False
|
||||
# What a text-mode pipe decodes with, so a line reads the same as in the board's log.
|
||||
self.encoding = locale.getpreferredencoding(False)
|
||||
|
||||
def _console(self, stage: "str | None"):
|
||||
if stage not in self.stages:
|
||||
return None
|
||||
with self._lock:
|
||||
console = self.consoles.get(stage)
|
||||
if console is None and not self._unwritable:
|
||||
try:
|
||||
console = self.consoles[stage] = leonida_tui.StageConsole(
|
||||
stage, os.path.join(self.log_dir, f"{stage}.log"))
|
||||
except OSError as e:
|
||||
self._unwritable = True
|
||||
print(f"cannot write the stage logs in {self.log_dir} ({e.strerror or e}); the build goes on "
|
||||
"without them", file=sys.stderr, flush=True)
|
||||
return console
|
||||
|
||||
def __enter__(self) -> "PlainStageLogs":
|
||||
global _plain_logs
|
||||
_plain_logs = self
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> bool:
|
||||
global _plain_logs
|
||||
if _plain_logs is self:
|
||||
_plain_logs = None
|
||||
for console in self.consoles.values():
|
||||
console.close()
|
||||
if self.consoles:
|
||||
print(f"stage logs in {self.log_dir}", flush=True)
|
||||
return False
|
||||
|
||||
def write(self, stage: "str | None", line: str) -> None:
|
||||
console = self._console(stage)
|
||||
if console is not None:
|
||||
console.write_line(line)
|
||||
|
||||
def _write_pieces(self, stage: str, data: str) -> str:
|
||||
"""Log each \\r- or \\n-ended piece of data (stripped, empty ones dropped); return the unended rest."""
|
||||
*ended, rest = re.split(r"[\r\n]", data)
|
||||
for piece in ended:
|
||||
text = piece.strip()
|
||||
if text:
|
||||
self.write(stage, text)
|
||||
return rest
|
||||
|
||||
@staticmethod
|
||||
def _echo(text: str) -> None:
|
||||
"""Show a command's text on the console as it wrote it (\\r and \\r\\n kept), in the console's encoding: a
|
||||
Windows console's sys.stdout.buffer takes UTF-8, so the command's own OEM or ANSI bytes would show wrong."""
|
||||
sys.stdout.flush() # a log() line printed by another stage's thread goes out first
|
||||
buffer = getattr(sys.stdout, "buffer", None)
|
||||
if buffer is None:
|
||||
sys.stdout.write(text)
|
||||
sys.stdout.flush()
|
||||
return
|
||||
buffer.write(text.encode(sys.stdout.encoding or "utf-8", errors="replace"))
|
||||
buffer.flush()
|
||||
|
||||
def run(self, cmd: list, stage: str, encoding: "str | None" = None, **kw) -> int:
|
||||
"""Run cmd with its stdout and stderr through one pipe. Its output is decoded as it comes, with encoding (the
|
||||
one the command writes in; by default what a text-mode pipe decodes with, as on the board), then goes on to
|
||||
the console (so a \\r progress line still redraws in place) and piece by piece to the stage's log. The child
|
||||
keeps the console, so Ctrl+C reaches it as before. Returns the exit code."""
|
||||
decoder = codecs.getincrementaldecoder(encoding or self.encoding)(errors="replace")
|
||||
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) as proc:
|
||||
try:
|
||||
rest = ""
|
||||
while True:
|
||||
chunk = proc.stdout.read1(65536) # what has arrived, not a full buffer: progress shows at once
|
||||
text = decoder.decode(chunk, final=not chunk) # a character split between reads waits for the rest
|
||||
if text:
|
||||
self._echo(text)
|
||||
rest = self._write_pieces(stage, rest + text)
|
||||
if not chunk:
|
||||
break
|
||||
self._write_pieces(stage, rest + "\n")
|
||||
except KeyboardInterrupt: # the child got the Ctrl+C too: a moment to stop on its own, as subprocess.run
|
||||
try:
|
||||
proc.wait(timeout=0.25)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
proc.kill()
|
||||
raise
|
||||
except BaseException: # a failed write: do not leave the child running
|
||||
proc.kill()
|
||||
raise
|
||||
return proc.wait()
|
||||
|
||||
|
||||
_plain_logs: "PlainStageLogs | None" = None
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
line = f"{time.strftime('%H:%M:%S')} {msg}"
|
||||
board = leonida_tui.current_board()
|
||||
@ -102,6 +212,8 @@ def log(msg: str) -> None:
|
||||
board.write(leonida_tui.current_stage(), line)
|
||||
return
|
||||
print(line, flush=True)
|
||||
if _plain_logs is not None:
|
||||
_plain_logs.write(leonida_tui.current_stage(), line)
|
||||
|
||||
|
||||
def fail(msg: str) -> "None":
|
||||
@ -113,6 +225,8 @@ def fail(msg: str) -> "None":
|
||||
board.set_status(stage, "failed")
|
||||
# Do not print through the board's stderr proxy (would duplicate into the pane).
|
||||
sys.exit(1)
|
||||
if _plain_logs is not None:
|
||||
_plain_logs.write(leonida_tui.current_stage(), f"ERROR: {msg}")
|
||||
print(f"\nERROR: {msg}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
@ -264,6 +378,18 @@ def run(args: list, hint: str = "", check: bool = True, **kw) -> int:
|
||||
if check and code != 0:
|
||||
fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else ""))
|
||||
return code
|
||||
# Without the board, a build stage's commands also go to its log (PlainStageLogs), with the same rule for pipes.
|
||||
stage = leonida_tui.current_stage()
|
||||
if (_plain_logs is not None and stage in _plain_logs.stages and kw.get("stdout") is None
|
||||
and kw.get("stderr") is None and not kw.get("capture_output")):
|
||||
extra = {k: v for k, v in kw.items()
|
||||
if k not in ("stdout", "stderr", "capture_output", "text", "universal_newlines", "encoding",
|
||||
"errors")}
|
||||
# A caller's encoding= names what the command writes in; the log and the console get the decoded text.
|
||||
code = _plain_logs.run([str(a) for a in args], stage, encoding=kw.get("encoding"), **extra)
|
||||
if check and code != 0:
|
||||
fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else ""))
|
||||
return code
|
||||
r = subprocess.run([str(a) for a in args], **kw)
|
||||
if check and r.returncode != 0:
|
||||
fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}" + (f". {hint}" if hint else ""))
|
||||
@ -3489,7 +3615,7 @@ def main() -> int:
|
||||
"the shaders need (144, or 152 with --mesh-compute)")
|
||||
ap.add_argument("--no-tui", action="store_true",
|
||||
help="plain console logs (default when stdout is not a TTY); skip the LEONIDA setup screen "
|
||||
"and per-stage log view")
|
||||
"and per-stage log view (the stage logs still go to <work>/logs)")
|
||||
a = ap.parse_args()
|
||||
if a.loop_limit is not None and not 0 <= a.loop_limit <= 0xffffffff:
|
||||
ap.error("--loop-limit must be in 0..4294967295")
|
||||
@ -3624,9 +3750,10 @@ def main() -> int:
|
||||
fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3)
|
||||
tui_board.set_summary(f"finished in {(time.time() - t0) / 60:.0f} min")
|
||||
else:
|
||||
run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs,
|
||||
runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated,
|
||||
fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3)
|
||||
with PlainStageLogs(build_stages, os.path.join(work, "logs")):
|
||||
run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs,
|
||||
runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated,
|
||||
fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3)
|
||||
log(f"finished in {(time.time() - t0) / 60:.0f} min")
|
||||
return 0
|
||||
|
||||
|
||||
203
tests/test_make_game_plain_logs.py
Normal file
203
tests/test_make_game_plain_logs.py
Normal file
@ -0,0 +1,203 @@
|
||||
"""make_game.py without the LEONIDA board (--no-tui, or stdout redirected) still writes <work>/logs/<stage>.log:
|
||||
log() and fail() lines and the output of the commands run() starts, which also reach the console as the same text,
|
||||
in the console's own encoding. No game files needed.
|
||||
|
||||
python -I tests/test_make_game_plain_logs.py
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
import make_game # noqa: E402
|
||||
|
||||
leonida_tui = make_game.leonida_tui
|
||||
|
||||
|
||||
def console(encoding: str = "utf-8"):
|
||||
"""A stdout with a byte buffer, like the real one (a Windows console's takes UTF-8), so what reached it can be
|
||||
read back."""
|
||||
return io.TextIOWrapper(io.BytesIO(), encoding=encoding, newline="")
|
||||
|
||||
|
||||
def console_bytes(stream) -> bytes:
|
||||
stream.flush()
|
||||
return stream.buffer.getvalue()
|
||||
|
||||
|
||||
def child(code: str) -> list:
|
||||
return [sys.executable, "-I", "-c", code]
|
||||
|
||||
|
||||
class PlainStageLogsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.logs_dir = os.path.join(self.dir.name, "logs")
|
||||
self.assertIsNone(leonida_tui.current_board())
|
||||
|
||||
def read(self, stage: str) -> list:
|
||||
with open(os.path.join(self.logs_dir, f"{stage}.log"), encoding="utf-8") as f:
|
||||
return f.read().splitlines()
|
||||
|
||||
def test_log_and_fail_lines_go_to_the_running_stage(self):
|
||||
out = console()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
|
||||
with make_game.PlainStageLogs(["shaders", "assets"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("shaders"):
|
||||
make_game.log("translating")
|
||||
with self.assertRaises(SystemExit):
|
||||
make_game.fail("llvm-mc is missing")
|
||||
with leonida_tui.stage_scope("assets"):
|
||||
make_game.log("exporting")
|
||||
make_game.log("outside every stage")
|
||||
shaders, assets = self.read("shaders"), self.read("assets")
|
||||
self.assertEqual(len(shaders), 2)
|
||||
self.assertTrue(shaders[0].endswith(" translating"))
|
||||
self.assertEqual(shaders[1], "ERROR: llvm-mc is missing")
|
||||
self.assertEqual(len(assets), 1)
|
||||
self.assertTrue(assets[0].endswith(" exporting"))
|
||||
text = console_bytes(out).decode()
|
||||
for line in ("translating", "exporting", "outside every stage", f"stage logs in {self.logs_dir}"):
|
||||
self.assertIn(line, text)
|
||||
|
||||
def test_run_mirrors_the_bytes_and_logs_each_piece(self):
|
||||
# A \r progress line, a \r\n ending, stderr after stdout and a last piece with no ending. The child writes
|
||||
# bytes, so its own text mode (\n -> \r\n on Windows) does not change what it sends.
|
||||
code = ("import sys; o, e = sys.stdout.buffer, sys.stderr.buffer; "
|
||||
"o.write(b'shard 1/2\\rshard 2/2\\r\\ndone\\n'); o.flush(); e.write(b'a warning\\n'); e.flush(); "
|
||||
"o.write(b'tail'); o.flush()")
|
||||
out = console()
|
||||
with contextlib.redirect_stdout(out):
|
||||
with make_game.PlainStageLogs(["shaders"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("shaders"):
|
||||
self.assertEqual(make_game.run(child(code)), 0)
|
||||
self.assertIn(b"shard 1/2\rshard 2/2\r\ndone\na warning\ntail", console_bytes(out))
|
||||
lines = self.read("shaders")
|
||||
self.assertIn(os.path.basename(sys.executable), lines[0]) # run() logs the command first
|
||||
self.assertEqual(lines[1:], ["shard 1/2", "shard 2/2", "done", "a warning", "tail"])
|
||||
|
||||
def test_the_console_and_the_log_get_the_text_in_the_callers_encoding(self):
|
||||
# A command that writes in an 8-bit code page (cp1252 here: "não parâmetro"). Its raw bytes on a console
|
||||
# that takes UTF-8 would show U+FFFD; decoded with the encoding the caller names, both get the same text.
|
||||
code = "import sys; sys.stdout.buffer.write(b'n\\xe3o par\\xe2metro\\r\\n'); sys.stdout.flush()"
|
||||
out = console()
|
||||
with contextlib.redirect_stdout(out):
|
||||
with make_game.PlainStageLogs(["runtime"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("runtime"):
|
||||
self.assertEqual(make_game.run(child(code), encoding="cp1252"), 0)
|
||||
self.assertIn("não parâmetro\r\n".encode("utf-8"), console_bytes(out))
|
||||
self.assertEqual(self.read("runtime")[1:], ["não parâmetro"])
|
||||
|
||||
def test_a_character_split_between_reads_is_decoded_whole(self):
|
||||
# The two bytes of a UTF-8 "ã" arrive in two reads: neither the console nor the log gets a broken half.
|
||||
code = ("import sys, time; o = sys.stdout.buffer; o.write(b'n\\xc3'); o.flush(); time.sleep(0.3); "
|
||||
"o.write(b'\\xa3o\\n'); o.flush()")
|
||||
out = console()
|
||||
with contextlib.redirect_stdout(out):
|
||||
with make_game.PlainStageLogs(["runtime"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("runtime"):
|
||||
make_game.run(child(code), encoding="utf-8")
|
||||
self.assertIn("não\n".encode("utf-8"), console_bytes(out))
|
||||
self.assertEqual(self.read("runtime")[1:], ["não"])
|
||||
|
||||
def test_a_character_the_console_cannot_show_is_replaced(self):
|
||||
# A redirected stdout in an 8-bit code page has no Cyrillic: the console gets "?", the log the text, and the
|
||||
# build goes on. (The child's code spells the word with escapes, so the logged command line stays ASCII.)
|
||||
code = ("import sys; sys.stdout.buffer.write('\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442\\n'.encode('utf-8')); "
|
||||
"sys.stdout.flush()")
|
||||
out = console("cp1252")
|
||||
with contextlib.redirect_stdout(out):
|
||||
with make_game.PlainStageLogs(["runtime"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("runtime"):
|
||||
self.assertEqual(make_game.run(child(code), encoding="utf-8"), 0)
|
||||
self.assertIn(b"??????\n", console_bytes(out))
|
||||
self.assertEqual(self.read("runtime")[1:], ["Привет"])
|
||||
|
||||
def test_a_failed_command_stops_the_build_with_its_code_in_the_log(self):
|
||||
with contextlib.redirect_stdout(console()), contextlib.redirect_stderr(io.StringIO()):
|
||||
with make_game.PlainStageLogs(["runtime"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("runtime"):
|
||||
self.assertEqual(make_game.run(child("import sys; sys.exit(3)"), check=False), 3)
|
||||
with self.assertRaises(SystemExit):
|
||||
make_game.run(child("import sys; sys.exit(4)"), hint="see the log")
|
||||
self.assertEqual(self.read("runtime")[-1], f"ERROR: {os.path.basename(sys.executable)} exited with 4. "
|
||||
"see the log")
|
||||
|
||||
def test_caller_pipes_and_unlogged_stages_keep_subprocess_run(self):
|
||||
done = subprocess.CompletedProcess([], 0)
|
||||
with contextlib.redirect_stdout(console()), patch("make_game.subprocess.run", return_value=done) as plain:
|
||||
with make_game.PlainStageLogs(["shaders"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("shaders"):
|
||||
make_game.run(["tool", "a"], stdout=subprocess.PIPE) # the caller reads the output
|
||||
with leonida_tui.stage_scope("check"):
|
||||
make_game.run(["tool", "b"]) # not a build stage with a log
|
||||
make_game.run(["tool", "c"]) # no stage at all
|
||||
self.assertEqual([c.args[0] for c in plain.call_args_list], [["tool", "a"], ["tool", "b"], ["tool", "c"]])
|
||||
|
||||
def test_extra_arguments_reach_the_child(self):
|
||||
with contextlib.redirect_stdout(console()):
|
||||
with make_game.PlainStageLogs(["pipelines"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("pipelines"):
|
||||
env = dict(os.environ, LEONIDA_PLAIN_LOG_TEST="from the caller")
|
||||
make_game.run(child("import os; print(os.getcwd()); print(os.environ['LEONIDA_PLAIN_LOG_TEST'])"),
|
||||
cwd=self.dir.name, env=env, text=True)
|
||||
lines = self.read("pipelines")
|
||||
self.assertEqual(os.path.normcase(lines[1]), os.path.normcase(os.path.realpath(self.dir.name)))
|
||||
self.assertEqual(lines[2], "from the caller")
|
||||
|
||||
def test_inactive_after_the_build_and_appends_like_the_board(self):
|
||||
for word in ("first", "second"):
|
||||
with contextlib.redirect_stdout(console()):
|
||||
with make_game.PlainStageLogs(["assets"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("assets"):
|
||||
make_game.log(word)
|
||||
self.assertIsNone(make_game._plain_logs)
|
||||
self.assertEqual([line.split(" ", 1)[1] for line in self.read("assets")], ["first", "second"])
|
||||
|
||||
def test_ctrl_c_stops_the_child(self):
|
||||
# Ctrl+C while the output is pumped: the interrupt goes on, and the child does not keep running.
|
||||
slow = child("import sys, time; print('started', flush=True); time.sleep(60)")
|
||||
started = time.monotonic()
|
||||
with contextlib.redirect_stdout(console()), \
|
||||
patch.object(make_game.PlainStageLogs, "_write_pieces", side_effect=KeyboardInterrupt):
|
||||
with make_game.PlainStageLogs(["assets"], self.logs_dir):
|
||||
with leonida_tui.stage_scope("assets"), self.assertRaises(KeyboardInterrupt):
|
||||
make_game.run(slow)
|
||||
self.assertLess(time.monotonic() - started, 20)
|
||||
|
||||
def test_an_unwritable_log_folder_does_not_stop_the_build(self):
|
||||
blocker = os.path.join(self.dir.name, "a file")
|
||||
with open(blocker, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write("not a folder\n")
|
||||
out, err = console(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
with make_game.PlainStageLogs(["shaders"], os.path.join(blocker, "logs")):
|
||||
with leonida_tui.stage_scope("shaders"):
|
||||
make_game.log("still logged to the console")
|
||||
self.assertEqual(make_game.run(child("print('child output')")), 0)
|
||||
text = console_bytes(out).decode()
|
||||
self.assertIn("still logged to the console", text)
|
||||
self.assertIn("child output", text)
|
||||
self.assertNotIn("stage logs in", text)
|
||||
self.assertEqual(err.getvalue().count("cannot write the stage logs"), 1)
|
||||
|
||||
def test_no_build_stage_writes_nothing(self):
|
||||
out = console()
|
||||
with contextlib.redirect_stdout(out):
|
||||
with make_game.PlainStageLogs([], self.logs_dir):
|
||||
make_game.log("check only")
|
||||
self.assertFalse(os.path.exists(self.logs_dir))
|
||||
self.assertNotIn(b"stage logs in", console_bytes(out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user