refactor: place every file through Placed

data_directory_members, pack_data_tree and manifest_core_entries take
the Placed record instead of three loose sets and a fold flag, and verify's
replay of the builder (_builder_placement), hidden_extras and the
emulator pack check keep a Placed of their own. hidden_extras records the
sha1 at each taken path through the new Placed content option, which keeps
its same-content case twin rule. No behavior change.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 20:03:26 +01:00
1 parent 899f591575
commit ca3ff1d4c5
15 files changed
+62 -97

No files matched your search

+15 -2
View File
@@ -140,19 +140,32 @@ PACK_DOCUMENTS = ("README.txt", "manifest.json")
class Placed:
"""The destinations a build has taken, and the folders they open.
``fold`` is whether a case twin of a taken path counts as taken.
``fold`` is whether a case twin of a taken path counts as taken. The
builder, the manifest, verify's replay of the builder and the data
tree walk all place files through this one record.
``content``, when given, records the sha1 of what each taken path holds,
keyed by its lowercased destination: a case twin carrying the same
bytes serves the core on a filesystem that folds the names.
"""
fold: bool
destinations: set[str] = field(default_factory=set)
lower: set[str] = field(default_factory=set) # only used when fold=True
parents: set[str] = field(default_factory=set) # parent dirs of added files (path conflict detection)
content: dict[str, str | None] | None = None
def take(self, dest: str) -> None:
def take(self, dest: str, sha1: str | None = None) -> None:
self.destinations.add(dest)
register_path(dest, self.destinations, self.parents)
if self.fold:
self.lower.add(dest.lower())
if self.content is not None:
self.content[dest.lower()] = sha1
def content_at(self, dest: str) -> str | None:
"""The sha1 recorded for the path a destination folds onto."""
return (self.content or {}).get(dest.lower())
def holds(self, dest: str) -> bool:
return dest in self.destinations or (self.fold and dest.lower() in self.lower)
+4 -11
View File
@@ -156,25 +156,18 @@ def _builder_placement(
path -> copy or None for each slot kept, a user_provided or external one
included).
"""
from packs.paths import has_path_conflict, register_path
from packs.archive import Placed
shipped: dict[str, str] = {}
occupied: dict[str, str | None] = {}
seen: set[str] = set()
folded: set[str] = set()
parents: set[str] = set()
placed = Placed(case_insensitive)
for _sys_id, full, local in sorted(packed_order, key=lambda item: item[0]):
# EmuDeck's system:md5 entries name no file: the builder writes none.
if not full or full.endswith("/"):
continue
if (
full in occupied
or (case_insensitive and full.lower() in folded)
or has_path_conflict(full, seen, parents)
):
if placed.block(full):
continue
register_path(full, seen, parents)
folded.add(full.lower())
placed.take(full)
occupied[full] = local
if local is not None:
shipped[full] = local
+8 -22
View File
@@ -15,10 +15,10 @@ from core.options import reject_unknown
from model.declarations import declared_root
from model.profiles import entry_system_ids, installed_data_refs
from model.systems import norm_system_id
from packs.archive import PackRecord, add_pack_member
from packs.archive import PackRecord, Placed, add_pack_member
from packs.datadirs import cache_lock, revisioned
from packs.extras import prefixed_destination
from packs.paths import MEDIA_MARKER, has_path_conflict, register_path, lands_on_android
from packs.paths import MEDIA_MARKER, lands_on_android
from resolve.cores import resolve_platform_cores as _platform_cores
from resolve.layout import core_system_dirs
from resolve.standalone import platform_layouts, standalone_set
@@ -182,10 +182,7 @@ def data_directory_members(
data_registry: dict | None,
platform_name: str,
base_dest: str,
case_insensitive: bool,
seen_destinations: set,
seen_lower: set,
seen_parents: set,
placed: Placed,
**options: Unpack[_TreeWalkOptions],
) -> Iterator[tuple[str, str]]:
"""Yield (source, destination) for the cached data directories a
@@ -232,15 +229,10 @@ def data_directory_members(
os.path.normpath(reclaim[full]) == os.path.normpath(src)
):
del reclaim[full]
elif full in seen_destinations or (
full.lower() in seen_lower and case_insensitive
) or has_path_conflict(full, seen_destinations, seen_parents):
elif placed.block(full):
continue
else:
seen_destinations.add(full)
register_path(full, seen_destinations, seen_parents)
if case_insensitive:
seen_lower.add(full.lower())
placed.take(full)
if refs_out is not None:
refs_out[full] = (ref_key, systems, dd_prefix, needed)
yield src, full
@@ -250,9 +242,7 @@ def pack_data_tree(
zf: zipfile.ZipFile | PackRecord,
local_cache: str,
dd_dest: str,
seen_destinations: set[str],
seen_parents: set[str],
seen_lower: set[str],
placed: Placed,
packed_at: dict[str, str] | None = None,
) -> int:
"""Write one data directory into an emulator pack, under its shared lock.
@@ -269,13 +259,9 @@ def pack_data_tree(
src = os.path.join(root, fname)
rel = os.path.relpath(src, local_cache)
full = f"{dd_dest}/{rel}" if dd_dest else rel
if full.lower() in seen_lower or has_path_conflict(
full, seen_destinations, seen_parents
):
if placed.block(full):
continue
seen_destinations.add(full)
register_path(full, seen_destinations, seen_parents)
seen_lower.add(full.lower())
placed.take(full)
add_pack_member(zf, src, full)
if packed_at is not None:
packed_at[full.lower()] = src
+4 -10
View File
@@ -20,6 +20,7 @@ from model.profiles import (
select_emulator_profiles,
)
from model.registry import load_data_dir_registry
from packs.archive import Placed
from packs.verdicts import (
RELEASE_ASSET_PENDING,
Severity,
@@ -211,8 +212,7 @@ class _EmulatorPack:
# Archives and data trees take paths too, before and after the loose
# files of their profile, as the pack writes them.
placed: dict[str, tuple[str | None, str, str]] = field(default_factory=dict)
placed_files: set[str] = field(default_factory=set)
placed_parents: set[str] = field(default_factory=set)
taken: Placed = field(default_factory=lambda: Placed(True))
content_ids: dict[str, str | None] = field(default_factory=dict)
def __post_init__(self) -> None:
@@ -242,19 +242,13 @@ class _EmulatorPack:
return self.content_ids[path]
def block(self, dest: str) -> str | None:
from packs.paths import placement_block
return placement_block(
dest, self.placed_files, set(self.placed), self.placed_parents, True
)
return self.taken.block(dest)
def occupy(self, dest: str, path: str | None, owner: str) -> None:
from packs.paths import register_path
if self.block(dest):
return
self.placed[dest.lower()] = (path, owner, dest)
register_path(dest, self.placed_files, self.placed_parents)
self.taken.take(dest)
def occupy_trees(self, emu_name: str, profile: dict) -> None:
"""The profile's data trees follow its files in the pack, which
+2 -3
View File
@@ -190,7 +190,7 @@ class _EmulatorPackBuild:
data_dir_registry=self.data_registry,
offline=self.offline,
)
taken = archive_dest.lower() in self.placed.lower
taken = self.placed.holds(archive_dest)
if taken or self.placed.conflicts(archive_dest):
# Another profile's file holds this path. The same archive
# asked for twice is served. Anything else leaves this
@@ -402,8 +402,7 @@ class _EmulatorPackBuild:
if prefix:
dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix
self.data_files += pack_data_tree(
self.zf, local_cache, dd_dest, self.placed.destinations,
self.placed.parents, self.placed.lower, self.packed_at,
self.zf, local_cache, dd_dest, self.placed, self.packed_at,
)
def nothing_needed(self) -> bool:
+6 -14
View File
@@ -405,7 +405,7 @@ def hidden_extras(
``required_only`` are the builder's for a --source truth or a
--required-only pack: an optional extra is skipped before it takes a path.
"""
from packs.paths import register_path, placement_block
from packs.archive import Placed
reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__)
report = options.get("report")
@@ -419,14 +419,9 @@ def hidden_extras(
entry.get("path"): sha1 for sha1, entry in db.get("files", {}).items()
}
base_dest = config.get("base_destination", "")
case_insensitive = bool(config.get("case_insensitive_fs", False))
seen: set[str] = set()
parents: set[str] = set()
content: dict[str, str | None] = {}
taken = Placed(bool(config.get("case_insensitive_fs", False)), content={})
for dest, local in shipped.items():
register_path(dest, seen, parents)
content[dest.lower()] = sha1_by_path.get(local)
lower = set(content) if case_insensitive else set()
taken.take(dest, sha1_by_path.get(local))
prefix = detect_extras_prefix(config, base_dest)
region_prefix = declared_root(config)
hidden: dict[tuple[str, str, str], str] = {}
@@ -451,7 +446,7 @@ def hidden_extras(
full = extra_full_destination(fe, prefix)
if not full:
continue
reason = placement_block(full, seen, lower, parents, case_insensitive)
reason = taken.block(full)
if reason == "taken":
# Another core's claim on the same path, settled by the claims
# the collector records: not a file left out.
@@ -465,7 +460,7 @@ def hidden_extras(
fe, db, dest_hint=fe.get("destination", "")
)
held = (sha1_by_path.get(local) or _file_sha1(local)) if local else None
if reason == "case_twin" and held and content.get(full.lower()) == held:
if reason == "case_twin" and held and taken.content_at(full) == held:
continue
key = (
fe.get("source_emulator", ""), fe.get("source_name", ""),
@@ -475,10 +470,7 @@ def hidden_extras(
hidden.setdefault(key, reason)
continue
packed_keys.add(key)
register_path(full, seen, parents)
content[full.lower()] = held
if case_insensitive:
lower.add(full.lower())
taken.take(full, held)
if local:
_record_placed(full, local, fe, placed, placed_kind, placed_local)
# A file read below a save directory kept per system is packed once per
+3 -5
View File
@@ -422,9 +422,8 @@ class _ManifestBuild:
self.total_size += manifest_core_entries(
core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root,
self.zip_contents, opts.offline,
region_drops=self.region_drops, case_insensitive=self.case_insensitive,
seen_destinations=self.placed.destinations, seen_lower=self.placed.lower,
seen_parents=self.placed.parents, manifest_files=self.manifest_files,
region_drops=self.region_drops, placed=self.placed,
manifest_files=self.manifest_files,
omitted_by_destination=self.omitted_by_destination,
record_omission=self.record_omission, pack_only_sizes=self.pack_only_sizes,
selection=self.fields, required_only=opts.required_only,
@@ -473,8 +472,7 @@ class _ManifestBuild:
self.data_registry, opts.target_cores))
self.data_members = list(data_directory_members(
self.pack_systems, self.data_registry, self.platform_name, self.base_dest,
self.case_insensitive, self.placed.destinations, self.placed.lower,
self.placed.parents, refs_out=data_refs, required_only=required_only,
self.placed, refs_out=data_refs, required_only=required_only,
core_trees=core_trees,
reclaim=reclaim,
))
+6 -19
View File
@@ -31,7 +31,7 @@ from packs.manifestentry import (
manifest_entry,
)
from packs.manifestselect import SelectionIndex
from packs.paths import register_path, placement_block
from packs.archive import Placed
from packs.platformpack import one_per_slot_drops
from resolve import regions as resolve_regions, slot as slot_mod
from resolve.contentlayout import TARGET_KEY, core_key, content_folder_boards
@@ -51,10 +51,7 @@ class _CoreEntryState(TypedDict):
"""What manifest_core_entries reads and fills of the manifest being listed."""
region_drops: set
case_insensitive: bool
seen_destinations: set
seen_lower: set
seen_parents: set
placed: Placed
manifest_files: list
omitted_by_destination: dict
record_omission: Callable[..., None]
@@ -106,18 +103,11 @@ class _CoreEntryLister:
if not full_dest:
return
if (
state["case_insensitive"]
and full_dest not in state["seen_destinations"]
and full_dest.lower() in state["seen_lower"]
):
block = state["placed"].block(full_dest)
if block == "case_twin":
self._join_spelling(fe, full_dest, dest)
return
if placement_block(
full_dest, state["seen_destinations"], state["seen_lower"], state["seen_parents"],
state["case_insensitive"],
):
if block:
return
# The builder's own lookup (ExtraResolver): the data directories, the
@@ -211,10 +201,7 @@ class _CoreEntryLister:
{k: v for k, v in displaced.items() if k not in ("dest", "held")}
)
self.total_size += file_size
state["seen_destinations"].add(full_dest)
register_path(full_dest, state["seen_destinations"], state["seen_parents"])
if state["case_insensitive"]:
state["seen_lower"].add(full_dest.lower())
state["placed"].take(full_dest)
def manifest_core_entries(
+1 -3
View File
@@ -951,12 +951,10 @@ class _PlatformPackBuild:
"""Add the data directories to the pack. Returns how many files went in."""
plan = self.plan
required_only = plan.opts.required_only
seen_parents = self.placed.parents
added = 0
for src, full in data_directory_members(
pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest,
self.placed.fold, self.placed.destinations, self.placed.lower,
seen_parents, required_only=required_only,
self.placed, required_only=required_only,
core_trees=core_trees,
):
add_pack_member(self.zf, src, self._flat(full))
+2 -1
View File
@@ -459,6 +459,7 @@ def _tree_members(
from packs import datatrees
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.archive import Placed
from packs.paths import flat_arcname
config = load_platform_config(platform, platforms_dir)
@@ -471,7 +472,7 @@ def _tree_members(
with contextlib.redirect_stdout(io.StringIO()):
for src, full in datatrees.data_directory_members(
config.get("systems", {}), registry,
platform, base_dest, False, set(), set(), set(),
platform, base_dest, Placed(False),
core_trees=core_trees,
):
members[flat_arcname(full, base_dest, True)] = os.path.getsize(src)
+2 -1
View File
@@ -7109,6 +7109,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
def _members(self, required_only: bool) -> list[str]:
from scripts.packs import datatrees
from scripts.packs.archive import Placed
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp:
for key in ("needed", "optional"):
@@ -7129,7 +7130,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
return [
dest
for _src, dest in datatrees.data_directory_members(
systems, registry, "retroarch", "", False, set(), set(), set(),
systems, registry, "retroarch", "", Placed(False),
required_only=required_only,
)
]
+1 -1
View File
@@ -177,7 +177,7 @@ class AmberelecCarriesTheMachines(unittest.TestCase):
members = dict(
(full, src) for src, full in datatrees.data_directory_members(
config.get("systems", {}), registry, "amberelec",
config.get("base_destination", ""), False, set(), set(), set(),
config.get("base_destination", ""), archive.Placed(False),
refs_out=refs, core_trees=trees,
)
)
+3 -1
View File
@@ -42,9 +42,11 @@ class OneRule(unittest.TestCase):
)
def test_builder_and_report_read_it(self):
self.assertIn("placement_block(", script_source("packs/archive.py"))
for module in ("generate_pack.py", "packs/extras.py"):
source = script_source(module)
self.assertIn("placement_block(", source, module)
self.assertIn("Placed(", source, module)
self.assertIn(".block(", source, module)
builder = script_source("generate_pack.py")
self.assertNotIn("if full_dest.lower() in seen_lower and case_insensitive", builder)
+2 -2
View File
@@ -19,6 +19,7 @@ from pathlib import Path
from unittest import mock
from packs import manifestcores
from packs.archive import Placed
from packs import manifestentry
from packs.manifestselect import SelectionIndex
@@ -69,8 +70,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase):
manifestcores.manifest_core_entries(
[extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT),
{}, True,
region_drops=set(), case_insensitive=False, seen_destinations=set(),
seen_lower=set(), seen_parents=set(), manifest_files=files,
region_drops=set(), placed=Placed(False), manifest_files=files,
omitted_by_destination={}, record_omission=record,
pack_only_sizes=pack_only, selection=SelectionIndex.build({}, {}, {}, []),
)
+3 -2
View File
@@ -23,6 +23,7 @@ from unittest import mock
import refresh_data_dirs as rdd
from packs import datadirs
from model.registry import load_versions
from packs.archive import Placed
from packs.datatrees import data_directory_members
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -203,7 +204,7 @@ class PackWalkHoldsTheCache(unittest.TestCase):
(cache / "b.mkf").write_bytes(b"b")
systems = {"s": {"data_directories": [{"ref": "sdlpal", "destination": "sdlpal"}]}}
registry = {"sdlpal": {"local_cache": str(cache)}}
walk = data_directory_members(systems, registry, "p", "", False, set(), set(), set())
walk = data_directory_members(systems, registry, "p", "", Placed(False))
next(walk)
with open(cache.with_name(".sdlpal.lock"), "a") as handle, self.assertRaises(
BlockingIOError
@@ -237,7 +238,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase):
held.append(False)
with mock.patch("packs.datatrees.add_pack_member", member):
pack_data_tree(None, str(cache), "scummvm", set(), set(), set())
pack_data_tree(None, str(cache), "scummvm", Placed(True))
self.assertEqual(held, [True])