mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-28 12:28:51 -06:00
fix: place hashless files by their own system
The wanted list puts firmware first, then game data, labels each row, and leaves out what no one can share (the profile's reason: user written, emulator written, per person). validate_pr.placement() takes a file known by name alone to its system's folder or the directory it declares, never beside a homonym held for another system.
This commit is contained in:
1 parent
3fd61df038
commit
b3a5109955
6 files changed
+386
-67
No files matched your search
+113
-31
@@ -127,27 +127,62 @@ def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) ->
|
||||
return named
|
||||
|
||||
|
||||
def _directory(entry: dict) -> str:
|
||||
"""The directory a declaration names for its file: a platform's
|
||||
destination, a profile's path. Empty for a bare name."""
|
||||
where = str(entry.get("destination") or entry.get("path") or "")
|
||||
return where.rsplit("/", 1)[0] + "/" if "/" in where else ""
|
||||
|
||||
|
||||
def _paired(files: list, details: list[dict]) -> Iterable[tuple[dict, dict]]:
|
||||
"""Each verify detail of a system with the declaration it scores.
|
||||
|
||||
verify scores the declarations of a system in order, one detail each,
|
||||
so the k-th detail of a name is the k-th declaration of that name:
|
||||
AmberELEC declares config.ini once per blueMSX machine, and a match by
|
||||
name alone gave each missing one every machine's folder.
|
||||
"""
|
||||
by_name: dict[str, list[dict]] = {}
|
||||
for entry in files:
|
||||
if isinstance(entry, dict):
|
||||
by_name.setdefault(str(entry.get("name")), []).append(entry)
|
||||
seen: dict[str, int] = {}
|
||||
for detail in details:
|
||||
name = str(detail.get("name"))
|
||||
position = seen.get(name, 0)
|
||||
seen[name] = position + 1
|
||||
same = by_name.get(name, [])
|
||||
if position < len(same):
|
||||
yield detail, same[position]
|
||||
|
||||
|
||||
def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> list[dict]:
|
||||
"""Every declaration of a file the gaps page reports as lacking.
|
||||
|
||||
Each is {name, system, required, reader: (kind, key, label), entry,
|
||||
reason}, the reason a file not collected yet carries, empty otherwise.
|
||||
reason, category, directory}: the reason a file not collected yet
|
||||
carries, empty otherwise, and game_data or bios as verify (a
|
||||
platform's entry) or the profile (an emulator's) gives it.
|
||||
"""
|
||||
found: list[dict] = []
|
||||
for key, coverage in sorted(coverages.items()):
|
||||
systems = coverage.get("config", {}).get("systems") or {}
|
||||
by_system: dict[str, list[dict]] = {}
|
||||
for detail in coverage.get("details", []):
|
||||
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
|
||||
continue
|
||||
system = detail.get("system", "")
|
||||
for entry in (systems.get(system) or {}).get("files") or []:
|
||||
if isinstance(entry, dict) and entry.get("name") == detail.get("name"):
|
||||
found.append({
|
||||
"name": str(entry["name"]), "system": system,
|
||||
"required": bool(detail.get("required", True)),
|
||||
"reader": ("platform", key, coverage["platform"]), "entry": entry,
|
||||
"reason": "",
|
||||
})
|
||||
by_system.setdefault(detail.get("system", ""), []).append(detail)
|
||||
for system, details in sorted(by_system.items()):
|
||||
files = (systems.get(system) or {}).get("files") or []
|
||||
for detail, entry in _paired(files, details):
|
||||
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
|
||||
continue
|
||||
found.append({
|
||||
"name": str(entry["name"]), "system": system,
|
||||
"required": bool(detail.get("required", True)),
|
||||
"reader": ("platform", key, coverage["platform"]), "entry": entry,
|
||||
"reason": "",
|
||||
"category": GAME_DATA if detail.get("category") == GAME_DATA else BIOS,
|
||||
"directory": _directory(entry),
|
||||
})
|
||||
unique = unique_emulator_profiles(profiles)
|
||||
for key, data in sorted(gap_report.items()):
|
||||
profile = unique.get(key)
|
||||
@@ -166,6 +201,8 @@ def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> li
|
||||
"required": bool(row.get("required", False)),
|
||||
"reader": ("emulator", key, str(data.get("emulator", key))), "entry": entry,
|
||||
"reason": str(row.get("reason") or "") if unsourceable else "",
|
||||
"category": GAME_DATA if entry.get("category") == GAME_DATA else BIOS,
|
||||
"directory": _directory(entry),
|
||||
})
|
||||
return found
|
||||
|
||||
@@ -186,9 +223,37 @@ def catalog_listings(report: dict | None, labels: dict[str, str]) -> dict[tuple[
|
||||
return out
|
||||
|
||||
|
||||
BIOS = "bios"
|
||||
GAME_DATA = "game_data"
|
||||
# A name the code builds from the content (<serial>.txt, *.ini) is a
|
||||
# pattern, not a file anyone can upload.
|
||||
PATTERN = re.compile(r"[<>*?]")
|
||||
# A file not collected yet stays wanted, however hard it is to find ("no
|
||||
# public dump located", "retail data the collection does not hold"). It
|
||||
# leaves the list only when its reason (the profile's `unsourceable:`)
|
||||
# says no copy can be shared, read by the rules below.
|
||||
NOT_SHAREABLE = re.compile("|".join([
|
||||
# Any file of the name serves: there is no one file to collect.
|
||||
r"\bno canonical\b",
|
||||
# The user writes, picks, records or places it (WHDLoad's key aside,
|
||||
# emucorev's config.txt: "plugin list the user writes").
|
||||
r"\bthe user\b|\buser[- ](?:supplied|authored|created|settings|overlay|placeholder)\b"
|
||||
r"|\bother users\b",
|
||||
# The emulator or the guest writes it: a save, a state, a generated key.
|
||||
r"\bwritten by (?:the (?:emulator|guest|firmware editor)|bam)\b|\bgenerated by the emulator\b"
|
||||
r"|\bwith the debug key\b|\bmachine state\b|\bcreat\w* (?:this directory )?empty\b",
|
||||
# It belongs to one person, one account or one copy (puae's WHDLoad.key).
|
||||
r"\bper[- ]user\b|\btied to the (?:account|tag)\b|\bnever distributed generically\b"
|
||||
r"|\bissued for one copy\b",
|
||||
# Nothing was ever released under the name.
|
||||
r"\bno (?:distributed form|released artefact|hardware dump equivalent)\b"
|
||||
r"|\bno file of this name is distributed\b",
|
||||
]), re.I)
|
||||
|
||||
|
||||
def shareable(reason: str) -> bool:
|
||||
"""False when a reason says no copy of the file can be shared."""
|
||||
return not NOT_SHAREABLE.search(reason)
|
||||
# What a row says the file is: the first sentence of the declaration's
|
||||
# description or note, cut at a word past this many characters.
|
||||
DESCRIPTION_LIMIT = 160
|
||||
@@ -249,17 +314,22 @@ class Placer:
|
||||
for path in [record.get("path"), *(record.get("paths") or [])] if path
|
||||
}
|
||||
|
||||
def place(self, hashes: dict[str, list[str]], name: str) -> Placement:
|
||||
def place(self, hashes: dict[str, list[str]], name: str, systems: Iterable[str] = (),
|
||||
directory: str = "") -> Placement:
|
||||
"""A declaration that writes no hash is known by its name alone,
|
||||
as the review knows a file whose hashes nothing declares."""
|
||||
as the review knows a file whose hashes nothing declares, and its
|
||||
folder comes from its systems and its declared directory."""
|
||||
values = [value for algo in ("sha1", "md5", "sha256") for value in hashes.get(algo, [])
|
||||
if len(value) == FULL_LENGTH[algo]]
|
||||
return placement(values, name, self.db, self.platform_hashes, self.profile_hashes,
|
||||
declared=bool(hashes), exists=self.paths.__contains__)
|
||||
declared=bool(hashes), exists=self.paths.__contains__,
|
||||
systems=sorted(systems), directory=directory)
|
||||
|
||||
def folder(self, entry: dict) -> str:
|
||||
def folder(self, entry: dict, system: str = "") -> str:
|
||||
"""The folder an upload of a profile or platform entry goes to."""
|
||||
return self.place(declared_hashes(entry), str(entry.get("name", ""))).folder
|
||||
system = str(entry.get("system") or system)
|
||||
return self.place(declared_hashes(entry), str(entry.get("name", "")),
|
||||
[system] if system else [], _directory(entry)).folder
|
||||
|
||||
|
||||
FULL_LENGTH = {"sha1": 40, "md5": 32, "sha256": 64}
|
||||
@@ -272,10 +342,11 @@ def upload_href(root: str, folder: str) -> str:
|
||||
|
||||
|
||||
def _order(record: dict) -> tuple:
|
||||
"""Most useful first: required before optional, then by how many
|
||||
setups and emulators read the file."""
|
||||
return (not record["required"], -len(record["readers"]), record["name"].casefold(),
|
||||
sorted(record["readers"]))
|
||||
"""Most useful first: required firmware, optional firmware, then game
|
||||
data, required first, and within each by how many setups and
|
||||
emulators read the file."""
|
||||
return (record["category"] != BIOS, not record["required"], -len(record["readers"]),
|
||||
record["name"].casefold(), sorted(record["readers"]))
|
||||
|
||||
|
||||
def build_wanted(
|
||||
@@ -293,15 +364,17 @@ def build_wanted(
|
||||
Readers, systems and folders are written once and named by position.
|
||||
An entry: n name, h hashes (absent when the declarations write none:
|
||||
the file is known by its name only), w readers, s systems, r required,
|
||||
z sizes, d what the file is, u why it is not collected yet, l the
|
||||
catalogs that list it with the name they give it, f folder, t the name
|
||||
it is uploaded under, v that name goes to the folder's .variants/ with
|
||||
the first 8 characters of its sha1. Entries come most useful first.
|
||||
z sizes, g game data (firmware when absent), d what the file is, u why
|
||||
it is not collected yet, l the catalogs that list it with the name
|
||||
they give it, f folder, t the name it is uploaded under, v that name
|
||||
goes to the folder's .variants/ with the first 8 characters of its
|
||||
sha1. Entries come most useful first. A file no one can share (the
|
||||
reason says so, NOT_SHAREABLE) is left out.
|
||||
"""
|
||||
held = Held(db, ledger)
|
||||
records: dict[tuple, dict] = {}
|
||||
for declaration in wanted_declarations(profiles, coverages, gap_report):
|
||||
if PATTERN.search(declaration["name"]):
|
||||
if PATTERN.search(declaration["name"]) or not shareable(declaration["reason"]):
|
||||
continue
|
||||
entry = declaration["entry"]
|
||||
sizes = _sizes(entry)
|
||||
@@ -310,12 +383,16 @@ def build_wanted(
|
||||
continue
|
||||
key = ((declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
|
||||
tuple(sizes)) if hashes
|
||||
else (declaration["name"].casefold(), declaration["system"]))
|
||||
else (declaration["name"].casefold(), declaration["system"],
|
||||
declaration["directory"]))
|
||||
record = records.setdefault(key, {
|
||||
"name": declaration["name"], "hashes": {a: list(v) for a, v in hashes.items()},
|
||||
"sizes": sizes, "systems": set(), "required": False, "readers": set(),
|
||||
"description": "", "reason": "", "listed": [],
|
||||
"description": "", "reason": "", "listed": [], "category": GAME_DATA,
|
||||
"directory": declaration["directory"],
|
||||
})
|
||||
if declaration["category"] == BIOS:
|
||||
record["category"] = BIOS
|
||||
if declaration["system"]:
|
||||
record["systems"].add(declaration["system"])
|
||||
record["required"] = record["required"] or declaration["required"]
|
||||
@@ -341,7 +418,8 @@ def build_wanted(
|
||||
folder_at: dict[str, int] = {}
|
||||
entries = []
|
||||
for record in ordered:
|
||||
spot = placer.place(record["hashes"], record["name"])
|
||||
spot = placer.place(record["hashes"], record["name"], record["systems"],
|
||||
record["directory"])
|
||||
if spot.folder and spot.folder not in folder_at:
|
||||
folder_at[spot.folder] = len(folders)
|
||||
folders.append(spot.folder)
|
||||
@@ -356,6 +434,8 @@ def build_wanted(
|
||||
item["r"] = 1
|
||||
if record["sizes"]:
|
||||
item["z"] = record["sizes"]
|
||||
if record["category"] == GAME_DATA:
|
||||
item["g"] = 1
|
||||
for field, value in (("d", record["description"]), ("u", record["reason"])):
|
||||
if value:
|
||||
item[field] = value
|
||||
@@ -389,7 +469,7 @@ def _merge_named(records: dict[tuple, dict]) -> None:
|
||||
for system in record["systems"] or {""}:
|
||||
hashed.setdefault((record["name"].casefold(), system), []).append(record)
|
||||
for key in [k for k, record in records.items() if not record["hashes"]]:
|
||||
targets = hashed.get(key, [])
|
||||
targets = hashed.get(key[:2], [])
|
||||
if len(targets) != 1:
|
||||
continue
|
||||
record = records.pop(key)
|
||||
@@ -398,6 +478,8 @@ def _merge_named(records: dict[tuple, dict]) -> None:
|
||||
target["required"] = target["required"] or record["required"]
|
||||
target["description"] = target["description"] or record["description"]
|
||||
target["reason"] = target["reason"] or record["reason"]
|
||||
if record["category"] == BIOS:
|
||||
target["category"] = BIOS
|
||||
target["listed"] += [w for w in record["listed"] if w not in target["listed"]]
|
||||
|
||||
|
||||
@@ -451,7 +533,7 @@ def page(total: int, known: int) -> str:
|
||||
"",
|
||||
"## The wanted list",
|
||||
"",
|
||||
(f"The list holds {total:,} files, most useful first. Of these, {known:,} have a "
|
||||
(f"The list holds {total:,} files, firmware first, then game data. Of these, {known:,} have a "
|
||||
"fingerprint (a hash), so a dropped copy is recognised."),
|
||||
"",
|
||||
"The others are known by name only: upload one and the check decides.",
|
||||
|
||||
+120
-16
@@ -182,7 +182,8 @@ def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
|
||||
under, read from the other files of that system it holds.
|
||||
"""
|
||||
known = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(),
|
||||
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}}
|
||||
"names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {},
|
||||
"name_systems": {}, "system_dirs": {}, "system_folders": {}}
|
||||
systems_of: dict[str, set[str]] = {}
|
||||
folders_of: dict[str, dict[str, int]] = {}
|
||||
files = (db or {}).get("files", {})
|
||||
@@ -227,32 +228,49 @@ def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict:
|
||||
known["entries"].setdefault(file_entry["name"].lower(), []).append(
|
||||
(file_entry, mode, rule, name)
|
||||
)
|
||||
known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id)
|
||||
for value in (*sha1s, *md5s):
|
||||
systems_of.setdefault(value, set()).add(system_id)
|
||||
for value in (*sha1s, *md5s, *sha256s):
|
||||
if "name" in file_entry:
|
||||
known["named"].setdefault(value, set()).add(file_entry["name"])
|
||||
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s)
|
||||
_note_folder(folders_of, system_id, files, by_md5, sha1s, md5s,
|
||||
known["system_dirs"])
|
||||
|
||||
known["folders"] = _system_homes(systems_of, folders_of)
|
||||
known["system_folders"] = _single_maker_folders(folders_of)
|
||||
return known
|
||||
|
||||
|
||||
def _note_folder(
|
||||
folders_of: dict[str, dict[str, int]], system_id: str, files: dict,
|
||||
by_md5: dict, sha1s: list[str], md5s: list[str],
|
||||
dirs_of: dict[str, set[str]] | None = None,
|
||||
) -> None:
|
||||
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in."""
|
||||
"""Count the bios/<Manufacturer>/<Console>/ folder a held file sits in,
|
||||
and note the directory it sits in under *dirs_of*."""
|
||||
held = next((s for s in sha1s if s in files), None) or next(
|
||||
(by_md5[m] for m in md5s if m in by_md5), None
|
||||
)
|
||||
parts = str(files.get(held, {}).get("path", "")).split("/")
|
||||
path = str(files.get(held, {}).get("path", ""))
|
||||
if dirs_of is not None and "/" in path and "/.variants/" not in path:
|
||||
dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/")
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."):
|
||||
folder = "/".join(parts[:3]) + "/"
|
||||
counts = folders_of.setdefault(system_id, {})
|
||||
counts[folder] = counts.get(folder, 0) + 1
|
||||
|
||||
|
||||
def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]:
|
||||
"""System id to the folders the collection files it under, for a system
|
||||
filed under one manufacturer only, the rule _system_homes applies."""
|
||||
return {
|
||||
system_id: set(held_in) for system_id, held_in in folders_of.items()
|
||||
if len({folder.split("/")[1] for folder in held_in}) == 1
|
||||
}
|
||||
|
||||
|
||||
def _system_homes(
|
||||
systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]]
|
||||
) -> dict[str, set[str]]:
|
||||
@@ -289,7 +307,7 @@ def load_profile_hashes(
|
||||
"""
|
||||
known: dict[str, dict] = {
|
||||
"sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {},
|
||||
"named": {},
|
||||
"named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {},
|
||||
}
|
||||
systems_of: dict[str, set[str]] = {}
|
||||
folders_of: dict[str, dict[str, int]] = {}
|
||||
@@ -322,10 +340,14 @@ def load_profile_hashes(
|
||||
if isinstance(system, str):
|
||||
for value in (v for values in hashes.values() for v in values):
|
||||
systems_of.setdefault(value, set()).add(system)
|
||||
for n in names:
|
||||
if isinstance(n, str):
|
||||
known["name_systems"].setdefault(n.lower(), set()).add(system)
|
||||
sha1s = [*hashes["sha1"], *(
|
||||
by_sha256[v] for v in hashes["sha256"] if v in by_sha256
|
||||
)]
|
||||
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"])
|
||||
_note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"],
|
||||
known["system_dirs"])
|
||||
if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")):
|
||||
size = entry.get("size")
|
||||
sizes = [int(v) for v in size] if isinstance(size, list) else (
|
||||
@@ -336,6 +358,7 @@ def load_profile_hashes(
|
||||
key = (value.zfill(8), accepted)
|
||||
known["crc32"].setdefault(key, set()).add(emulator)
|
||||
known["folders"] = _system_homes(systems_of, folders_of)
|
||||
known["system_folders"] = _single_maker_folders(folders_of)
|
||||
return known
|
||||
|
||||
|
||||
@@ -618,13 +641,23 @@ def validate_file(
|
||||
|
||||
if (name_known and not (sha1_known or md5_known or other_known or accepted_by)
|
||||
and not by_profile and size_fits):
|
||||
home = _variant_home(db, result.filename)
|
||||
owners = name_systems(result.filename, platform_hashes, profile_hashes)
|
||||
home = _variant_home(db, result.filename, "", set() if len(owners) > 1 else {
|
||||
d for table in (platform_hashes, profile_hashes or {}) for s in owners
|
||||
for d in table.get("system_dirs", {}).get(s, ())
|
||||
} if owners else None)
|
||||
if not home and normalized.startswith("bios" + os.sep):
|
||||
# Beside the file, in the folder the contributor chose.
|
||||
home = os.path.dirname(normalized).replace(os.sep, "/") + "/"
|
||||
slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}"
|
||||
if home and not normalized.startswith("bios" + os.sep):
|
||||
result.destination = slot
|
||||
result.add_info(
|
||||
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
|
||||
)
|
||||
if home:
|
||||
result.add_info(
|
||||
f"This may be a valid variant. If accepted, it will be placed in `{slot}`"
|
||||
)
|
||||
else:
|
||||
result.add_info("This may be a valid variant of a file the collection lacks")
|
||||
|
||||
return result
|
||||
|
||||
@@ -708,6 +741,8 @@ def placement(
|
||||
profile_hashes: dict | None,
|
||||
declared: bool,
|
||||
exists: Callable[[str], bool] = os.path.exists,
|
||||
systems: Iterable[str] = (),
|
||||
directory: str = "",
|
||||
) -> Placement:
|
||||
"""Where a file goes, by its hashes and its name.
|
||||
|
||||
@@ -715,6 +750,15 @@ def placement(
|
||||
folder a contributor is sent to is the folder the review accepts.
|
||||
*declared* says a list or a profile declares one of the hashes: a file
|
||||
known by its name alone gets a slot only once its size fits.
|
||||
|
||||
Without a folder from its hashes, the folder comes from its system:
|
||||
*systems*, or every system that declares the name (several of them
|
||||
name no copy to sit beside). A file of that name held elsewhere is a
|
||||
homonym and says nothing: AmberELEC's MSX config.ini
|
||||
was sent beside msx.emu's ColecoVision config.ini. A declared
|
||||
*directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a
|
||||
copy by name counts only in a directory of that tail, and a held
|
||||
directory of that tail is the folder.
|
||||
"""
|
||||
values = [value for value in values if value]
|
||||
folders = expected_folders(values, platform_hashes, profile_hashes)
|
||||
@@ -730,26 +774,86 @@ def placement(
|
||||
return Placement(tuple(folders), name=name, variant=exists(folders[0] + name))
|
||||
return Placement(tuple(folders))
|
||||
held = next((value for value in values if value in (db or {}).get("files", {})), "")
|
||||
home = _variant_home(db, filename, held)
|
||||
owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes)
|
||||
tables = (platform_hashes, profile_hashes or {})
|
||||
# A name several systems declare does not say which one a file is:
|
||||
# a copy held for one of them is no answer.
|
||||
within = set() if not systems and len(owners) > 1 else {
|
||||
d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ())
|
||||
}
|
||||
tail = _directory_tail(db, directory)
|
||||
if tail:
|
||||
within = {d for d in within if d.endswith("/" + tail) or d == tail} if owners else None
|
||||
home = _variant_home(db, filename, held, within if owners or tail else None)
|
||||
if declared and home and filename and "/" not in filename:
|
||||
# The folder holds a file of that name already.
|
||||
return Placement(home=home, name=filename, variant=True)
|
||||
return Placement(home=home)
|
||||
if home:
|
||||
return Placement(home=home)
|
||||
if tail:
|
||||
return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail))
|
||||
homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())}
|
||||
return Placement(tuple(sorted(homes)))
|
||||
|
||||
|
||||
def _variant_home(db: dict | None, name: str, held: str = "") -> str:
|
||||
_HELD_DIRECTORIES: dict[int, frozenset[str]] = {}
|
||||
|
||||
|
||||
def _held_directories(db: dict | None) -> frozenset[str]:
|
||||
"""Every directory a file of the database sits in, .variants/ aside."""
|
||||
key = id(db)
|
||||
if key not in _HELD_DIRECTORIES:
|
||||
_HELD_DIRECTORIES[key] = frozenset(
|
||||
path.rsplit("/", 1)[0] + "/"
|
||||
for record in (db or {}).get("files", {}).values()
|
||||
for path in [record.get("path"), *(record.get("paths") or [])]
|
||||
if path and "/" in path and "/.variants/" not in path
|
||||
)
|
||||
return _HELD_DIRECTORIES[key]
|
||||
|
||||
|
||||
def _directory_tail(db: dict | None, directory: str) -> str:
|
||||
"""The longest tail of a declared directory, two segments at least,
|
||||
that exactly one held directory ends with, empty when none does."""
|
||||
parts = [p for p in directory.strip("/").split("/") if p]
|
||||
held = _held_directories(db)
|
||||
for size in range(len(parts), 1, -1):
|
||||
tail = "/".join(parts[-size:]) + "/"
|
||||
found = [d for d in held if d.endswith("/" + tail) or d == tail]
|
||||
if len(found) == 1:
|
||||
return tail
|
||||
if found:
|
||||
return ""
|
||||
return ""
|
||||
|
||||
|
||||
def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]:
|
||||
"""The systems whose platform or profile entries declare this name."""
|
||||
return {
|
||||
system for table in (platform_hashes, profile_hashes or {})
|
||||
for system in table.get("name_systems", {}).get(filename.lower(), ())
|
||||
}
|
||||
|
||||
|
||||
def _variant_home(db: dict | None, name: str, held: str = "",
|
||||
within: set[str] | None = None) -> str:
|
||||
"""The folder the collection keeps a name in, for its variants beside it.
|
||||
|
||||
The folder of an identical copy comes first: adam_fdc.zip, held in
|
||||
bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder
|
||||
the name index gave.
|
||||
the name index gave. A copy found by name alone counts only in a
|
||||
directory of *within*, those the file's own systems are held in, when
|
||||
the systems are known.
|
||||
"""
|
||||
files = (db or {}).get("files", {})
|
||||
by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, [])
|
||||
for sha1 in ([held] if held in files else []) + list(by_name):
|
||||
copies = [(held, True)] if held in files else []
|
||||
for sha1, identical in copies + [(sha1, False) for sha1 in by_name]:
|
||||
path = str(files.get(sha1, {}).get("path", ""))
|
||||
folder = path.rsplit("/", 1)[0] + "/" if "/" in path else ""
|
||||
if folder and "/.variants" not in "/" + folder:
|
||||
if not folder or "/.variants" in "/" + folder:
|
||||
continue
|
||||
if identical or within is None or folder in within:
|
||||
return folder
|
||||
return ""
|
||||
|
||||
|
||||
Reference in new issue
Block a user