refactor: join name lists through core.text

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:03:21 +01:00
1 parent 4b8e91bb6f
commit a9d8e571c1
16 files changed
+54 -56

No files matched your search

+2 -1
View File
@@ -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."),
+2 -1
View File
@@ -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:]
+2 -1
View File
@@ -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:
+2 -5
View File
@@ -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",
+5 -9
View File
@@ -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<line>.*)$(?P<list>(?:\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)
+2 -2
View File
@@ -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"}
+6 -6
View File
@@ -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"<p><small>In this collection: {said_as_list(held)}.</small></p>", ""]
return [f"<p><small>In this collection: {series(held)}.</small></p>", ""]
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:
+3 -2
View File
@@ -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}")
+2 -1
View File
@@ -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).",
"",
+3 -7
View File
@@ -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)
+3 -6
View File
@@ -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", [
+2 -1
View File
@@ -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)
+2 -7
View File
@@ -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",
"",
+2 -1
View File
@@ -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:
+5 -5
View File
@@ -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]]:
+11 -1
View File
@@ -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()