refactor: take a recorded choice in one place

The journey to another device's folder no longer stops on Create the folder?: one missing level is created as line mode does, since the shared rule for a missing BIOS folder.
This commit is contained in:
Abdessamad Derraz committed 2026-11-22 01:06:40 +01:00
1 parent c113a79c70
commit 352e2bbb5e
7 files changed
+125 -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 = "1fb588c9bcfea3bcd391237d1974a9a47a1565c699d5fab346efee008034bafb"
$defaultInstallSha256 = "28fae70165876bee5d900fc3862f68d473ea57d5e1279663b7ee8c331839e2d6"
# 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 -16
View File
@@ -10368,6 +10368,33 @@ def drop_recorded(args: argparse.Namespace, plat: str, flag: str, why: str,
print(f" Left out of the recorded choice: {flag} ({why}).")
class RecordedChoice(NamedTuple):
"""A recorded choice as a run takes it: parsed, its words once the
parts that no longer apply are out, and those parts in words."""
parsed: argparse.Namespace
choice: list[str]
left_out: list[str]
def take_recorded_choice(choice: list[str]) -> RecordedChoice | None:
"""The recorded choice made the run's, None where this installer lacks
one of its options. A games folder that is gone gives the card's own."""
try:
parsed = build_parser().parse_args(choice)
except SystemExit:
return None
words, left_out = list(choice), []
if isinstance(parsed.for_games, Path) and not _is_dir(parsed.for_games):
parsed.for_games = True
options = [(flag, None if flag == "--for-games" else value)
for flag, value in record_options(choice)]
words = [word for flag, value in options
for word in ([flag] if value is None else [flag, value])]
left_out.append("its games folder (no longer there)")
return RecordedChoice(parsed, words, left_out)
def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | None:
"""Take the choice recorded for plat in folder as the run's, as if its
options had been typed: the plan's first choice. Returns the record,
@@ -10376,30 +10403,26 @@ def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | No
say_record_problem(plat, folder, path, problem)
if setup is None:
return None
try:
parsed = build_parser().parse_args(setup["choice"])
except SystemExit:
taken = take_recorded_choice(setup["choice"])
if taken is None:
say_record_problem(plat, folder, path,
f"The install record {path} names options this installer lacks")
return None
parsed = taken.parsed
for flag in RECORD_CHOICE:
name = flag[2:].replace("-", "_")
setattr(args, name, getattr(parsed, name))
if args.for_games is not None:
args.all_files = False
args.from_record = True
options = record_options(setup["choice"])
options = record_options(taken.choice)
if any(flag in RECORD_NARROWING for flag, _value in options):
# Said where it narrows the list: the whole list again is the run
# a person expects, and said nothing new.
_RECORD_TAKEN[plat] = setup
_INVOCATION.chosen[plat] = [option for option in options if option[0] != "--all-files"]
if isinstance(args.for_games, Path) and not _is_dir(args.for_games):
# The games folder recorded is gone: the card's own games are read.
_INVOCATION.chosen[plat] = [(flag, None if flag == "--for-games" else value)
for flag, value in _INVOCATION.chosen[plat]]
args.for_games = True
print(" Left out of the recorded choice: its games folder (no longer there).")
for part in taken.left_out:
print(f" Left out of the recorded choice: {part}.")
message = record_menu_words(setup)
EVENTS.emit("record", platform=plat, folder=str(folder), path=str(path), status="applied",
choice=list(setup["choice"]), date=setup["written"],
@@ -16774,6 +16797,7 @@ def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
f = job.f
reason: str = "download failed"
refused = False
delay: float | None
for attempt in range(1, MAX_RETRIES + 1):
job.begin()
try:
@@ -16806,7 +16830,10 @@ def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
except urllib.error.HTTPError as exc:
reason = _http_attempt_failure(job, exc, attempt)
delay = _server_delay(exc, attempt)
# A 416 refused the partial copy, dropped above: the next attempt
# asks for the whole file.
delay = (_server_delay(exc, attempt) if exc.code == 416 and attempt < MAX_RETRIES
else _retry_after_failure(exc, attempt, MAX_RETRIES))
# http.client raises IncompleteRead (an HTTPException, not an
# OSError) when a chunked transfer is cut, as a proxy re-encoding
@@ -16817,14 +16844,14 @@ def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
print(f" Attempt {attempt} failed: {exc}", file=sys.stderr)
if not refused:
job.drop_private()
delay = _retry_delay(attempt, None)
delay = _retry_after_failure(exc, attempt, MAX_RETRIES)
finally:
if job.partial is not None:
job.partial.close()
job.take_back()
if refused or reason == DRIVE_FULL:
if refused or reason == DRIVE_FULL or delay is None:
return f["dest"], False, reason
if attempt < MAX_RETRIES and delay and _stop.wait(delay):
return f["dest"], False, "stopped"
@@ -28920,12 +28947,17 @@ def _start_run(state: TuiState, run: str) -> list[tuple]:
def _tui_record_take(state: TuiState) -> None:
"""The recorded choice made the screen's, as its options would make it."""
setup = state.record or {}
try:
parsed = build_parser().parse_args(setup.get("choice") or [])
except SystemExit:
taken = take_recorded_choice(setup.get("choice") or [])
if taken is None:
state.status = "The install record names options this installer lacks, so it is ignored."
state.record = None
return
parsed = taken.parsed
if taken.left_out:
# What the run takes, as line mode keeps it: the plan reads as the
# record's own choice again.
setup = state.record = {**setup, "choice": taken.choice}
state.status = f"Left out of the recorded choice: {', '.join(taken.left_out)}."
state.cli_systems = list(parsed.system or [])
state.cores = [token.strip() for value in parsed.core or [] for token in value.split(",")
if token.strip()]
+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="1fb588c9bcfea3bcd391237d1974a9a47a1565c699d5fab346efee008034bafb"
DEFAULT_INSTALL_SHA256="28fae70165876bee5d900fc3862f68d473ea57d5e1279663b7ee8c331839e2d6"
# 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": 1473352,
"sha256": "1fb588c9bcfea3bcd391237d1974a9a47a1565c699d5fab346efee008034bafb",
"size": 1475874,
"sha256": "28fae70165876bee5d900fc3862f68d473ea57d5e1279663b7ee8c331839e2d6",
"executable": false
},
{
@@ -71,8 +71,8 @@
"muos": {
"archive": {
"dest": "ARCHIVE/RetroBIOS.muxapp",
"size": 1526977,
"sha256": "5a5101c98833239883e318087d4c6e60e8de515794f962fe8e2ac71672cdd731"
"size": 1529499,
"sha256": "3c2b413f2e5b533bbb899175337b7e443eb81faef809ecbb83fc6112111ac593"
},
"members": [
{
@@ -92,8 +92,8 @@
{
"name": "RetroBIOS/install.py",
"repo_path": "install.py",
"size": 1473352,
"sha256": "1fb588c9bcfea3bcd391237d1974a9a47a1565c699d5fab346efee008034bafb",
"size": 1475874,
"sha256": "28fae70165876bee5d900fc3862f68d473ea57d5e1279663b7ee8c331839e2d6",
"executable": false
},
{
@@ -166,8 +166,8 @@
{
"dest": ".config/modules/retrobios/install.py",
"repo_path": "install.py",
"size": 1473352,
"sha256": "1fb588c9bcfea3bcd391237d1974a9a47a1565c699d5fab346efee008034bafb",
"size": 1475874,
"sha256": "28fae70165876bee5d900fc3862f68d473ea57d5e1279663b7ee8c331839e2d6",
"executable": false
},
{
+33 -10
View File
@@ -414,6 +414,33 @@ def drop_recorded(args: argparse.Namespace, plat: str, flag: str, why: str,
print(f" Left out of the recorded choice: {flag} ({why}).")
class RecordedChoice(NamedTuple):
"""A recorded choice as a run takes it: parsed, its words once the
parts that no longer apply are out, and those parts in words."""
parsed: argparse.Namespace
choice: list[str]
left_out: list[str]
def take_recorded_choice(choice: list[str]) -> RecordedChoice | None:
"""The recorded choice made the run's, None where this installer lacks
one of its options. A games folder that is gone gives the card's own."""
try:
parsed = build_parser().parse_args(choice)
except SystemExit:
return None
words, left_out = list(choice), []
if isinstance(parsed.for_games, Path) and not _is_dir(parsed.for_games):
parsed.for_games = True
options = [(flag, None if flag == "--for-games" else value)
for flag, value in record_options(choice)]
words = [word for flag, value in options
for word in ([flag] if value is None else [flag, value])]
left_out.append("its games folder (no longer there)")
return RecordedChoice(parsed, words, left_out)
def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | None:
"""Take the choice recorded for plat in folder as the run's, as if its
options had been typed: the plan's first choice. Returns the record,
@@ -422,30 +449,26 @@ def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | No
say_record_problem(plat, folder, path, problem)
if setup is None:
return None
try:
parsed = build_parser().parse_args(setup["choice"])
except SystemExit:
taken = take_recorded_choice(setup["choice"])
if taken is None:
say_record_problem(plat, folder, path,
f"The install record {path} names options this installer lacks")
return None
parsed = taken.parsed
for flag in RECORD_CHOICE:
name = flag[2:].replace("-", "_")
setattr(args, name, getattr(parsed, name))
if args.for_games is not None:
args.all_files = False
args.from_record = True
options = record_options(setup["choice"])
options = record_options(taken.choice)
if any(flag in RECORD_NARROWING for flag, _value in options):
# Said where it narrows the list: the whole list again is the run
# a person expects, and said nothing new.
_RECORD_TAKEN[plat] = setup
_INVOCATION.chosen[plat] = [option for option in options if option[0] != "--all-files"]
if isinstance(args.for_games, Path) and not _is_dir(args.for_games):
# The games folder recorded is gone: the card's own games are read.
_INVOCATION.chosen[plat] = [(flag, None if flag == "--for-games" else value)
for flag, value in _INVOCATION.chosen[plat]]
args.for_games = True
print(" Left out of the recorded choice: its games folder (no longer there).")
for part in taken.left_out:
print(f" Left out of the recorded choice: {part}.")
message = record_menu_words(setup)
EVENTS.emit("record", platform=plat, folder=str(folder), path=str(path), status="applied",
choice=list(setup["choice"]), date=setup["written"],
+15 -5
View File
@@ -7,7 +7,6 @@ from collections.abc import Callable
from pathlib import Path
from typing import TYPE_CHECKING
from installer.arguments import build_parser
from installer.cards import (
_card_boundary,
_mount_name,
@@ -36,7 +35,13 @@ from installer.embedded import CARD_PLATFORMS, _a
from installer.frontend_folders import _retroarch_config_at
from installer.games import games_probe
from installer.host_fs import _exists, _folder_writable, _is_dir, _nearest_folder, closed_folder
from installer.install_record import RECORD_NARROWING, _RECORD_SAID, record_options, setup_record
from installer.install_record import (
RECORD_NARROWING,
_RECORD_SAID,
record_options,
setup_record,
take_recorded_choice,
)
from installer.invocation import OFFLINE_VARIABLE
from installer.lists import local_targets
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE
@@ -227,12 +232,17 @@ def _start_run(state: TuiState, run: str) -> list[tuple]:
def _tui_record_take(state: TuiState) -> None:
"""The recorded choice made the screen's, as its options would make it."""
setup = state.record or {}
try:
parsed = build_parser().parse_args(setup.get("choice") or [])
except SystemExit:
taken = take_recorded_choice(setup.get("choice") or [])
if taken is None:
state.status = "The install record names options this installer lacks, so it is ignored."
state.record = None
return
parsed = taken.parsed
if taken.left_out:
# What the run takes, as line mode keeps it: the plan reads as the
# record's own choice again.
setup = state.record = {**setup, "choice": taken.choice}
state.status = f"Left out of the recorded choice: {', '.join(taken.left_out)}."
state.cli_systems = list(parsed.system or [])
state.cores = [token.strip() for value in parsed.core or [] for token in value.split(",")
if token.strip()]
+19 -3
View File
@@ -48,7 +48,7 @@ JOURNEY_KEYS = {
"one_system": (13, 14),
"one_system_again": (1, 2),
"what_is_missing": (4, 5),
"another_device": (20, 21),
"another_device": (19, 20),
}
# Words each journey's screens show by default, summed over the screens it
@@ -346,9 +346,8 @@ class Journeys(unittest.TestCase):
term.wait("Which folder?", timeout=40)
self.press(term, DOWN, "\r")
term.wait("RetroBIOS: Type a path")
# One missing level is created without a question, as line mode does.
self.press(term, "~/bios", "\r")
term.wait("Create the folder?")
self.press(term, "\r")
screen = term.wait("files to download", timeout=40)
self.assertIn("RetroBIOS: Batocera", screen)
self.press(term, "\r")
@@ -675,6 +674,23 @@ class RecordReview(unittest.TestCase):
self.assertEqual(events(proc, "record")[0]["status"], "unreadable")
self.assertEqual(self.dests(proc), self.everything())
def test_a_games_folder_that_is_gone_gives_the_card_games_both_ways(self):
"""Line mode read the card's games, the screen gave the child run the
folder that is gone, and its check ended on an error."""
gone = self.dest.parent / "roms-gone"
self.write(["--for-games", str(gone), "--system", "nintendo-gba"])
state = install.TuiState()
state.platform, state.dest = "retroarch", self.dest
install._tui_record_load(state)
self.assertIn(("--for-games", None), install.tui_flags(state))
self.assertNotIn(str(gone), [value for _flag, value in install.tui_flags(state)])
self.assertIn("its games folder (no longer there)", state.status)
self.assertTrue(install.tui_record_kept(state))
proc = self.run_line("--check")
self.assertIn("Left out of the recorded choice: its games folder (no longer there).",
proc.stdout)
self.assertNotIn("does not exist", proc.stdout + proc.stderr)
def test_a_recorded_option_that_cannot_apply_is_left_out(self):
"""A run nobody typed options for went on failing: the list has no
cores, no categories and no board list, and a region is unknown."""