refactor: print sizes with one function

core.sizes.size_text replaces readme format_size, release record
size_text, render fmt_size, the large-files notes _mib and the handheld
_size. It prints one decimal in the largest unit reached, as the site
and the installer already did.

The README download table, the release notes and the large-files page
now say 29.2 MB where they said 29 MB, a handheld archive says 85.3 KB
where it said 85 KB, and a large-files asset under 1 MB is given in KB.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 20:03:26 +01:00
1 parent 3a76cf48ba
commit ab0805e6cb
19 files changed
+60 -71

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
"""Byte counts as the README, the site and the release notes print them."""
from __future__ import annotations
def size_text(count: int) -> str:
"""A byte count in the largest binary unit it reaches, one decimal: 29.2 MB.
The installer prints the same text (installer/text.py format_size), so a
figure reads alike on every surface.
"""
for unit, scale in (("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
if count >= scale:
return f"{count / scale:.1f} {unit}"
return f"{count} B"
+3 -6
View File
@@ -12,6 +12,7 @@ from typing import NamedTuple
from core.paths import EMULATORS_DIR
from core.hashing import file_digest
from core.sizes import size_text
from model.composition import composition_tier
from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths
@@ -157,10 +158,6 @@ def _section_for(path: str) -> str:
return "Other"
def _mib(size: int) -> str:
return f"{round(size / 1048576)} MB"
def render_notes(
db: dict,
gitignore_text: str,
@@ -205,9 +202,9 @@ def render_notes(
description = description or name
link = f"[{name}]({ASSET_URL}{name})"
if section == NOT_INDEXED:
line = f"| {link} | {description} | {_mib(size)} |"
line = f"| {link} | {description} | {size_text(size)} |"
else:
line = f"| {link} | {description} | {_mib(size)} | `{sha1}` |"
line = f"| {link} | {description} | {size_text(size)} | `{sha1}` |"
rows[section].append((-size, line))
out = [
+2 -2
View File
@@ -7,6 +7,7 @@ import re
import subprocess
from collections.abc import Callable
from core.sizes import size_text
from model.guides import install_command
from model.platforms import load_platform_config
from model.registry import (
@@ -14,7 +15,6 @@ from model.registry import (
list_release_pack_platforms,
load_platform_registry,
)
from release import record as release_record
REPO = "Abdess/retrobios"
@@ -240,7 +240,7 @@ def render(record: dict, platforms_dir: str, whats_new: str,
folder = folders.get(name)
lines.append(
f"| {_display(name)} | {_link(pack, tag)} |"
f" {release_record.size_text(pack['extracted_size'])} | {pack['files']:,} |"
f" {size_text(pack['extracted_size'])} | {pack['files']:,} |"
f" {f'`{folder}`' if folder else '-'} |"
)
lines += [
-6
View File
@@ -115,9 +115,3 @@ def manifest_mismatches(record: dict, install_dir: str | Path) -> list[str]:
f"install/{manifest_path.name} expects {expected}"
)
return found
def size_text(count: int) -> str:
if count >= 1024**3:
return f"{count / 1024**3:.1f} GB"
return f"{count / 1024**2:.0f} MB"
+1 -1
View File
@@ -22,13 +22,13 @@ import sys
from pathlib import Path
from core.artifacts import ArtifactLockBusy, write_text_atomic
from core.sizes import size_text
from model.releaserecord import RECORD
from release.record import (
NotAReleasePackError,
UnfinishedSplitError,
build_record,
manifest_mismatches,
size_text,
)
+4 -3
View File
@@ -13,7 +13,8 @@ from model.safeparse import yaml_load
from sitegen import markup, measurements as sitemeasurements
from sitegen.config import RELEASE_URL, REPO_URL, SITE_URL
from core.paths import REPO_ROOT
from sitegen.render import escape_tags, fmt_size
from core.sizes import size_text
from sitegen.render import escape_tags
def _is_manifest(item: dict) -> bool:
@@ -178,7 +179,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N
)
lines.append(
f"| {item['title']} | [`{item['url']}`]({item['url']}) | "
f"{schema} | {fmt_size(item['bytes'])} |"
f"{schema} | {size_text(item['bytes'])} |"
)
lines.extend([
"",
@@ -354,7 +355,7 @@ def generate_data_page(exports: list[dict], measurements_sqlite: Path | None = N
continue
lines.append(
f"| [{item['title']}]({item['url']}) | `{item['media_type']}` | "
f"{fmt_size(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |"
f"{size_text(item['bytes'])} | {_short_sha256(item, 'api/v1/catalog.json')} |"
)
lines.extend([
"",
+5 -5
View File
@@ -10,6 +10,7 @@ from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from core.sizes import size_text
from model.collection import manufacturer_slug
from model.systemnames import system_name
from packs.crossref import FileConsumers, entry_target, held_copy
@@ -43,7 +44,6 @@ from sitegen.render import (
code_span,
count_text,
escape_tags,
fmt_size,
card_page,
console_href,
)
@@ -273,7 +273,7 @@ def _validation_names(validation: dict | list | None) -> set[str]:
def _exact_size(size: int) -> str:
"""A rounded size with its bytes, where the bytes are not the same figure."""
return fmt_size(size) if size < 1024 else f"{fmt_size(size)} ({size:,} bytes)"
return size_text(size) if size < 1024 else f"{size_text(size)} ({size:,} bytes)"
def _build_file_links(pin_build: list[dict]) -> list[str]:
@@ -393,7 +393,7 @@ def _card_size_details(f: dict) -> list[str]:
fmax = f.get("max_size")
# Where the code compares the size, the exact bytes: raze tells three
# DUKE3D.GRP apart by size, all three shown as 42.3 MB.
sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else fmt_size
sized = _exact_size if "size" in _validation_names(f.get("validation", [])) else size_text
bounds = []
if fmin:
bounds.append(f"min {sized(fmin)}")
@@ -663,7 +663,7 @@ def _contents_lines(contents: list) -> list[str]:
if c.get("description"):
parts.append(escape_tags(str(c["description"])))
if c.get("size"):
parts.append(fmt_size(c["size"]))
parts.append(size_text(c["size"]))
if c.get("crc32"):
parts.append(f"CRC32 `{c['crc32']}`")
if c.get("sha1"):
@@ -1036,7 +1036,7 @@ def render_metadata_rows(profile: dict) -> list[str]:
# inside the app's own data folder, which the notes describe.
lines.append(f"| {label} | {code_span(val)}, inside the app's own data folder |")
elif field == "bios_size" and isinstance(val, int):
lines.append(f"| {label} | {fmt_size(val)} ({val:,} bytes) |")
lines.append(f"| {label} | {size_text(val)} ({val:,} bytes) |")
elif isinstance(val, str) and val.startswith("http"):
lines.append(f"| {label} | [{val}]({val}) |")
else:
+2 -2
View File
@@ -9,6 +9,7 @@ from collections.abc import Callable, Sequence
from dataclasses import dataclass
from core.hashing import parse_hash_list
from core.sizes import size_text
from model.systemnames import system_name
from packs.crossref import FileConsumers
from sitegen import entries as siteentries, markup, measurements as sitemeasurements
@@ -48,7 +49,6 @@ from sitegen.render import (
code_span,
count_text,
escape_tags,
fmt_size,
card_page,
record_emulator_cards,
)
@@ -253,7 +253,7 @@ def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[
anchor = f"sha1-{sha1[:12]}"
span = "" if anchor in anchors else f'<span id="{anchor}"></span>'
anchors.add(anchor)
table.append(f"| {span}{code_span(member)} | {fmt_size(int(info.get('size', 0)))} | {code_span(sha1)} |")
table.append(f"| {span}{code_span(member)} | {size_text(int(info.get('size', 0)))} | {code_span(sha1)} |")
return table
+4 -4
View File
@@ -14,6 +14,7 @@ from installer_build.handhelds import GROUP_PAGE
from sitegen import handheld as sitehandheld, markup
from sitegen.config import RELEASE_URL, REPO_URL
from core.paths import REPO_ROOT
from core.sizes import size_text
from sitegen.descriptions import PAGE_DATA
from sitegen.guidepage import (
NO_ZIP_FAQ,
@@ -27,7 +28,6 @@ from sitegen.home import next_block
from sitegen.install import has_release_pack
from sitegen.parts import parent_front_matter
from sitegen.readme import asset_links
from sitegen.render import fmt_size
from sitegen.versions import release_line, version_line
@@ -62,8 +62,8 @@ def _pack_lines(platform_name: str, display: str, record: dict, pack: dict) -> l
asset_links(platform_name, record, REPO_URL, f"Download {display} Pack",
button=lambda text, url: markup.button(text, url, primary=True)),
"",
f"- {fmt_size(pack['download_size'])} to download, "
f"{fmt_size(pack['extracted_size'])} once unzipped.",
f"- {size_text(pack['download_size'])} to download, "
f"{size_text(pack['extracted_size'])} once unzipped.",
*(["- Both parts are needed." if parts == 2 else f"- All {parts} parts are needed."]
if parts > 1 else []),
*_unzip_into(platform_name, display, extract_to, parts),
@@ -104,7 +104,7 @@ def generate_get_page(platform_name: str) -> str:
if released and pack and tag_date:
PAGE_DATA[f"{releaserecord.GET_DIR}/{platform_name}.md"] = {"dateModified": "-".join(tag_date.groups())}
if released and pack and pack.get("assets"):
description = (f"The BIOS pack for {display}: {fmt_size(pack['download_size'])} to "
description = (f"The BIOS pack for {display}: {size_text(pack['download_size'])} to "
"download. The address stays the same and always gives the latest ZIP.")
else:
description = f"The BIOS files for {display}: one command installs and checks them."
+3 -3
View File
@@ -22,11 +22,11 @@ from resolve.nativemode import digest_algorithm
from installer_build.handhelds import GROUP_PAGE
from sitegen import handheld as sitehandheld, markup
from core.paths import REPO_ROOT
from core.sizes import size_text
from sitegen.guides import platform_args, terminal_tabs
from sitegen.home import next_block
from sitegen.install import installer_module, has_release_pack
from sitegen.readme import download_links, extract_notes
from sitegen.render import fmt_size
from sitegen.versions import release_line, setup_version, version_line
@@ -316,8 +316,8 @@ def _guide_download(name: str, display: str, guide: Guide, extract_to: str | Non
if pack and pack.get("assets"):
parts = len(pack["assets"])
bullets = [
f"{fmt_size(pack['download_size'])} to download, "
f"{fmt_size(pack['extracted_size'])} once unzipped."
f"{size_text(pack['download_size'])} to download, "
f"{size_text(pack['extracted_size'])} once unzipped."
]
if parts > 1:
bullets.append("Both parts are needed." if parts == 2 else f"All {parts} parts are needed.")
+2 -7
View File
@@ -29,6 +29,7 @@ from installer_build.port import (
build_archive,
)
from core.paths import REPO_ROOT
from core.sizes import size_text
from installer_build.handhelds import Launcher, PLATFORM_OF, SERVED_DIR, launchers_for, systems
GROUP_TITLE = "RetroBIOS app for handhelds"
@@ -98,17 +99,11 @@ def _launcher_block(launcher: Launcher, system: str, root: Path) -> list[str]:
"",
f"- {verb} {launcher.folder_for(system)}.",
f"- Start it from {launcher.start}.",
f"- {_size(archive.size)}. SHA-256: `{archive.sha256}`",
f"- {size_text(archive.size)}. SHA-256: `{archive.sha256}`",
"",
]
def _size(count: int) -> str:
if count >= 1024 * 1024:
return f"{count / 1024 ** 2:.1f} MB"
return f"{count / 1024:.0f} KB"
APP_LINE = "RetroBIOS also runs on the handheld, with the controller."
# The installer's handheld section opens on the download of every system.
INSTALLER_SECTION = "wiki/installer.md#on-a-handheld-the-retrobios-port"
+2 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import html
from core.paths import PLATFORMS_DIR
from core.sizes import size_text
from model.composition import compute_composition
from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES, Guide, TRUST_ITEMS, setup_count
from model.platforms import load_platform_config
@@ -12,7 +13,6 @@ from model.profiles import unique_emulator_profiles
from model.registry import load_platform_registry
from sitegen import markup
from sitegen.readme import demo_description, demo_facts
from sitegen.render import fmt_size
# Home page
@@ -179,7 +179,7 @@ def generate_explore_index(db: dict, coverages: dict, profiles: dict) -> str:
*stat_block(f"{total_files:,}", COLLECTION_FILES_LABEL),
*stat_block(str(setup_count()), "Setups supported"),
*stat_block(str(emulator_count), "Emulators documented"),
*stat_block(fmt_size(total_size), "Size of the collection"),
*stat_block(size_text(total_size), "Size of the collection"),
"</div>",
"",
composition_sentence(db),
+3 -3
View File
@@ -16,6 +16,7 @@ from sitegen import entries as siteentries, markup
from sitegen.cards import SHORT_HASH
from sitegen.config import REPO_URL, date_line
from core.paths import REPO_ROOT
from core.sizes import size_text
from sitegen.fields import hash_spans, search_excluded
from sitegen.parts import (
PAGE_BYTES,
@@ -32,7 +33,6 @@ from sitegen.render import (
count_text,
emulator_link,
escape_tags,
fmt_size,
card_page,
console_href,
)
@@ -276,9 +276,9 @@ def _platform_file_row(f: dict, cfg_entry: dict, hash_type: str = "",
# The size closes the hash lines: a line of its own was one more
# element per row.
if size and facts:
facts[-1] += f" ({fmt_size(size)})"
facts[-1] += f" ({size_text(size)})"
elif size:
facts.append(f"Size: {fmt_size(size)}")
facts.append(f"Size: {size_text(size)}")
if f.get("status") == "untested" and f.get("reason"):
facts.append(_text_html(f"Not confirmed: {f['reason']}"))
# Not every entry is firmware: the platform may list a game's data or a
+4 -10
View File
@@ -18,6 +18,7 @@ from core.artifacts import write_if_changed
from core.cli import InputMissing
from core.github import github_token
from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT
from core.sizes import size_text
from model.composition import compute_composition, count_catalog_matched
from model.declarations import declared_root
from model.guides import PACKAGE_COMMAND, install_command
@@ -390,7 +391,7 @@ def download_table(
files, size = release_totals(name, record)
lines.append(
f"| {cov['platform']} | {f'{files:,}' if files else '-'} |"
f" {format_size(size) if size else '-'} |"
f" {size_text(size) if size else '-'} |"
f" {extract_paths.get(cov['platform'], '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
@@ -431,13 +432,6 @@ def collection_line(total_files: int, comp: dict) -> str:
)
def format_size(size: int) -> str:
"""Human-readable pack size."""
if size >= 1024**3:
return f"{size / 1024**3:.1f} GB"
return f"{size / 1024**2:.0f} MB"
SITE_URL = "https://abdess.github.io/retrobios/"
# The installer demo (scripts/make_demo.py): the recording and what it shows.
DEMO_DIR = REPO_ROOT / "docs_assets" / "demo"
@@ -464,7 +458,7 @@ def clone_line(db: dict) -> str:
)
return (
"Packs are built from a clone, and the clone carries the collection:"
f" its checkout alone is over {format_size(committed)}."
f" its checkout alone is over {size_text(committed)}."
f" `git clone --depth 1 https://github.com/{REPO}.git` leaves the"
" history out. Files kept as release assets are downloaded when a"
" pack needs them. Then generate packs for any platform, emulator,"
@@ -692,7 +686,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str
files, size = release_totals(name, record)
display = coverages[name]["platform"]
lines.append(
f"| {display} | {files:,} | {format_size(size) if size else '-'} |"
f"| {display} | {files:,} | {size_text(size) if size else '-'} |"
f" {extract_paths.get(display, '')} |"
f" {download_links(name, record, 'Download', site=SITE_URL)} |"
)
-9
View File
@@ -662,15 +662,6 @@ def emulator_link(name: str, prefix: str = "") -> str:
"""Generate a markdown link to an emulator page."""
return f"[{name}]({prefix}emulators/{name}.md)"
def fmt_size(size: int) -> str:
if size >= 1024 * 1024 * 1024:
return f"{size / (1024**3):.1f} GB"
if size >= 1024 * 1024:
return f"{size / (1024**2):.1f} MB"
if size >= 1024:
return f"{size / 1024:.1f} KB"
return f"{size} B"
def percent_text(n: int, total: int) -> str:
if total == 0:
return "0%"
+2 -2
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
from model import releaserecord
from core.paths import REPO_ROOT
from core.sizes import size_text
from core.ziptools import build_zip_contents_index
from model import siteinputs
from model.guides import (
@@ -26,7 +27,6 @@ from sitegen.guides import fence, terminal_tabs, trust_box
from sitegen.home import group_keys, next_block, runs_on_text, setup_picker
from sitegen.install import installer_module, has_release_pack
from sitegen.readme import NO_PACK, download_links
from sitegen.render import fmt_size
# Build cross-reference indexes
@@ -86,7 +86,7 @@ def _pack_cell(name: str, record: dict, prefix: str = "") -> str:
link = download_links(name, record, "ZIP", page=get_page_link(name, prefix),
button=lambda text, url: markup.button(text, url))
size = pack.get("download_size") if pack else None
return f"{link} ({fmt_size(size)})" if size else link
return f"{link} ({size_text(size)})" if size else link
def _own_root_folders(registry: dict) -> dict[str, str]:
+3 -2
View File
@@ -797,13 +797,14 @@ class PublishedNumbersShareOneFormat(unittest.TestCase):
the site home as 15.6 GB, and the emulators page `10095 files`."""
def test_generators_format_counts_and_sizes_alike(self):
from core.sizes import size_text
from sitegen import readme as sitegen_readme
readme_source = inspect.getsource(sitegen_readme.generate_readme)
self.assertNotIn("size_mb", readme_source)
self.assertIn("format_size(size)", readme_source)
self.assertIn("size_text(size)", readme_source)
self.assertIn("{total_files:,}", script_source("generate_site.py"))
self.assertEqual(sitegen_readme.format_size(16011 * 1024 * 1024), "15.6 GB")
self.assertEqual(size_text(16011 * 1024 * 1024), "15.6 GB")
def test_the_readme_has_no_bare_large_count(self):
readme = (ROOT / "README.md").read_text(encoding="utf-8")
+3 -3
View File
@@ -18,6 +18,7 @@ import unittest
from functools import cache
from pathlib import Path
from core.sizes import size_text
from model import releaserecord
from sitegen.readme import (
SITE_URL,
@@ -25,7 +26,6 @@ from sitegen.readme import (
contributing_text,
download_links,
download_table,
format_size,
)
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -380,8 +380,8 @@ class SizesComeFromTheRecord(unittest.TestCase):
if tag != RECORD.get("tag"):
self.skipTest(f"release.json records {RECORD.get('tag')}, not {tag}")
pack = releaserecord.pack_for(platform.lower(), RECORD)
self.assertEqual(download, format_size(pack["download_size"]))
self.assertEqual(extracted, format_size(pack["extracted_size"]))
self.assertEqual(download, size_text(pack["download_size"]))
self.assertEqual(extracted, size_text(pack["extracted_size"]))
class ContributorChecksMatchCi(unittest.TestCase):
+2 -1
View File
@@ -23,6 +23,7 @@ from unittest import mock
from installer_build import port
from model.registry import list_registered_platforms
from core.sizes import size_text
from sitegen import handheld as sitehandheld
from installer_build import handhelds
@@ -91,7 +92,7 @@ class TheSiteServesTheLaunchers(unittest.TestCase):
self.assertTrue((public / target).is_file(), target)
block = text.split(f'href="handheld/{name}"', 1)[1].split("\n\n", 2)[1]
self.assertIn(f"SHA-256: `{digest}`", block)
self.assertIn(sitehandheld._size(len(data)), block)
self.assertIn(size_text(len(data)), block)
self.assertRegex(block, r"- (Copy it to|Unzip it into) .+\.")
self.assertRegex(block, r"- Start it from .+\.")