From a9d8e571c18130bd0d09fee1b274fdec565fb972 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:42:18 +0100 Subject: [PATCH] refactor: join name lists through core.text --- scripts/release/notes.py | 3 ++- scripts/sitegen/cards.py | 3 ++- scripts/sitegen/consolecards.py | 3 ++- scripts/sitegen/datapage.py | 7 ++----- scripts/sitegen/descriptions.py | 14 +++++--------- scripts/sitegen/emulatorcards.py | 4 ++-- scripts/sitegen/emulatorpage.py | 12 ++++++------ scripts/sitegen/gaps.py | 5 +++-- scripts/sitegen/guidepage.py | 3 ++- scripts/sitegen/handheld.py | 10 +++------- scripts/sitegen/install.py | 9 +++------ scripts/sitegen/measurements.py | 3 ++- scripts/sitegen/readme.py | 9 ++------- scripts/sitegen/sources.py | 3 ++- scripts/sitegen/startwith.py | 10 +++++----- tests/test_text.py | 12 +++++++++++- 16 files changed, 54 insertions(+), 56 deletions(-) diff --git a/scripts/release/notes.py b/scripts/release/notes.py index 7a9120da7..ee10598ce 100644 --- a/scripts/release/notes.py +++ b/scripts/release/notes.py @@ -6,6 +6,7 @@ import json import subprocess from collections.abc import Callable +from core.text import series from core.sizes import size_text from model.guides import install_command from model.platforms import load_platform_config @@ -55,7 +56,7 @@ def no_pack_paragraph(platforms_dir: str) -> list[str]: names = without_pack(platforms_dir) if not names: return [] - listed = ", ".join(names[:-1]) + f" and {names[-1]}" if len(names) > 1 else names[0] + listed = series(names) return [ ("Only the most used setups have a pack, to keep the release small." f" For {listed}, use the command above."), diff --git a/scripts/sitegen/cards.py b/scripts/sitegen/cards.py index e7c3e5ed4..8154b698d 100644 --- a/scripts/sitegen/cards.py +++ b/scripts/sitegen/cards.py @@ -10,6 +10,7 @@ import urllib.parse import zipfile from collections.abc import Callable +from core.text import series from core.hashing import parse_hash_list from model.collection import profiles_on_disk from packs.crossref import FileConsumers @@ -565,7 +566,7 @@ _CARD_MORE_WORDS = {"Romset": "romset", "Collection path": "collection path", def listed_words(words: list[str]) -> str: """"a", "a and b", "a, b and c", first letter capital.""" - text = words[0] if len(words) == 1 else f"{', '.join(words[:-1])} and {words[-1]}" + text = series(words) return text[:1].upper() + text[1:] diff --git a/scripts/sitegen/consolecards.py b/scripts/sitegen/consolecards.py index b57b8410b..be40d8979 100644 --- a/scripts/sitegen/consolecards.py +++ b/scripts/sitegen/consolecards.py @@ -5,6 +5,7 @@ from __future__ import annotations import re from typing import TypeVar +from core.text import series from model.collection import profiles_on_disk from model.composition import GAME_DATA_TOPS from model.guides import INSTALL_PS1, INSTALL_SH @@ -244,7 +245,7 @@ def without_files(emulators: list[str]) -> str: names = sorted({emulator_display(e) for e in emulators}, key=str.casefold) if len(names) > 3: return f": none of its {len(names)} emulators requires one" - return " with " + (", ".join(names[:-1]) + f" or {names[-1]}" if len(names) > 1 else names[0]) + return " with " + series(names, "or") def visible_name(name: str) -> str: diff --git a/scripts/sitegen/datapage.py b/scripts/sitegen/datapage.py index 5759e9472..4d9eb157c 100644 --- a/scripts/sitegen/datapage.py +++ b/scripts/sitegen/datapage.py @@ -7,6 +7,7 @@ import re import urllib.parse from pathlib import Path +from core.text import series from model import siteinputs from model.registry import load_platform_registry from sitegen import markup, measurements as sitemeasurements @@ -126,10 +127,6 @@ def _platforms_without_a_list(platforms_dir: Path | None = None) -> list[str]: return names -def _join_names(names: list[str]) -> str: - return names[0] if len(names) == 1 else ", ".join(names[:-1]) + f" and {names[-1]}" - - def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = None) -> str: manifest_schema = json.loads( (REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text(encoding="utf-8")) @@ -326,7 +323,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N "passes when any file in the BIOS folder has one of its md5.", "- `hash_rule: size_and_any_hash` (RomM) wants the size and any one hash. " "The script below does not apply it.", - *([f"- {_join_names(no_list)} have no list of their own (`native_list: none`). " + *([f"- {series(no_list)} have no list of their own (`native_list: none`). " "An empty list does not mean nothing is needed."] if no_list else []), "", "```python", diff --git a/scripts/sitegen/descriptions.py b/scripts/sitegen/descriptions.py index 48fd72e90..b5962d90b 100644 --- a/scripts/sitegen/descriptions.py +++ b/scripts/sitegen/descriptions.py @@ -8,6 +8,7 @@ from collections import Counter from collections.abc import Iterable from pathlib import Path +from core.text import series from model import releaserecord from sitegen import measurements as sitemeasurements from sitegen.config import SITE_NAME @@ -84,7 +85,7 @@ def title_noun(names: Iterable[str]) -> str: if not distinct: return BIOS_FILES counts = Counter(file_kind(name) for name in distinct.values()) - return said_as_list([kind for kind in ("keys", "firmware", BIOS_FILES) + return series([kind for kind in ("keys", "firmware", BIOS_FILES) if counts[kind] * 4 >= len(distinct)]) @@ -260,7 +261,7 @@ def _files_snippet(markdown: str, key: str, title: str, intro: str) -> str: for count in range(min(len(names), 4), 0, -1): shown = (names if count == len(names) else [*names[:count - 1], f"{len(names) - count + 1:,} more"]) - head = f"{subject}: {said_as_list(shown)}, {need}." + head = f"{subject}: {series(shown)}, {need}." forms += [f"{head} {tail}" for tail in tails if tail] + [head] return next((form for form in forms if len(form) <= 155), intro) @@ -305,7 +306,7 @@ def _system_description(markdown: str, browser: str) -> str: consoles = [name for name in consoles if name and name not in _NOT_A_CONSOLE] if len(consoles) > 1: shown = consoles if len(consoles) <= 4 else consoles[:3] + [f"{len(consoles) - 3} more"] - return _shorten(f"{browser} for {said_as_list(shown)}, one card per file with its " + return _shorten(f"{browser} for {series(shown)}, one card per file with its " "hashes and the emulators that read it.", 155) start = re.search(r"^\*\*Start with\*\*(?P.*)$(?P(?:\n+- .*)*)", markdown, re.M) if start: @@ -317,7 +318,7 @@ def _system_description(markdown: str, browser: str) -> str: names = list(dict.fromkeys(html.unescape(name) for name in _CARD_TITLE.findall(markdown))) if names: shown = names if len(names) <= 3 else names[:3] + [f"{len(names) - 3} more"] - return _shorten(f"{browser}: {said_as_list(shown)}, with their hashes and the " + return _shorten(f"{browser}: {series(shown)}, with their hashes and the " "emulators that read them.", 155) return _shorten(f"{browser}, one card per file with its hashes and the emulators " "that read it.", 155) @@ -339,8 +340,3 @@ TITLE_NOUNS: dict[str, str] = {} # manufacturer, a run of an emulator's cards), by path relative to docs/: # their H1 already says what they are. PART_PAGES: set[str] = set() - - -def said_as_list(items: list[str]) -> str: - """"a, b and c".""" - return ", ".join(items[:-1]) + f" and {items[-1]}" if len(items) > 1 else "".join(items) diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py index 3e3b345fa..407691807 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -29,7 +29,7 @@ from sitegen.cards import ( card_fold, ) from sitegen.config import REPO_URL -from sitegen.descriptions import said_as_list +from core.text import series from sitegen.fields import hash_spans from sitegen.install import ( OS_LABELS, @@ -90,7 +90,7 @@ def region_words(value: object, most: int = 0) -> str: words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw] if most and len(words) > most: words = words[:most] + [f"{len(words) - most} more"] - return said_as_list(words) + return series(words) _CATEGORY_WORDS = {"bios": "BIOS", "game_data": "game data", "bios_zip": "BIOS ZIP"} diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 91af04636..ae5ba9036 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -17,7 +17,7 @@ from sitegen import entries as siteentries, markup, measurements as sitemeasurem from sitegen.cards import ROMSET_FAQ, emulator_file_anchors from sitegen.config import REPO_URL, date_line, yaml from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT -from sitegen.descriptions import said_as_list +from core.text import series from sitegen.emulatorcards import ( CardLayout, DATA_MEMBERS, @@ -200,7 +200,7 @@ def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> lis ) if categories.count(key) ] - lines.extend([f"By kind: {said_as_list(cats)}.", ""]) + lines.extend([f"By kind: {series(cats)}.", ""]) return lines @@ -218,7 +218,7 @@ def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) -> held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"] if unsourceable: held.append(f"{unsourceable:,} unsourceable") - return [f"

In this collection: {said_as_list(held)}.

", ""] + return [f"

In this collection: {series(held)}.

", ""] DATA_REVISIONS: dict[str, dict] = {} @@ -252,7 +252,7 @@ def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], stem, names = pages[index] members = DATA_MEMBERS.get(ref) or {} part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else "" - read_by = said_as_list([f"[{escape_tags(display)}]({key}.md#data-directories)" + read_by = series([f"[{escape_tags(display)}]({key}.md#data-directories)" for key, display in DATA_READERS.get(ref, [])]) # A file list out of the search: "dolphin" found three parts of the # dolphin-sys tree, on their title, before the Dolphin page. @@ -615,7 +615,7 @@ def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = "" sentences = [] if names: shown = names if len(names) <= 4 else names[:3] + [f"{len(names) - 3} more systems"] - sentences.append(f"{emu_name} emulates {said_as_list(shown)}.") + sentences.append(f"{emu_name} emulates {series(shown)}.") regional = _regional_set(requirements) by_region = "" if regional else _regional_choice(required) others = len(files) - len(required) @@ -667,7 +667,7 @@ def _regional_choice(required: list[dict], most: int = 6) -> str: if len({region_words(f["region"]) for f in required}) < 2: return "" choices = [f"{f.get('name', '')} ({region_words(f['region'], 3)})" for f in required] - return ", ".join(choices[:-1]) + f" or {choices[-1]}" + return series(choices, "or") def _alias_page(name: str, profile: dict) -> str: diff --git a/scripts/sitegen/gaps.py b/scripts/sitegen/gaps.py index 3a0d105fa..2324ead5f 100644 --- a/scripts/sitegen/gaps.py +++ b/scripts/sitegen/gaps.py @@ -7,6 +7,7 @@ import html import re from dataclasses import dataclass +from core.text import series from model.platforms import native_layer from model.profiles import is_emulator from resolve.cores import resolve_platform_cores @@ -310,7 +311,7 @@ def _platform_lists_sentence( parts.append(f"{untested:,} {_is(untested)} held but not verified " "(listed under Untested below)") parts.append(f"{missing:,} {_is(missing)} missing") - listed = ", ".join(parts[:-1]) + f" and {parts[-1]}" + listed = series(parts) split = "" if missing and not_firmware: labels = {"game_data": "game data", @@ -320,7 +321,7 @@ def _platform_lists_sentence( f"{count:,} {'is' if count == 1 else 'are'} {labels.get(category, category)}" for category, count in sorted(not_firmware.items()) ] - others_text = others[0] if len(others) == 1 else ", ".join(others[:-1]) + f" and {others[-1]}" + others_text = series(others) head = (f"None of the missing is firmware: {others_text}" if not firmware else f"Of the missing, {firmware:,} {'is' if firmware == 1 else 'are'} " f"firmware, {others_text}") diff --git a/scripts/sitegen/guidepage.py b/scripts/sitegen/guidepage.py index ace1465dd..7abd666d6 100644 --- a/scripts/sitegen/guidepage.py +++ b/scripts/sitegen/guidepage.py @@ -5,6 +5,7 @@ from __future__ import annotations import html import json +from core.text import series from model import releaserecord from model import siteinputs from model.collection import profiles_on_disk @@ -454,7 +455,7 @@ def generate_handheld_guide(guide: HandheldGuide) -> str: "", *_guide_download(guide.uses, display, uses, None, "## Download { #download }"), *_offline_line(guide.uses), - f"On {sitehandheld.joined(sitehandheld.group_systems(), 'or')}: " + f"On {series(sitehandheld.group_systems(), 'or')}: " f"[{sitehandheld.GROUP_TITLE}]" f"(../get/{GROUP_PAGE}.md).", "", diff --git a/scripts/sitegen/handheld.py b/scripts/sitegen/handheld.py index ea0e41fe5..51523dc97 100644 --- a/scripts/sitegen/handheld.py +++ b/scripts/sitegen/handheld.py @@ -21,6 +21,7 @@ import tempfile from dataclasses import dataclass from pathlib import Path +from core.text import series from sitegen import markup from core.artifacts import write_bytes_atomic from installer_build.port import ( @@ -39,11 +40,6 @@ def group_systems() -> list[str]: return [name for name in systems() if name not in PLATFORM_OF] -def joined(names: list[str], last: str = "and") -> str: - """muOS, ArkOS and JELOS.""" - return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {last} {names[-1]}" - - @dataclass(frozen=True) class Served: data: bytes @@ -126,7 +122,7 @@ def group_page(root: Path = REPO_ROOT) -> str: """get/linux-handhelds/: the app for the systems no setup page answers for, then the setup pages that carry it for the others.""" names = group_systems() - listed = joined(names) + listed = series(names) lines = [ "---", "search: exclude", f'description: "The RetroBIOS app for {listed}: the file to put on the card ' @@ -141,6 +137,6 @@ def group_page(root: Path = REPO_ROOT) -> str: lines += _launcher_block(launcher, system, root) others = [f"[{name}]({PLATFORM_OF[name]}.md#on-the-handheld)" for name in sorted(PLATFORM_OF, key=str.casefold)] - lines += ["## Other systems", "", f"On {joined(others, 'or')}: on its page.", "", + lines += ["## Other systems", "", f"On {series(others, 'or')}: on its page.", "", DETAILS_LINK, ""] return "\n".join(lines) diff --git a/scripts/sitegen/install.py b/scripts/sitegen/install.py index f740cf81c..571353462 100644 --- a/scripts/sitegen/install.py +++ b/scripts/sitegen/install.py @@ -9,6 +9,7 @@ import re import shlex from collections import Counter +from core.text import series from model import siteinputs from model.guides import GUIDES, TERMINALS, install_command from model.platforms import load_platform_config @@ -189,10 +190,6 @@ def _standalone_cores_in(platforms_dir: str, platform: str) -> frozenset[str]: return frozenset(standalone_set(config)) -def _said_or(names: list[str]) -> str: - return names[0] if len(names) == 1 else ", ".join(names[:-1]) + f" or {names[-1]}" - - def install_block(name: str, profile: dict) -> list[str]: """One command that installs this emulator's files where it reads them. @@ -209,7 +206,7 @@ def install_block(name: str, profile: dict) -> list[str]: emu = str(profile.get("emulator") or name) shown = [platform_display(setup) for setup in setups] if profile.get("type") == "standalone": - lead = (f"With {_said_or(shown)}: the installer finds {_said_or(shown)} and its " + lead = (f"With {series(shown, 'or')}: the installer finds {series(shown, 'or')} and its " f"BIOS folder, then downloads only the files {emu} reads there and checks " "each one.") else: @@ -217,7 +214,7 @@ def install_block(name: str, profile: dict) -> list[str]: "only the files this emulator reads there and checks each one.") if profile.get("type") == "standalone + libretro": # The command fills a setup, never the app's own folder. - where = (_said_or(shown) if len(shown) <= 3 + where = (series(shown, 'or') if len(shown) <= 3 else f"{shown[0]}, {shown[1]} or another setup") lead = f"For {emu} inside {where}. {lead}" return search_excluded(markup.details("tip", "Install this emulator's files", [ diff --git a/scripts/sitegen/measurements.py b/scripts/sitegen/measurements.py index fd399a3d7..bdfc59f66 100644 --- a/scripts/sitegen/measurements.py +++ b/scripts/sitegen/measurements.py @@ -31,6 +31,7 @@ import sys from dataclasses import dataclass from pathlib import Path +from core.text import series from model import measurements as mr from sitegen import markup from core.artifacts import json_text, write_if_changed @@ -514,7 +515,7 @@ def proof_result(verdicts: list[dict]) -> str: return VERDICT_WORDS.get(verdict["verdict"], verdict["verdict"].replace("_", " ")) if len(verdicts) == 1: staged = verdicts[0].get("staged") or [] - given = " and ".join(staged) if len(staged) < 3 else f"{', '.join(staged[:-1])} and {staged[-1]}" + given = series(staged) return f"with {given or 'no BIOS'}, it {said(verdicts[0])}" return ". ".join(f"{v['variant']}: {said(v)}" for v in verdicts) diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index c5b8b158c..98eb0b8e5 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -10,6 +10,7 @@ from collections.abc import Callable from datetime import datetime, timezone from pathlib import Path +from core.text import series from romrecipes import ledger from devtools import prchecks from model import releaserecord @@ -409,12 +410,6 @@ def download_table( ] -def _names_list(coverages: dict) -> str: - """The platforms' names in reading order, the last after "and".""" - names = sorted(c["platform"] for c in coverages.values()) - return ", ".join(names[:-1]) + f", and {names[-1]}" if len(names) > 1 else "".join(names) - - def collection_line(total_files: int, comp: dict) -> str: """The size of the whole collection, said as such. @@ -632,7 +627,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str "", "Some consoles need a small program, the **BIOS**, to start their games: PlayStation 1" " and 2, Saturn, Neo Geo, Dreamcast and more. RetroBIOS installs the BIOS and firmware" - f" files for {_names_list(coverages)}, checked the way each one checks them.", + f" files for {series(sorted(c['platform'] for c in coverages.values()))}, checked the way each one checks them.", "", "## Install in one line", "", diff --git a/scripts/sitegen/sources.py b/scripts/sitegen/sources.py index b753d95f7..9662a45d0 100644 --- a/scripts/sitegen/sources.py +++ b/scripts/sitegen/sources.py @@ -11,6 +11,7 @@ from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path +from core.text import series from core import upstream from core.artifacts import repository_output_lock, write_if_changed from core.paths import REPO_ROOT @@ -482,7 +483,7 @@ def requested_by(profile: dict, value: str | dict | None) -> str: labels.append(label) if not labels or not _two_repositories(profile): return "" - return labels[0] if len(labels) == 1 else ", ".join(labels[:-1]) + f" and {labels[-1]}" + return series(labels) def _two_repositories(profile: dict) -> bool: diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index db8cc7ab1..ab16836d1 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -24,7 +24,7 @@ from sitegen.consolecards import ( visible_name, without_files, ) -from sitegen.descriptions import said_as_list +from core.text import series from sitegen.emulatorcards import region_words from sitegen.install import comes_with_app from sitegen.render import card_anchor, code_span, count_text, console_anchor @@ -446,7 +446,7 @@ def _names_counted(names: list[str], most: int = 3, noun: str = "") -> str: if len(names) > most + 1: more = f"{len(names) - most} more" + (f" {noun}" if noun else "") return f"{', '.join(names[:most])} and {more}" - return said_as_list(names) + return series(names) def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: @@ -475,7 +475,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: zipped = " Keep it zipped." if top.casefold().endswith(".zip") else "" names = _display_names(readers) said = (_names_counted(names, 2, "emulators") if len(names) > 2 - else said_as_list(names)) + else series(names)) lines = [f"**Start with** {written[top]}.{zipped} {said} read{'s' if len(names) == 1 else ''} it.", ""] # The emulators that require other files and not this one, by the @@ -490,7 +490,7 @@ def _lead_file(groups: dict[str | None, _StartGroup]) -> list[str]: for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])): names = _display_names(who) verb = "reads" if len(names) == 1 else "read" - sentences.append(f"{_names_counted(names)} {verb} {said_as_list(list(files))} instead.") + sentences.append(f"{_names_counted(names)} {verb} {series(list(files))} instead.") if sentences: lines += [" ".join(sentences), ""] return lines @@ -527,7 +527,7 @@ class _GroupWords: for files, who in sorted(others.items(), key=lambda item: (-len(item[1]), item[0])): shown = _display_names(who) verb = "reads" if len(shown) == 1 else "read" - sentences.append(f"{_names_counted(shown)} {verb} {said_as_list(list(files))} instead.") + sentences.append(f"{_names_counted(shown)} {verb} {series(list(files))} instead.") return " ".join(sentences) def split(self, line: str, names: list[str]) -> tuple[list[str], str, set[str]]: diff --git a/tests/test_text.py b/tests/test_text.py index 3b5212c8a..beb091bc7 100644 --- a/tests/test_text.py +++ b/tests/test_text.py @@ -6,7 +6,7 @@ import tests import unittest -from core.text import count_text +from core.text import count_text, series class CountsTakeTheirNumber(unittest.TestCase): @@ -20,5 +20,15 @@ class CountsTakeTheirNumber(unittest.TestCase): self.assertEqual(count_text(2, "entry", "entries"), "2 entries") +class ListsHaveNoSerialComma(unittest.TestCase): + """The README alone wrote "RetroPie, and RomM", every page "B and C".""" + + def test_series(self): + self.assertEqual(series([]), "") + self.assertEqual(series(["a"]), "a") + self.assertEqual(series(["a", "b"]), "a and b") + self.assertEqual(series(["a", "b", "c"], "or"), "a, b or c") + + if __name__ == "__main__": unittest.main()