refactor: keep detection lines as data

Detection now keeps what it says in DETECTION_NOTES and prints it only in
line mode. The full screen reads the list under detection_held() instead
of capturing stdout and stderr and dropping refusals by comparing text,
which said a refusal twice once screen_text escaped its folder.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 16:44:02 +01:00
1 parent 36d5827b25
commit 4cb82adce3
12 files changed
+148 -44

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@
# and Invoke-WebRequest throws on a cut transfer before the hash is read:
# the site's build rewrites this line there (scripts/sitebootstrap.py).
$mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
$defaultInstallSha256 = "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08"
$defaultInstallSha256 = "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
$maximumInstallerBytes = 8MB
+48 -15
View File
@@ -66,6 +66,41 @@ except ImportError as _missing:
sys.exit(1)
# --- installer/detection_notes.py --------------------------------------------
# Each line detection said, in order, other than a folder it could not look
# in (_DETECTION_REFUSED keeps those): a system found with no folder, a
# configuration naming a folder nobody can type, an Android folder out of
# reach, a card that fits two systems.
DETECTION_NOTES: list[str] = []
# Set while the full screen runs detection: it shows the notes and the
# refusals itself, and a line printed under it would tear the screen.
_HELD = {"active": False}
def echo_detection(line: str, stream: TextIO | None = None) -> None:
"""Print a line detection says, unless the screen shows it itself."""
if not _HELD["active"]:
print(line, file=stream if stream is not None else sys.stderr)
def note_detection(line: str, stream: TextIO | None = None) -> None:
"""Keep a line detection says, and print it in line mode."""
DETECTION_NOTES.append(line)
echo_detection(line, stream)
@contextlib.contextmanager
def detection_held() -> Iterator[None]:
"""Detection that keeps its lines without printing them."""
outer = _HELD["active"]
_HELD["active"] = True
try:
yield
finally:
_HELD["active"] = outer
# --- installer/embedded.py ---------------------------------------------------
# Frontends whose BIOS live on their SD card, installed from a computer the
@@ -1690,7 +1725,7 @@ def _note_refused(path: Path, exc: OSError) -> None:
_DETECTION_UNREADABLE.add(refused[0])
words = refused_words(*refused)
EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words)
print(f" {screen_text(words)}", file=sys.stderr)
echo_detection(f" {screen_text(words)}")
def _held(path: Path) -> bool:
@@ -4947,7 +4982,7 @@ def _detect_embedded() -> list[tuple[str, Path]]:
reason = _NO_FOLDER.get(
name, "nothing on it names the folder its RetroArch reads")
closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest."
print(f"{name} found here, but {reason}.{closing}", file=sys.stderr)
note_detection(f"{name} found here, but {reason}.{closing}")
continue
_DETECTED_OS[(plat, folder)] = name
found.append((plat, folder))
@@ -5029,7 +5064,7 @@ def _note_windows_unasked() -> None:
_DETECTION_REFUSED.append(refused)
words = refused_words(*refused)
EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words)
print(f" {screen_text(words)}", file=sys.stderr)
echo_detection(f" {screen_text(words)}")
def _winreg_value(key: str, value: str) -> str | None:
@@ -5743,10 +5778,9 @@ def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None:
if not rd_home:
# A home moved to an SD card lives only in this file: the
# default is a guess, and the user is told so.
print(
note_detection(
f"Warning: could not read paths.rd_home_path from "
f"{retrodeck_json}: assuming {home / 'retrodeck'}",
file=sys.stderr,
)
rd_root = Path(rd_home) if rd_home else home / "retrodeck"
_record_moved_folders(rd_root, retrodeck_json)
@@ -5868,9 +5902,9 @@ def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]]
# setup reads the folder named.
if name not in _UNNAMEABLE:
_UNNAMEABLE.append(name)
print(f" {display_name(name)}: the folder its configuration names holds a "
f"control character ({shown_path(path)}). Name its BIOS folder with "
"--dest.", file=sys.stderr)
note_detection(f" {display_name(name)}: the folder its configuration names "
f"holds a control character ({shown_path(path)}). Name its BIOS "
"folder with --dest.")
continue
kept.append((name, path))
return kept
@@ -5886,7 +5920,7 @@ def detect_platforms(os_type: str) -> list[tuple[str, Path]]:
if os_type == "android":
found.extend(_detect_android())
for line in android_unreachable_folders():
print(line, file=sys.stderr)
note_detection(line)
if os_type in ("linux", "wsl"):
found.extend(_detect_embedded())
@@ -14372,7 +14406,7 @@ def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]:
# A drive whose files fit two systems is said, never guessed.
words = doubt_words(mount)
if words:
print(f" {words}")
note_detection(f" {words}", sys.stdout)
continue
if (card[0], card[1]) not in found and card[2] not in here:
_DETECTED_OS.setdefault((card[0], card[1]), card[2])
@@ -30633,19 +30667,18 @@ def _tui_take_args(state: TuiState, args: argparse.Namespace) -> None:
def _tui_detect(state: TuiState, os_type: str) -> None:
"""The setups and cards found here, and what detection said."""
captured = io.StringIO()
with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
start = len(DETECTION_NOTES)
with detection_held():
state.setups, state.mounted_setups = found_setups(os_type)
frontends = detect_frontends(os_type)
# Said on the normal screen before this one covered it, and kept
# above the list: a status line under 18 setups was never drawn.
state.refused = [refused_words(folder, why, _short_path(folder, state.home))
for folder, why in _DETECTION_REFUSED]
unsaid = {refused_words(*refused) for refused in _DETECTION_REFUSED}
if "esde" in frontends:
state.notes.append(TUI_ESDE_NOTE)
state.notes += [line.strip() for line in captured.getvalue().splitlines()
if line.strip() and line.strip() not in unsaid]
state.notes += [line.strip() for note in DETECTION_NOTES[start:]
for line in note.splitlines() if line.strip()]
def _start_on_platform(state: TuiState, args: argparse.Namespace, plat: str,
+1 -1
View File
@@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins
# curl or wget stop on a cut transfer before the hash is read: the site's
# build rewrites this line there (scripts/sitebootstrap.py).
MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
DEFAULT_INSTALL_SHA256="27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08"
DEFAULT_INSTALL_SHA256="9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
MAX_INSTALLER_BYTES=8388608
+8 -8
View File
@@ -27,8 +27,8 @@
{
"dest": "roms/ports/retrobios/install.py",
"repo_path": "install.py",
"size": 1450927,
"sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08",
"size": 1449987,
"sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb",
"executable": false
},
{
@@ -71,8 +71,8 @@
"muos": {
"archive": {
"dest": "ARCHIVE/RetroBIOS.muxapp",
"size": 1504552,
"sha256": "7011d54d1dbf6dbf135f319c17bc3a4ba1d57a479ccb0442086a7a3b0457d86b"
"size": 1503612,
"sha256": "4247f8fe1a0aee1d958ce838701795d176fb4725a32e12a6ce601af4f9a39030"
},
"members": [
{
@@ -92,8 +92,8 @@
{
"name": "RetroBIOS/install.py",
"repo_path": "install.py",
"size": 1450927,
"sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08",
"size": 1449987,
"sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb",
"executable": false
},
{
@@ -166,8 +166,8 @@
{
"dest": ".config/modules/retrobios/install.py",
"repo_path": "install.py",
"size": 1450927,
"sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08",
"size": 1449987,
"sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb",
"executable": false
},
{
+6 -7
View File
@@ -5,7 +5,6 @@ import contextlib
import functools
import os
import re
import sys
import xml.etree.ElementTree as ET
from collections.abc import Callable, Iterator
from pathlib import Path
@@ -18,6 +17,7 @@ from installer.config_values import (
_retroarch_cfg_dir,
_retroarch_cfg_value,
)
from installer.detection_notes import note_detection
from installer.detect_os import (
_detect_embedded,
_macos_retroarch_base,
@@ -693,10 +693,9 @@ def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None:
if not rd_home:
# A home moved to an SD card lives only in this file: the
# default is a guess, and the user is told so.
print(
note_detection(
f"Warning: could not read paths.rd_home_path from "
f"{retrodeck_json}: assuming {home / 'retrodeck'}",
file=sys.stderr,
)
rd_root = Path(rd_home) if rd_home else home / "retrodeck"
_record_moved_folders(rd_root, retrodeck_json)
@@ -818,9 +817,9 @@ def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]]
# setup reads the folder named.
if name not in _UNNAMEABLE:
_UNNAMEABLE.append(name)
print(f" {display_name(name)}: the folder its configuration names holds a "
f"control character ({shown_path(path)}). Name its BIOS folder with "
"--dest.", file=sys.stderr)
note_detection(f" {display_name(name)}: the folder its configuration names "
f"holds a control character ({shown_path(path)}). Name its BIOS "
"folder with --dest.")
continue
kept.append((name, path))
return kept
@@ -836,7 +835,7 @@ def detect_platforms(os_type: str) -> list[tuple[str, Path]]:
if os_type == "android":
found.extend(_detect_android())
for line in android_unreachable_folders():
print(line, file=sys.stderr)
note_detection(line)
if os_type in ("linux", "wsl"):
found.extend(_detect_embedded())
+3 -2
View File
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
from installer.cards import card_platform, setup_bios_folder
from installer.config_values import _RETROARCH_CONFIGS, _parse_retroarch_system_dir
from installer.detection_notes import echo_detection, note_detection
from installer.embedded import CARD_MARKER, _EMBEDDED_RULES, _NO_FOLDER
from installer.events import EVENTS
from installer.host_fs import (
@@ -301,7 +302,7 @@ def _detect_embedded() -> list[tuple[str, Path]]:
reason = _NO_FOLDER.get(
name, "nothing on it names the folder its RetroArch reads")
closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest."
print(f"{name} found here, but {reason}.{closing}", file=sys.stderr)
note_detection(f"{name} found here, but {reason}.{closing}")
continue
_DETECTED_OS[(plat, folder)] = name
found.append((plat, folder))
@@ -383,7 +384,7 @@ def _note_windows_unasked() -> None:
_DETECTION_REFUSED.append(refused)
words = refused_words(*refused)
EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words)
print(f" {screen_text(words)}", file=sys.stderr)
echo_detection(f" {screen_text(words)}")
def _winreg_value(key: str, value: str) -> str | None:
+39
View File
@@ -0,0 +1,39 @@
"""What detection says, kept as lines the screen reads and printed as it comes in line mode."""
from __future__ import annotations
import contextlib
import sys
from collections.abc import Iterator
from typing import TextIO
# Each line detection said, in order, other than a folder it could not look
# in (_DETECTION_REFUSED keeps those): a system found with no folder, a
# configuration naming a folder nobody can type, an Android folder out of
# reach, a card that fits two systems.
DETECTION_NOTES: list[str] = []
# Set while the full screen runs detection: it shows the notes and the
# refusals itself, and a line printed under it would tear the screen.
_HELD = {"active": False}
def echo_detection(line: str, stream: TextIO | None = None) -> None:
"""Print a line detection says, unless the screen shows it itself."""
if not _HELD["active"]:
print(line, file=stream if stream is not None else sys.stderr)
def note_detection(line: str, stream: TextIO | None = None) -> None:
"""Keep a line detection says, and print it in line mode."""
DETECTION_NOTES.append(line)
echo_detection(line, stream)
@contextlib.contextmanager
def detection_held() -> Iterator[None]:
"""Detection that keeps its lines without printing them."""
outer = _HELD["active"]
_HELD["active"] = True
try:
yield
finally:
_HELD["active"] = outer
+2 -2
View File
@@ -7,13 +7,13 @@ import os
import re
import shutil
import stat
import sys
import tempfile
import threading
from collections.abc import Callable
from pathlib import Path
from typing import Any
from installer.detection_notes import echo_detection
from installer.events import EVENTS
from installer.text import screen_text
@@ -103,7 +103,7 @@ def _note_refused(path: Path, exc: OSError) -> None:
_DETECTION_UNREADABLE.add(refused[0])
words = refused_words(*refused)
EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words)
print(f" {screen_text(words)}", file=sys.stderr)
echo_detection(f" {screen_text(words)}")
def _held(path: Path) -> bool:
+3 -1
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING
@@ -19,6 +20,7 @@ from installer.cards import (
drive_kind,
)
from installer.console import _ask, _quit
from installer.detection_notes import note_detection
from installer.detect_frontends import _UNNAMEABLE, _android_storage_root, detect_platforms
from installer.detect_os import (
_DETECTED_OS,
@@ -555,7 +557,7 @@ def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]:
# A drive whose files fit two systems is said, never guessed.
words = doubt_words(mount)
if words:
print(f" {words}")
note_detection(f" {words}", sys.stdout)
continue
if (card[0], card[1]) not in found and card[2] not in here:
_DETECTED_OS.setdefault((card[0], card[1]), card[2])
+5 -6
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import argparse
import codecs
import contextlib
import errno
import functools
import io
@@ -24,6 +23,7 @@ from installer.cards import _SHARE_FOLDERS, _mounted_cards, card_bound, card_pla
from installer.console import QUIT_CODE
from installer.destination import card_choice, dest_default
from installer.detect_frontends import detect_frontends
from installer.detection_notes import DETECTION_NOTES, detection_held
from installer.detect_os import _enter_wsl, _wsl_dest, detect_os, detected_os
from installer.from_folders import _open_local_sources, from_folder_problem
from installer.host_fs import _DETECTION_REFUSED, refused_words
@@ -135,19 +135,18 @@ def _tui_take_args(state: TuiState, args: argparse.Namespace) -> None:
def _tui_detect(state: TuiState, os_type: str) -> None:
"""The setups and cards found here, and what detection said."""
captured = io.StringIO()
with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
start = len(DETECTION_NOTES)
with detection_held():
state.setups, state.mounted_setups = found_setups(os_type)
frontends = detect_frontends(os_type)
# Said on the normal screen before this one covered it, and kept
# above the list: a status line under 18 setups was never drawn.
state.refused = [refused_words(folder, why, _short_path(folder, state.home))
for folder, why in _DETECTION_REFUSED]
unsaid = {refused_words(*refused) for refused in _DETECTION_REFUSED}
if "esde" in frontends:
state.notes.append(TUI_ESDE_NOTE)
state.notes += [line.strip() for line in captured.getvalue().splitlines()
if line.strip() and line.strip() not in unsaid]
state.notes += [line.strip() for note in DETECTION_NOTES[start:]
for line in note.splitlines() if line.strip()]
def _start_on_platform(state: TuiState, args: argparse.Namespace, plat: str,
+31
View File
@@ -4723,6 +4723,37 @@ class AFolderThisUserCannotOpen(unittest.TestCase):
# The list keeps its focused row in view.
self.assertIn("RetroArch", screen)
def test_detection_lines_are_read_not_captured(self):
"""The screen read detection's lines by capturing stdout and stderr,
and dropped a refusal by comparing its printed text: a folder whose
name the terminal text escapes was then said twice."""
closed = self.lock.parent / "esc\x1bape"
closed.mkdir()
os.chmod(closed, 0o000)
self.addCleanup(os.chmod, closed, 0o755)
install._DETECTION_REFUSED.clear()
self.addCleanup(install._DETECTION_REFUSED.clear)
def detect(_os_type: str) -> list:
install._SETUP_SEARCH.active = True
try:
install._is_dir(closed / "bios")
install.note_detection("Batocera found here, but no folder.")
finally:
install._SETUP_SEARCH.active = False
return []
with mock.patch.object(install, "detect_platforms", side_effect=detect), \
mock.patch.object(install, "detect_frontends", return_value=[]), \
mock.patch.object(install, "_mounted_cards", return_value=[]), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
state, _effects = install.tui_start(_args(), "linux")
self.assertEqual((out.getvalue(), err.getvalue()), ("", ""))
self.assertEqual(install._DETECTION_REFUSED, [(closed, "Permission denied")])
self.assertEqual(len(state.refused), 1)
self.assertEqual(state.notes, ["Batocera found here, but no folder."])
class AGoesIntoASubfolder(unittest.TestCase):
"""At HOME or a drive root A went into the first "dir" row: a mounted
+1 -1
View File
@@ -500,7 +500,7 @@ those it imports:
| Shared words and limits | `remote`, `regions`, `platforms`, `manifest`, `embedded`, `text`, `events`, `invocation` |
| Terminal and line output | `terminal`, `console` |
| Files and folders | `host_fs`, `paths`, `filesystems`, `config_values`, `local_check`, `safe_replace` |
| This machine | `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` |
| This machine | `detection_notes`, `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` |
| Sources of files | `offline`, `network`, `pack_source`, `from_folders`, `diagnosis`, `download`, `datadirs`, `standalone` |
| What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `game_files`, `games`, `tally` |
| Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `outcome` |