diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 3b190c066..02d9c59f9 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -335,16 +335,16 @@ def _region_rank() -> ColumnElement: """ # Imported here because handler.filesystem and handler.metadata import each # other, and reaching filesystem first from this module trips the cycle. - from handler.filesystem.base_handler import region_names_for_priority + from handler.filesystem.base_handler import region_ranks_for_priority - priority_regions = region_names_for_priority(cm.get_config().SCAN_REGION_PRIORITY) - if not priority_regions: + ranks = region_ranks_for_priority(cm.get_config().SCAN_REGION_PRIORITY) + if not ranks: return literal(0) return case( - {region: index for index, region in enumerate(priority_regions)}, + ranks, value=Rom.generated_primary_region, - else_=len(priority_regions), + else_=max(ranks.values()) + 1, ) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index fea4e4f04..701f42051 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -159,19 +159,27 @@ for _name, _code in REGION_NAME_TO_PROVIDER_SHORTCODE.items(): _REGION_NAMES_BY_PROVIDER_SHORTCODE.setdefault(_code, []).append(_name) -def region_names_for_priority(shortcodes: Sequence[str]) -> list[str]: - """Expand a provider-shortcode priority list into canonical region names. +def region_ranks_for_priority(shortcodes: Sequence[str]) -> dict[str, int]: + """Map canonical region names to their rank in a shortcode priority list. + + The rank is the shortcode's position, not the name's, so two names claiming + one shortcode ("nl" for both Holland and Netherlands) rank equally and fall + through to whatever tiebreak follows. A shortcode naming no known region (ScreenScraper's "ss", or a typo the open-ended settings input allowed) contributes nothing rather than shifting - the ranks of everything after it. + the ranks of everything after it. Nor does a repeated shortcode. """ - names: list[str] = [] - for shortcode in shortcodes: - for name in _REGION_NAMES_BY_PROVIDER_SHORTCODE.get(shortcode.lower(), ()): - if name not in names: - names.append(name) - return names + ranks: dict[str, int] = {} + next_rank = 0 + for shortcode in dict.fromkeys(code.lower() for code in shortcodes): + names = _REGION_NAMES_BY_PROVIDER_SHORTCODE.get(shortcode) + if not names: + continue + for name in names: + ranks[name] = next_rank + next_rank += 1 + return ranks LANGUAGES_BY_SHORTCODE = {lang[0]: lang[1] for lang in LANGUAGES} diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index 41ca38bd0..ac212638a 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -10,7 +10,7 @@ import pytest from fastapi import UploadFile from config.config_manager import DEFAULT_EXCLUDED_FILES -from handler.filesystem.base_handler import FSHandler +from handler.filesystem.base_handler import FSHandler, region_ranks_for_priority from models.base import FILE_NAME_MAX_LENGTH @@ -605,3 +605,35 @@ class TestFSHandlerInit: ): with pytest.raises(PermissionError): FSHandler("/some/unwritable/path") + + +class TestRegionRanksForPriority: + """Ranking is per configured shortcode, not per expanded region name.""" + + def test_two_names_sharing_a_shortcode_rank_equally(self): + ranks = region_ranks_for_priority(["nl", "jp"]) + + assert ranks["Holland"] == ranks["Netherlands"] + # And the next shortcode still ranks strictly below them. + assert ranks["Japan"] > ranks["Netherlands"] + + def test_unknown_shortcode_does_not_shift_later_ranks(self): + # "ss" is a ScreenScraper bucket, not a region. + assert region_ranks_for_priority(["us", "ss", "jp"]) == { + "USA": 0, + "Japan": 1, + } + + def test_repeated_shortcode_does_not_shift_later_ranks(self): + assert region_ranks_for_priority(["us", "us", "jp"]) == { + "USA": 0, + "Japan": 1, + } + + def test_ranks_follow_the_configured_order(self): + ranks = region_ranks_for_priority(["jp", "us"]) + + assert ranks["Japan"] < ranks["USA"] + + def test_empty_priority_yields_no_ranks(self): + assert region_ranks_for_priority([]) == {} diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index 326787d31..99cada660 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -1,4 +1,6 @@ from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import patch import pytest from sqlalchemy.exc import IntegrityError @@ -493,6 +495,26 @@ def test_group_by_meta_id_ranks_region_below_release_status(platform: Platform): assert _grouped_names(platform) == ["Sonic (Japan)"] +def test_group_by_meta_id_ties_names_sharing_a_region_shortcode( + platform: Platform, +): + """Holland and Netherlands both configure as "nl", so neither outranks the + other and the filename tiebreak decides. + + The filenames deliberately sort opposite to the order the reverse shortcode + map emits those two names in, so ranking them separately picks the Holland + rom and ranking them equally picks the alphabetically first one. + """ + _add_sibling(platform, "(NL-a)", 5678, ["Netherlands"]) + _add_sibling(platform, "(NL-b)", 5678, ["Holland"]) + + with patch( + "handler.database.roms_handler.cm.get_config", + return_value=SimpleNamespace(SCAN_REGION_PRIORITY=["nl"]), + ): + assert _grouped_names(platform) == ["Sonic (NL-a)"] + + def test_group_by_meta_id_keeps_a_prerelease_only_group(platform: Platform): """A game that exists only as a pre-release still gets a gallery entry.""" name = "Unreleased Game (Proto)"