Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46f364ea8b | ||
|
|
bb5f29ff0c | ||
|
|
5c47fe57e0 | ||
|
|
7222207f3b | ||
|
|
2b5955e8a5 | ||
|
|
bbb139bbaf | ||
|
|
11e3ebb44f | ||
|
|
665e2ebb52 | ||
|
|
571c4bbfd9 | ||
|
|
6e0b0724de | ||
|
|
f0ab5181ab | ||
|
|
4adb8ea635 | ||
|
|
6f3500d8c8 | ||
|
|
cdf0aa6774 | ||
|
|
c07a47362e | ||
|
|
1f9633c7e5 | ||
|
|
f462ec5fa0 | ||
|
|
0530c007a8 | ||
|
|
b070d1a41a | ||
|
|
0f3fe1932f | ||
|
|
1839916ca2 | ||
|
|
e36516f3b0 | ||
|
|
3df143cbe1 | ||
|
|
e0cbf35adc | ||
|
|
0617598e21 | ||
|
|
e0339e2f20 | ||
|
|
2f9cfc8e8d | ||
|
|
d1b0c77039 | ||
|
|
3df7a60e43 | ||
|
|
29fb089a2b | ||
|
|
3779f07bb5 | ||
|
|
e8704a793e | ||
|
|
c68a63b7ca | ||
|
|
1b597ae510 | ||
|
|
8d9495a478 | ||
|
|
0d82c50a63 | ||
|
|
8fc294ef97 | ||
|
|
0b0bf29089 | ||
|
|
c888ae8101 | ||
|
|
eba627aa89 | ||
|
|
ced68a9135 | ||
|
|
80f42f0573 | ||
|
|
475dfe0e0a | ||
|
|
05b6b9edcf | ||
|
|
eec4ff9972 | ||
|
|
6c92b0172e | ||
|
|
9814bb1234 | ||
|
|
cf7e13808f | ||
|
|
66c83b06b0 | ||
|
|
4835c59508 | ||
|
|
472b06a3e0 | ||
|
|
eddb26f104 | ||
|
|
91e385598e | ||
|
|
dae6b3a146 | ||
|
|
6721a738b4 | ||
|
|
01f8408038 | ||
|
|
9a6003c22f | ||
|
|
416299b6e0 | ||
|
|
9521dd040a | ||
|
|
380b3df823 | ||
|
|
ff3b2699bd | ||
|
|
5a931ad4b1 | ||
|
|
1b7d30967b | ||
|
|
398782a5cd | ||
|
|
bc48d4028a | ||
|
|
184f84effd | ||
|
|
1593dfa85a | ||
|
|
5bfc9953e2 | ||
|
|
61a4e909bd | ||
|
|
1e6f106525 | ||
|
|
5436a45d4a | ||
|
|
4cb82adce3 | ||
|
|
36d5827b25 | ||
|
|
0e2be04f9c | ||
|
|
49dbb2828d | ||
|
|
a30984912c | ||
|
|
8ec1c3aa2f | ||
|
|
3869a24b6a | ||
|
|
75ccaf460c | ||
|
|
35ad46e8c5 | ||
|
|
3b16ee2633 | ||
|
|
3e55385410 | ||
|
|
b018681f06 | ||
|
|
745ab63e63 | ||
|
|
69d29e786a | ||
|
|
8787f453c7 | ||
|
|
57ee0cdd8f | ||
|
|
714683d63c | ||
|
|
2025a71cb9 | ||
|
|
beefb32cc8 | ||
|
|
8780398518 | ||
|
|
6aca93231a | ||
|
|
ef7884500e | ||
|
|
83f7693ccb | ||
|
|
8a9591dad2 | ||
|
|
93d45b6241 | ||
|
|
bce9abedc7 | ||
|
|
0fdca4145a | ||
|
|
b6599375f5 | ||
|
|
12b00e024b | ||
|
|
24463647f6 | ||
|
|
e6295aba88 | ||
|
|
14cc76132f | ||
|
|
c3054bef4c | ||
|
|
e0f4d7eba5 | ||
|
|
19681a3735 | ||
|
|
6d21a98342 | ||
|
|
4630946656 | ||
|
|
48d88da168 | ||
|
|
cff440613d | ||
|
|
f8c317b63f | ||
|
|
b520e48798 | ||
|
|
8afccc3d0f | ||
|
|
2123bd8317 | ||
|
|
fd1c2e1c16 | ||
|
|
37ec04aed1 | ||
|
|
ac06822d2e | ||
|
|
7623e49981 | ||
|
|
4e9dbd6fa9 | ||
|
|
770a25dcf4 | ||
|
|
b6e1f1b3c0 | ||
|
|
64c7d25bdc | ||
|
|
00443c1c57 | ||
|
|
7aa93f4ad4 | ||
|
|
54bd4f2c1e | ||
|
|
cf20111eef | ||
|
|
6e1852211d | ||
|
|
9cb1e613b0 | ||
|
|
2a49bf237b | ||
|
|
d87993129a | ||
|
|
d6a0b33521 | ||
|
|
d36a5d4bc5 | ||
|
|
1ff9ba1ba9 | ||
|
|
506a40c88a | ||
|
|
d4dfa18c9e | ||
|
|
61547d08b3 | ||
|
|
f158f1d485 | ||
|
|
0b91bc9e37 | ||
|
|
2428d92e6a | ||
|
|
75a69a4a42 | ||
|
|
22a81c384d | ||
|
|
ccb78ef5d9 | ||
|
|
75aef7e001 | ||
|
|
f61d6a187f | ||
|
|
e24c5b6900 | ||
|
|
676d0a5d9a | ||
|
|
c17d0e0cec | ||
|
|
e521f4af4f | ||
|
|
cadca657a3 | ||
|
|
2486c06932 | ||
|
|
2f428a01a8 | ||
|
|
1ca8a775c1 | ||
|
|
b28973440e | ||
|
|
6ba52a9682 | ||
|
|
1e95a73a4d | ||
|
|
a1b8a10cf9 | ||
|
|
c58f3e624e | ||
|
|
d0ce43eb90 | ||
|
|
a60ec786b6 | ||
|
|
d413fb263b | ||
|
|
7f19ff2ceb | ||
|
|
f77caa1885 | ||
|
|
a0579c687e | ||
|
|
198515f1cb | ||
|
|
056e12a14c | ||
|
|
1978d371ee | ||
|
|
ed6ae84d2c | ||
|
|
9de949dfdb | ||
|
|
7ff8b5faf6 | ||
|
|
985d07b97e | ||
|
|
5be72484d8 | ||
|
|
7203b5be84 | ||
|
|
88e39b6380 | ||
|
|
8a2ef047ab | ||
|
|
5fa802a3c5 | ||
|
|
1227152bef | ||
|
|
84bad2e271 | ||
|
|
8303c133ab |
No files matched your search
@@ -12,6 +12,7 @@ on:
|
||||
# Every script the build runs or imports, and no other
|
||||
# (tests/test_workflow_paths.py).
|
||||
- "scripts/acquire/provenance.py"
|
||||
- "scripts/check_platform_folder.py"
|
||||
- "scripts/core/__init__.py"
|
||||
- "scripts/core/anchors.py"
|
||||
- "scripts/core/artifacts.py"
|
||||
@@ -54,6 +55,7 @@ on:
|
||||
- "scripts/model/measurements.py"
|
||||
- "scripts/model/nodedup.py"
|
||||
- "scripts/model/platforms.py"
|
||||
- "scripts/model/profilerepos.py"
|
||||
- "scripts/model/profiles.py"
|
||||
- "scripts/model/profilekinds.py"
|
||||
- "scripts/model/region.py"
|
||||
@@ -69,6 +71,7 @@ on:
|
||||
- "scripts/model/systemnames.py"
|
||||
- "scripts/model/systems.py"
|
||||
- "scripts/model/targets.py"
|
||||
- "scripts/orchestrate/labels.py"
|
||||
- "scripts/packs/__init__.py"
|
||||
- "scripts/packs/archive.py"
|
||||
- "scripts/packs/coverage.py"
|
||||
@@ -112,6 +115,21 @@ on:
|
||||
- "scripts/romrecipes/__init__.py"
|
||||
- "scripts/romrecipes/ledger.py"
|
||||
- "scripts/romrecipes/romsets.py"
|
||||
- "scripts/schemas/citations.py"
|
||||
- "scripts/schemas/documents.py"
|
||||
- "scripts/schemas/events.py"
|
||||
- "scripts/schemas/games.py"
|
||||
- "scripts/schemas/installs.py"
|
||||
- "scripts/schemas/measurements.py"
|
||||
- "scripts/schemas/packmanifests.py"
|
||||
- "scripts/schemas/platformchecks.py"
|
||||
- "scripts/schemas/profilechecks.py"
|
||||
- "scripts/schemas/registry.py"
|
||||
- "scripts/schemas/romfolders.py"
|
||||
- "scripts/schemas/run.py"
|
||||
- "scripts/schemas/sources.py"
|
||||
- "scripts/schemas/sourcetree.py"
|
||||
- "scripts/schemas/validators.py"
|
||||
- "scripts/site_markdown.py"
|
||||
- "scripts/sitegen/__init__.py"
|
||||
- "scripts/sitegen/agents.py"
|
||||
@@ -121,10 +139,12 @@ on:
|
||||
- "scripts/sitegen/cards.py"
|
||||
- "scripts/sitegen/config.py"
|
||||
- "scripts/sitegen/consolecards.py"
|
||||
- "scripts/sitegen/coverage.py"
|
||||
- "scripts/sitegen/crossref.py"
|
||||
- "scripts/sitegen/dataexports.py"
|
||||
- "scripts/sitegen/datapage.py"
|
||||
- "scripts/sitegen/decorate.py"
|
||||
- "scripts/sitegen/demovariants.py"
|
||||
- "scripts/sitegen/descriptions.py"
|
||||
- "scripts/sitegen/diagrams.py"
|
||||
- "scripts/sitegen/emulatorcards.py"
|
||||
@@ -132,6 +152,7 @@ on:
|
||||
- "scripts/sitegen/emulatorsindex.py"
|
||||
- "scripts/sitegen/entries.py"
|
||||
- "scripts/sitegen/exports.py"
|
||||
- "scripts/sitegen/extraction.py"
|
||||
- "scripts/sitegen/fields.py"
|
||||
- "scripts/sitegen/gaps.py"
|
||||
- "scripts/sitegen/getpages.py"
|
||||
@@ -139,6 +160,7 @@ on:
|
||||
- "scripts/sitegen/guides.py"
|
||||
- "scripts/sitegen/handheld.py"
|
||||
- "scripts/sitegen/home.py"
|
||||
- "scripts/sitegen/indexnow.py"
|
||||
- "scripts/sitegen/install.py"
|
||||
- "scripts/sitegen/lookup.py"
|
||||
- "scripts/sitegen/markup.py"
|
||||
@@ -154,6 +176,7 @@ on:
|
||||
- "scripts/sitegen/publish.py"
|
||||
- "scripts/sitegen/readme.py"
|
||||
- "scripts/sitegen/reference.py"
|
||||
- "scripts/sitegen/releasepacks.py"
|
||||
- "scripts/sitegen/render.py"
|
||||
- "scripts/sitegen/sources.py"
|
||||
- "scripts/sitegen/starlight.py"
|
||||
|
||||
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 62 KiB |
@@ -29,4 +29,11 @@ notes: |
|
||||
ref: src/adapters/libretro/libretro_entry.c:330-345, src/adapters/libretro/libretro_entry.c:418-421,
|
||||
src/api/anygm.h:318-326, src/content/container/content_router.c:2027-2050
|
||||
|
||||
exclusion_note: >
|
||||
The system directory is asked for, and the only file read from it is
|
||||
AnyGM.ini, written by the user and optional. Saves and the extraction cache
|
||||
go under it only when the frontend names no save directory. Nothing in it
|
||||
is a file to obtain (src/adapters/libretro/libretro_entry.c:330-351,
|
||||
src/content/container/content_router.c:2027-2052).
|
||||
|
||||
files: []
|
||||
@@ -49,4 +49,13 @@ notes: |
|
||||
#if !defined(M64P_PLUGIN_API), and the Makefile defines that macro.
|
||||
ref: custom/mupen64plus-rsp-cxd4/module.c:358-380, Makefile:378
|
||||
|
||||
exclusion_note: >
|
||||
The system directory is asked for, and everything read under its
|
||||
Mupen64plus/ folder is written by the core or by the user: mupen64plus.ini,
|
||||
rewritten from the compiled-in ROM database on every init, an optional
|
||||
GLideN64.custom.ini, and hi-res texture packs with the caches built from
|
||||
them. Nothing in it is a file to obtain (custom/mupen64plus-core/api/config.c:1288-1300,
|
||||
libretro/libretro.c:369-395, custom/GLideN64/mupenplus/Config_mupenplus.cpp:33-47,
|
||||
GLideN64/src/GLideNHQ/TxHiResCache.cpp:99-114).
|
||||
|
||||
files: []
|
||||
@@ -16,7 +16,7 @@
|
||||
# and Invoke-WebRequest throws on a cut transfer before the hash is read:
|
||||
# the site's build rewrites this line there (scripts/sitebootstrap.py).
|
||||
$mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
|
||||
$defaultInstallSha256 = "9a5c17126ec0a23a3733bfa94cf96d260b562552a0a1014116c4ff305e8a7b0b"
|
||||
$defaultInstallSha256 = "d245aefa5fc0b6ee54bccbaf2b5788c8c032aac4f7f25e9967328ed3dc7bd8e3"
|
||||
# The pin above refuses any changed byte: this cap only stops a body that
|
||||
# cannot be the installer (a sign-in portal's page) before it is hashed.
|
||||
$maximumInstallerBytes = 8MB
|
||||
|
||||
@@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins
|
||||
# curl or wget stop on a cut transfer before the hash is read: the site's
|
||||
# build rewrites this line there (scripts/sitebootstrap.py).
|
||||
MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
|
||||
DEFAULT_INSTALL_SHA256="9a5c17126ec0a23a3733bfa94cf96d260b562552a0a1014116c4ff305e8a7b0b"
|
||||
DEFAULT_INSTALL_SHA256="d245aefa5fc0b6ee54bccbaf2b5788c8c032aac4f7f25e9967328ed3dc7bd8e3"
|
||||
# The pin above refuses any changed byte: this cap only stops a body that
|
||||
# cannot be the installer (a sign-in portal's page) before it is hashed.
|
||||
MAX_INSTALLER_BYTES=8388608
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
{
|
||||
"dest": "roms/ports/retrobios/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1448904,
|
||||
"sha256": "9a5c17126ec0a23a3733bfa94cf96d260b562552a0a1014116c4ff305e8a7b0b",
|
||||
"size": 1470751,
|
||||
"sha256": "d245aefa5fc0b6ee54bccbaf2b5788c8c032aac4f7f25e9967328ed3dc7bd8e3",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
@@ -71,8 +71,8 @@
|
||||
"muos": {
|
||||
"archive": {
|
||||
"dest": "ARCHIVE/RetroBIOS.muxapp",
|
||||
"size": 1502529,
|
||||
"sha256": "f5e68d76e05ceb75c2603a3bf502a0dc2ddeecf9afa6a8be342c651529e238aa"
|
||||
"size": 1524376,
|
||||
"sha256": "71f1b4e07193fd40e74c7910597aa9f0c86ede64472fb6935e7b7dd73cb0079d"
|
||||
},
|
||||
"members": [
|
||||
{
|
||||
@@ -92,8 +92,8 @@
|
||||
{
|
||||
"name": "RetroBIOS/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1448904,
|
||||
"sha256": "9a5c17126ec0a23a3733bfa94cf96d260b562552a0a1014116c4ff305e8a7b0b",
|
||||
"size": 1470751,
|
||||
"sha256": "d245aefa5fc0b6ee54bccbaf2b5788c8c032aac4f7f25e9967328ed3dc7bd8e3",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
@@ -166,8 +166,8 @@
|
||||
{
|
||||
"dest": ".config/modules/retrobios/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1448904,
|
||||
"sha256": "9a5c17126ec0a23a3733bfa94cf96d260b562552a0a1014116c4ff305e8a7b0b",
|
||||
"size": 1470751,
|
||||
"sha256": "d245aefa5fc0b6ee54bccbaf2b5788c8c032aac4f7f25e9967328ed3dc7bd8e3",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"platform": "retrodeck",
|
||||
"display_name": "RetroDECK",
|
||||
"version": "0.10.10b",
|
||||
"generated": "2026-11-13T11:31:17Z",
|
||||
"generated": "2026-11-20T03:39:07Z",
|
||||
"base_destination": "",
|
||||
"detect": [
|
||||
{
|
||||
@@ -2365,10 +2365,10 @@
|
||||
}
|
||||
}
|
||||
],
|
||||
"total_files": 12197,
|
||||
"total_size": 10572282384,
|
||||
"pack_files": 16110,
|
||||
"pack_size": 10688969670,
|
||||
"total_files": 12216,
|
||||
"total_size": 10573616128,
|
||||
"pack_files": 16129,
|
||||
"pack_size": 10690303414,
|
||||
"total_omitted": 340,
|
||||
"omitted_files": [
|
||||
{
|
||||
@@ -7898,7 +7898,8 @@
|
||||
"pc8800"
|
||||
],
|
||||
"nec-pc-98": [
|
||||
"pc98"
|
||||
"pc98",
|
||||
"pc9800"
|
||||
],
|
||||
"nec-pc-engine": [
|
||||
"pcengine",
|
||||
@@ -14717,29 +14718,6 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/decocass.zip",
|
||||
"sha1": "5c5f300f3ab2bd10e2adf4dd96baa78317578d8d",
|
||||
"sha256": "fb7051f8864f10d5a1079bd63fe3ceab88cd8c394024b69fc773eb709bc3493a",
|
||||
"size": 13225,
|
||||
"repo_path": "bios/Arcade/Arcade/.variants/decocass.zip.5c5f300f",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"arcade"
|
||||
],
|
||||
"alternatives": [
|
||||
{
|
||||
"sha1": "1b33cf0e730a6cde96479b0face108b6931d433e",
|
||||
"sha256": "bd86d293abab2e816d307626cdd793e2da2ed69c4124bf92f7e7eca69f9a5096",
|
||||
"size": 22379,
|
||||
"repo_path": "bios/Arcade/Arcade/decocass.zip",
|
||||
"cores": [
|
||||
"fbalpha2019"
|
||||
]
|
||||
}
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/dectalk_isa.zip",
|
||||
"sha1": "c0c4ee9868d14ddf234a0639bd389f8a568931a7",
|
||||
@@ -23450,29 +23428,6 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/skns.zip",
|
||||
"sha1": "44bc8180dca3dfdf1b461268919da8efb2e3fb07",
|
||||
"sha256": "43e0385c53f004a8eb08a2075957b28a852883c29917ba88ecefc68c11753400",
|
||||
"size": 783788,
|
||||
"repo_path": "bios/Arcade/Arcade/.variants/skns.zip.44bc8180",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"arcade"
|
||||
],
|
||||
"alternatives": [
|
||||
{
|
||||
"sha1": "4257bd14b541fafbd555cb98ba079a3416a45934",
|
||||
"sha256": "6edf22c68e70be06c9b32741e0d1df1aa38cf6fc162c1027c15d6c1d882f621b",
|
||||
"size": 924762,
|
||||
"repo_path": "bios/Arcade/Arcade/skns.zip",
|
||||
"cores": [
|
||||
"fbalpha2019"
|
||||
]
|
||||
}
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/sms_diypaddle.zip",
|
||||
"sha1": "bc9f567b606b8e88cfd88564c8f02f832ea0016a",
|
||||
@@ -26427,6 +26382,51 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/decocass.zip",
|
||||
"sha1": "30b97b2670b79d0de41cba190324c504846c6fa1",
|
||||
"sha256": "ff29929e3e094459f6358a5a3ca4d2dabe64f64e2cade0faa407969d83e096bf",
|
||||
"size": 16107,
|
||||
"repo_path": "bios/Arcade/Arcade/.variants/decocass.zip.30b97b26",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"arcade"
|
||||
],
|
||||
"alternatives": [
|
||||
{
|
||||
"sha1": "1b33cf0e730a6cde96479b0face108b6931d433e",
|
||||
"sha256": "bd86d293abab2e816d307626cdd793e2da2ed69c4124bf92f7e7eca69f9a5096",
|
||||
"size": 22379,
|
||||
"repo_path": "bios/Arcade/Arcade/decocass.zip",
|
||||
"cores": [
|
||||
"fbalpha2019"
|
||||
]
|
||||
}
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/skns.zip",
|
||||
"sha1": "4257bd14b541fafbd555cb98ba079a3416a45934",
|
||||
"sha256": "6edf22c68e70be06c9b32741e0d1df1aa38cf6fc162c1027c15d6c1d882f621b",
|
||||
"size": 924762,
|
||||
"repo_path": "bios/Arcade/Arcade/skns.zip",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"arcade"
|
||||
],
|
||||
"alternatives": [
|
||||
{
|
||||
"sha1": "4257bd14b541fafbd555cb98ba079a3416a45934",
|
||||
"sha256": "6edf22c68e70be06c9b32741e0d1df1aa38cf6fc162c1027c15d6c1d882f621b",
|
||||
"size": 924762,
|
||||
"repo_path": "bios/Arcade/Arcade/skns.zip",
|
||||
"cores": [
|
||||
"fbalpha2019"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/coleco.zip",
|
||||
"sha1": "db2190922f359f19b47f8270fa87a7c1b38f5b2b",
|
||||
@@ -28843,7 +28843,28 @@
|
||||
"repo_path": "bios/Microsoft/MSX/DISK.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
"microsoft-msx",
|
||||
"nec-pc-88"
|
||||
],
|
||||
"declared_choices": [
|
||||
{
|
||||
"sha1": "032cb1c1c75b9a191fa1230978971698d9d2a17f",
|
||||
"sha256": "31740a761447d7590c304338d389b0ae114546a8b9f79c9ffd5e374f80b7d354",
|
||||
"size": 16384,
|
||||
"repo_path": "bios/Microsoft/MSX/DISK.ROM",
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"sha1": "bb7103a0818850a039c67ff666a31ce49a8d516f",
|
||||
"sha256": "9dc63118728a171ce2ed437ad38ef280b8b7bcf4a5a95fedf18946501b010456",
|
||||
"size": 2048,
|
||||
"repo_path": "bios/NEC/PC-88/N88SUB.ROM",
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
]
|
||||
}
|
||||
],
|
||||
"alternatives": [
|
||||
{
|
||||
@@ -29169,6 +29190,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/FMPAC.rom",
|
||||
"sha1": "9d789166e3caf28e4742fe933d962e99618c633d",
|
||||
"sha256": "3cfe44646b69a622656b96305f1b975f48ca018839f7946895f7a1352d9720aa",
|
||||
"size": 65536,
|
||||
"repo_path": "bios/Microsoft/MSX/FMPAC.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/GCVMX80.ROM",
|
||||
"sha1": "977fed1135b6cc73e765b47f51570fc00acd5b79",
|
||||
@@ -29193,6 +29226,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/KANJI.rom",
|
||||
"sha1": "5aff2d9b6efc723bc395b0f96f0adfa83cc54a49",
|
||||
"sha256": "d87ce758a7171870a2a3e7893e09cbba2bd68ee70b4d0f0e49dd2ecd60aafdd1",
|
||||
"size": 262144,
|
||||
"repo_path": "bios/Microsoft/MSX/openmsx/fs-a1wsx_kanjifont.rom",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MICROSOLDISK.ROM",
|
||||
"sha1": "f59d33311c95edc0168445f74eddd8a6772aa6a0",
|
||||
@@ -29265,6 +29310,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2EXT.rom",
|
||||
"sha1": "5c1f9c7fb655e43d38e5dd1fcc6b942b2ff68b02",
|
||||
"sha256": "6c6f421a10c428d960b7ecc990f99af1c638147f747bddca7b0bf0e2ab738300",
|
||||
"size": 16384,
|
||||
"repo_path": "bios/Microsoft/MSX/MSX2EXT.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2FREXT.rom",
|
||||
"sha1": "792e6b2814ab783d06c7576c1e3ccd6a9bbac34a",
|
||||
@@ -29373,6 +29430,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2PEXT.rom",
|
||||
"sha1": "fe0254cbfc11405b79e7c86c7769bd6322b04995",
|
||||
"sha256": "36000685128f95ff515a128973f8d439116c1a1a8e38c1777293a428894434a2",
|
||||
"size": 16384,
|
||||
"repo_path": "bios/Microsoft/MSX/MSX2PEXT.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2PMUS.rom",
|
||||
"sha1": "6354ccc5c100b1c558c9395fa8c00784d2e9b0a3",
|
||||
@@ -29385,6 +29454,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2P.rom",
|
||||
"sha1": "e90f80a61d94c617850c415e12ad70ac41e66bb7",
|
||||
"sha256": "ca45b50d49a8199a2b8f74300556367a776df1bb28bf8af24d33e65f0fe37a99",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/Other/msx-emu/Machines/Shared Roms/MSX2P.rom",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2R2.ROM",
|
||||
"sha1": "04990aa1c3a3fc7294ec884b81deaa89832df614",
|
||||
@@ -29409,6 +29490,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2.rom",
|
||||
"sha1": "6103b39f1e38d1aa2d84b1c3219c44f1abb5436e",
|
||||
"sha256": "4bc4ae85ca5f28246cd3e7b7e017d298ddd375603657f84ef2c7954bc2d9b919",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/Microsoft/MSX/MSX2.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX2R.rom",
|
||||
"sha1": "0f851ee7a1cf79819f61cc89e9948ee72a413802",
|
||||
@@ -29577,6 +29670,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSX.rom",
|
||||
"sha1": "e998f0c441f4f1800ef44e42cd1659150206cf79",
|
||||
"sha256": "1c85dac5536fa3ba6f2cb70deba02ff680b34ac6cc787d2977258bd663a99555",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/Microsoft/MSX/MSX_8020-20bios.rom",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/MSXR.rom",
|
||||
"sha1": "4f3114e96d7b892911e3dccf1eece712be26f396",
|
||||
@@ -29793,6 +29898,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/fmpac.rom",
|
||||
"sha1": "9d789166e3caf28e4742fe933d962e99618c633d",
|
||||
"sha256": "3cfe44646b69a622656b96305f1b975f48ca018839f7946895f7a1352d9720aa",
|
||||
"size": 65536,
|
||||
"repo_path": "bios/Microsoft/MSX/FMPAC.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/phc-70fd2_basickun.rom",
|
||||
"sha1": "22b3191d865010264001b9d896186a9818478a6b",
|
||||
@@ -30078,6 +30195,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88.ROM",
|
||||
"sha1": "3b31fc68fa7f47b21c1a1cb027b86b9e87afbfff",
|
||||
"sha256": "cf0b48f5541f5efd54a006d1a6042dd7ce613ccc69e13f2f41ca678569b5d650",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/NEC/PC-88/.variants/N88.ROM.3b31fc68",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88SUB.ROM",
|
||||
"sha1": "bb7103a0818850a039c67ff666a31ce49a8d516f",
|
||||
@@ -30090,6 +30219,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88N.ROM",
|
||||
"sha1": "5b922ed9de07d2a729bdf1da7b57c50ddf08809a",
|
||||
"sha256": "11c3c727d7d12d0c7e044dd02ce154a5715bd7a2b8a9007132645962c7803881",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/NEC/PC-88/.variants/N88N.ROM.5b922ed9",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N80.ROM",
|
||||
"sha1": "5b922ed9de07d2a729bdf1da7b57c50ddf08809a",
|
||||
@@ -30114,6 +30255,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88_0.ROM",
|
||||
"sha1": "d239c26ad7ac5efac6e947b0e9549b1534aa970d",
|
||||
"sha256": "290286a513c39af02581481958b8f1291c0ee8409b3940ae808352e0c3a2e2f8",
|
||||
"size": 8192,
|
||||
"repo_path": "bios/NEC/PC-88/N88EXT0.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88EXT1.ROM",
|
||||
"sha1": "8528eef7946edf6501a6ccb1f416b60c64efac7c",
|
||||
@@ -30126,6 +30279,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88_1.ROM",
|
||||
"sha1": "8528eef7946edf6501a6ccb1f416b60c64efac7c",
|
||||
"sha256": "bbb6283a0810eb4468909a364ccbc6d9cec51024aa0a2afa2e72a7af6d23049b",
|
||||
"size": 8192,
|
||||
"repo_path": "bios/NEC/PC-88/N88EXT1.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88EXT2.ROM",
|
||||
"sha1": "b7c8bcea219b77d9cc3ee0efafe343cc307425d1",
|
||||
@@ -30138,6 +30303,18 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88_2.ROM",
|
||||
"sha1": "b7c8bcea219b77d9cc3ee0efafe343cc307425d1",
|
||||
"sha256": "ad0f26064f44718eedd0103fde3d41bd29e60317680611e784dc9c1943e7574b",
|
||||
"size": 8192,
|
||||
"repo_path": "bios/NEC/PC-88/N88EXT2.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88EXT3.ROM",
|
||||
"sha1": "efce0b51cab9f0da6cf68507757f1245a2867a72",
|
||||
@@ -30150,6 +30327,30 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88_3.ROM",
|
||||
"sha1": "efce0b51cab9f0da6cf68507757f1245a2867a72",
|
||||
"sha256": "8580fecc6574b40a082aaf227afc3c1dbd06f333ba7549278ff73647b02b2303",
|
||||
"size": 8192,
|
||||
"repo_path": "bios/NEC/PC-88/N88EXT3.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/N88KNJ1.ROM",
|
||||
"sha1": "82e11a177af6a5091dd67f50a2f4bafda84d6556",
|
||||
"sha256": "7608040cffb1951e5cc567abb63f75b5746777a1ba96196c1b75606b793bb4bb",
|
||||
"size": 131072,
|
||||
"repo_path": "bios/NEC/PC-88/KANJI1.ROM",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/KANJI1.ROM",
|
||||
"sha1": "82e11a177af6a5091dd67f50a2f4bafda84d6556",
|
||||
@@ -30354,6 +30555,54 @@
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/font.rom",
|
||||
"sha1": "78ba9960f135372825ab7244b5e4e73a810002ff",
|
||||
"sha256": "8db165d567e13bce3f50ee495975671faa5a0ff332dcb08e187aa91125c81ec6",
|
||||
"size": 288768,
|
||||
"repo_path": "bios/NEC/PC-98/font.rom",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-98"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/BIOS.ROM",
|
||||
"sha1": "910fae6763c0cd59b3957b6cde479c72e21f33c1",
|
||||
"sha256": "2c2684d21ca44ab022d294a42709083ebe53f678e66b96c0ddd48f06aa5c869d",
|
||||
"size": 98304,
|
||||
"repo_path": "bios/NEC/PC-98/.variants/BIOS.ROM.910fae67",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-98"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/SOUND.ROM",
|
||||
"sha1": "34137c287c39c44300b04ee97c1e6459bb826b60",
|
||||
"sha256": "4db8274393f8267db83665bbb70be8efb83201818dff3ad76c11f451be96a803",
|
||||
"size": 16384,
|
||||
"repo_path": "bios/NEC/PC-98/.variants/SOUND.ROM.34137c28",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-98"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/ITF.ROM",
|
||||
"sha1": "9bca7d5116788776ed0f297bccb4dfc485379b41",
|
||||
"sha256": "2ca3ee3c7d5a6b6304a0205fec3cd7eaeb4e1e197e5db740cff0665006498076",
|
||||
"size": 32768,
|
||||
"repo_path": "bios/NEC/PC-98/.variants/ITF.ROM.9bca7d51",
|
||||
"cores": null,
|
||||
"systems": [
|
||||
"nec-pc-98"
|
||||
],
|
||||
"truth": false
|
||||
},
|
||||
{
|
||||
"dest": "bios/syscard3.pce",
|
||||
"sha1": "79f5ff55dd10187c7fd7b8daab0b3ffbd1f56a2c",
|
||||
@@ -120081,19 +120330,6 @@
|
||||
"microsoft-msx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/openmsx/share/systemroms/fmpac.rom",
|
||||
"sha1": "9d789166e3caf28e4742fe933d962e99618c633d",
|
||||
"sha256": "3cfe44646b69a622656b96305f1b975f48ca018839f7946895f7a1352d9720aa",
|
||||
"size": 65536,
|
||||
"repo_path": "bios/Microsoft/MSX/FMPAC.ROM",
|
||||
"cores": [
|
||||
"openmsx-libretro"
|
||||
],
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/openmsx/share/systemroms/novaxis.rom",
|
||||
"sha1": "352ec8c99fe1397a88ecb3aee6dbb4d121c818e9",
|
||||
@@ -138055,19 +138291,6 @@
|
||||
"nec-pc-88"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/quasi88/font.rom",
|
||||
"sha1": "84b90f69671d4b72e8f219e1fe7cd667e976cf7f",
|
||||
"sha256": "3227087599afd9304f260cdeb3bf1533e39e425cf444ceb3c24f55f561e71a0c",
|
||||
"size": 2048,
|
||||
"repo_path": "bios/NEC/PC-88/font.rom",
|
||||
"cores": [
|
||||
"quasi88"
|
||||
],
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/quasi88/font2.rom",
|
||||
"sha1": "0a056b6d28b4b9e29a2d255bdaa25c24f176cf1e",
|
||||
@@ -178565,6 +178788,19 @@
|
||||
"microsoft-msx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/openmsx/share/systemroms/fmpac.rom",
|
||||
"sha1": "9d789166e3caf28e4742fe933d962e99618c633d",
|
||||
"sha256": "3cfe44646b69a622656b96305f1b975f48ca018839f7946895f7a1352d9720aa",
|
||||
"size": 65536,
|
||||
"repo_path": "bios/Microsoft/MSX/FMPAC.ROM",
|
||||
"cores": [
|
||||
"openmsx-libretro"
|
||||
],
|
||||
"systems": [
|
||||
"microsoft-msx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/GBA/gba_bios.bin",
|
||||
"sha1": "300c20df6731a33952ded8c436f7f186d25d3492",
|
||||
@@ -178816,6 +179052,19 @@
|
||||
"nec-pc-88"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/quasi88/font.rom",
|
||||
"sha1": "84b90f69671d4b72e8f219e1fe7cd667e976cf7f",
|
||||
"sha256": "3227087599afd9304f260cdeb3bf1533e39e425cf444ceb3c24f55f561e71a0c",
|
||||
"size": 2048,
|
||||
"repo_path": "bios/NEC/PC-88/font.rom",
|
||||
"cores": [
|
||||
"quasi88"
|
||||
],
|
||||
"systems": [
|
||||
"nec-pc-88"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/flash.bin",
|
||||
"sha1": "94d44d7f9529ec1642ba3771ed3c5f756d5bc872",
|
||||
@@ -198301,20 +198550,6 @@
|
||||
"arcade"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/skns.zip",
|
||||
"sha1": "4257bd14b541fafbd555cb98ba079a3416a45934",
|
||||
"sha256": "6edf22c68e70be06c9b32741e0d1df1aa38cf6fc162c1027c15d6c1d882f621b",
|
||||
"size": 924762,
|
||||
"repo_path": "bios/Arcade/Arcade/skns.zip",
|
||||
"cores": [
|
||||
"fbneo",
|
||||
"fbalpha2019"
|
||||
],
|
||||
"systems": [
|
||||
"arcade"
|
||||
]
|
||||
},
|
||||
{
|
||||
"dest": "bios/ssio.zip",
|
||||
"sha1": "54275c9833e497f71f76ab239030cc386c863991",
|
||||
|
||||
@@ -6,7 +6,7 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
from installer.invocation import OFFLINE_VARIABLE, _INVOCATION, installer_id
|
||||
from installer.remote import INSTALLER_PAGE, RELEASE_REF
|
||||
from installer.remote import INSTALLER_PAGE, active_remote
|
||||
from installer.safe_replace import BACKUP_DIR
|
||||
from installer.text import format_size
|
||||
|
||||
@@ -373,7 +373,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument(
|
||||
"--version",
|
||||
action="version",
|
||||
version=f"retrobios installer {installer_id()} (ref {RELEASE_REF})",
|
||||
version=f"retrobios installer {installer_id()} (ref {active_remote().ref})",
|
||||
help="print the installer version and exit",
|
||||
)
|
||||
parser.add_argument(
|
||||
|
||||
@@ -464,6 +464,12 @@ def setup_bios_folder(plat: str, path: Path) -> Path:
|
||||
return path / "bios" if rule is not None and rule.manifest == plat else path
|
||||
|
||||
|
||||
def setup_folders(setups: list) -> dict:
|
||||
"""The BIOS folder each found setup announces, keyed by (platform,
|
||||
folder), read once for a screen that shows them on every frame."""
|
||||
return {(plat, path): setup_bios_folder(plat, path) for plat, path, *_rest in setups}
|
||||
|
||||
|
||||
def card_setup(named: str, plat: str) -> CardSetup | None:
|
||||
"""The card setup a name stands for with plat's list: a system by its
|
||||
own name, or a list that is one (MinUI). RetroArch names a list, not a
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Collection, Iterable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.console import detail
|
||||
from installer.install_record import drop_recorded
|
||||
from installer.lists import _pack_alone, fetch_standalone
|
||||
from installer.manifest import OTHER_SYSTEMS, entry_copies
|
||||
from installer.narrowing import _filter_by_target, designated_cores, narrow, narrow_to_cores, standalone_layout
|
||||
from installer.network import _pack_alone, fetch_standalone
|
||||
from installer.offline import LOCAL
|
||||
from installer.platforms import (
|
||||
SYSTEM_KEY_FILES,
|
||||
@@ -22,8 +21,9 @@ from installer.platforms import (
|
||||
key_file_holders,
|
||||
refuse_name,
|
||||
)
|
||||
from installer.refusal import Refusal
|
||||
from installer.regions import WORLD_REGION, resolve_regions
|
||||
from installer.remote import DEFAULT_RELEASE_REF, RELEASE_REF
|
||||
from installer.remote import DEFAULT_RELEASE_REF, active_remote
|
||||
from installer.text import _plural
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -173,6 +173,32 @@ def resolve_choices(
|
||||
return chosen
|
||||
|
||||
|
||||
def resolve_systems(values: list[str], manifest: dict | None, files: list[dict],
|
||||
omitted: list[dict]) -> list[str]:
|
||||
"""The systems --system names, for an install and a removal alike: the
|
||||
list's ids, the platform's own names and the site's titles. --remove
|
||||
took the ids alone, and refused the psx that installed the files."""
|
||||
return resolve_choices(values, available_choices(files, omitted)["systems"], "system",
|
||||
system_aliases(manifest), key_file_holders(files, omitted))
|
||||
|
||||
|
||||
def system_ids(names: Iterable[str], manifest: dict | None, files: list[dict],
|
||||
omitted: list[dict]) -> dict[str, str]:
|
||||
"""Each of names that --system takes, with the system id it stands for:
|
||||
a record keeps the psx typed at the install."""
|
||||
known = available_choices(files, omitted)["systems"]
|
||||
aliases, holders = system_aliases(manifest), key_file_holders(files, omitted)
|
||||
ids: dict[str, str] = {}
|
||||
for name in names:
|
||||
try:
|
||||
picked = resolve_choices([name], known, "system", aliases, holders)
|
||||
except ValueError:
|
||||
continue
|
||||
if len(picked) == 1:
|
||||
ids[name] = picked[0]
|
||||
return ids
|
||||
|
||||
|
||||
def parse_selection(text: str, count: int, ordered: bool = False) -> list[int]:
|
||||
"""Numbers typed at a prompt: `3`, `1,4`, `2-5`, or `all`, 1-based.
|
||||
|
||||
@@ -280,8 +306,9 @@ def _older_list_advice(plat: str = "") -> str:
|
||||
if _pack_alone(plat) and LOCAL.pack is not None:
|
||||
return (f" The list in {LOCAL.pack.name} does not record it: add --manifest FILE, "
|
||||
f"a copy of install/{plat or '<platform>'}.json, or run without the option.")
|
||||
if RELEASE_REF != DEFAULT_RELEASE_REF:
|
||||
return (f" RETROBIOS_REF={RELEASE_REF} selects file lists published before "
|
||||
ref = active_remote().ref
|
||||
if ref != DEFAULT_RELEASE_REF:
|
||||
return (f" RETROBIOS_REF={ref} selects file lists published before "
|
||||
"this option existed: unset RETROBIOS_REF to use the current ones, "
|
||||
"or run without the option.")
|
||||
return (" The file list comes from an older release: run the one-line "
|
||||
@@ -320,10 +347,9 @@ def _narrow_to_emulators(
|
||||
does not run is refused rather than read as nothing to install.
|
||||
"""
|
||||
if "system_cores" not in manifest:
|
||||
print(f"Error: the {plat} file list does not say which emulators read "
|
||||
"which systems, which --emulator needs.", file=sys.stderr)
|
||||
print(_older_list_advice(plat), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat,
|
||||
f"Error: the {plat} file list does not say which emulators read "
|
||||
"which systems, which --emulator needs.", _older_list_advice(plat))
|
||||
known = sorted(emulator_names(manifest, files, omitted))
|
||||
try:
|
||||
chosen = resolve_choices(names, known, "emulator")
|
||||
@@ -356,10 +382,9 @@ def _standalone_builds(
|
||||
place of the files its core reads. An emulator with no standalone
|
||||
build is refused, as `generate_pack.py --standalone` refuses it."""
|
||||
if "standalone_builds" not in manifest:
|
||||
print(f"Error: the {plat} file list does not say which emulators have a "
|
||||
"standalone build, which --standalone needs.", file=sys.stderr)
|
||||
print(_older_list_advice(plat), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat,
|
||||
f"Error: the {plat} file list does not say which emulators have a "
|
||||
"standalone build, which --standalone needs.", _older_list_advice(plat))
|
||||
profiles = sorted({names[name] for name in resolve_choices(values, sorted(names),
|
||||
"emulator")})
|
||||
lacking = [p for p in profiles if p not in manifest["standalone_builds"]]
|
||||
@@ -463,16 +488,12 @@ def _requested_narrowing(
|
||||
# lacks, with what works on it.
|
||||
source = (LOCAL.pack.name if pack_alone and LOCAL.pack is not None
|
||||
else f"the {plat} file list")
|
||||
print(f"Error: {source} records no {axis}, so {flag} cannot narrow it.",
|
||||
file=sys.stderr)
|
||||
print(_narrowing_advice(plat, axis, flag, recorded, pack_alone), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat,
|
||||
f"Error: {source} records no {axis}, so {flag} cannot narrow it.",
|
||||
_narrowing_advice(plat, axis, flag, recorded, pack_alone))
|
||||
choices = available_choices(files, omitted)
|
||||
try:
|
||||
systems = resolve_choices(
|
||||
args.system or [], choices["systems"], "system", system_aliases(manifest),
|
||||
key_file_holders(files, omitted),
|
||||
)
|
||||
systems = resolve_systems(args.system or [], manifest, files, omitted)
|
||||
cores = resolve_choices(args.core or [], choices["cores"], "core")
|
||||
regions = resolve_regions(args.region or [])
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -30,7 +30,9 @@ from installer.narrowing import FIND_KINDS
|
||||
from installer.network import _RAW_ERRORS, install_bounded_opener
|
||||
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE, offline_named
|
||||
from installer.platforms import AVAILABLE_PLATFORMS, TARGET_PLATFORMS, _name_key, display_name, refuse_name
|
||||
from installer.refusal import Refusal
|
||||
from installer.regions import resolve_regions
|
||||
from installer.remote import remote_from_env, remote_in_use
|
||||
from installer.removal import run_backups, run_delete_backup, run_removal
|
||||
from installer.run import _install
|
||||
from installer.tui_routes import TUI_LIST_ENV, TUI_RECORD_ENV, line_mode_reason, plain_requested, tui_blocker
|
||||
@@ -218,9 +220,10 @@ def _main_check_add_app(parser: argparse.ArgumentParser, args: argparse.Namespac
|
||||
|
||||
def _main_check_offline(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
|
||||
"""Record --offline, and refuse --target where no core list can be read."""
|
||||
if args.offline:
|
||||
if args.offline and not offline_requested():
|
||||
# The runs the full-screen interface starts read it from here, and
|
||||
# the words name the option given.
|
||||
# the words name the option given. A variable already set keeps its
|
||||
# value: dropping --offline alone would leave the run offline.
|
||||
os.environ[OFFLINE_VARIABLE] = OFFLINE_FLAG_VALUE
|
||||
named = next((plat for plat in AVAILABLE_PLATFORMS if args.platform and _name_key(
|
||||
args.platform) in (_name_key(plat), _name_key(display_name(plat)))), "")
|
||||
@@ -303,7 +306,23 @@ def _main_dispatch(args: argparse.Namespace) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Entry point."""
|
||||
"""Entry point: the remote resolved once, then the run."""
|
||||
try:
|
||||
remote = remote_from_env()
|
||||
except ValueError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
with remote_in_use(remote):
|
||||
try:
|
||||
_main_run()
|
||||
except Refusal as refusal:
|
||||
# Raised outside an install, which reports its own: the full
|
||||
# screen's start, an action and the sources opened before it.
|
||||
refusal.report()
|
||||
raise
|
||||
|
||||
|
||||
def _main_run() -> None:
|
||||
_INVOCATION.os_type = detect_os()
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
@@ -331,8 +350,7 @@ def main() -> None:
|
||||
_main_check_offline(parser, args)
|
||||
install_bounded_opener()
|
||||
if args.remove or args.backups:
|
||||
_open_local_sources(args)
|
||||
_run_action(args, run_removal if args.remove else run_backups)
|
||||
_run_action(args, _with_local_sources(run_removal if args.remove else run_backups))
|
||||
_main_check_sources(parser, args)
|
||||
_main_dispatch(args)
|
||||
|
||||
@@ -413,6 +431,17 @@ def _check_pack(parser: argparse.ArgumentParser, args: argparse.Namespace) -> No
|
||||
f"name): {name}")
|
||||
|
||||
|
||||
def _with_local_sources(action: Callable[[argparse.Namespace], int],
|
||||
) -> Callable[[argparse.Namespace], int]:
|
||||
"""action, the list and the pack it was given opened first. Opened
|
||||
before the action, they said the list's platform on stdout ahead of
|
||||
start, the first line of --events no JSON."""
|
||||
def opened(args: argparse.Namespace) -> int:
|
||||
_open_local_sources(args)
|
||||
return action(args)
|
||||
return opened
|
||||
|
||||
|
||||
def _run_action(args: argparse.Namespace,
|
||||
action: Callable[[argparse.Namespace], int]) -> NoReturn:
|
||||
"""Run an action and exit with its code, its events framed by start and
|
||||
@@ -427,6 +456,8 @@ def _run_action(args: argparse.Namespace,
|
||||
try:
|
||||
code = action(args)
|
||||
except SystemExit as exc:
|
||||
if isinstance(exc, Refusal):
|
||||
exc.report()
|
||||
EVENTS.emit("end", code=_event_exit_code(exc.code))
|
||||
raise
|
||||
except KeyboardInterrupt:
|
||||
|
||||
@@ -3,8 +3,8 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import NoReturn
|
||||
|
||||
from installer.config_values import _retroarch_cfg_dir
|
||||
from installer.events import EVENTS
|
||||
@@ -14,6 +14,7 @@ from installer.invocation import _INVOCATION
|
||||
from installer.local_check import closed_folder_words
|
||||
from installer.manifest import entry_copies
|
||||
from installer.platforms import display_name
|
||||
from installer.refusal import Refusal
|
||||
from installer.text import _plural, screen_text
|
||||
|
||||
# A libretro core as RetroArch loads it: <name>_libretro.so|dll|dylib, and
|
||||
@@ -145,7 +146,7 @@ def unknown_cores(manifest: dict, names: list[str]) -> list[str]:
|
||||
return sorted(name for name in names if name not in known)
|
||||
|
||||
|
||||
def _check_cores_dir(folder: Path) -> None:
|
||||
def _check_cores_dir(folder: Path, plat: str) -> None:
|
||||
"""Refuse a --cores-dir that cannot be listed, saying why: a typo
|
||||
(core/ for cores/) or a closed folder read as an empty one, and the
|
||||
run said "none in" and asked for the --cores-dir it was given."""
|
||||
@@ -153,20 +154,20 @@ def _check_cores_dir(folder: Path) -> None:
|
||||
with os.scandir(folder):
|
||||
return
|
||||
except FileNotFoundError:
|
||||
why = "does not exist"
|
||||
reason, why = "not_found", "does not exist"
|
||||
except NotADirectoryError:
|
||||
why = "is not a folder"
|
||||
reason, why = "not_a_folder", "is not a folder"
|
||||
except PermissionError as exc:
|
||||
closed = closed_folder(folder)
|
||||
reason = "unreadable"
|
||||
why = (f"cannot be opened by this user ({exc.strerror or exc})"
|
||||
if closed is None or closed[0] == folder
|
||||
else f"cannot be opened: {closed_folder_words(folder, closed)}")
|
||||
except OSError as exc:
|
||||
why = f"could not be read ({exc.strerror or exc})"
|
||||
print(f"Error: --cores-dir {screen_text(str(folder))} {why}.", file=sys.stderr)
|
||||
print(" Name the folder RetroArch loads cores from (libretro_directory in "
|
||||
"retroarch.cfg, cores/ beside RetroArch by default).", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
reason, why = "unreadable", f"could not be read ({exc.strerror or exc})"
|
||||
raise Refusal("cores", reason, plat, f"Error: --cores-dir {screen_text(str(folder))} {why}.",
|
||||
" Name the folder RetroArch loads cores from (libretro_directory in "
|
||||
"retroarch.cfg, cores/ beside RetroArch by default).")
|
||||
|
||||
|
||||
def _unprofiled_cores_firmware(
|
||||
@@ -200,7 +201,7 @@ def _unprofiled_cores_firmware(
|
||||
return dests
|
||||
|
||||
|
||||
def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None:
|
||||
def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> NoReturn:
|
||||
"""Refuse --installed-cores with no core, and say how to point at them.
|
||||
|
||||
With no retroarch.cfg naming the folder as its system_directory, and
|
||||
@@ -209,11 +210,10 @@ def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None:
|
||||
"""
|
||||
where = (f"none in {', '.join(map(str, searched))}" if searched
|
||||
else f"no retroarch.cfg was found for {bios_path} to name their folder")
|
||||
print(f"Error: no installed core found for {display_name(plat)}: {where}.",
|
||||
file=sys.stderr)
|
||||
print(" Name the folder RetroArch loads cores from (libretro_directory in "
|
||||
"retroarch.cfg, cores/ beside RetroArch by default):", file=sys.stderr)
|
||||
command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir"))
|
||||
print(f" {command} --cores-dir <cores folder>", file=sys.stderr)
|
||||
print(" Or run it without --installed-cores to install every file.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("cores", "none", plat,
|
||||
f"Error: no installed core found for {display_name(plat)}: {where}.",
|
||||
" Name the folder RetroArch loads cores from (libretro_directory in "
|
||||
"retroarch.cfg, cores/ beside RetroArch by default):",
|
||||
f" {command} --cores-dir <cores folder>",
|
||||
" Or run it without --installed-cores to install every file.")
|
||||
@@ -26,11 +26,11 @@ from installer.cards import (
|
||||
from installer.console import _answer_yes, _folder_answer, _numbers_hint, _typed_folder, detail
|
||||
from installer.detect_os import _DETECTED_OS, card_title, detect_os, detected_os, os_conflict
|
||||
from installer.embedded import CARD_MARKER, CARD_PLATFORMS, _EMBEDDED_RULES, _a, _built_on
|
||||
from installer.events import EVENTS
|
||||
from installer.host_fs import _exists, _is_dir, closed_folder
|
||||
from installer.local_check import closed_folder_words
|
||||
from installer.paths import shown_path
|
||||
from installer.platforms import _name_key, did_you_mean, display_name, normalize_platform, refuse_name
|
||||
from installer.refusal import Refusal
|
||||
from installer.setups import _choose_platform, _setup_label, drive_example, found_setups
|
||||
from installer.text import _names_and, _plural, screen_text
|
||||
|
||||
@@ -42,11 +42,10 @@ def _refuse_closed(dest: Path, named: str) -> None:
|
||||
if closed is None:
|
||||
return
|
||||
message = closed_folder_words(dest, closed)
|
||||
EVENTS.emit("error", stage="dest", reason="unreadable", platform="", message=message)
|
||||
print(f"Error: {screen_text(message)}. Give this user access to it, run as "
|
||||
f"its owner, or choose another folder than the one {named}.",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("dest", "unreadable", "",
|
||||
f"Error: {screen_text(message)}. Give this user access to it, run as "
|
||||
f"its owner, or choose another folder than the one {named}.",
|
||||
message=message)
|
||||
|
||||
|
||||
def _refuse_file(dest: Path, named: str) -> None:
|
||||
@@ -64,10 +63,9 @@ def _refuse_file(dest: Path, named: str) -> None:
|
||||
return
|
||||
where = (f"{shown_path(dest)} is a file, not a folder" if folder == dest
|
||||
else f"{shown_path(dest)} cannot be a folder: {shown_path(folder)} is a file")
|
||||
EVENTS.emit("error", stage="dest", reason="not_a_folder", platform="", message=where)
|
||||
print(f"Error: {screen_text(where)}. Name the folder the BIOS files go in, not "
|
||||
f"the file {named}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("dest", "not_a_folder", "",
|
||||
f"Error: {screen_text(where)}. Name the folder the BIOS files go in, not "
|
||||
f"the file {named}.", message=where)
|
||||
|
||||
|
||||
def _missing_dest(dest: Path, ask: bool, named: str = "named with --dest",
|
||||
@@ -434,11 +432,8 @@ def card_dest(named: str, plat: str, dest: Path) -> tuple[str, Path]:
|
||||
choice = card_choice(named, plat, dest)
|
||||
if choice.refused:
|
||||
message = _dest_refusal_words(choice, card_setup(named, plat))
|
||||
# A script reading the stream learned code 1 and no reason.
|
||||
EVENTS.emit("error", stage="detect", reason="not_found", platform=choice.plat,
|
||||
message=message)
|
||||
print(f"Error: {message}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "not_found", choice.plat, f"Error: {message}",
|
||||
message=message)
|
||||
for line in (choice.found, choice.note):
|
||||
if line:
|
||||
print(f" {line}")
|
||||
@@ -523,12 +518,11 @@ def card_install_dest(named: str, plat: str, interactive: bool, ask: bool = True
|
||||
print(f" {len(cards)} {system} cards are mounted: "
|
||||
+ ", ".join(_mount_name(card) for card in cards) + ".", file=sys.stderr)
|
||||
if not interactive:
|
||||
EVENTS.emit("error", stage="detect", reason="not_found", platform=plat,
|
||||
message=f"{system} keeps its BIOS files on its SD card, and no "
|
||||
"card was named with --dest")
|
||||
print(f" {system} keeps its BIOS files on its SD card, not on this machine. "
|
||||
f"Mount it and give its root with --dest: {example}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "not_found", plat,
|
||||
f" {system} keeps its BIOS files on its SD card, not on this machine. "
|
||||
f"Mount it and give its root with --dest: {example}",
|
||||
message=f"{system} keeps its BIOS files on its SD card, and no "
|
||||
"card was named with --dest")
|
||||
print(f" {system} keeps its BIOS files {card_where(system, setup.below)}, not on "
|
||||
"this machine. "
|
||||
+ ("" if setup.known() else
|
||||
@@ -633,16 +627,16 @@ def _platform_for_dest(os_type: str, dest: Path, interactive: bool) -> tuple[str
|
||||
found = list(dict.fromkeys(name for name, _path, _label in found_setups(os_type)[0]))
|
||||
default = found[0] if len(found) == 1 else "" if found else "retroarch"
|
||||
if not default:
|
||||
print(f"Error: {' and '.join(display_name(n) for n in found)} found here. "
|
||||
f"Name the platform {dest} is for with --platform.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "conflict", "",
|
||||
f"Error: {' and '.join(display_name(n) for n in found)} found here. "
|
||||
f"Name the platform {dest} is for with --platform.")
|
||||
why = "the platform found here" if found else "nothing was detected here"
|
||||
print(f" File list: {display_name(default)} ({why}). For another platform's "
|
||||
"list, add --platform (--list-platforms names them).")
|
||||
return default, dest
|
||||
|
||||
|
||||
def _several_found(platforms: list[tuple[str, Path]], setups: list) -> None:
|
||||
def _several_found(platforms: list[tuple[str, Path]], setups: list) -> NoReturn:
|
||||
"""Stop a run without questions that found more than one setup, each
|
||||
named with the options that choose it."""
|
||||
labels = {(name, path): label for name, path, label in setups}
|
||||
@@ -653,11 +647,9 @@ def _several_found(platforms: list[tuple[str, Path]], setups: list) -> None:
|
||||
if conflict else f"{len(shown)} setups were found here")
|
||||
message = (f"{lead}, and a run without questions installs for one: "
|
||||
+ ", ".join(label for label, _n, _p in shown))
|
||||
EVENTS.emit("error", stage="detect", reason="conflict", platform="", message=message)
|
||||
print(f"Error: {message}. Name the one to install for:", file=sys.stderr)
|
||||
for label, name, path in shown:
|
||||
print(f" {label}: --platform {name} --dest {shown_path(path)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "conflict", "", f"Error: {message}. Name the one to install for:",
|
||||
*(f" {label}: --platform {name} --dest {shown_path(path)}"
|
||||
for label, name, path in shown), message=message)
|
||||
|
||||
|
||||
def _unknown_target(target: str, plat: str, targets: dict, *after: str) -> NoReturn:
|
||||
|
||||
@@ -5,7 +5,6 @@ import contextlib
|
||||
import functools
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
@@ -18,6 +17,7 @@ from installer.config_values import (
|
||||
_retroarch_cfg_dir,
|
||||
_retroarch_cfg_value,
|
||||
)
|
||||
from installer.detection_notes import note_detection
|
||||
from installer.detect_os import (
|
||||
_detect_embedded,
|
||||
_macos_retroarch_base,
|
||||
@@ -693,10 +693,9 @@ def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None:
|
||||
if not rd_home:
|
||||
# A home moved to an SD card lives only in this file: the
|
||||
# default is a guess, and the user is told so.
|
||||
print(
|
||||
note_detection(
|
||||
f"Warning: could not read paths.rd_home_path from "
|
||||
f"{retrodeck_json}: assuming {home / 'retrodeck'}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
rd_root = Path(rd_home) if rd_home else home / "retrodeck"
|
||||
_record_moved_folders(rd_root, retrodeck_json)
|
||||
@@ -818,9 +817,9 @@ def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]]
|
||||
# setup reads the folder named.
|
||||
if name not in _UNNAMEABLE:
|
||||
_UNNAMEABLE.append(name)
|
||||
print(f" {display_name(name)}: the folder its configuration names holds a "
|
||||
f"control character ({shown_path(path)}). Name its BIOS folder with "
|
||||
"--dest.", file=sys.stderr)
|
||||
note_detection(f" {display_name(name)}: the folder its configuration names "
|
||||
f"holds a control character ({shown_path(path)}). Name its BIOS "
|
||||
"folder with --dest.")
|
||||
continue
|
||||
kept.append((name, path))
|
||||
return kept
|
||||
@@ -836,7 +835,7 @@ def detect_platforms(os_type: str) -> list[tuple[str, Path]]:
|
||||
if os_type == "android":
|
||||
found.extend(_detect_android())
|
||||
for line in android_unreachable_folders():
|
||||
print(line, file=sys.stderr)
|
||||
note_detection(line)
|
||||
|
||||
if os_type in ("linux", "wsl"):
|
||||
found.extend(_detect_embedded())
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from installer.cards import card_platform, setup_bios_folder
|
||||
from installer.config_values import _RETROARCH_CONFIGS, _parse_retroarch_system_dir
|
||||
from installer.detection_notes import echo_detection, note_detection
|
||||
from installer.embedded import CARD_MARKER, _EMBEDDED_RULES, _NO_FOLDER
|
||||
from installer.events import EVENTS
|
||||
from installer.host_fs import (
|
||||
@@ -301,7 +302,7 @@ def _detect_embedded() -> list[tuple[str, Path]]:
|
||||
reason = _NO_FOLDER.get(
|
||||
name, "nothing on it names the folder its RetroArch reads")
|
||||
closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest."
|
||||
print(f"{name} found here, but {reason}.{closing}", file=sys.stderr)
|
||||
note_detection(f"{name} found here, but {reason}.{closing}")
|
||||
continue
|
||||
_DETECTED_OS[(plat, folder)] = name
|
||||
found.append((plat, folder))
|
||||
@@ -383,7 +384,7 @@ def _note_windows_unasked() -> None:
|
||||
_DETECTION_REFUSED.append(refused)
|
||||
words = refused_words(*refused)
|
||||
EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words)
|
||||
print(f" {screen_text(words)}", file=sys.stderr)
|
||||
echo_detection(f" {screen_text(words)}")
|
||||
|
||||
|
||||
def _winreg_value(key: str, value: str) -> str | None:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""What detection says, kept as lines the screen reads and printed as it comes in line mode."""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import sys
|
||||
from collections.abc import Iterator
|
||||
from typing import TextIO
|
||||
|
||||
# Each line detection said, in order, other than a folder it could not look
|
||||
# in (_DETECTION_REFUSED keeps those): a system found with no folder, a
|
||||
# configuration naming a folder nobody can type, an Android folder out of
|
||||
# reach, a card that fits two systems.
|
||||
DETECTION_NOTES: list[str] = []
|
||||
# Set while the full screen runs detection: it shows the notes and the
|
||||
# refusals itself, and a line printed under it would tear the screen.
|
||||
_HELD = {"active": False}
|
||||
|
||||
|
||||
def echo_detection(line: str, stream: TextIO | None = None) -> None:
|
||||
"""Print a line detection says, unless the screen shows it itself."""
|
||||
if not _HELD["active"]:
|
||||
print(line, file=stream if stream is not None else sys.stderr)
|
||||
|
||||
|
||||
def note_detection(line: str, stream: TextIO | None = None) -> None:
|
||||
"""Keep a line detection says, and print it in line mode."""
|
||||
DETECTION_NOTES.append(line)
|
||||
echo_detection(line, stream)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def detection_held() -> Iterator[None]:
|
||||
"""Detection that keeps its lines without printing them."""
|
||||
outer = _HELD["active"]
|
||||
_HELD["active"] = True
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_HELD["active"] = outer
|
||||
@@ -41,7 +41,7 @@ from installer.offline import LOCAL, offline_words
|
||||
from installer.outcome import HttpReason, NetworkReason, OfflineReason, _transfer_failure
|
||||
from installer.pack_source import NOT_IN_PACK, _extract_from_pack
|
||||
from installer.paths import _entry_path, _entry_place
|
||||
from installer.remote import MAX_DOWNLOAD_SIZE, MAX_RETRIES, RAW_FILE_URL, RELEASE_URL, RESUME_FROM_SIZE
|
||||
from installer.remote import MAX_DOWNLOAD_SIZE, MAX_RETRIES, RELEASE_URL, RESUME_FROM_SIZE, active_remote
|
||||
from installer.safe_replace import KEPT, NOT_KEPT, _NotKept, _kept_slot
|
||||
from installer.terminal import Terminal
|
||||
|
||||
@@ -134,7 +134,7 @@ def _download_one(
|
||||
if f.get("release_asset"):
|
||||
url = RELEASE_URL.format(asset=urllib.parse.quote(f["release_asset"], safe=""))
|
||||
else:
|
||||
url = RAW_FILE_URL.format(path=urllib.parse.quote(f["repo_path"], safe="/"))
|
||||
url = active_remote().raw_file_url.format(path=urllib.parse.quote(f["repo_path"], safe="/"))
|
||||
return _fetch_file(_FileFetch(f, bios_path, dest, url, verbose, progress))
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,9 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
||||
# stage: manifest (reason: network, not_found, invalid, clock for a
|
||||
# refused certificate under a clock set in the past, no_ca for no
|
||||
# trusted certificates on the machine, or no_ssl for a Python built
|
||||
# without ssl) or detect (reason: conflict, two
|
||||
# without ssl, unreadable for a --manifest file that cannot be read,
|
||||
# unavailable for the standalone layout --standalone needs) or detect
|
||||
# (reason: conflict, two
|
||||
# systems found on one machine, or not_found, the platform named with
|
||||
# --platform, or by a file list or a pack in a run without questions,
|
||||
# found nowhere and no folder to assume) or from (a folder named with --from,
|
||||
@@ -33,8 +35,21 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
||||
# is a file or lies under one, or not_writable, the BIOS folder cannot
|
||||
# be created, a summary following) or option (reason:
|
||||
# unknown, a platform, target, system, core or emulator the run cannot
|
||||
# use, refused before any download).
|
||||
# use, refused before any download, or not_recorded, the list does not
|
||||
# record what --system, --core, --region, --emulator or --standalone
|
||||
# reads) or cores (--installed-cores, reason: not_found, not_a_folder
|
||||
# or unreadable for the --cores-dir, none for no core installed) or
|
||||
# targets (the board list a run cannot go on without, reason: the
|
||||
# manifest's codes, http for a refused answer) or pack (--from-pack,
|
||||
# reason: invalid, other_platform for a pack of another platform, or
|
||||
# no_platform when none is named and the pack does not say) or space
|
||||
# (reason: drive_full, the drive cannot hold the download, after
|
||||
# no_space, before any file of the setup is written).
|
||||
"error": ("stage", "reason", "platform", "message"),
|
||||
# Right before the error of stage space: the BIOS folder, and the bytes
|
||||
# the run needs and the drive has free. A kind of its own, since schema
|
||||
# 1 never adds a key to error.
|
||||
"no_space": ("platform", "folder", "bytes_needed", "bytes_free"),
|
||||
# A folder named with --from, once read: the files it holds (counted
|
||||
# up to MAX_SCANNED_FILES, truncated past them), and the folders below
|
||||
# it on another drive, not entered.
|
||||
@@ -103,6 +118,12 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
||||
# data_missing) and the bytes they write. A kind of its own, since
|
||||
# schema 1 never adds a key to check.
|
||||
"data": ("platform", "files", "bytes"),
|
||||
# Right after data: the bytes the run writes on the drive of the BIOS
|
||||
# folder, the files missing or replaced and the data trees rebuilt
|
||||
# beside them. The number the run's refusal for space and both plans
|
||||
# hold against the free space. A kind of its own, since schema 1 never
|
||||
# adds a key to check.
|
||||
"space": ("platform", "bytes"),
|
||||
# A file to install that this machine already holds: misplaced in the
|
||||
# BIOS folder (folder is its bios_dir, reason says why in words) or in
|
||||
# a folder named with --from (reason empty). member names the ZIP member
|
||||
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import contextlib
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import zipfile
|
||||
from collections.abc import Callable, Collection, Iterator
|
||||
@@ -19,6 +18,7 @@ from installer.offline import LOCAL, local_manifest_platform
|
||||
from installer.pack_source import _PART_FILE, PackSource
|
||||
from installer.paths import _entry_path, _safe_relative_path, shown_path
|
||||
from installer.platforms import display_name, normalize_platform
|
||||
from installer.refusal import Refusal
|
||||
from installer.safe_replace import BACKUP_DIR, _MEMBER_ERRORS, _write_verified, unreadable_words
|
||||
from installer.tally import _bytes
|
||||
from installer.text import _plural, format_size, screen_text, shown_lines
|
||||
@@ -821,8 +821,7 @@ def _open_local_sources(args: argparse.Namespace) -> None:
|
||||
try:
|
||||
LOCAL.pack = PackSource(args.from_pack)
|
||||
except ValueError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("pack", "invalid", args.platform or "", f"Error: {exc}") from None
|
||||
pack = LOCAL.pack
|
||||
parts = len(pack.files)
|
||||
print(f" Pack: {pack.name}"
|
||||
@@ -831,10 +830,10 @@ def _open_local_sources(args: argparse.Namespace) -> None:
|
||||
if args.platform is not None:
|
||||
plat = normalize_platform(args.platform, say=False)
|
||||
if spelled and plat not in spelled:
|
||||
print(f"Error: {pack.name} is a pack for "
|
||||
f"{' and '.join(display_name(n) for n in spelled)}, not "
|
||||
f"{display_name(plat)}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("pack", "other_platform", plat,
|
||||
f"Error: {pack.name} is a pack for "
|
||||
f"{' and '.join(display_name(n) for n in spelled)}, not "
|
||||
f"{display_name(plat)}.")
|
||||
elif len(spelled) == 1:
|
||||
# Named by the pack, not by the user: the setups that read its list
|
||||
# are offered, as for a --manifest.
|
||||
@@ -842,9 +841,9 @@ def _open_local_sources(args: argparse.Namespace) -> None:
|
||||
args.platform_from_list = True
|
||||
else:
|
||||
among = (" (" + ", ".join(spelled) + ")") if spelled else ""
|
||||
print(f"Error: name the platform {pack.name} is installed for with "
|
||||
f"--platform{among}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("pack", "no_platform", "",
|
||||
f"Error: name the platform {pack.name} is installed for with "
|
||||
f"--platform{among}.")
|
||||
|
||||
|
||||
def _system_folder(folder: Path) -> str:
|
||||
@@ -898,9 +897,8 @@ def _open_from_folders(folders: list[Path]) -> None:
|
||||
if problem is not None:
|
||||
reason, what = problem
|
||||
message = f"{label} {what}: --from names the folder to copy BIOS files from"
|
||||
EVENTS.emit("error", stage="from", reason=reason, platform="", message=message)
|
||||
print(f"Error: {screen_text(message)}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("from", reason, "", f"Error: {screen_text(message)}.",
|
||||
message=message)
|
||||
_read_from_folder(label)
|
||||
|
||||
|
||||
|
||||
@@ -152,14 +152,14 @@ def save_directory_for(
|
||||
|
||||
def place_save_entries(
|
||||
files: list[dict], bios_path: Path, manifest: dict, override: Path | None,
|
||||
display: str, say: bool = True,
|
||||
display: str,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Find the save directory for the entries read below it.
|
||||
|
||||
Returns the files to install and, when the save directory is unknown,
|
||||
the entries left out as omissions, said once with the reason. Without
|
||||
say nothing is printed or sent: the run says it (say_saves) once a
|
||||
choice of systems has kept the files it counts.
|
||||
the entries left out as omissions. Nothing is printed or sent: the run
|
||||
says it (say_saves) once a choice of systems has kept the files it
|
||||
counts.
|
||||
"""
|
||||
saved = [entry for entry in files if entry.get("root") == "save"]
|
||||
if not saved:
|
||||
@@ -175,15 +175,8 @@ def place_save_entries(
|
||||
if place.by_core:
|
||||
where += f"{os.sep}<core>"
|
||||
_SAVE_WHERE[bios_path] = where
|
||||
if say:
|
||||
print(f" {saves_line(display, len(saved), where)}")
|
||||
EVENTS.emit("saves", platform=str(manifest.get("platform", "")),
|
||||
files=len(saved), folder=where)
|
||||
return files, []
|
||||
_SAVE_WHY[bios_path] = place
|
||||
if say:
|
||||
print(f" {_plural(len(saved), 'file')} read from {display}'s save directory "
|
||||
f"left out: {place}.")
|
||||
kept = [entry for entry in files if entry.get("root") != "save"]
|
||||
unplaced = [
|
||||
{"dest": entry["dest"], "name": PurePosixPath(entry["dest"]).name,
|
||||
@@ -197,7 +190,7 @@ def place_save_entries(
|
||||
|
||||
|
||||
def place_relative_entries(
|
||||
files: list[dict], bios_path: Path, manifest: dict, display: str, say: bool = True,
|
||||
files: list[dict], bios_path: Path, manifest: dict,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Find the roms and configs folders for the entries read below them.
|
||||
|
||||
@@ -205,7 +198,8 @@ def place_relative_entries(
|
||||
source places them (ROCKNIX's /storage/roms holds bios/, Batocera's
|
||||
configs folder is ../system/configs): a BIOS folder of the platform's
|
||||
name puts the root there. Any other is a folder this run cannot relate
|
||||
to the root, and the entries are left out with the reason.
|
||||
to the root, and the entries are left out, the reason kept for
|
||||
say_unplaced.
|
||||
"""
|
||||
unplaced: list[dict] = []
|
||||
for root in RELATIVE_ROOTS:
|
||||
@@ -220,9 +214,8 @@ def place_relative_entries(
|
||||
if folder is not None:
|
||||
_RELATIVE_DIRS[(bios_path, root)] = folder
|
||||
continue
|
||||
if say:
|
||||
print(f" {_plural(len(below), 'file')} read from {display}'s {root} folder left "
|
||||
f"out: {bios_path} is not its {layout.get('bios_folder') or 'BIOS'} folder.")
|
||||
_UNPLACED_WHY[(bios_path, root)] = (
|
||||
f"{bios_path} is not its {layout.get('bios_folder') or 'BIOS'} folder")
|
||||
files = [entry for entry in files if entry.get("root") != root]
|
||||
unplaced += [
|
||||
{"dest": entry["dest"], "name": PurePosixPath(entry["dest"]).name,
|
||||
@@ -234,7 +227,7 @@ def place_relative_entries(
|
||||
|
||||
|
||||
def place_emulator_entries(
|
||||
files: list[dict], bios_path: Path, manifest: dict, display: str, say: bool = True,
|
||||
files: list[dict], bios_path: Path, manifest: dict,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Find the emulator folder each entry a launcher runs from one goes to.
|
||||
|
||||
@@ -242,9 +235,9 @@ def place_emulator_entries(
|
||||
launcher config (RetroBat's bios beside emulationstation): a BIOS
|
||||
folder of that name whose parent holds the config is the platform's.
|
||||
A key the config sets moves the folder somewhere this run does not
|
||||
follow, so its files are left out. Otherwise the folder is the first of
|
||||
the searched places that exists, the default one when none does, as the
|
||||
launcher searches them.
|
||||
follow, so its files are left out, the reason kept for say_unplaced.
|
||||
Otherwise the folder is the first of the searched places that exists,
|
||||
the default one when none does, as the launcher searches them.
|
||||
"""
|
||||
inside = [entry for entry in files if entry.get("root") == "emulators"]
|
||||
if not inside:
|
||||
@@ -289,15 +282,32 @@ def place_emulator_entries(
|
||||
"reason": "no_emulators_directory", "cores": entry.get("cores"),
|
||||
"root": "emulators",
|
||||
})
|
||||
if unplaced and say:
|
||||
why = (f"{config} sets their folder" if matches
|
||||
else f"{bios_path} is not the {layout.get('bios_folder') or 'BIOS'} folder "
|
||||
f"beside {layout.get('config') or 'its config'}")
|
||||
print(f" {_plural(len(unplaced), 'file')} read from {display}'s emulator folders "
|
||||
f"left out: {why}.")
|
||||
if unplaced:
|
||||
_UNPLACED_WHY[(bios_path, "emulators")] = (
|
||||
f"{config} sets their folder" if matches
|
||||
else f"{bios_path} is not the {layout.get('bios_folder') or 'BIOS'} folder "
|
||||
f"beside {layout.get('config') or 'its config'}")
|
||||
return kept, unplaced
|
||||
|
||||
|
||||
# Per BIOS folder and root, why the files read below a roms, configs or
|
||||
# emulators folder are left out: said once a choice keeps the ones counted.
|
||||
_UNPLACED_WHY: dict[tuple[Path, str], str] = {}
|
||||
_UNPLACED_FOLDERS = {"roms": "roms folder", "configs": "configs folder",
|
||||
"emulators": "emulator folders"}
|
||||
|
||||
|
||||
def say_unplaced(omitted: list[dict], bios_path: Path, display: str) -> None:
|
||||
"""The roms, configs and emulator folder lines, over the entries a
|
||||
narrowed run still counts: --system panasonic-3do said 1918 files read
|
||||
from EmuDeck's roms folder were left out, 6 of them the 3DO's."""
|
||||
for root, folder in _UNPLACED_FOLDERS.items():
|
||||
left = sum(1 for entry in omitted if entry.get("reason") == f"no_{root}_directory")
|
||||
why = _UNPLACED_WHY.get((bios_path, root))
|
||||
if left and why is not None:
|
||||
print(f" {_plural(left, 'file')} read from {display}'s {folder} left out: {why}.")
|
||||
|
||||
|
||||
# Per BIOS folder, where its save files go in words, or why that is not
|
||||
# known: read by the lines that count them once a choice is made.
|
||||
_SAVE_WHERE: dict[Path, str] = {}
|
||||
|
||||
@@ -42,7 +42,7 @@ from installer.offline import LOCAL, _Offline, offline_words
|
||||
from installer.paths import shown_path
|
||||
from installer.platforms import entry_systems, system_title
|
||||
from installer.regions import WORLD_REGION, _region_comparable, region_title
|
||||
from installer.remote import BASE_URL
|
||||
from installer.remote import active_remote
|
||||
from installer.text import _plural, agree
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -57,8 +57,14 @@ if TYPE_CHECKING:
|
||||
# and for an arcade set the BIOS sets its romof chain reaches. Any doubt
|
||||
# keeps the wider set: the game must run.
|
||||
|
||||
GAMES_URL = f"{BASE_URL}/install/games/{{path}}"
|
||||
GAMES_FORMAT = 1
|
||||
|
||||
|
||||
def games_url(path: str) -> str:
|
||||
"""Where install/games/<path> is read from in this run."""
|
||||
return f"{active_remote().base}/install/games/{path}"
|
||||
|
||||
|
||||
MAX_GAMES_INDEX_BYTES = 4 * 1024 * 1024
|
||||
MAX_GAMES_DOC_BYTES = 32 * 1024 * 1024
|
||||
|
||||
@@ -119,7 +125,7 @@ class GamesData:
|
||||
failure = ""
|
||||
if raw is None and network:
|
||||
try:
|
||||
raw = _fetch_json(GAMES_URL.format(path="index.json"), MAX_GAMES_INDEX_BYTES,
|
||||
raw = _fetch_json(games_url("index.json"), MAX_GAMES_INDEX_BYTES,
|
||||
"games index", attempts=attempts, raw=True)
|
||||
except _Offline:
|
||||
reason = "offline"
|
||||
@@ -165,7 +171,7 @@ class GamesData:
|
||||
cached: Path | None) -> bytes | None:
|
||||
"""A listed document downloaded and cached, None when offline."""
|
||||
try:
|
||||
fetched = _fetch_json(GAMES_URL.format(path=name), limit, f"games {kind}",
|
||||
fetched = _fetch_json(games_url(name), limit, f"games {kind}",
|
||||
attempts=attempts, raw=True)
|
||||
except _Offline:
|
||||
return None
|
||||
|
||||
@@ -26,7 +26,7 @@ from installer.network import _fetch_json, _read_limited, _retry_after_failure,
|
||||
from installer.offline import LOCAL, _Offline, _network_allowed
|
||||
from installer.outcome import _transfer_failure
|
||||
from installer.paths import _destination_path, _safe_relative_path
|
||||
from installer.remote import BASE_URL, MAX_RETRIES, RAW_FILE_URL
|
||||
from installer.remote import MAX_RETRIES, active_remote
|
||||
from installer.safe_replace import KEPT, _write_verified
|
||||
from installer.text import _plural
|
||||
|
||||
@@ -36,7 +36,11 @@ from installer.text import _plural
|
||||
# same ref as the file lists, listed with their hashes in
|
||||
# install/launchers/index.json, which scripts/generate_launcher_index.py
|
||||
# writes from the members of the launcher archives.
|
||||
LAUNCHERS_URL = f"{BASE_URL}/install/launchers/index.json"
|
||||
def launchers_url() -> str:
|
||||
"""Where install/launchers/index.json is read from in this run."""
|
||||
return f"{active_remote().base}/install/launchers/index.json"
|
||||
|
||||
|
||||
MAX_LAUNCHERS_BYTES = 256 * 1024
|
||||
MAX_APP_FILE_SIZE = 8 * 1024 * 1024
|
||||
MAX_APP_FILES = 64
|
||||
@@ -226,7 +230,7 @@ def _app_bytes(entry: dict, name: str) -> bytes:
|
||||
if content is not None:
|
||||
data = content.encode("utf-8")
|
||||
else:
|
||||
url = RAW_FILE_URL.format(path=urllib.parse.quote(entry["repo_path"], safe="/"))
|
||||
url = active_remote().raw_file_url.format(path=urllib.parse.quote(entry["repo_path"], safe="/"))
|
||||
data = _app_download(url, entry["size"])
|
||||
if len(data) != entry["size"]:
|
||||
raise ValueError(f"{name} holds {len(data)} bytes, the list records {entry['size']}")
|
||||
@@ -279,7 +283,7 @@ def put_app(card: CardApp) -> dict:
|
||||
if card.place is None:
|
||||
return fields
|
||||
try:
|
||||
data = _fetch_json(LAUNCHERS_URL, MAX_LAUNCHERS_BYTES, "list of the app's files")
|
||||
data = _fetch_json(launchers_url(), MAX_LAUNCHERS_BYTES, "list of the app's files")
|
||||
targets = app_targets(data, card.place)
|
||||
except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc:
|
||||
fields["reason"] = f"its list of files could not be read: {_app_failure(exc)}"
|
||||
|
||||
@@ -7,13 +7,13 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from installer.detection_notes import echo_detection
|
||||
from installer.events import EVENTS
|
||||
from installer.text import screen_text
|
||||
|
||||
@@ -103,7 +103,7 @@ def _note_refused(path: Path, exc: OSError) -> None:
|
||||
_DETECTION_UNREADABLE.add(refused[0])
|
||||
words = refused_words(*refused)
|
||||
EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words)
|
||||
print(f" {screen_text(words)}", file=sys.stderr)
|
||||
echo_detection(f" {screen_text(words)}")
|
||||
|
||||
|
||||
def _held(path: Path) -> bool:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"""Line mode's menu: the plan above it and the systems, cores and regions it narrows to."""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
@@ -16,7 +14,7 @@ from installer.choices import (
|
||||
parse_selection,
|
||||
recorded_axes,
|
||||
)
|
||||
from installer.console import _ask, _live_stdout, _quit
|
||||
from installer.console import _ask, _quit
|
||||
from installer.datadirs import data_directory_state, data_fetch_bytes, select_data_directories
|
||||
from installer.destination import _last_name, on_its_card, shown_bios_folder
|
||||
from installer.from_folders import plan_local_copies
|
||||
@@ -25,7 +23,7 @@ from installer.host_fs import _is_file
|
||||
from installer.install_record import _RECORD_TAKEN
|
||||
from installer.invocation import _INVOCATION
|
||||
from installer.line_folder import _ask_from_folder
|
||||
from installer.local_check import _classify_local
|
||||
from installer.local_check import not_in_place, read_in_place
|
||||
from installer.manifest import OTHER_SYSTEMS
|
||||
from installer.narrowing import _chosen, narrow
|
||||
from installer.offline import LOCAL, _offline_only, offline_named
|
||||
@@ -463,7 +461,7 @@ def _print_menu_head(
|
||||
# Done, where the screen names it on every plan.
|
||||
print(f" BIOS folder: {shown_path(shown_bios_folder(bios_path, files))}")
|
||||
for line in folder_warnings(plat, bios_path, shown, _INVOCATION, True,
|
||||
on_its_card(plat, bios_path)):
|
||||
on_its_card(plat, bios_path), kept_trees):
|
||||
print(f" {line}")
|
||||
# The frontend's save directory, named as the end of the run and the
|
||||
# screen name it: "Onion's" before the menu, "RetroArch's" after.
|
||||
@@ -485,28 +483,7 @@ def found_head(files: list[dict], trees: list[dict], bios_path: Path) -> str:
|
||||
"nothing to download" stood over a run that left it. What is read here is
|
||||
kept for the check after Enter (_HEAD_READS): a card read twice is read at
|
||||
the speed of its reader."""
|
||||
|
||||
def held(path: Path, size: object) -> bool:
|
||||
try:
|
||||
return _is_file(path) and path.stat().st_size == size
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
needed, sized = [], []
|
||||
for entry in files:
|
||||
try:
|
||||
path = _entry_path(bios_path, entry)
|
||||
except ValueError:
|
||||
continue
|
||||
if held(path, entry.get("size")):
|
||||
sized.append((entry, path))
|
||||
else:
|
||||
needed.append(entry)
|
||||
# Only a copy of the right size is read, on the check's workers and
|
||||
# with its count: one at a time and silent, 400 files of a card read
|
||||
# as a hung run before the menu.
|
||||
needed += [entry for (entry, _path), verdict in zip(sized, read_in_place(sized))
|
||||
if verdict != "up_to_date"]
|
||||
needed = not_in_place(bios_path, files)
|
||||
copies = plan_local_copies(needed, bios_path, None, LOCAL.folders)
|
||||
if not copies:
|
||||
return ""
|
||||
@@ -557,30 +534,6 @@ def all_in_place(files: list[dict], trees: list[dict], bios_path: Path) -> bool:
|
||||
for tree in trees))
|
||||
|
||||
|
||||
def read_in_place(pairs: list[tuple[dict, Path]]) -> list[str]:
|
||||
"""_classify_local of each (entry, path), read before the line menu as
|
||||
the check after it reads: on --jobs workers, a count moving at a
|
||||
terminal, what is read kept for that check (_HEAD_READS). Each file is
|
||||
read once whatever the question: the head reads the files of the right
|
||||
size only, and the check after Enter reads none of them again."""
|
||||
if not pairs:
|
||||
return []
|
||||
live = _live_stdout()
|
||||
verdicts: list[str] = []
|
||||
last = 0.0
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=LOCAL.jobs) as pool:
|
||||
for done, verdict in enumerate(pool.map(
|
||||
lambda pair: _classify_local(pair[0], pair[1], remember=True), pairs), 1):
|
||||
verdicts.append(verdict)
|
||||
now = time.monotonic()
|
||||
if live and (now - last >= 0.1 or done == len(pairs)):
|
||||
last = now
|
||||
print(f"\r read {done}/{len(pairs)}", end="", flush=True)
|
||||
if live:
|
||||
print("\r\033[K", end="", flush=True)
|
||||
return verdicts
|
||||
|
||||
|
||||
def menu_choice(
|
||||
files: list[dict], omitted: list[dict],
|
||||
installed: tuple[list[dict], list[dict]] | None, current: object, cut: bool,
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
"""The file lists and board lists a run reads, and why one could not be had."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
from installer.host_fs import _is_file, read_local_json
|
||||
from installer.manifest import _check_standalone_layouts, _validate_manifest, _validate_targets
|
||||
from installer.network import _address_lines, _fetch_json, network_words, request_proxy
|
||||
from installer.offline import LOCAL, _Offline, offline_named, offline_undo, offline_words
|
||||
from installer.platforms import TARGET_PLATFORMS, display_name
|
||||
from installer.refusal import Refusal
|
||||
from installer.remote import (
|
||||
DEFAULT_RELEASE_REF,
|
||||
MAX_MANIFEST_BYTES,
|
||||
MAX_RETRIES,
|
||||
MAX_STANDALONE_BYTES,
|
||||
MAX_TARGETS_BYTES,
|
||||
STANDALONE_DIR,
|
||||
TROUBLESHOOTING_PAGE,
|
||||
Remote,
|
||||
active_remote,
|
||||
)
|
||||
|
||||
NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a "
|
||||
"proxy, then run the same command again.\n"
|
||||
f" More help: {TROUBLESHOOTING_PAGE}")
|
||||
|
||||
|
||||
class ListProblem(NamedTuple):
|
||||
"""A list that could not be had, classified once: line mode prints it
|
||||
and stops, the full screen draws it.
|
||||
|
||||
source is file or pack for a list this run was given (where names it),
|
||||
network for one asked at the address where. code is unreadable or
|
||||
invalid, http (status), offline, or the network_words code (network,
|
||||
clock, no_ca, no_ssl), with words saying it. garbled is an answer that
|
||||
is not JSON at all: a Wi-Fi sign-in page or a cut download. fatal is the
|
||||
code line mode ends on, 0 when the run carries on without the list.
|
||||
proxy names what sent a network request through a proxy (a variable or
|
||||
the system settings), empty when it went direct.
|
||||
"""
|
||||
|
||||
plat: str
|
||||
code: str
|
||||
words: str
|
||||
source: str = "network"
|
||||
where: str = ""
|
||||
remote: Remote | None = None
|
||||
status: int = 0
|
||||
attempts: int = MAX_RETRIES
|
||||
garbled: bool = False
|
||||
fatal: int = 1
|
||||
proxy: str = ""
|
||||
|
||||
@property
|
||||
def overridden(self) -> bool:
|
||||
"""Whether RETROBIOS_BASE_URL chose the address that failed."""
|
||||
return self.remote is not None and self.remote.overridden
|
||||
|
||||
@property
|
||||
def ref(self) -> str:
|
||||
return self.remote.ref if self.remote is not None else DEFAULT_RELEASE_REF
|
||||
|
||||
|
||||
class ListFailure(Exception):
|
||||
"""A list that could not be had, its problem carried to who says it."""
|
||||
|
||||
def __init__(self, problem: ListProblem) -> None:
|
||||
super().__init__(problem.words)
|
||||
self.problem = problem
|
||||
|
||||
|
||||
def _download_failure(plat: str, url: str, remote: Remote, exc: Exception,
|
||||
fatal: int = 1) -> ListFailure:
|
||||
"""What a list asked at url gave instead of a valid document."""
|
||||
if isinstance(exc, ValueError):
|
||||
garbled = isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError))
|
||||
return ListFailure(ListProblem(plat, "invalid", str(exc), where=url, remote=remote,
|
||||
garbled=garbled, fatal=fatal))
|
||||
if isinstance(exc, urllib.error.HTTPError):
|
||||
return ListFailure(ListProblem(plat, "http", str(exc), where=url, remote=remote,
|
||||
status=exc.code, fatal=fatal))
|
||||
code, words = network_words(exc)
|
||||
return ListFailure(ListProblem(plat, code, words, where=url, remote=remote, fatal=fatal,
|
||||
attempts=getattr(exc, "attempts", MAX_RETRIES),
|
||||
proxy=request_proxy(url)))
|
||||
|
||||
|
||||
def missing_list_advice(plat: str, again: str, ref: str) -> str:
|
||||
"""What to do when the revision asked for has no file list for plat:
|
||||
the name was checked before any request, so the revision is the cause."""
|
||||
if ref != DEFAULT_RELEASE_REF:
|
||||
return (f"RETROBIOS_REF={ref} has no list for {plat}: unset it, or pick a "
|
||||
"newer tag from https://github.com/Abdess/retrobios/releases.")
|
||||
return f"The repository may be moving its files: {again} in a few minutes."
|
||||
|
||||
|
||||
def load_manifest(plat: str, attempts: int = MAX_RETRIES, timeout: float | None = None) -> dict:
|
||||
"""The file list of plat: the one this run was given, else downloaded.
|
||||
ListFailure when it cannot be had."""
|
||||
if LOCAL.manifest is not None:
|
||||
path = str(LOCAL.manifest)
|
||||
try:
|
||||
return _validate_manifest(read_local_json(LOCAL.manifest, MAX_MANIFEST_BYTES), plat)
|
||||
except OSError as exc:
|
||||
raise ListFailure(ListProblem(plat, "unreadable", str(exc.strerror or exc),
|
||||
source="file", where=path)) from exc
|
||||
except ValueError as exc:
|
||||
raise ListFailure(ListProblem(plat, "invalid", str(exc), source="file", where=path)) from exc
|
||||
if LOCAL.pack is not None:
|
||||
try:
|
||||
return _validate_manifest(LOCAL.pack.manifest(plat), plat)
|
||||
except ValueError as exc:
|
||||
raise ListFailure(ListProblem(plat, "invalid", str(exc), source="pack",
|
||||
where=LOCAL.pack.name)) from exc
|
||||
remote = active_remote()
|
||||
url = remote.manifest_url.format(platform=plat)
|
||||
try:
|
||||
return _validate_manifest(_fetch_json(url, MAX_MANIFEST_BYTES, "file list",
|
||||
attempts=attempts, timeout=timeout), plat)
|
||||
except (ValueError, OSError) as exc:
|
||||
raise _download_failure(plat, url, remote, exc) from exc
|
||||
|
||||
|
||||
def invalid_list_words(failure: ListProblem) -> str:
|
||||
"""A file list that arrived and is not one, in line mode's words."""
|
||||
if failure.garbled:
|
||||
# The parser's "Expecting value: line 1 column 1" told no one
|
||||
# anything, where the full screen names the usual cause.
|
||||
return ("what arrived is not a file list: a Wi-Fi sign-in page or a cut "
|
||||
"download looks like this")
|
||||
return f"the file list is not valid: {failure.words}"
|
||||
|
||||
|
||||
def _manifest_event(failure: ListProblem) -> tuple[str, str] | None:
|
||||
"""The reason and message of the error event line mode writes, if any."""
|
||||
code, words = failure.code, failure.words
|
||||
if failure.source != "network":
|
||||
return ("invalid", f"the file list is not valid: {words}") \
|
||||
if failure.source == "file" and code == "invalid" else None
|
||||
if code == "invalid":
|
||||
return code, invalid_list_words(failure)
|
||||
if code == "http":
|
||||
return ("not_found" if failure.status == 404 else "network",
|
||||
f"the file list could not be fetched: HTTP {failure.status}")
|
||||
return code, words if code != "network" else f"the file list could not be fetched: {words}"
|
||||
|
||||
|
||||
def _manifest_local_lines(failure: ListProblem) -> list[str]:
|
||||
where, words = failure.where, failure.words
|
||||
if failure.source == "pack":
|
||||
return [f" The file list in {where} is not valid: {words}"]
|
||||
if failure.code == "unreadable":
|
||||
return [f" Cannot read the file list {where}: {words}."]
|
||||
return [f" The file list {where} is not valid for {failure.plat}: {words}"]
|
||||
|
||||
|
||||
def manifest_failure_lines(failure: ListProblem) -> list[str]:
|
||||
"""What line mode prints of a file list it could not have."""
|
||||
if failure.source != "network":
|
||||
return _manifest_local_lines(failure)
|
||||
plat, code, words = failure.plat, failure.code, failure.words
|
||||
address = _address_lines(failure.where, failure.overridden)
|
||||
if code == "invalid":
|
||||
lines = [f" For {display_name(plat)}, {invalid_list_words(failure)}."]
|
||||
if failure.garbled:
|
||||
lines += [*address, " Check the connection (sign in to the Wi-Fi if it asks), "
|
||||
"then run the same command again."]
|
||||
return lines
|
||||
if code == "http" and failure.status == 404:
|
||||
if failure.overridden:
|
||||
return [f" No file list for {plat} there.", *address]
|
||||
# Asked once, a 4xx being final. The name was checked before any
|
||||
# request, so the revision is what has no such list.
|
||||
return [f" No file list for {plat} at {failure.ref}.",
|
||||
f" {missing_list_advice(plat, 'run the same command again', failure.ref)}"]
|
||||
if code == "http":
|
||||
return [f" Could not fetch the file list for {plat}: HTTP {failure.status}",
|
||||
*address, NETWORK_ADVICE]
|
||||
if code == "offline":
|
||||
return [f" No file list for {plat}: {offline_words()}. Give --manifest FILE "
|
||||
f"(a copy of install/{plat}.json) or --from-pack PACK, or run "
|
||||
f"{offline_undo()}."]
|
||||
if code != "network":
|
||||
return [f" Could not fetch the file list for {plat}.", f" {words}."]
|
||||
return [f" Could not fetch the file list for {plat} after {failure.attempts} "
|
||||
f"attempts: {words}", *address, NETWORK_ADVICE]
|
||||
|
||||
|
||||
def fetch_manifest(plat: str) -> dict:
|
||||
"""The file list of plat, or the run stopped on what went wrong, code 1."""
|
||||
try:
|
||||
return load_manifest(plat)
|
||||
except ListFailure as stopped:
|
||||
failure = stopped.problem
|
||||
lines = manifest_failure_lines(failure)
|
||||
# A list given as a file or in a pack that cannot be used ended the
|
||||
# run on code 1 with no event: its words are the message.
|
||||
reason, message = _manifest_event(failure) or (
|
||||
failure.code, " ".join(line.strip() for line in lines))
|
||||
raise Refusal("manifest", reason, plat, *lines, code=failure.fatal,
|
||||
message=message) from None
|
||||
|
||||
|
||||
def _say(lines: list[str]) -> None:
|
||||
for line in lines:
|
||||
print(line, file=sys.stderr)
|
||||
|
||||
|
||||
def _pack_alone(plat: str) -> bool:
|
||||
"""A pack read without a file list for plat: one built before packs
|
||||
carried their install list records the systems of its files only."""
|
||||
return (LOCAL.pack is not None and LOCAL.manifest is None
|
||||
and (LOCAL.pack.install_list or {}).get("platform") != plat)
|
||||
|
||||
|
||||
def fetch_standalone(plat: str, manifest: dict) -> dict:
|
||||
"""What each standalone build reads, for --standalone only: the file
|
||||
beside --manifest (standalone/<platform>.json, where the repository
|
||||
keeps it), else downloaded as the list is. Missing, unreachable or
|
||||
invalid, the run stops on one line, code 1."""
|
||||
beside = (LOCAL.manifest.parent / STANDALONE_DIR / f"{plat}.json"
|
||||
if LOCAL.manifest is not None else None)
|
||||
url = active_remote().standalone_url.format(platform=plat)
|
||||
where = str(beside) if beside is not None and _is_file(beside) else url
|
||||
try:
|
||||
if where != url:
|
||||
data = read_local_json(Path(where), MAX_STANDALONE_BYTES)
|
||||
else:
|
||||
data = _fetch_json(url, MAX_STANDALONE_BYTES, "standalone layout")
|
||||
return _check_standalone_layouts(data, manifest, plat)
|
||||
except urllib.error.HTTPError as exc:
|
||||
problem = f"HTTP {exc.code}"
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
problem = (str(exc) if isinstance(exc, _Offline)
|
||||
else exc.strerror or str(exc) if where != url
|
||||
else network_words(exc)[1])
|
||||
except ValueError as exc:
|
||||
problem = f"not valid: {exc}"
|
||||
raise Refusal("manifest", "unavailable", plat,
|
||||
f"Error: --standalone needs {where}, which could not be read ({problem}).",
|
||||
message=f"--standalone needs {where}: {problem}")
|
||||
|
||||
|
||||
def held_targets(plat: str) -> dict | None:
|
||||
"""The cores per board this run has without the network: the list the
|
||||
pack carries, else targets/<platform>.json beside --manifest, where the
|
||||
repository keeps it (install/targets/). None when there is neither,
|
||||
ListFailure, code 1, when the file beside --manifest cannot be used:
|
||||
read as absent, the offline run asked for the file already there."""
|
||||
if LOCAL.pack is not None and LOCAL.pack.targets is not None \
|
||||
and plat in LOCAL.pack.platforms():
|
||||
return LOCAL.pack.targets
|
||||
if LOCAL.manifest is None:
|
||||
return None
|
||||
beside = LOCAL.manifest.parent / "targets" / f"{plat}.json"
|
||||
if not _is_file(beside):
|
||||
return None
|
||||
try:
|
||||
return _validate_targets(read_local_json(beside, MAX_TARGETS_BYTES))
|
||||
except OSError as exc:
|
||||
raise ListFailure(ListProblem(plat, "unreadable", str(exc.strerror or exc), source="file",
|
||||
where=str(beside))) from exc
|
||||
except ValueError as exc:
|
||||
raise ListFailure(ListProblem(plat, "invalid", str(exc), source="file", where=str(beside))) from exc
|
||||
|
||||
|
||||
def local_targets(plat: str) -> dict | None:
|
||||
"""held_targets, the run stopped on a file beside --manifest it cannot use."""
|
||||
try:
|
||||
return held_targets(plat)
|
||||
except ListFailure as stopped:
|
||||
raise _targets_refusal(stopped.problem) from None
|
||||
|
||||
|
||||
def load_targets(plat: str, attempts: int = MAX_RETRIES,
|
||||
timeout: float | None = None) -> dict:
|
||||
"""The target core list: the one this run has at hand, else downloaded.
|
||||
|
||||
Empty on 404, where the platform publishes no targets. ListFailure when
|
||||
the list could not be read: a timeout says nothing about the platform,
|
||||
and answering "no targets" for it sent users to the full pack. A run
|
||||
without the network and with no list at hand fails with code 2, before
|
||||
any file is written. A list the network did not bring lets the run go
|
||||
on (fatal 0).
|
||||
"""
|
||||
held = held_targets(plat)
|
||||
if held is not None:
|
||||
return held
|
||||
if LOCAL.offline and plat not in TARGET_PLATFORMS:
|
||||
return {}
|
||||
if LOCAL.offline:
|
||||
source = (f"{LOCAL.pack.name} carries none" if LOCAL.pack is not None
|
||||
else f"{offline_named()} makes no request")
|
||||
raise ListFailure(ListProblem(plat, "offline", source, fatal=2))
|
||||
remote = active_remote()
|
||||
url = remote.targets_url.format(platform=plat)
|
||||
try:
|
||||
return _validate_targets(_fetch_json(url, MAX_TARGETS_BYTES, "target list",
|
||||
attempts=attempts, timeout=timeout))
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return {}
|
||||
raise _download_failure(plat, url, remote, exc, fatal=0) from exc
|
||||
except (ValueError, OSError) as exc:
|
||||
raise _download_failure(plat, url, remote, exc, fatal=0) from exc
|
||||
|
||||
|
||||
def targets_file_words(failure: ListProblem) -> str:
|
||||
"""Why the board list beside --manifest cannot be used, in one clause."""
|
||||
state = "cannot be read" if failure.code == "unreadable" else "is not valid"
|
||||
return f"the target list {failure.where} {state}: {failure.words}"
|
||||
|
||||
|
||||
def targets_failure_lines(failure: ListProblem) -> list[str]:
|
||||
"""What line mode prints of a board list it could not have."""
|
||||
plat, code, words, where = failure.plat, failure.code, failure.words, failure.where
|
||||
if failure.source == "file":
|
||||
return [f" Error: {targets_file_words(failure)}"]
|
||||
if code == "offline":
|
||||
return [f"Error: --target needs the {display_name(plat)} board list ({words}). Put "
|
||||
f"install/targets/{plat}.json beside the --manifest file, or go online."]
|
||||
if code == "invalid":
|
||||
return [f" Error: the target list for {plat} is not valid: {words}"]
|
||||
return [f" Error: failed to fetch targets for {plat}: {words}",
|
||||
*_address_lines(where, failure.overridden), NETWORK_ADVICE]
|
||||
|
||||
|
||||
def _targets_refusal(failure: ListProblem) -> Refusal:
|
||||
"""A board list the run cannot go on without, as the run's refusal."""
|
||||
return Refusal("targets", failure.code, failure.plat, *targets_failure_lines(failure),
|
||||
code=failure.fatal)
|
||||
|
||||
|
||||
def fetch_targets(plat: str, attempts: int = MAX_RETRIES,
|
||||
timeout: float | None = None) -> dict | None:
|
||||
"""load_targets in line mode: what went wrong said, None when the run
|
||||
carries on without the list, the run stopped when it cannot."""
|
||||
try:
|
||||
return load_targets(plat, attempts, timeout)
|
||||
except ListFailure as stopped:
|
||||
if stopped.problem.fatal:
|
||||
raise _targets_refusal(stopped.problem) from None
|
||||
_say(targets_failure_lines(stopped.problem))
|
||||
return None
|
||||
@@ -3,11 +3,13 @@ from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import IO, TYPE_CHECKING
|
||||
|
||||
from installer.console import ReadCounter
|
||||
from installer.host_fs import _held
|
||||
from installer.console import ReadCounter, _live_stdout
|
||||
from installer.host_fs import _held, _is_file
|
||||
from installer.offline import LOCAL
|
||||
from installer.paths import _entry_path
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -164,3 +166,53 @@ def check_local(
|
||||
counter.end()
|
||||
|
||||
return to_download, up_to_date, mismatched
|
||||
|
||||
|
||||
def read_in_place(pairs: list[tuple[dict, Path]]) -> list[str]:
|
||||
"""_classify_local of each (entry, path), read before the line menu as
|
||||
the check after it reads: on --jobs workers, a count moving at a
|
||||
terminal, what is read kept for that check (_HEAD_READS). Each file is
|
||||
read once whatever the question: the head reads the files of the right
|
||||
size only, and the check after Enter reads none of them again."""
|
||||
if not pairs:
|
||||
return []
|
||||
live = _live_stdout()
|
||||
verdicts: list[str] = []
|
||||
last = 0.0
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=LOCAL.jobs) as pool:
|
||||
for done, verdict in enumerate(pool.map(
|
||||
lambda pair: _classify_local(pair[0], pair[1], remember=True), pairs), 1):
|
||||
verdicts.append(verdict)
|
||||
now = time.monotonic()
|
||||
if live and (now - last >= 0.1 or done == len(pairs)):
|
||||
last = now
|
||||
print(f"\r read {done}/{len(pairs)}", end="", flush=True)
|
||||
if live:
|
||||
print("\r\033[K", end="", flush=True)
|
||||
return verdicts
|
||||
|
||||
|
||||
def not_in_place(bios_path: Path, files: list[dict]) -> list[dict]:
|
||||
"""The files a run puts in place: absent, of another size, or of the
|
||||
right size and not the list's. Only a copy of the right size is read,
|
||||
on the check's workers and with its count (read_in_place): judged by
|
||||
its size, a wrong copy of the right size was in place."""
|
||||
|
||||
def held(path: Path, size: object) -> bool:
|
||||
try:
|
||||
return _is_file(path) and path.stat().st_size == size
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
needed, sized = [], []
|
||||
for entry in files:
|
||||
try:
|
||||
path = _entry_path(bios_path, entry)
|
||||
except ValueError:
|
||||
continue
|
||||
if held(path, entry.get("size")):
|
||||
sized.append((entry, path))
|
||||
else:
|
||||
needed.append(entry)
|
||||
return needed + [entry for (entry, _path), verdict in zip(sized, read_in_place(sized))
|
||||
if verdict != "up_to_date"]
|
||||
@@ -11,28 +11,15 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any, NoReturn
|
||||
from typing import Any
|
||||
|
||||
from installer.events import EVENTS
|
||||
from installer.host_fs import _is_file, read_local_json
|
||||
from installer.manifest import _check_standalone_layouts, _validate_manifest, _validate_targets
|
||||
from installer.offline import LOCAL, _Offline, _network_allowed, offline_named, offline_undo, offline_words
|
||||
from installer.platforms import TARGET_PLATFORMS, display_name
|
||||
from installer.offline import _Offline, _network_allowed
|
||||
from installer.remote import (
|
||||
CONNECT_TIMEOUT,
|
||||
DEFAULT_RELEASE_REF,
|
||||
MANIFEST_URL,
|
||||
MAX_MANIFEST_BYTES,
|
||||
MAX_RETRIES,
|
||||
MAX_STANDALONE_BYTES,
|
||||
MAX_TARGETS_BYTES,
|
||||
RELEASE_REF,
|
||||
STANDALONE_DIR,
|
||||
STANDALONE_URL,
|
||||
TARGETS_URL,
|
||||
TROUBLESHOOTING_PAGE,
|
||||
)
|
||||
|
||||
|
||||
@@ -78,25 +65,6 @@ def _read_limited_json(
|
||||
raise ValueError(f"invalid {label}: {exc}") from exc
|
||||
|
||||
|
||||
NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a "
|
||||
"proxy, then run the same command again.\n"
|
||||
f" More help: {TROUBLESHOOTING_PAGE}")
|
||||
|
||||
|
||||
def read_local_manifest(path: Path, plat: str) -> dict:
|
||||
"""A file list saved on disk, checked as a downloaded one is."""
|
||||
try:
|
||||
return _validate_manifest(read_local_json(path, MAX_MANIFEST_BYTES), plat)
|
||||
except OSError as exc:
|
||||
print(f" Cannot read the file list {path}: {exc.strerror or exc}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except ValueError as exc:
|
||||
EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat,
|
||||
message=f"the file list is not valid: {exc}")
|
||||
print(f" The file list {path} is not valid for {plat}: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# The installer was written after this day. A clock that reads earlier is
|
||||
# wrong, and TLS then finds every certificate not yet valid: a handheld
|
||||
# with no clock battery boots on 1970 or 1980.
|
||||
@@ -203,17 +171,17 @@ def network_words(
|
||||
return code, words
|
||||
|
||||
|
||||
def _address_lines(url: str) -> list[str]:
|
||||
OVERRIDE_LINE = (" RETROBIOS_BASE_URL is set in this environment and chose that "
|
||||
"address: unset it to read from the project itself.")
|
||||
|
||||
|
||||
def _address_lines(url: str, overridden: bool) -> list[str]:
|
||||
"""The address that failed, and the override that chose it if one did.
|
||||
|
||||
A RETROBIOS_BASE_URL left from a mirror that is down read as a network
|
||||
fault: neither the host nor the variable was named.
|
||||
"""
|
||||
lines = [f" Address: {url}"]
|
||||
if os.environ.get("RETROBIOS_BASE_URL"):
|
||||
lines.append(" RETROBIOS_BASE_URL is set in this environment and chose that "
|
||||
"address: unset it to read from the project itself.")
|
||||
return lines
|
||||
return [f" Address: {url}", *([OVERRIDE_LINE] if overridden else [])]
|
||||
|
||||
|
||||
def _open_socket(
|
||||
@@ -258,6 +226,24 @@ def install_bounded_opener() -> None:
|
||||
urllib.request.install_opener(urllib.request.build_opener(*handlers))
|
||||
|
||||
|
||||
def request_proxy(url: str) -> str:
|
||||
"""What sends a request for url through a proxy, as urllib's
|
||||
ProxyHandler decides it: the variable naming the proxy for the URL's
|
||||
scheme, "system settings" for one set in the Windows registry or the
|
||||
macOS settings, "" when the request goes direct (none set, or the host
|
||||
bypassed by NO_PROXY or the system's exceptions)."""
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
proxy = urllib.request.getproxies().get(parts.scheme)
|
||||
host = parts.netloc.rpartition("@")[2]
|
||||
if not proxy or (host and urllib.request.proxy_bypass(host)):
|
||||
return ""
|
||||
wanted = f"{parts.scheme}_proxy"
|
||||
# urllib lets the lower-case variable win over the upper-case one.
|
||||
names = sorted((name for name in os.environ if name.lower() == wanted
|
||||
and os.environ[name] == proxy), key=lambda name: name != wanted)
|
||||
return names[0] if names else "system settings"
|
||||
|
||||
|
||||
# The wait for each answer of a file list, its first byte included: a
|
||||
# server that takes the connection and never answers (a captive portal, a
|
||||
# stuck proxy) held the run 93 s on three waits of 30 s. A list is a few
|
||||
@@ -324,212 +310,6 @@ def _fetch_json(
|
||||
raise AssertionError("unreachable")
|
||||
|
||||
|
||||
def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn:
|
||||
"""Stop on a file list that arrived and is not valid."""
|
||||
words = f"the file list is not valid: {exc}"
|
||||
if isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError)):
|
||||
# The parser's "Expecting value: line 1 column 1" told no one
|
||||
# anything, where the full screen names the usual cause.
|
||||
words = ("what arrived is not a file list: a Wi-Fi sign-in page or a cut "
|
||||
"download looks like this")
|
||||
EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat,
|
||||
message=words)
|
||||
print(f" For {display_name(plat)}, {words}.", file=sys.stderr)
|
||||
if words.startswith("what arrived"):
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
print(" Check the connection (sign in to the Wi-Fi if it asks), then run the "
|
||||
"same command again.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def missing_list_advice(plat: str, again: str) -> str:
|
||||
"""What to do when the revision asked for has no file list for plat:
|
||||
the name was checked before any request, so the revision is the cause."""
|
||||
if RELEASE_REF != DEFAULT_RELEASE_REF:
|
||||
return (f"RETROBIOS_REF={RELEASE_REF} has no list for {plat}: unset it, or pick a "
|
||||
"newer tag from https://github.com/Abdess/retrobios/releases.")
|
||||
return f"The repository may be moving its files: {again} in a few minutes."
|
||||
|
||||
|
||||
def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError) -> NoReturn:
|
||||
"""Stop on a file list the server answered with an HTTP error."""
|
||||
EVENTS.emit(
|
||||
"error", stage="manifest", reason="not_found" if exc.code == 404 else "network",
|
||||
platform=plat, message=f"the file list could not be fetched: HTTP {exc.code}",
|
||||
)
|
||||
if exc.code == 404 and os.environ.get("RETROBIOS_BASE_URL"):
|
||||
print(f" No file list for {plat} there.", file=sys.stderr)
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if exc.code == 404:
|
||||
# Asked once, a 4xx being final. The name was checked before any
|
||||
# request, so the revision is what has no such list.
|
||||
print(f" No file list for {plat} at {RELEASE_REF}.", file=sys.stderr)
|
||||
print(f" {missing_list_advice(plat, 'run the same command again')}",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(f" Could not fetch the file list for {plat}: HTTP {exc.code}", file=sys.stderr)
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
print(NETWORK_ADVICE, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn:
|
||||
"""Stop on a file list the network did not bring."""
|
||||
code, words = network_words(exc)
|
||||
EVENTS.emit("error", stage="manifest", reason=code, platform=plat,
|
||||
message=words if code != "network"
|
||||
else f"the file list could not be fetched: {words}")
|
||||
if code == "offline":
|
||||
print(f" No file list for {plat}: {offline_words()}. Give --manifest FILE "
|
||||
f"(a copy of install/{plat}.json) or --from-pack PACK, or run "
|
||||
f"{offline_undo()}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if code != "network":
|
||||
print(f" Could not fetch the file list for {plat}.", file=sys.stderr)
|
||||
print(f" {words}.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
tries = getattr(exc, "attempts", MAX_RETRIES)
|
||||
print(f" Could not fetch the file list for {plat} after {tries} "
|
||||
f"attempts: {words}", file=sys.stderr)
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
print(NETWORK_ADVICE, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_manifest(plat: str) -> dict:
|
||||
"""Download platform manifest JSON, or read the one this run was given."""
|
||||
if LOCAL.manifest is not None:
|
||||
return read_local_manifest(LOCAL.manifest, plat)
|
||||
if LOCAL.pack is not None:
|
||||
try:
|
||||
return _validate_manifest(LOCAL.pack.manifest(plat), plat)
|
||||
except ValueError as exc:
|
||||
print(f" The file list in {LOCAL.pack.name} is not valid: {exc}",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
url = MANIFEST_URL.format(platform=plat)
|
||||
try:
|
||||
return _validate_manifest(_fetch_json(url, MAX_MANIFEST_BYTES, "file list"), plat)
|
||||
except ValueError as exc:
|
||||
_manifest_invalid(plat, url, exc)
|
||||
except urllib.error.HTTPError as exc:
|
||||
_manifest_http_error(plat, url, exc)
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
_manifest_unreachable(plat, url, exc)
|
||||
|
||||
|
||||
def _pack_alone(plat: str) -> bool:
|
||||
"""A pack read without a file list for plat: one built before packs
|
||||
carried their install list records the systems of its files only."""
|
||||
return (LOCAL.pack is not None and LOCAL.manifest is None
|
||||
and (LOCAL.pack.install_list or {}).get("platform") != plat)
|
||||
|
||||
|
||||
def local_targets(plat: str) -> "dict | None":
|
||||
"""The cores per board this run has without the network: the list the
|
||||
pack carries, else targets/<platform>.json beside --manifest, where the
|
||||
repository keeps it (install/targets/). None when there is neither."""
|
||||
if LOCAL.pack is not None and LOCAL.pack.targets is not None \
|
||||
and plat in LOCAL.pack.platforms():
|
||||
return LOCAL.pack.targets
|
||||
if LOCAL.manifest is None:
|
||||
return None
|
||||
beside = LOCAL.manifest.parent / "targets" / f"{plat}.json"
|
||||
if not _is_file(beside):
|
||||
return None
|
||||
try:
|
||||
return _validate_targets(read_local_json(beside, MAX_TARGETS_BYTES))
|
||||
except OSError as exc:
|
||||
# Read as absent, the offline run asked for the file already there.
|
||||
print(f" Error: the target list {beside} cannot be read: {exc.strerror or exc}",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except ValueError as exc:
|
||||
print(f" Error: the target list {beside} is not valid: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_standalone(plat: str, manifest: dict) -> dict:
|
||||
"""What each standalone build reads, for --standalone only: the file
|
||||
beside --manifest (standalone/<platform>.json, where the repository
|
||||
keeps it), else downloaded as the list is. Missing, unreachable or
|
||||
invalid, the run stops on one line, code 1."""
|
||||
beside = (LOCAL.manifest.parent / STANDALONE_DIR / f"{plat}.json"
|
||||
if LOCAL.manifest is not None else None)
|
||||
url = STANDALONE_URL.format(platform=plat)
|
||||
where = str(beside) if beside is not None and _is_file(beside) else url
|
||||
try:
|
||||
if where != url:
|
||||
data = read_local_json(Path(where), MAX_STANDALONE_BYTES)
|
||||
else:
|
||||
data = _fetch_json(url, MAX_STANDALONE_BYTES, "standalone layout")
|
||||
return _check_standalone_layouts(data, manifest, plat)
|
||||
except urllib.error.HTTPError as exc:
|
||||
problem = f"HTTP {exc.code}"
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
problem = (str(exc) if isinstance(exc, _Offline)
|
||||
else exc.strerror or str(exc) if where != url
|
||||
else network_words(exc)[1])
|
||||
except ValueError as exc:
|
||||
problem = f"not valid: {exc}"
|
||||
EVENTS.emit("error", stage="manifest", reason="unavailable", platform=plat,
|
||||
message=f"--standalone needs {where}: {problem}")
|
||||
print(f"Error: --standalone needs {where}, which could not be read ({problem}).",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_targets(plat: str, attempts: int = MAX_RETRIES,
|
||||
timeout: float | None = None) -> "dict | None":
|
||||
"""The target core list: the one this run has at hand, else downloaded.
|
||||
|
||||
Empty on 404, where the platform publishes no targets. None when the list
|
||||
could not be read: a timeout says nothing about the platform, and
|
||||
answering "no targets" for it sent users to the full pack. A run without
|
||||
the network and with no list at hand is refused, code 2, before any
|
||||
file is written.
|
||||
"""
|
||||
held = local_targets(plat)
|
||||
if held is not None:
|
||||
return held
|
||||
if LOCAL.offline and plat not in TARGET_PLATFORMS:
|
||||
return {}
|
||||
if LOCAL.offline:
|
||||
source = (f"{LOCAL.pack.name} carries none" if LOCAL.pack is not None
|
||||
else f"{offline_named()} makes no request")
|
||||
print(f"Error: --target needs the {display_name(plat)} board list ({source}). Put "
|
||||
f"install/targets/{plat}.json beside the --manifest file, or go online.",
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
url = TARGETS_URL.format(platform=plat)
|
||||
try:
|
||||
return _validate_targets(_fetch_json(url, MAX_TARGETS_BYTES, "target list",
|
||||
attempts=attempts, timeout=timeout))
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return {}
|
||||
print(f" Error: failed to fetch targets for {plat}: {exc}", file=sys.stderr)
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
print(NETWORK_ADVICE, file=sys.stderr)
|
||||
return None
|
||||
except ValueError as exc:
|
||||
print(f" Error: the target list for {plat} is not valid: {exc}", file=sys.stderr)
|
||||
return None
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
print(f" Error: failed to fetch targets for {plat}: "
|
||||
f"{network_words(exc)[1]}", file=sys.stderr)
|
||||
for line in _address_lines(url):
|
||||
print(line, file=sys.stderr)
|
||||
print(NETWORK_ADVICE, file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _retry_delay(attempt: int, retry_after: str | None) -> float:
|
||||
"""Seconds before the next attempt: what the server asks, else 1, 2, 4."""
|
||||
if retry_after:
|
||||
|
||||
@@ -17,12 +17,12 @@ from installer.destination import on_its_card
|
||||
from installer.detect_os import detected_os
|
||||
from installer.host_fs import DRIVE_FULL, NOT_WRITABLE, READ_ONLY, _held
|
||||
from installer.invocation import _INVOCATION
|
||||
from installer.network import _address_lines
|
||||
from installer.network import OVERRIDE_LINE
|
||||
from installer.offline import LOCAL, OFFLINE_WORDS, _offline_only, offline_named, offline_undo
|
||||
from installer.pack_source import NOT_IN_PACK
|
||||
from installer.paths import shown_path
|
||||
from installer.platforms import display_name
|
||||
from installer.remote import BASE_URL, TROUBLESHOOTING_PAGE
|
||||
from installer.remote import TROUBLESHOOTING_PAGE, active_remote
|
||||
from installer.romm import ROMM_SCAN_WORDS
|
||||
from installer.safe_replace import BACKUP_DIR, KEPT, NOT_KEPT, _kept_lines
|
||||
from installer.tally import _omission_lines, installed_words, needed_absent_words
|
||||
@@ -172,8 +172,8 @@ def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]:
|
||||
return []
|
||||
more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else ""
|
||||
lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."]
|
||||
if os.environ.get("RETROBIOS_BASE_URL"):
|
||||
return lines + _address_lines(refused[0].url)[1:]
|
||||
if active_remote().overridden:
|
||||
return [*lines, OVERRIDE_LINE]
|
||||
return lines + [" The file list names files the server does not hold, and running "
|
||||
"again changes nothing until the two match.",
|
||||
f" More help: {TROUBLESHOOTING_PAGE}"]
|
||||
@@ -279,9 +279,9 @@ def _failure_advice(
|
||||
advice += _http_failure_lines(failures)
|
||||
if any(isinstance(reason, NetworkReason) for _dest, reason in failures):
|
||||
advice.append(NETWORK_FAILURE_ADVICE)
|
||||
if os.environ.get("RETROBIOS_BASE_URL"):
|
||||
if active_remote().overridden:
|
||||
# A mirror that is down read as this machine's connection.
|
||||
advice += _address_lines(BASE_URL)[1:]
|
||||
advice.append(OVERRIDE_LINE)
|
||||
if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures):
|
||||
# The same run fails the same way: "retry only those" sent a phone
|
||||
# user round the loop with nothing changed.
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -26,7 +24,7 @@ from installer.events import EVENTS
|
||||
from installer.filesystems import fat32_drive
|
||||
from installer.from_folders import plan_local_copies
|
||||
from installer.host_fs import DRIVE_FULL, _drive_full, _is_dir, _stop
|
||||
from installer.network import fetch_targets, local_targets
|
||||
from installer.lists import ListFailure, held_targets, load_targets, targets_file_words
|
||||
from installer.offline import LOCAL
|
||||
from installer.pack_source import (
|
||||
_PART_FILE,
|
||||
@@ -627,13 +625,18 @@ def _listed_paths(folder: Path) -> list[Path]:
|
||||
def _pack_targets(plat: str) -> dict | None:
|
||||
"""The cores per board the pack carries, as a pack built by the
|
||||
repository does: the list at hand offline, else the one fetched. None
|
||||
for a platform that publishes none, or a list that cannot be read."""
|
||||
for a platform that publishes none, or a list the network did not
|
||||
bring. ListFailure for a list this run was given and cannot use."""
|
||||
if plat not in TARGET_PLATFORMS:
|
||||
return None
|
||||
if LOCAL.offline:
|
||||
return local_targets(plat)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
return fetch_targets(plat)
|
||||
return held_targets(plat)
|
||||
try:
|
||||
return load_targets(plat)
|
||||
except ListFailure as stopped:
|
||||
if stopped.problem.fatal:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def _pack_event(plat: str, path: Path, members: dict[str, tuple[str, int]],
|
||||
@@ -692,8 +695,15 @@ def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[di
|
||||
members, rows, sources = pack_layout(files, data_dirs)
|
||||
if not members:
|
||||
return _pack_refused(plat, path, "the choice keeps no file to put in a pack", 2)
|
||||
try:
|
||||
targets = _pack_targets(plat)
|
||||
except ListFailure as stopped:
|
||||
failure = stopped.problem
|
||||
words = (targets_file_words(failure) if failure.source == "file" else
|
||||
f"the board list for {display} could not be read: {failure.words}")
|
||||
return _pack_refused(plat, path, words, failure.fatal, members)
|
||||
body = pack_manifest(plat, pack_install_list(manifest, files, omitted, data_dirs), rows,
|
||||
_pack_targets(plat))
|
||||
targets)
|
||||
planned = [PackMember(name, sha1, size, Path())
|
||||
for name, (sha1, size) in sorted(members.items())]
|
||||
fat = fat32_drive(path.parent)
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
"""The plan shown before a download: what comes, its size and the space it needs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import sys
|
||||
from collections.abc import Collection
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.datadirs import data_fetch_bytes
|
||||
from installer.host_fs import _exists
|
||||
from installer.events import EVENTS
|
||||
from installer.invocation import _INVOCATION
|
||||
from installer.narrowing import _filter_by_target
|
||||
from installer.offline import LOCAL, _offline_only, offline_named, offline_undo
|
||||
@@ -16,6 +14,8 @@ from installer.outcome import EVERYTHING_IN_PLACE
|
||||
from installer.paths import shown_path
|
||||
from installer.plan_words import _sized
|
||||
from installer.platforms import OTHER_TITLE, entry_systems, system_title
|
||||
from installer.refusal import Refusal
|
||||
from installer.space import space_shortfall
|
||||
from installer.tally import _bytes, parts_words, tally
|
||||
from installer.terminal import terminal_size
|
||||
from installer.text import _plural, cell_width, format_size
|
||||
@@ -243,31 +243,27 @@ def _check_free_space(bios_path: Path, needed: int, plat: str = "", code: int =
|
||||
the status a script reads as "nothing installed", 1 after an earlier
|
||||
platform of the run installed files.
|
||||
"""
|
||||
probe = bios_path
|
||||
while not _exists(probe) and probe != probe.parent:
|
||||
probe = probe.parent
|
||||
try:
|
||||
free = shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
shortfall = space_shortfall(bios_path, needed)
|
||||
if shortfall is None:
|
||||
return
|
||||
if free >= needed:
|
||||
return
|
||||
print(f"\nNot enough space on the drive holding {bios_path}.", file=sys.stderr)
|
||||
print(f" Needed: {format_size(needed)}. Free: {format_size(free)}.",
|
||||
file=sys.stderr)
|
||||
free = shortfall[1]
|
||||
EVENTS.emit("no_space", platform=plat, folder=str(bios_path), bytes_needed=needed,
|
||||
bytes_free=free)
|
||||
lines = [f"\nNot enough space on the drive holding {bios_path}.",
|
||||
f" Needed: {format_size(needed)}. Free: {format_size(free)}."]
|
||||
if card:
|
||||
# Its system reads this card alone: another drive, with RetroArch's
|
||||
# list, was offered for an Onion card.
|
||||
print(f" Free up {format_size(needed - free)} on the card, then run it again: "
|
||||
"its system reads its BIOS files there only.", file=sys.stderr)
|
||||
sys.exit(code)
|
||||
if not plat:
|
||||
print(f" Free up {format_size(needed - free)}, or use --dest to install "
|
||||
"to another drive.", file=sys.stderr)
|
||||
sys.exit(code)
|
||||
# --dest alone used to mean RetroArch's list: the platform is named, so
|
||||
# a Batocera install moved to a USB drive stays Batocera's.
|
||||
print(f" Free up {format_size(needed - free)}, or install to another drive:\n"
|
||||
f" {_INVOCATION.command(plat, '<folder on another drive>')}",
|
||||
file=sys.stderr)
|
||||
sys.exit(code)
|
||||
lines.append(f" Free up {format_size(needed - free)} on the card, then run it "
|
||||
"again: its system reads its BIOS files there only.")
|
||||
elif not plat:
|
||||
lines.append(f" Free up {format_size(needed - free)}, or use --dest to install "
|
||||
"to another drive.")
|
||||
else:
|
||||
# --dest alone used to mean RetroArch's list: the platform is named, so
|
||||
# a Batocera install moved to a USB drive stays Batocera's.
|
||||
lines.append(f" Free up {format_size(needed - free)}, or install to another "
|
||||
f"drive:\n {_INVOCATION.command(plat, '<folder on another drive>')}")
|
||||
raise Refusal("space", "drive_full", plat, *lines, code=code,
|
||||
message=f"Not enough space on the drive holding {bios_path}: "
|
||||
f"{format_size(needed)} needed, {format_size(free)} free.")
|
||||
@@ -1,19 +1,21 @@
|
||||
"""What a plan says on the line and on the screen: sizes, systems kept, space and folders."""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from collections.abc import Collection
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.choices import GamesChoice, available_choices, recorded_axes
|
||||
from installer.destination import shown_bios_folder
|
||||
from installer.host_fs import _exists, _folder_writable, _nearest_folder
|
||||
from installer.datadirs import data_directory_state
|
||||
from installer.host_fs import _exists, _folder_writable
|
||||
from installer.local_check import not_in_place
|
||||
from installer.manifest import GAME_DATA, OTHER_SYSTEMS
|
||||
from installer.narrowing import _chosen, narrow
|
||||
from installer.outcome import _on_read_only_mount, write_remedy
|
||||
from installer.paths import _entry_path
|
||||
from installer.platforms import entry_systems, system_title
|
||||
from installer.space import bytes_written, free_space
|
||||
from installer.tally import game_data_missing, sized_words, tally
|
||||
from installer.text import _names_and, _no_widow, _wrap, cell_width, format_size
|
||||
|
||||
@@ -149,35 +151,37 @@ def systems_in_order(systems: list[str], files: list[dict], manifest: dict | Non
|
||||
in_place(system), system_title(system, manifest).casefold()))
|
||||
|
||||
|
||||
def _space_short(bios_path: Path, files: list[dict]) -> tuple[int, int] | None:
|
||||
"""(bytes needed, bytes free) when the files absent from the folder do
|
||||
not fit on its drive, None when they fit or it cannot be told. The
|
||||
screen's plan warns of this before Install, line mode only after Enter."""
|
||||
probe = _nearest_folder(bios_path)
|
||||
try:
|
||||
free = shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
def _space_short(bios_path: Path, files: list[dict],
|
||||
trees: Collection[dict] = ()) -> tuple[int, int] | None:
|
||||
"""(bytes needed, bytes free) when what the run writes (bytes_written:
|
||||
the files not in place, missing or replaced, and the data trees) does
|
||||
not fit on the folder's drive, None when it fits or it cannot be told.
|
||||
Counted as the run's refusal counts it: the absent files alone said
|
||||
nothing of a run that then stopped for space after Enter."""
|
||||
free = free_space(bios_path)
|
||||
if free is None:
|
||||
return None
|
||||
needed = 0
|
||||
for entry in files:
|
||||
try:
|
||||
where = _entry_path(bios_path, entry)
|
||||
except ValueError:
|
||||
continue
|
||||
if not _exists(where):
|
||||
needed += entry.get("size", 0)
|
||||
# Every file and every tree file written: what fits so needs no read.
|
||||
if bytes_written(files, [(tree, (bios_path, tree.get("files") or {}, 0))
|
||||
for tree in trees]) <= free:
|
||||
return None
|
||||
needed = bytes_written(not_in_place(bios_path, files),
|
||||
[(tree, data_directory_state(tree, bios_path, remember=True))
|
||||
for tree in trees])
|
||||
return (needed, free) if needed > free else None
|
||||
|
||||
|
||||
def folder_warnings(plat: str, bios_path: Path, files: list[dict], hint: Invocation,
|
||||
commands: bool = True, card: bool = False) -> list[str]:
|
||||
"""What the plan says of a folder the files cannot go to, before the
|
||||
question that installs them: the folder refused, or too small. card is
|
||||
a setup that runs from that card, whose own folder is the one it reads."""
|
||||
commands: bool = True, card: bool = False,
|
||||
trees: Collection[dict] = ()) -> list[str]:
|
||||
"""What the plan says of a folder the files and the data trees cannot go
|
||||
to, before the question that installs them: the folder refused, or too
|
||||
small. card is a setup that runs from that card, whose own folder is the
|
||||
one it reads."""
|
||||
lines = []
|
||||
if not _folder_writable(bios_path):
|
||||
lines += cannot_write_words(bios_path, plat, hint, commands, card)
|
||||
short = _space_short(bios_path, files)
|
||||
short = _space_short(bios_path, files, trees)
|
||||
if short is not None:
|
||||
lines.append(space_words(short[0], short[1], card))
|
||||
return lines
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import NoReturn
|
||||
|
||||
from installer.embedded import _EMBEDDED_RULES, _NO_FOLDER
|
||||
from installer.events import EVENTS
|
||||
from installer.manifest import OTHER_SYSTEMS
|
||||
from installer.refusal import Refusal
|
||||
|
||||
# The platforms that publish a core list per board, install/targets/ in the
|
||||
# repository: a test holds the two equal. Offline, a platform outside it
|
||||
@@ -197,14 +196,7 @@ def refuse_name(platform: str, *lines: str) -> NoReturn:
|
||||
2, as for an option argparse refuses: 1 also means --check found files
|
||||
to fetch, and a script reading it reran the install on a typo forever.
|
||||
"""
|
||||
message = " ".join(line.strip() for line in lines)
|
||||
if message.startswith("Error: "):
|
||||
message = message[len("Error: "):]
|
||||
EVENTS.emit("error", stage="option", reason="unknown", platform=platform,
|
||||
message=message)
|
||||
for line in lines:
|
||||
print(line, file=sys.stderr)
|
||||
sys.exit(2)
|
||||
raise Refusal("option", "unknown", platform, *lines, code=2)
|
||||
|
||||
|
||||
# Frontends and systems that keep no BIOS folder of their own: each
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""A refusal that ends the run, raised where it is decided and reported once by the command."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from installer.events import EVENTS
|
||||
|
||||
|
||||
class Refusal(SystemExit):
|
||||
"""The run refused, with the error event a script reads and the lines a
|
||||
person reads. Each site printed its lines and chose on its own whether
|
||||
--events got the reason, and several did not: a script learned code 1
|
||||
and nothing else. message is the event's, by default the lines joined
|
||||
without their leading "Error: "."""
|
||||
|
||||
def __init__(self, stage: str, reason: str, platform: str, *lines: str,
|
||||
code: int = 1, message: str | None = None) -> None:
|
||||
super().__init__(code)
|
||||
self.stage, self.reason, self.platform = stage, reason, platform
|
||||
self.lines = lines
|
||||
if message is None:
|
||||
message = " ".join(line.strip() for line in lines)
|
||||
if message.startswith("Error: "):
|
||||
message = message[len("Error: "):]
|
||||
self.message = message
|
||||
self.reported = False
|
||||
|
||||
def report(self) -> None:
|
||||
"""The error event, then the lines on stderr, once."""
|
||||
if self.reported:
|
||||
return
|
||||
self.reported = True
|
||||
EVENTS.emit("error", stage=self.stage, reason=self.reason, platform=self.platform,
|
||||
message=self.message)
|
||||
for line in self.lines:
|
||||
print(line, file=sys.stderr)
|
||||
@@ -1,26 +1,29 @@
|
||||
"""Where file lists and files come from, the pages the installer names, and bounds on what it reads."""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
from collections.abc import Iterator
|
||||
from typing import NamedTuple
|
||||
|
||||
# File lists are read from main, the newest ones, whichever commit the
|
||||
# installer came from. RETROBIOS_REF pins them to a tag or a commit when
|
||||
# reproducibility matters.
|
||||
DEFAULT_RELEASE_REF = "main"
|
||||
RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF)
|
||||
DEFAULT_BASE_URL = (
|
||||
"https://raw.githubusercontent.com/Abdess/retrobios/"
|
||||
+ urllib.parse.quote(RELEASE_REF, safe="")
|
||||
)
|
||||
|
||||
|
||||
def default_base_url(ref: str) -> str:
|
||||
"""The project's own address for the file lists of ref."""
|
||||
return ("https://raw.githubusercontent.com/Abdess/retrobios/"
|
||||
+ urllib.parse.quote(ref, safe=""))
|
||||
|
||||
|
||||
_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1")
|
||||
|
||||
|
||||
def _checked_base_url(value: str) -> str:
|
||||
"""Refuse a base URL that is neither HTTPS nor loopback.
|
||||
"""Refuse a base URL that is neither HTTPS nor loopback, as ValueError.
|
||||
|
||||
This base serves the manifest and the files it declares, so whoever
|
||||
controls it controls the expected hashes too and verification stops
|
||||
@@ -36,22 +39,69 @@ def _checked_base_url(value: str) -> str:
|
||||
host = (parsed.hostname or "").lower()
|
||||
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
|
||||
return value
|
||||
print(
|
||||
f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
raise ValueError(f"RETROBIOS_BASE_URL must use HTTPS, got {value!r}")
|
||||
|
||||
|
||||
BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL))
|
||||
MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json"
|
||||
TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json"
|
||||
# What --standalone reads, apart from the list every run downloads.
|
||||
STANDALONE_DIR = "standalone"
|
||||
STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json"
|
||||
|
||||
|
||||
RAW_FILE_URL = f"{BASE_URL}/{{path}}"
|
||||
class Remote(NamedTuple):
|
||||
"""Where a run reads its lists and files: the revision, the base
|
||||
address, and whether RETROBIOS_BASE_URL chose that base."""
|
||||
|
||||
ref: str
|
||||
base: str
|
||||
overridden: bool
|
||||
|
||||
@property
|
||||
def manifest_url(self) -> str:
|
||||
return f"{self.base}/install/{{platform}}.json"
|
||||
|
||||
@property
|
||||
def targets_url(self) -> str:
|
||||
return f"{self.base}/install/targets/{{platform}}.json"
|
||||
|
||||
@property
|
||||
def standalone_url(self) -> str:
|
||||
return f"{self.base}/install/{STANDALONE_DIR}/{{platform}}.json"
|
||||
|
||||
@property
|
||||
def raw_file_url(self) -> str:
|
||||
return f"{self.base}/{{path}}"
|
||||
|
||||
|
||||
def remote_from_env() -> Remote:
|
||||
"""The remote RETROBIOS_REF and RETROBIOS_BASE_URL name, ValueError for
|
||||
a base that is neither HTTPS nor loopback. A variable set but empty is
|
||||
unset, as every other reading of them takes it."""
|
||||
ref = os.environ.get("RETROBIOS_REF") or DEFAULT_RELEASE_REF
|
||||
override = os.environ.get("RETROBIOS_BASE_URL") or ""
|
||||
if override:
|
||||
return Remote(ref, _checked_base_url(override), True)
|
||||
return Remote(ref, default_base_url(ref), False)
|
||||
|
||||
|
||||
# The remote main resolved, for the length of its run.
|
||||
_IN_USE: list[Remote] = []
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def remote_in_use(remote: Remote) -> Iterator[None]:
|
||||
"""remote answers active_remote() until the block ends."""
|
||||
_IN_USE.append(remote)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_IN_USE.pop()
|
||||
|
||||
|
||||
def active_remote() -> Remote:
|
||||
"""The remote of this run: the one main resolved, else the one the
|
||||
environment names now, for a caller that did not come through main."""
|
||||
return _IN_USE[-1] if _IN_USE else remote_from_env()
|
||||
|
||||
|
||||
RELEASE_URL = (
|
||||
"https://github.com/Abdess/retrobios/releases/download/large-files/{asset}"
|
||||
)
|
||||
|
||||
@@ -10,11 +10,11 @@ import re
|
||||
import stat
|
||||
import sys
|
||||
import urllib.error
|
||||
from collections.abc import Collection, Iterable
|
||||
from collections.abc import Collection, Iterable, Mapping
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import NamedTuple
|
||||
|
||||
from installer.choices import available_choices, emulator_names, resolve_choices
|
||||
from installer.choices import available_choices, emulator_names, resolve_choices, resolve_systems, system_ids
|
||||
from installer.console import QUIT_CODE, _answer_yes
|
||||
from installer.destination import card_dest
|
||||
from installer.detect_frontends import detect_platforms
|
||||
@@ -35,13 +35,15 @@ from installer.install_record import (
|
||||
setup_record,
|
||||
)
|
||||
from installer.invocation import _INVOCATION, offline_requested
|
||||
from installer.lists import fetch_manifest
|
||||
from installer.local_check import _digest_file
|
||||
from installer.manifest import OTHER_SYSTEMS, _validate_manifest, entry_copies
|
||||
from installer.narrowing import designated_cores
|
||||
from installer.network import _fetch_json, fetch_manifest
|
||||
from installer.network import _fetch_json
|
||||
from installer.paths import shown_path, spelled
|
||||
from installer.platforms import display_name, entry_systems, normalize_platform, refuse_name, system_title
|
||||
from installer.remote import MANIFEST_URL, MAX_MANIFEST_BYTES
|
||||
from installer.refusal import Refusal
|
||||
from installer.remote import MAX_MANIFEST_BYTES, active_remote
|
||||
from installer.safe_replace import (
|
||||
BACKUP_DIR,
|
||||
KEPT,
|
||||
@@ -135,14 +137,15 @@ def _choice_names(options: list[tuple[str, str | None]], flag: str) -> list[str]
|
||||
|
||||
|
||||
def _choice_without(choice: list[str], flag: str, names: Collection[str],
|
||||
left: list[str]) -> list[str]:
|
||||
left: list[str], ids: Mapping[str, str] | None = None) -> list[str]:
|
||||
"""A recorded choice once names of flag are taken out: those it named
|
||||
go, and a choice that named none gets the names left. A flag left with
|
||||
no name is dropped."""
|
||||
no name is dropped. ids gives a recorded name the id it stands for."""
|
||||
options = [option for option in record_options(choice) if option[0] != "--all-files"]
|
||||
gone = {name.casefold() for name in names}
|
||||
same = ids or {}
|
||||
remaining = [name for name in (_choice_names(options, flag) or left)
|
||||
if name.casefold() not in gone]
|
||||
if same.get(name, name).casefold() not in gone]
|
||||
kept = [option for option in options if option[0] != flag]
|
||||
if remaining:
|
||||
kept.append((flag, ",".join(remaining)))
|
||||
@@ -162,6 +165,7 @@ class _RemovalScope(NamedTuple):
|
||||
named_cores: list[str]
|
||||
others: dict[tuple[str, str], str]
|
||||
wanted: set[str]
|
||||
system_ids: dict[str, str]
|
||||
|
||||
def norm(self, dest: str) -> str:
|
||||
"""dest as the drive compares it, folded where it folds case."""
|
||||
@@ -188,7 +192,10 @@ def _removal_scope(
|
||||
wanted = {_drive_key(dest, fold) for dest in files}
|
||||
# What stays chosen once the removal is done, as an install names it:
|
||||
# the systems or cores the record named, else every one of the list.
|
||||
named_systems = {name.casefold() for name in _choice_names(options, "--system")}
|
||||
recorded_systems = _choice_names(options, "--system")
|
||||
ids = system_ids(recorded_systems, manifest, list(manifest.get("files") or []),
|
||||
list(manifest.get("omitted_files") or []))
|
||||
named_systems = {ids.get(name, name).casefold() for name in recorded_systems}
|
||||
staying_systems = {name for name in known["systems"] if not named_systems
|
||||
or name.casefold() in named_systems} - chosen_systems
|
||||
named_cores = _choice_names(options, "--core")
|
||||
@@ -196,7 +203,7 @@ def _removal_scope(
|
||||
else set(known["cores"]) | set(manifest.get("core_names") or {})
|
||||
) - chosen_cores
|
||||
return _RemovalScope(fold, known, options, chosen_systems, chosen_cores,
|
||||
staying_systems, staying_cores, named_cores, others, wanted)
|
||||
staying_systems, staying_cores, named_cores, others, wanted, ids)
|
||||
|
||||
|
||||
def _removal_takes(scope: _RemovalScope, found: tuple, dest: str) -> bool:
|
||||
@@ -257,7 +264,8 @@ def _removal_choice(scope: _RemovalScope, recorded: list[str], *, files: Collect
|
||||
return recorded
|
||||
if scope.chosen_systems:
|
||||
choice = _choice_without(recorded, "--system", scope.chosen_systems,
|
||||
sorted(scope.staying_systems | scope.chosen_systems))
|
||||
sorted(scope.staying_systems | scope.chosen_systems),
|
||||
scope.system_ids)
|
||||
if not _choice_names(record_options(choice), "--system"):
|
||||
return None
|
||||
return choice
|
||||
@@ -514,7 +522,7 @@ def _other_setup_list(name: str) -> tuple[dict | None, str]:
|
||||
if offline_requested():
|
||||
return None, "this run is offline: run it again with the internet"
|
||||
try:
|
||||
return _validate_manifest(_fetch_json(MANIFEST_URL.format(platform=name),
|
||||
return _validate_manifest(_fetch_json(active_remote().manifest_url.format(platform=name),
|
||||
MAX_MANIFEST_BYTES, "file list"), name), ""
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
@@ -621,8 +629,9 @@ def _record_after_removal(removal: Removal, removed: list[dict]) -> str:
|
||||
return _update_record(removal.folder, removal.plat, change)
|
||||
|
||||
|
||||
def _named_files(values: Iterable[Path], folder: Path) -> list[str] | None:
|
||||
"""The --file values as dests below folder, None for one outside it."""
|
||||
def _named_files(values: Iterable[Path], folder: Path) -> tuple[list[str], str]:
|
||||
"""The --file values as dests below folder, and why nothing is removed
|
||||
when one is outside it, else ""."""
|
||||
files = []
|
||||
for value in values:
|
||||
given = Path(os.path.expanduser(str(value)))
|
||||
@@ -630,16 +639,17 @@ def _named_files(values: Iterable[Path], folder: Path) -> list[str] | None:
|
||||
try:
|
||||
given = Path(os.path.abspath(given)).relative_to(folder)
|
||||
except ValueError:
|
||||
print(f"Error: {value} is not inside {shown_path(folder)}: --file names a "
|
||||
"file of the BIOS folder.", file=sys.stderr)
|
||||
return None
|
||||
return [], (f"Error: {value} is not inside {shown_path(folder)}: --file "
|
||||
"names a file of the BIOS folder.")
|
||||
files.append(PurePosixPath(*given.parts).as_posix())
|
||||
return files
|
||||
return files, ""
|
||||
|
||||
|
||||
def _removal_refused(plat: str, folder: Path, message: str, backup: bool) -> int:
|
||||
"""A removal that touches nothing: the reason said and sent, exit 2."""
|
||||
print(message, file=sys.stderr)
|
||||
if message.startswith("Error: "):
|
||||
message = message[len("Error: "):]
|
||||
EVENTS.emit("removal_plan", platform=plat, folder=str(folder), files=0, bytes=0,
|
||||
systems=[], dests=[], kept=[], gone=0, backup=backup,
|
||||
message=message)
|
||||
@@ -717,16 +727,16 @@ def _print_removal_plan(args: argparse.Namespace, removal: Removal, by_hand: lis
|
||||
print(f" {rel}")
|
||||
|
||||
|
||||
def _removal_answer(args: argparse.Namespace) -> int | None:
|
||||
def _removal_answer(args: argparse.Namespace, plat: str) -> int | None:
|
||||
"""The exit code when the plan stops before removing, None to go on."""
|
||||
if args.dry_run:
|
||||
print("Nothing was removed (--dry-run).")
|
||||
return 0
|
||||
if not args.yes:
|
||||
if args.no_input or not sys.stdin.isatty():
|
||||
print("Error: removing files needs a yes: add --yes to remove them without "
|
||||
"a question, or --dry-run to list them.", file=sys.stderr)
|
||||
return 2
|
||||
raise Refusal("option", "needs_yes", plat,
|
||||
"Error: removing files needs a yes: add --yes to remove them "
|
||||
"without a question, or --dry-run to list them.", code=2)
|
||||
question = ("Move them to a backup? [y/N] " if args.backup
|
||||
else "Remove them for good? [y/N] ")
|
||||
if not _answer_yes(question):
|
||||
@@ -788,16 +798,15 @@ def run_removal(args: argparse.Namespace) -> int:
|
||||
omitted = list(manifest.get("omitted_files") or [])
|
||||
known = available_choices(every, omitted)
|
||||
try:
|
||||
systems = resolve_choices(args.system, known["systems"], "system") \
|
||||
if args.system else []
|
||||
systems = resolve_systems(args.system or [], manifest, every, omitted)
|
||||
cores = resolve_choices(args.core, known["cores"], "core") if args.core else []
|
||||
emulators = resolve_choices(args.emulator, sorted(emulator_names(
|
||||
manifest, every, omitted)), "emulator") if args.emulator else []
|
||||
except ValueError as exc:
|
||||
refuse_name(plat, f"Error: {plat}: {exc}")
|
||||
files = _named_files(args.file or [], folder)
|
||||
if files is None:
|
||||
return 2
|
||||
files, outside = _named_files(args.file or [], folder)
|
||||
if outside:
|
||||
return _removal_refused(plat, folder, outside, bool(args.backup))
|
||||
misplaced = bool(getattr(args, "misplaced", False))
|
||||
if misplaced:
|
||||
others, message = _misplaced_others(plat, folder, read.dropped, read.data["setups"])
|
||||
@@ -824,7 +833,7 @@ def run_removal(args: argparse.Namespace) -> int:
|
||||
if not removal.remove:
|
||||
# The record keeps what it says until a removal is confirmed.
|
||||
return 2
|
||||
stop = _removal_answer(args)
|
||||
stop = _removal_answer(args, plat)
|
||||
if stop is not None:
|
||||
return stop
|
||||
KEPT.reset()
|
||||
@@ -908,9 +917,9 @@ def run_delete_backup(args: argparse.Namespace) -> int:
|
||||
0 done, 1 a file failed, 2 refused or declined."""
|
||||
run = Path(os.path.abspath(os.path.expanduser(str(args.delete_backup))))
|
||||
if not _is_backup_run(run):
|
||||
print(f"Error: {run} is not a folder the installer kept files in.", file=sys.stderr)
|
||||
print(" Name one of the dated folders --backups lists.", file=sys.stderr)
|
||||
return 2
|
||||
raise Refusal("backup", "not_a_backup", "",
|
||||
f"Error: {run} is not a folder the installer kept files in.",
|
||||
" Name one of the dated folders --backups lists.", code=2)
|
||||
files = _backup_files(run)
|
||||
size = sum(path.stat().st_size for path in files)
|
||||
date = _backup_date(run)
|
||||
@@ -922,9 +931,9 @@ def run_delete_backup(args: argparse.Namespace) -> int:
|
||||
return 0
|
||||
if not args.yes:
|
||||
if args.no_input or not sys.stdin.isatty():
|
||||
print("Error: deleting a backup needs a yes: add --yes to delete it without "
|
||||
"a question.", file=sys.stderr)
|
||||
return 2
|
||||
raise Refusal("option", "needs_yes", "",
|
||||
"Error: deleting a backup needs a yes: add --yes to delete it "
|
||||
"without a question.", code=2)
|
||||
if not _answer_yes("Delete it for good? [y/N] "):
|
||||
print("Nothing was deleted.")
|
||||
return QUIT_CODE
|
||||
@@ -979,20 +988,18 @@ def _action_setup(args: argparse.Namespace) -> tuple[str, Path]:
|
||||
setups = sorted((load_record(folder).data or {}).get("setups") or {})
|
||||
if len(setups) == 1:
|
||||
return setups[0], folder
|
||||
print(f"Error: name the setup of {shown_path(folder)} with --platform"
|
||||
+ (f": {', '.join(setups)}." if setups else "."), file=sys.stderr)
|
||||
sys.exit(2)
|
||||
raise Refusal("detect", "conflict" if setups else "not_found", "",
|
||||
f"Error: name the setup of {shown_path(folder)} with --platform"
|
||||
+ (f": {', '.join(setups)}." if setups else "."), code=2)
|
||||
found = [(name, path) for name, path in detect_platforms(detect_os())
|
||||
if not plat or name == plat]
|
||||
if len(found) == 1:
|
||||
return found[0][0], Path(os.path.abspath(found[0][1]))
|
||||
if not found:
|
||||
print("Error: no setup found here: name its BIOS folder with --dest"
|
||||
+ ("." if plat else " and its setup with --platform."), file=sys.stderr)
|
||||
else:
|
||||
print("Error: several setups found here: name one with --platform and --dest.",
|
||||
file=sys.stderr)
|
||||
for name, path in found:
|
||||
print(f" --platform {name} --dest {_INVOCATION.word(str(path))}",
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
raise Refusal("detect", "not_found", plat,
|
||||
"Error: no setup found here: name its BIOS folder with --dest"
|
||||
+ ("." if plat else " and its setup with --platform."), code=2)
|
||||
raise Refusal("detect", "conflict", plat,
|
||||
"Error: several setups found here: name one with --platform and --dest.",
|
||||
*(f" --platform {name} --dest {_INVOCATION.word(str(path))}"
|
||||
for name, path in found), code=2)
|
||||
@@ -1,12 +1,12 @@
|
||||
"""RomM: where it reads each platform's firmware, and the list laid out under its library."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.console import detail
|
||||
from installer.host_fs import _is_dir
|
||||
from installer.refusal import Refusal
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from installer.run_files import _PlatformPass
|
||||
@@ -133,14 +133,13 @@ def _check_run_romm(run: _InstallRun) -> None:
|
||||
return
|
||||
# Applied or refused, never ignored.
|
||||
if not any(name == "romm" for name, _path in run.platforms):
|
||||
print("Error: --romm-firmware applies to RomM, which this run does not "
|
||||
"install for.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_applicable", "romm",
|
||||
"Error: --romm-firmware applies to RomM, which this run does not "
|
||||
"install for.")
|
||||
try:
|
||||
parse_romm_firmware(args.romm_firmware)
|
||||
except ValueError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None
|
||||
|
||||
|
||||
def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
@@ -149,8 +148,7 @@ def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
try:
|
||||
layout = romm_firmware_layout(bios_path, run.args.romm_firmware)
|
||||
except ValueError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None
|
||||
if layout is not None:
|
||||
p.files, library = romm_relayout(p.files, bios_path, *layout)
|
||||
if library != bios_path:
|
||||
|
||||
@@ -8,7 +8,7 @@ from pathlib import Path
|
||||
from typing import TYPE_CHECKING, TextIO
|
||||
|
||||
from installer.console import OUTPUT, Progress, _confirm, detail
|
||||
from installer.datadirs import data_directory_state, data_fetch_bytes, data_space_bytes, install_data_directory
|
||||
from installer.datadirs import data_directory_state, data_fetch_bytes, install_data_directory
|
||||
from installer.destination import _missing_dest, _refuse_closed, _refuse_file, on_its_card
|
||||
from installer.detect_frontends import launchbox_bios_dirs, launchbox_root
|
||||
from installer.detect_os import detected_shown
|
||||
@@ -57,6 +57,7 @@ from installer.pack_source import NOT_IN_PACK, pack_holds_trees, pack_lacks, pac
|
||||
from installer.paths import _entry_path, shown_path
|
||||
from installer.plan import CONFIRM_FROM_BYTES, _check_free_space, _print_plan, bulk_hint
|
||||
from installer.platforms import display_name
|
||||
from installer.refusal import Refusal
|
||||
from installer.romm import ROMM_SCAN_WORDS, _check_run_romm, _pass_romm_layout
|
||||
from installer.run_files import _select_setup_files
|
||||
from installer.run_setups import (
|
||||
@@ -68,6 +69,7 @@ from installer.run_setups import (
|
||||
_start_install,
|
||||
)
|
||||
from installer.safe_replace import KEPT, NOT_KEPT, plan_kept
|
||||
from installer.space import bytes_written
|
||||
from installer.standalone import do_standalone_copies, standalone_folders_here
|
||||
from installer.tally import (
|
||||
CheckTally,
|
||||
@@ -178,12 +180,17 @@ def _pass_check_existing(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
)
|
||||
|
||||
if EVENTS.on:
|
||||
# What the run would write, as _pass_download holds it against the
|
||||
# free space: the screen's plan warns on this number.
|
||||
lacking = {id(f) for f in pack_lacks([f for f in to_download if id(f) not in copies])}
|
||||
_emit_check(
|
||||
p.plat_name, p.manifest, bios_path,
|
||||
CheckTally(files, up_to_date, mismatched,
|
||||
sum(len(state[1]) for _entry, state in data_states),
|
||||
len(p.omitted_files),
|
||||
sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states)),
|
||||
sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states),
|
||||
bytes_written([f for f in to_download if id(f) not in lacking],
|
||||
data_states)),
|
||||
chosen=selection[0] if selection else None,
|
||||
)
|
||||
emit_copies(p.plat_name, to_download, copies, bios_index, bios_path, files)
|
||||
@@ -401,13 +408,13 @@ def _pass_download_head(run: _InstallRun, p: _PlatformPass, fetched: list[dict],
|
||||
"carries on from here.")
|
||||
|
||||
|
||||
def _pass_make_folder(run: _InstallRun, p: _PlatformPass, dl_size: int) -> bool:
|
||||
def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool:
|
||||
"""The space checked and the BIOS folder made. True when it was created."""
|
||||
args, plat_name, bios_path = run.args, p.plat_name, p.bios_path
|
||||
# Checked before the folder is created: a run stopped for space
|
||||
# left an empty BIOS folder behind. The data trees count too,
|
||||
# written after the files on the same drive.
|
||||
_check_free_space(bios_path, dl_size + data_space_bytes(p.data_states), plat_name,
|
||||
_check_free_space(bios_path, written, plat_name,
|
||||
1 if run.total_downloaded else 2, on_its_card(plat_name, bios_path))
|
||||
p.space_checked = True
|
||||
created = not bios_path.exists()
|
||||
@@ -501,7 +508,8 @@ def _pass_download(run: _InstallRun, p: _PlatformPass) -> str:
|
||||
run.files_pending += len(p.to_download)
|
||||
run.total_up_to_date += len(p.up_to_date)
|
||||
return "next"
|
||||
dl_size = sum(f.get("size", 0) for f in p.to_download if id(f) not in lacking)
|
||||
coming = [f for f in p.to_download if id(f) not in lacking]
|
||||
dl_size = _bytes(coming)
|
||||
fetch_size = _bytes([f for f in fetched if id(f) not in lacking])
|
||||
if not p.to_download:
|
||||
run.total_up_to_date += len(p.up_to_date)
|
||||
@@ -515,7 +523,7 @@ def _pass_download(run: _InstallRun, p: _PlatformPass) -> str:
|
||||
return "next"
|
||||
EVENTS.emit("download", platform=p.plat_name, files=len(p.to_download), bytes=dl_size)
|
||||
_pass_download_head(run, p, fetched, lacking, dl_size)
|
||||
created = _pass_make_folder(run, p, dl_size)
|
||||
created = _pass_make_folder(run, p, bytes_written(coming, p.data_states))
|
||||
return "stop" if _pass_fetch(run, p, dl_size, created) else "go"
|
||||
|
||||
|
||||
@@ -603,7 +611,7 @@ def _pass_data_trees(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
if writable and not p.space_checked:
|
||||
# With every BIOS file in place, the trees alone: checked
|
||||
# before the first archive is written.
|
||||
_check_free_space(p.bios_path, data_space_bytes(writable), p.plat_name,
|
||||
_check_free_space(p.bios_path, bytes_written([], writable), p.plat_name,
|
||||
1 if run.total_downloaded else 2,
|
||||
on_its_card(p.plat_name, p.bios_path))
|
||||
if writable:
|
||||
@@ -755,7 +763,17 @@ def _finish_install(run: _InstallRun, real_stdout: TextIO) -> None:
|
||||
|
||||
|
||||
def _install(args: argparse.Namespace, real_stdout: TextIO) -> None:
|
||||
"""One run of the installer, once the options are read."""
|
||||
"""One run of the installer, once the options are read, a refusal
|
||||
reported where it ends the run: its error event before end, its lines
|
||||
before what the unwinding run says."""
|
||||
try:
|
||||
_install_run(args, real_stdout)
|
||||
except Refusal as refusal:
|
||||
refusal.report()
|
||||
raise
|
||||
|
||||
|
||||
def _install_run(args: argparse.Namespace, real_stdout: TextIO) -> None:
|
||||
run = _start_install(args, real_stdout)
|
||||
|
||||
# Early exit for listing
|
||||
|
||||
@@ -43,11 +43,13 @@ from installer.frontend_folders import (
|
||||
place_relative_entries,
|
||||
place_save_entries,
|
||||
say_saves,
|
||||
say_unplaced,
|
||||
)
|
||||
from installer.games import fallback_lines, read_games
|
||||
from installer.install_record import _RECORD_TAKEN, by_record, drop_recorded, record_menu_words
|
||||
from installer.invocation import _INVOCATION
|
||||
from installer.line_menu import MenuContext, _prompt_custom_selection
|
||||
from installer.lists import ListFailure, fetch_manifest, fetch_targets, load_targets, local_targets, targets_failure_lines
|
||||
from installer.manifest import GAME_DATA
|
||||
from installer.narrowing import (
|
||||
_chosen,
|
||||
@@ -60,7 +62,6 @@ from installer.narrowing import (
|
||||
one_per_slot,
|
||||
truth_lists,
|
||||
)
|
||||
from installer.network import fetch_manifest, fetch_targets, local_targets
|
||||
from installer.offline import LOCAL
|
||||
from installer.pack import _pack_refused, pack_path
|
||||
from installer.paths import shown_path
|
||||
@@ -77,6 +78,7 @@ from installer.plan_words import (
|
||||
unlisted_saves_words,
|
||||
)
|
||||
from installer.platforms import PLATFORM_NAMES, display_name, system_title
|
||||
from installer.refusal import Refusal
|
||||
from installer.tally import (
|
||||
_bytes,
|
||||
_left_out_lines,
|
||||
@@ -173,13 +175,10 @@ def _found_files(args: argparse.Namespace, plat: str,
|
||||
*(f" {match['dest']} {match.get('sha1', '')}" for match in matches)],
|
||||
}.get(result)
|
||||
if lines is not None:
|
||||
EVENTS.emit("error", stage="option", reason="unknown", platform=plat,
|
||||
message=lines[0][len("Error: "):])
|
||||
for line in lines:
|
||||
print(line, file=sys.stderr)
|
||||
# 4: the hash was read and the list holds no one file for it, neither
|
||||
# a failure (1) nor an option refused (2).
|
||||
sys.exit(4)
|
||||
raise Refusal("option", "unknown", plat, *lines, code=4,
|
||||
message=lines[0][len("Error: "):])
|
||||
for match in matches:
|
||||
print(f" {value} is {match['dest']}")
|
||||
return matches, []
|
||||
@@ -257,10 +256,10 @@ def _pass_files(run: _InstallRun, plat_name: str, bios_path: Path) -> _PlatformP
|
||||
p = _PlatformPass(plat_name, bios_path, manifest)
|
||||
if run.args.source == "truth":
|
||||
if manifest.get("truth_files") is None:
|
||||
print(f"Error: the {plat_name} file list does not say what the emulator "
|
||||
"profiles prove is read, which --source truth needs.", file=sys.stderr)
|
||||
print(_older_list_advice(plat_name), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat_name,
|
||||
f"Error: the {plat_name} file list does not say what the emulator "
|
||||
"profiles prove is read, which --source truth needs.",
|
||||
_older_list_advice(plat_name))
|
||||
before = len(p.files)
|
||||
p.files, p.omitted_files = truth_lists(manifest, p.files, p.omitted_files)
|
||||
detail(f" What the emulator profiles prove is read: {before} to "
|
||||
@@ -321,10 +320,9 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool:
|
||||
if args.no_game_data and not p.manifest.get("categorized"):
|
||||
# Without the field nothing is marked, and the run would
|
||||
# install the game data it was asked to leave out.
|
||||
print(f"Error: the {plat_name} file list records no file category, "
|
||||
"which --no-game-data needs.", file=sys.stderr)
|
||||
print(_older_list_advice(plat_name), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat_name,
|
||||
f"Error: the {plat_name} file list records no file category, "
|
||||
"which --no-game-data needs.", _older_list_advice(plat_name))
|
||||
|
||||
if args.declared_only:
|
||||
before = len(p.files)
|
||||
@@ -333,9 +331,7 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool:
|
||||
"(--declared-only)")
|
||||
|
||||
if args.list_targets:
|
||||
targets = fetch_targets(plat_name)
|
||||
if targets is None:
|
||||
sys.exit(1)
|
||||
targets = needed_targets(plat_name)
|
||||
if not targets:
|
||||
print(f" No targets available for {plat_name}")
|
||||
else:
|
||||
@@ -389,13 +385,23 @@ def _pass_target(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
_pass_target_cores(run, p, target)
|
||||
|
||||
|
||||
def needed_targets(plat: str) -> dict:
|
||||
"""The board list a run cannot go on without, its failure the run's refusal."""
|
||||
try:
|
||||
return load_targets(plat)
|
||||
except ListFailure as stopped:
|
||||
# A list the run would carry on without stops this one all the same:
|
||||
# it said why on stderr and ended with code 1, no error event sent.
|
||||
problem = stopped.problem
|
||||
raise Refusal("targets", problem.code, problem.plat,
|
||||
*targets_failure_lines(problem), code=problem.fatal or 1) from None
|
||||
|
||||
|
||||
def _pass_target_cores(run: _InstallRun, p: _PlatformPass, target: str) -> None:
|
||||
"""The files narrowed to the cores the board's list names."""
|
||||
targets = run.target_lists.get(p.plat_name)
|
||||
if targets is None:
|
||||
targets = fetch_targets(p.plat_name)
|
||||
if targets is None:
|
||||
sys.exit(1)
|
||||
targets = needed_targets(p.plat_name)
|
||||
target_info = targets.get(target)
|
||||
if target_info is None:
|
||||
# Carrying on would install every file, which is the opposite
|
||||
@@ -432,13 +438,10 @@ def _pass_installed_cores(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
if not args.installed_cores:
|
||||
return
|
||||
if "system_cores" not in manifest:
|
||||
print(
|
||||
f"Error: the {plat_name} file list does not say which cores "
|
||||
"read which systems, which --installed-cores needs.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(_older_list_advice(plat_name), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat_name,
|
||||
f"Error: the {plat_name} file list does not say which cores "
|
||||
"read which systems, which --installed-cores needs.",
|
||||
_older_list_advice(plat_name))
|
||||
before = len(p.files)
|
||||
info_dests = _unprofiled_cores_firmware(
|
||||
plat_name, bios_path, manifest, found_cores,
|
||||
@@ -490,17 +493,15 @@ def _pass_version_and_saves(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
|
||||
# Before the menu: it offered 23 files, then 22 were checked, the
|
||||
# one read from an unknown save directory left out. Said once the
|
||||
# choice is made, over the files it keeps (say_saves).
|
||||
# choice is made, over the files it keeps (say_saves, say_unplaced).
|
||||
p.display = display = display_name(plat_name, manifest)
|
||||
if not run.packing:
|
||||
# A pack keeps every root's files: the device installing it
|
||||
# places them.
|
||||
files, unplaced = place_save_entries(
|
||||
p.files, bios_path, manifest, run.args.save_dir, display, say=False)
|
||||
files, beyond = place_relative_entries(
|
||||
files, bios_path, manifest, display, say=not run.listing)
|
||||
p.files, elsewhere = place_emulator_entries(
|
||||
files, bios_path, manifest, display, say=not run.listing)
|
||||
p.files, bios_path, manifest, run.args.save_dir, display)
|
||||
files, beyond = place_relative_entries(files, bios_path, manifest)
|
||||
p.files, elsewhere = place_emulator_entries(files, bios_path, manifest)
|
||||
p.unplaced = [*unplaced, *beyond, *elsewhere]
|
||||
if not manifest.get("save_directory") and not run.packing:
|
||||
# Its own list leaves these files out: naming the folder with
|
||||
@@ -698,10 +699,10 @@ def _pass_narrow(run: _InstallRun, p: _PlatformPass) -> None:
|
||||
detail(f" Narrowed {before} to {len(p.files)} files")
|
||||
if args.one_per_slot:
|
||||
if not p.manifest.get("slot_fields"):
|
||||
print(f"Error: the {plat_name} file list does not say which files a "
|
||||
"slot holds, which --one-per-slot needs.", file=sys.stderr)
|
||||
print(_older_list_advice(plat_name), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_recorded", plat_name,
|
||||
f"Error: the {plat_name} file list does not say which files a "
|
||||
"slot holds, which --one-per-slot needs.",
|
||||
_older_list_advice(plat_name))
|
||||
before = len(p.files)
|
||||
p.files, p.omitted_files = one_per_slot(p.files, p.omitted_files, p.slot_reach)
|
||||
detail(f" One BIOS per console and region: {before} to {len(p.files)} files")
|
||||
@@ -730,6 +731,8 @@ def _pass_unplaced(run: _InstallRun, p: _PlatformPass) -> bool:
|
||||
if not run.packing:
|
||||
say_saves(p.plat_name, p.files, p.omitted_files + p.unplaced, p.bios_path, p.display,
|
||||
p.menu)
|
||||
if not run.listing:
|
||||
say_unplaced(p.unplaced, p.bios_path, p.display)
|
||||
|
||||
if args.list_systems or args.list_cores:
|
||||
_print_choices(p.plat_name, p.files, p.omitted_files, args.list_systems, p.manifest)
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -28,12 +26,13 @@ from installer.line_folder import (
|
||||
ask_platform_folder,
|
||||
share_words,
|
||||
)
|
||||
from installer.network import fetch_targets, local_targets
|
||||
from installer.lists import ListFailure, load_targets
|
||||
from installer.offline import LOCAL
|
||||
from installer.pack import pack_path
|
||||
from installer.pack_source import pack_name_platforms
|
||||
from installer.platforms import AVAILABLE_PLATFORMS, TARGET_PLATFORMS, _NO_BIOS_FOLDER, display_name, normalize_platform
|
||||
from installer.run_files import _output_kind
|
||||
from installer.platforms import AVAILABLE_PLATFORMS, _NO_BIOS_FOLDER, display_name, normalize_platform
|
||||
from installer.refusal import Refusal
|
||||
from installer.run_files import _output_kind, needed_targets
|
||||
from installer.safe_replace import KEPT
|
||||
from installer.setups import PORTABLE_ONLY, _default_dest, _line_setups, drive_example, found_setups
|
||||
from installer.standalone import _install_standalone_folders
|
||||
@@ -147,9 +146,9 @@ def _start_install(args: argparse.Namespace, real_stdout: TextIO) -> _InstallRun
|
||||
if args.platform is None:
|
||||
spelled = pack_name_platforms(Path(os.path.expanduser(str(args.pack))).name)
|
||||
if len(spelled) != 1:
|
||||
print("Error: name the platform the pack is for with --platform.",
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
raise Refusal("pack", "no_platform", "",
|
||||
"Error: name the platform the pack is for with --platform.",
|
||||
code=2)
|
||||
args.platform = spelled[0]
|
||||
return _InstallRun(args, term, os_type, interactive, listing, packing)
|
||||
|
||||
@@ -189,9 +188,6 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn:
|
||||
else "the file list")
|
||||
message = (f"No supported platform detected: {display_name(args.platform)} was "
|
||||
f"not found here, and {source} does not say where it goes")
|
||||
EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform,
|
||||
message=message)
|
||||
print(f" {message}.", file=sys.stderr)
|
||||
hint = Invocation()
|
||||
hint.os_type, hint.options = run.os_type, _INVOCATION.options
|
||||
example = _default_dest(run.os_type, args.platform)
|
||||
@@ -199,10 +195,11 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn:
|
||||
# example stopped at a question.
|
||||
answered = "".join(f" {flag}" for flag, on in (
|
||||
("--yes", args.yes), ("--no-input", args.no_input)) if on)
|
||||
print(" Name its folder with --dest, for example:\n "
|
||||
+ hint.command(args.platform, example if example is not None
|
||||
else "<its BIOS folder>") + answered, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "not_found", args.platform, f" {message}.",
|
||||
" Name its folder with --dest, for example:\n "
|
||||
+ hint.command(args.platform, example if example is not None
|
||||
else "<its BIOS folder>") + answered,
|
||||
message=message)
|
||||
|
||||
|
||||
def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]:
|
||||
@@ -214,42 +211,32 @@ def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]:
|
||||
if args.platform in PORTABLE_ONLY:
|
||||
# A portable emulator reads the folder beside its executable:
|
||||
# any default would be a folder it never opens.
|
||||
EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform,
|
||||
message=f"Platform '{args.platform}' not found. "
|
||||
f"{PORTABLE_ONLY[args.platform]}")
|
||||
print(
|
||||
raise Refusal(
|
||||
"detect", "not_found", args.platform,
|
||||
f" Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]} "
|
||||
f"Name it with --dest, for example: --platform {args.platform} "
|
||||
f"--dest '<BizHawk folder>{os.sep}Firmware'",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
message=f"Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]}")
|
||||
if args.platform in _SHARE_FOLDERS:
|
||||
# Its own folder exists on the Batocera machine alone, which
|
||||
# detection would have found: here /userdata/bios was taken, and
|
||||
# the run ended on "Cannot create" with no event saying why.
|
||||
message = (f"Platform '{args.platform}' not found here. "
|
||||
f"{share_words(args.platform)}")
|
||||
EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform,
|
||||
message=message)
|
||||
example = drive_example(run.os_type, "SHARE", "bios", args.platform)
|
||||
print(f" {message} Name it with --dest, for example: --platform "
|
||||
f"{args.platform} --dest {example}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "not_found", args.platform,
|
||||
f" {message} Name it with --dest, for example: --platform "
|
||||
f"{args.platform} --dest {example}", message=message)
|
||||
default_dest = _default_dest(run.os_type, args.platform)
|
||||
if default_dest is None:
|
||||
where = ("where this user can look, and its default folder may not be "
|
||||
"the one it reads" if _default_set_aside(run.os_type, args.platform)
|
||||
else "and no folder on this system is one it reads")
|
||||
message = f"Platform '{args.platform}' not found {where}"
|
||||
EVENTS.emit("error", stage="detect", reason="not_found",
|
||||
platform=args.platform, message=message)
|
||||
print(
|
||||
f" {message}. Name it with --dest, for example: "
|
||||
f"--platform {args.platform} --dest <its BIOS folder>",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
raise Refusal("detect", "not_found", args.platform,
|
||||
f" {message}. Name it with --dest, for example: "
|
||||
f"--platform {args.platform} --dest <its BIOS folder>",
|
||||
message=message)
|
||||
print(
|
||||
f" Platform '{args.platform}' not detected, "
|
||||
f"using default path: {default_dest}"
|
||||
@@ -437,19 +424,18 @@ def _check_run_target(run: _InstallRun) -> None:
|
||||
if args.target and by_record(args) and len(platforms) == 1:
|
||||
# The screen's runs carry the record's options as typed ones.
|
||||
plat = platforms[0][0]
|
||||
if LOCAL.offline and local_targets(plat) is None and plat in TARGET_PLATFORMS:
|
||||
drop_recorded(args, plat, "--target", "the board list needs the internet")
|
||||
try:
|
||||
known = load_targets(plat)
|
||||
except ListFailure as stopped:
|
||||
drop_recorded(args, plat, "--target", "the board list needs the internet"
|
||||
if stopped.problem.code == "offline"
|
||||
else "the board list could not be read")
|
||||
else:
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
known = fetch_targets(plat)
|
||||
if known is None or args.target not in known:
|
||||
drop_recorded(args, plat, "--target", "the board list does not name it"
|
||||
if known is not None else "the board list could not be read")
|
||||
if args.target not in known:
|
||||
drop_recorded(args, plat, "--target", "the board list does not name it")
|
||||
if args.target:
|
||||
for plat_name, _bios_path in platforms:
|
||||
targets = fetch_targets(plat_name)
|
||||
if targets is None:
|
||||
sys.exit(1)
|
||||
targets = needed_targets(plat_name)
|
||||
run.target_lists[plat_name] = targets
|
||||
if args.target not in targets:
|
||||
_unknown_target(args.target, plat_name, targets, *(
|
||||
@@ -465,7 +451,7 @@ def _check_run_cores(run: _InstallRun) -> None:
|
||||
for plat_name, bios_path in [] if run.packing else run.platforms:
|
||||
if plat_name in CORE_PLATFORMS:
|
||||
if args.cores_dir:
|
||||
_check_cores_dir(args.cores_dir)
|
||||
_check_cores_dir(args.cores_dir, plat_name)
|
||||
searched = [args.cores_dir] if args.cores_dir else core_dirs(plat_name, bios_path)
|
||||
run.cores_found[(plat_name, bios_path)] = installed_cores(searched)
|
||||
run.cores_searched[(plat_name, bios_path)] = searched
|
||||
@@ -473,12 +459,9 @@ def _check_run_cores(run: _InstallRun) -> None:
|
||||
drop_recorded(args, plat_name, "--installed-cores",
|
||||
f"{plat_name} ships its cores with the system")
|
||||
elif args.installed_cores:
|
||||
print(
|
||||
f"Error: {plat_name} ships its cores with the system. "
|
||||
f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
raise Refusal("option", "not_applicable", plat_name,
|
||||
f"Error: {plat_name} ships its cores with the system. "
|
||||
f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}")
|
||||
if args.installed_cores and not run.cores_found[(plat_name, bios_path)]:
|
||||
if by_record(args):
|
||||
drop_recorded(args, plat_name, "--installed-cores", "no core is installed")
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -19,6 +20,7 @@ from installer.cards import (
|
||||
drive_kind,
|
||||
)
|
||||
from installer.console import _ask, _quit
|
||||
from installer.detection_notes import note_detection
|
||||
from installer.detect_frontends import _UNNAMEABLE, _android_storage_root, detect_platforms
|
||||
from installer.detect_os import (
|
||||
_DETECTED_OS,
|
||||
@@ -555,7 +557,7 @@ def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]:
|
||||
# A drive whose files fit two systems is said, never guessed.
|
||||
words = doubt_words(mount)
|
||||
if words:
|
||||
print(f" {words}")
|
||||
note_detection(f" {words}", sys.stdout)
|
||||
continue
|
||||
if (card[0], card[1]) not in found and card[2] not in here:
|
||||
_DETECTED_OS.setdefault((card[0], card[1]), card[2])
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""What a run writes on the drive of its BIOS folder, and the free space it is held against."""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
from installer.datadirs import data_space_bytes
|
||||
from installer.host_fs import _nearest_folder
|
||||
|
||||
|
||||
def bytes_written(files: Iterable[dict],
|
||||
data_states: list[tuple[dict, tuple[Path, dict[str, dict], int]]]) -> int:
|
||||
"""The files a run puts in place, missing or replaced, and the data
|
||||
trees it rebuilds beside them (data_space_bytes). The line plan, the
|
||||
screen's plan and the run's refusal hold this one number against the
|
||||
free space: the plans counted the files absent alone, and a run they
|
||||
said nothing of stopped for space right after Enter."""
|
||||
return sum(entry.get("size", 0) for entry in files) + data_space_bytes(data_states)
|
||||
|
||||
|
||||
def free_space(bios_path: Path) -> int | None:
|
||||
"""The bytes free on the drive that holds bios_path, read at its nearest
|
||||
existing folder since it may not exist yet. None when it cannot be told."""
|
||||
try:
|
||||
return shutil.disk_usage(_nearest_folder(bios_path)).free
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def space_shortfall(bios_path: Path, needed: int) -> tuple[int, int] | None:
|
||||
"""Needed and free when the drive holding bios_path cannot hold needed
|
||||
bytes, else None, also when its free space cannot be told."""
|
||||
free = free_space(bios_path)
|
||||
return None if free is None or free >= needed else (needed, free)
|
||||
@@ -13,8 +13,8 @@ from installer.detect_frontends import launchbox_bios_dirs, launchbox_root
|
||||
from installer.download import download_files
|
||||
from installer.host_fs import NOT_WRITABLE, _closed_to_this_user, _exists, _is_dir, _replace_with_copy, _write_refused
|
||||
from installer.invocation import offline_requested
|
||||
from installer.lists import fetch_manifest
|
||||
from installer.local_check import check_local, unreachable_words
|
||||
from installer.network import fetch_manifest
|
||||
from installer.outcome import EVERYTHING_IN_PLACE, OutcomeDetails, _check_fetch_line, _report_outcome
|
||||
from installer.paths import _destination_path, _within
|
||||
from installer.plan import _check_free_space, _print_plan
|
||||
|
||||
@@ -30,6 +30,7 @@ class CheckTally(NamedTuple):
|
||||
data_missing: int = 0
|
||||
not_installable: int = 0
|
||||
data_bytes: int = 0
|
||||
space_bytes: int = 0
|
||||
|
||||
|
||||
def _emit_check(
|
||||
@@ -99,6 +100,7 @@ def _emit_check(
|
||||
dests=[dest for dest, _s, _state in own_states],
|
||||
)
|
||||
EVENTS.emit("data", platform=plat, files=tally.data_missing, bytes=tally.data_bytes)
|
||||
EVENTS.emit("space", platform=plat, bytes=tally.space_bytes)
|
||||
|
||||
|
||||
def _declared_state(copy: dict, entry: dict, bios_path: Path) -> str:
|
||||
|
||||
@@ -32,11 +32,12 @@ from installer.destination import (
|
||||
)
|
||||
from installer.detect_os import _DETECTED_OS, _FROM_CARD, detected_os, detected_shown
|
||||
from installer.embedded import CARD_PLATFORMS, _a
|
||||
from installer.frontend_folders import _retroarch_config_at
|
||||
from installer.games import games_probe
|
||||
from installer.host_fs import _exists, _folder_writable, _is_dir, _nearest_folder, closed_folder
|
||||
from installer.install_record import RECORD_NARROWING, _RECORD_SAID, record_options, setup_record
|
||||
from installer.invocation import OFFLINE_VARIABLE, offline_requested
|
||||
from installer.network import local_targets
|
||||
from installer.invocation import OFFLINE_VARIABLE
|
||||
from installer.lists import local_targets
|
||||
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE
|
||||
from installer.pack import _listed
|
||||
from installer.pack_source import PackSource
|
||||
@@ -62,6 +63,7 @@ from installer.tui_choice import (
|
||||
tui_choices,
|
||||
)
|
||||
from installer.tui_commands import _tui_card, tui_flags, tui_pack_dir, tui_record_kept
|
||||
from installer.tui_folder_scan import card_mounts, scan_folder
|
||||
from installer.tui_paint import _CHECK_FIELDS, _short_path, _styled
|
||||
from installer.tui_rows import (
|
||||
TUI_TICK_ROWS,
|
||||
@@ -546,6 +548,7 @@ def _choose(state: TuiState, plat: str, dest: Path, proposed: bool = False) -> l
|
||||
# default beside it is one it does not, offered as "reads its BIOS
|
||||
# files from" and filled with Enter.
|
||||
state.folder_default, state.folder_kind = None, "closed"
|
||||
state.folder_scan = scan_folder(state)
|
||||
return _push(state, "folder")
|
||||
card = card_system(dest)
|
||||
if card and card[0] == plat and card[1] != dest:
|
||||
@@ -656,6 +659,7 @@ def _choose_card(state: TuiState, folder: Path) -> list[tuple]:
|
||||
if state.stack and state.screen in ("folder", "browse", "path"):
|
||||
return []
|
||||
state.folder_default, state.folder_kind = None, "usual"
|
||||
state.folder_scan = scan_folder(state)
|
||||
return _push(state, "folder")
|
||||
return _take_card(state, choice, folder)
|
||||
|
||||
@@ -713,12 +717,9 @@ def _open_folder_screen(state: TuiState, default: Path | None,
|
||||
else "")
|
||||
if system and not state.card_bound and card_bound(system, state.platform):
|
||||
state.card_bound = card_bound(system, state.platform)
|
||||
# The cards are looked for when the screen opens and on Look again: a
|
||||
# The drives are looked for when the screen opens and on Look again: a
|
||||
# card inserted meanwhile moved the rows under the focus.
|
||||
state.cards = None
|
||||
bound = _tui_card_bound(state)
|
||||
if bound:
|
||||
state.cards = mounted_cards_of(bound[0], state.platform)
|
||||
state.folder_scan = scan_folder(state)
|
||||
refused = kind == "chosen" and (state.facts.get("writable") is False
|
||||
or _short_of_space(state, state.check or {}))
|
||||
# A folder just refused as full or read-only: Browse, not Use this
|
||||
@@ -748,7 +749,9 @@ def _tui_folder_facts(state: TuiState) -> dict:
|
||||
free = None
|
||||
cores = (installed_cores(core_dirs(state.platform, dest))
|
||||
if state.platform in CORE_PLATFORMS else [])
|
||||
return {"free": free, "writable": _folder_writable(dest), "cores": cores}
|
||||
# The retroarch.cfg that names dest, said under it on the plan.
|
||||
return {"free": free, "writable": _folder_writable(dest), "cores": cores,
|
||||
"config": _retroarch_config_at(dest)}
|
||||
|
||||
|
||||
def _row_folder(row: TuiRow) -> Path:
|
||||
@@ -810,9 +813,10 @@ def _rescan_cards(state: TuiState) -> list[tuple]:
|
||||
"""Look again for the cards of the setup chosen."""
|
||||
bound = _tui_card_bound(state)
|
||||
assert bound is not None
|
||||
state.cards = mounted_cards_of(bound[0], state.platform)
|
||||
state.folder_scan = scan_folder(state)
|
||||
mounts = card_mounts(state.folder_scan)
|
||||
cards = [index for index, item in enumerate(tui_rows(state))
|
||||
if item.action == "card" and item.value in state.cards]
|
||||
if item.action == "card" and item.value in mounts]
|
||||
state.focus["folder"] = cards[0] if cards else state.focus.get("folder", 0)
|
||||
state.status = ("" if cards else f"Still no {bound[0]} card "
|
||||
"is mounted.")
|
||||
@@ -1183,7 +1187,7 @@ def _option_flag(state: TuiState, action: str, step: int) -> bool:
|
||||
|
||||
def _option_offline(state: TuiState, step: int) -> list[tuple]:
|
||||
"""Without the internet, turned on or off."""
|
||||
on = step > 0 if step else not offline_requested()
|
||||
on = step > 0 if step else not state.offline
|
||||
if (on and state.target and not state.manifest_given and not state.packs
|
||||
and not (state.targets_for == state.platform and state.targets)):
|
||||
# The run reads the board list beside the file list it is
|
||||
@@ -1194,6 +1198,7 @@ def _option_offline(state: TuiState, step: int) -> list[tuple]:
|
||||
return []
|
||||
# Set in this process by the effect, as --offline sets it: the
|
||||
# runs started next inherit it, and their command names it.
|
||||
state.offline = on
|
||||
return [("offline", on)]
|
||||
|
||||
|
||||
|
||||
@@ -281,9 +281,16 @@ def _dry_copies(state: TuiState) -> list[str]:
|
||||
return [event["dest"] for event in state.dry_files if event["dest"] in local]
|
||||
|
||||
|
||||
def space_needed(check: dict) -> int:
|
||||
"""What the run writes on the folder's drive, as its space event says
|
||||
it: the files and the data trees, the number its refusal holds against
|
||||
the free space. bytes_needed for a check that names none."""
|
||||
return check.get("space_bytes", check.get("bytes_needed", 0))
|
||||
|
||||
|
||||
def _short_of_space(state: TuiState, check: dict) -> bool:
|
||||
free = state.facts.get("free")
|
||||
return free is not None and check.get("bytes_needed", 0) > free
|
||||
return free is not None and space_needed(check) > free
|
||||
|
||||
|
||||
def _shared_needed(state: TuiState) -> dict[str, tuple[int, int]]:
|
||||
|
||||
@@ -11,8 +11,8 @@ from installer.choices import choosable_cores, emulator_names
|
||||
from installer.handheld_app import card_app
|
||||
from installer.host_fs import _is_dir
|
||||
from installer.install_record import RECORD_NARROWING, record_argv, record_options
|
||||
from installer.invocation import OFFLINE_VARIABLE, Invocation, offline_option
|
||||
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE
|
||||
from installer.invocation import Invocation
|
||||
from installer.offline import LOCAL
|
||||
from installer.tally import leave_out_game_data
|
||||
from installer.tui_routes import TUI_LIST_ENV, TUI_RECORD_ENV
|
||||
|
||||
@@ -78,10 +78,7 @@ def tui_flags(state: TuiState) -> list[tuple[str, str | None]]:
|
||||
# the runs, whose own reading of the record would narrow it again.
|
||||
flags.append(("--all-files", None))
|
||||
flags += [("--from", str(folder)) for folder in state.from_folders]
|
||||
if (os.environ.get(OFFLINE_VARIABLE) == OFFLINE_FLAG_VALUE
|
||||
and not any(flag == "--offline" for flag, _v in flags)):
|
||||
# Given as --offline: said so in the command. Set as the variable,
|
||||
# the runs inherit it and the words name it.
|
||||
if state.offline and not any(flag == "--offline" for flag, _v in flags):
|
||||
flags.append(("--offline", None))
|
||||
return flags
|
||||
|
||||
@@ -132,9 +129,6 @@ def tui_hint(state: TuiState) -> Invocation:
|
||||
hint.options += tui_flags(state)
|
||||
if state.add_app and _tui_app_ready(state):
|
||||
hint.options.append(("--add-app", None))
|
||||
# The runs inherit the variable, a command shown to the user does not.
|
||||
if offline_option(False) and ("--offline", None) not in hint.options:
|
||||
hint.options.append(("--offline", None))
|
||||
return hint
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""The work the screens hand off: child runs, fetches in this process, and their work folders."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
@@ -11,19 +10,13 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.events import _event_exit_code
|
||||
from installer.games import games_probe
|
||||
from installer.handheld_app import put_app
|
||||
from installer.manifest import _validate_manifest
|
||||
from installer.network import _fetch_json, fetch_manifest, fetch_targets, missing_list_advice, network_words
|
||||
from installer.offline import LOCAL, offline_named, offline_undo
|
||||
from installer.platforms import display_name
|
||||
from installer.remote import MANIFEST_URL, MAX_MANIFEST_BYTES
|
||||
from installer.tui_rows import TUI_OFFLINE_TITLE
|
||||
from installer.lists import ListFailure, load_manifest, load_targets
|
||||
from installer.tui_list_words import manifest_failure_screen, targets_failure_words
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from installer.handheld_app import CardApp
|
||||
@@ -131,93 +124,35 @@ def _tui_put_app(card: CardApp, inbox: queue.Queue) -> None:
|
||||
inbox.put(("app", put_app(card)))
|
||||
|
||||
|
||||
def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None:
|
||||
def _tui_fetch(plat: str, inbox: queue.Queue) -> None:
|
||||
"""The file list, fetched once in this process, or what went wrong."""
|
||||
if LOCAL.manifest is not None or LOCAL.pack is not None:
|
||||
mark = len(log.getvalue())
|
||||
try:
|
||||
inbox.put(("manifest", plat, fetch_manifest(plat)))
|
||||
except SystemExit as exc:
|
||||
inbox.put(("manifest_failed", plat, "", log.getvalue()[mark:].splitlines(),
|
||||
_event_exit_code(exc.code)))
|
||||
return
|
||||
url = MANIFEST_URL.format(platform=plat)
|
||||
try:
|
||||
data = _fetch_json(url, MAX_MANIFEST_BYTES, "file list", attempts=1,
|
||||
timeout=TUI_FETCH_TIMEOUT)
|
||||
inbox.put(("manifest", plat, _validate_manifest(data, plat)))
|
||||
manifest = load_manifest(plat, attempts=1, timeout=TUI_FETCH_TIMEOUT)
|
||||
except ListFailure as failure:
|
||||
inbox.put(("manifest_failed", plat, *manifest_failure_screen(failure.problem)))
|
||||
return
|
||||
except ValueError as exc:
|
||||
title, lines = "The file list is not valid", [f"What arrived is not a file list: {exc}."]
|
||||
if isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError)):
|
||||
# The parser's "Expecting value: line 2 column 1" told no one anything.
|
||||
lines = ["What arrived is not a file list: a Wi-Fi sign-in page or a cut "
|
||||
"download looks like this.", "Check the connection, then choose Try again."]
|
||||
except urllib.error.HTTPError as exc:
|
||||
title = "No file list"
|
||||
lines = [f"There is no file list for {display_name(plat)} at this address."
|
||||
if exc.code == 404 else f"The server answered HTTP {exc.code}."]
|
||||
if exc.code == 404 and not os.environ.get("RETROBIOS_BASE_URL"):
|
||||
# Line mode named RETROBIOS_REF as the cause, the screen nothing.
|
||||
lines.append(missing_list_advice(plat, "choose Try again"))
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
code, words = network_words(exc)
|
||||
if code == "offline":
|
||||
# Asked for, not a failure: no Try again, and the two ways a
|
||||
# run without the network gets its list.
|
||||
inbox.put(("manifest_failed", plat, TUI_OFFLINE_TITLE, [
|
||||
f"This run makes no network request ({offline_named()}), and the list "
|
||||
"of BIOS files comes from the network.",
|
||||
"Run the installer again with the list saved as a file "
|
||||
f"(--manifest FILE, a copy of install/{plat}.json) or with a pack "
|
||||
f"(--from-pack PACK), or {offline_undo()}."], 1))
|
||||
return
|
||||
title = {"clock": "The clock is wrong",
|
||||
"no_ca": "No trusted certificates",
|
||||
"no_ssl": "This Python cannot use HTTPS"}.get(code, "No connection")
|
||||
# The screen's first row is Try again: "then run again" was a second way.
|
||||
lines = [words[0].upper() + words[1:].replace(", then run again",
|
||||
", then choose Try again") + "."]
|
||||
if code == "network":
|
||||
lines = [f"The list of BIOS files could not be downloaded: {words}.",
|
||||
"Check the Wi-Fi or the cable, then choose Try again.",
|
||||
# A handheld with no Wi-Fi has the pack as its way.
|
||||
"Or copy a pack to the card and run the installer with --from-pack "
|
||||
"PACK: no network is needed then."]
|
||||
proxy = next((name for name in ("HTTPS_PROXY", "https_proxy", "ALL_PROXY",
|
||||
"all_proxy") if os.environ.get(name)), "")
|
||||
if proxy:
|
||||
# Named, never shown: the value can hold a password.
|
||||
lines.append(f"{proxy} is set, so the connection goes through a proxy: "
|
||||
"check that it answers.")
|
||||
if os.environ.get("RETROBIOS_BASE_URL"):
|
||||
lines.append(f"RETROBIOS_BASE_URL chose the address: {url}")
|
||||
inbox.put(("manifest_failed", plat, title, lines, 1))
|
||||
inbox.put(("manifest", plat, manifest))
|
||||
|
||||
|
||||
def _tui_fetch_targets(plat: str, inbox: queue.Queue, log: io.StringIO) -> None:
|
||||
def _tui_fetch_targets(plat: str, inbox: queue.Queue) -> None:
|
||||
"""The platform's board list for Device, fetched in this process as a
|
||||
--target run reads it: the pack's or the list's beside --manifest, else
|
||||
the network's. None and why when it cannot be read."""
|
||||
mark = len(log.getvalue())
|
||||
try:
|
||||
# One attempt and the list's own timeout, as the file list is
|
||||
# fetched here: Device says Reading while it waits.
|
||||
targets = fetch_targets(plat, attempts=1, timeout=TUI_FETCH_TIMEOUT)
|
||||
except SystemExit:
|
||||
targets = None
|
||||
said = [line.strip() for line in log.getvalue()[mark:].splitlines() if line.strip()]
|
||||
problem = "" if targets is not None else (
|
||||
f"The board list could not be read{': ' + said[0] if said else '.'}")
|
||||
inbox.put(("targets", plat, targets, problem))
|
||||
targets = load_targets(plat, attempts=1, timeout=TUI_FETCH_TIMEOUT)
|
||||
except ListFailure as failure:
|
||||
inbox.put(("targets", plat, None, targets_failure_words(failure.problem)))
|
||||
return
|
||||
inbox.put(("targets", plat, targets, ""))
|
||||
|
||||
|
||||
def _tui_fetch_games(plat: str, inbox: queue.Queue, log: io.StringIO, dest: Path | None,
|
||||
look: bool) -> None:
|
||||
def _tui_fetch_games(plat: str, inbox: queue.Queue, dest: Path | None, look: bool) -> None:
|
||||
"""The file list, then, once it came, a look at the card for games
|
||||
(look), said before the list so that the check reads them."""
|
||||
held: queue.Queue = queue.Queue()
|
||||
_tui_fetch(plat, held, log)
|
||||
_tui_fetch(plat, held)
|
||||
message = held.get()
|
||||
if look and message[0] == "manifest" and dest is not None:
|
||||
# One attempt, as the list's own: a retry says so on stderr, under
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""The drives the folder screen offers, read when it opens and on Look again."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from installer.cards import _doubt_kinds, share_doubt
|
||||
from installer.destination import _card_what, blank_cards_of, doubt_cards, mounted_cards_of
|
||||
from installer.host_fs import _is_dir
|
||||
from installer.line_folder import (
|
||||
_said_with,
|
||||
drives_left_out,
|
||||
folder_drives,
|
||||
share_targets,
|
||||
unproven_words,
|
||||
)
|
||||
from installer.tui_choice import _tui_card_bound
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from installer.tui_state import TuiState
|
||||
|
||||
|
||||
class FolderScan(NamedTuple):
|
||||
"""What the mounted drives said when the folder screen last looked."""
|
||||
|
||||
# (mount, what its own files say) of the cards that run the system.
|
||||
cards: tuple = ()
|
||||
# (mount, the systems it could be) of the drives two systems fit.
|
||||
doubtful: tuple = ()
|
||||
# (mount, what it is) of the drives no system claims.
|
||||
blank: tuple = ()
|
||||
# (row label, bios folder) of each share drive.
|
||||
shares: tuple = ()
|
||||
# (row label, folder) of each drive, its label saying a missing folder.
|
||||
drives: tuple = ()
|
||||
# The notes under the rows: drives left out, drives nothing proves.
|
||||
notes: tuple = ()
|
||||
|
||||
|
||||
def scan_folder(state: TuiState) -> FolderScan:
|
||||
"""The mounted drives the folder screen lists, read once: a frame that
|
||||
read them moved the rows under the focus when a stick was inserted, and
|
||||
Enter acted on a row nobody chose."""
|
||||
bound = _tui_card_bound(state)
|
||||
if bound:
|
||||
mounts = mounted_cards_of(bound[0], state.platform)
|
||||
doubtful = [mount for mount in doubt_cards(state.platform) if mount not in mounts]
|
||||
taken = [*mounts, *doubtful]
|
||||
return FolderScan(
|
||||
cards=tuple((mount, _card_what(mount)) for mount in mounts),
|
||||
doubtful=tuple((mount, _doubt_kinds(share_doubt(mount)[0])) for mount in doubtful),
|
||||
blank=tuple((mount, _card_what(mount))
|
||||
for mount in blank_cards_of(bound[0], state.platform)
|
||||
if mount not in taken))
|
||||
if state.folder_kind == "share":
|
||||
return FolderScan(shares=tuple(share_targets(state.platform)))
|
||||
drives = tuple((label if _is_dir(folder) else _said_with(label, "does not exist yet"),
|
||||
folder)
|
||||
for label, folder in folder_drives(state.os_type, state.platform,
|
||||
state.folder_kind == "usual"))
|
||||
notes = tuple(note for note in (drives_left_out(state.platform), unproven_words()) if note)
|
||||
return FolderScan(drives=drives, notes=notes)
|
||||
|
||||
|
||||
def card_mounts(scan: FolderScan) -> list[Path]:
|
||||
"""The mounts of the cards found running the system."""
|
||||
return [mount for mount, _what in scan.cards]
|
||||
@@ -0,0 +1,85 @@
|
||||
"""What the full screen says of a file list or board list it could not have."""
|
||||
from __future__ import annotations
|
||||
|
||||
from installer.lists import ListProblem, manifest_failure_lines, missing_list_advice
|
||||
from installer.offline import offline_named, offline_undo
|
||||
from installer.platforms import display_name
|
||||
from installer.tui_rows import TUI_OFFLINE_TITLE
|
||||
|
||||
_NETWORK_TITLES = {"clock": "The clock is wrong", "no_ca": "No trusted certificates",
|
||||
"no_ssl": "This Python cannot use HTTPS"}
|
||||
|
||||
|
||||
def _download_lines(failure: ListProblem) -> tuple[str, list[str]]:
|
||||
"""The title and lines of a file list the network did not bring."""
|
||||
plat, code, words = failure.plat, failure.code, failure.words
|
||||
if code == "invalid":
|
||||
if failure.garbled:
|
||||
# The parser's "Expecting value: line 2 column 1" told no one anything.
|
||||
return "The file list is not valid", [
|
||||
"What arrived is not a file list: a Wi-Fi sign-in page or a cut "
|
||||
"download looks like this.", "Check the connection, then choose Try again."]
|
||||
return "The file list is not valid", [f"What arrived is not a file list: {words}."]
|
||||
if code == "http":
|
||||
lines = [f"There is no file list for {display_name(plat)} at this address."
|
||||
if failure.status == 404 else f"The server answered HTTP {failure.status}."]
|
||||
if failure.status == 404 and not failure.overridden:
|
||||
lines.append(missing_list_advice(plat, "choose Try again", failure.ref))
|
||||
return "No file list", lines
|
||||
if code != "network":
|
||||
# The screen's first row is Try again: "then run again" was a second way.
|
||||
return _NETWORK_TITLES.get(code, "No connection"), [
|
||||
words[0].upper() + words[1:].replace(", then run again",
|
||||
", then choose Try again") + "."]
|
||||
lines = [f"The list of BIOS files could not be downloaded: {words}.",
|
||||
"Check the Wi-Fi or the cable, then choose Try again.",
|
||||
# A handheld with no Wi-Fi has the pack as its way.
|
||||
"Or copy a pack to the card and run the installer with --from-pack "
|
||||
"PACK: no network is needed then."]
|
||||
# Named, never shown: the value can hold a password.
|
||||
if failure.proxy == "system settings":
|
||||
lines.append("The system settings set a proxy, so the connection goes through "
|
||||
"it: check that it answers.")
|
||||
elif failure.proxy:
|
||||
lines.append(f"{failure.proxy} is set, so the connection goes through a proxy: "
|
||||
"check that it answers.")
|
||||
return "No connection", lines
|
||||
|
||||
|
||||
def manifest_failure_screen(failure: ListProblem) -> tuple[str, list[str], int]:
|
||||
"""The title, lines and exit code the screen shows for a file list it
|
||||
could not have, from the failure line mode prints."""
|
||||
plat = failure.plat
|
||||
if failure.source != "network":
|
||||
# A list given on disk or in a pack: line mode's words, as they are.
|
||||
return "", manifest_failure_lines(failure), failure.fatal
|
||||
if failure.code == "offline":
|
||||
# Asked for, not a failure: no Try again, and the two ways a run
|
||||
# without the network gets its list.
|
||||
return TUI_OFFLINE_TITLE, [
|
||||
f"This run makes no network request ({offline_named()}), and the list "
|
||||
"of BIOS files comes from the network.",
|
||||
"Run the installer again with the list saved as a file "
|
||||
f"(--manifest FILE, a copy of install/{plat}.json) or with a pack "
|
||||
f"(--from-pack PACK), or {offline_undo()}."], failure.fatal
|
||||
title, lines = _download_lines(failure)
|
||||
if failure.overridden:
|
||||
lines.append(f"RETROBIOS_BASE_URL chose the address: {failure.where}")
|
||||
return title, lines, failure.fatal
|
||||
|
||||
|
||||
def targets_failure_words(failure: ListProblem) -> str:
|
||||
"""The line Device shows for a board list it could not have."""
|
||||
code, words, where = failure.code, failure.words, failure.where
|
||||
if failure.source == "file":
|
||||
state = "cannot be read" if code == "unreadable" else "is not valid"
|
||||
cause = f"the list {where} {state}: {words}"
|
||||
elif code == "offline":
|
||||
cause = words
|
||||
elif code == "invalid":
|
||||
cause = f"it is not valid: {words}"
|
||||
elif code == "http":
|
||||
cause = f"the server answered HTTP {failure.status}"
|
||||
else:
|
||||
cause = words
|
||||
return f"The board list could not be read: {cause}."
|
||||
@@ -1,7 +1,6 @@
|
||||
"""The result screen: what an install, a pack or a More action did, in words."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
@@ -38,23 +37,17 @@ from installer.tui_routes import TUI_PAD_ROUTES
|
||||
if TYPE_CHECKING:
|
||||
from installer.tui_state import TuiState
|
||||
|
||||
_SPACE_NEEDED = re.compile(r"Needed: (\S+ \S+)\. Free: (\S+ \S+)\.")
|
||||
|
||||
|
||||
def _space_stop(state: TuiState) -> re.Match | None:
|
||||
"""Needed and free, when the run stopped for lack of space."""
|
||||
return next(filter(None, (_SPACE_NEEDED.search(line) for line in state.tail)), None)
|
||||
|
||||
|
||||
def _space_words(state: TuiState) -> str:
|
||||
"""The run's stop for lack of space, in words, "" for another stop."""
|
||||
match = _space_stop(state)
|
||||
if match is None:
|
||||
def full_drive_words(state: TuiState) -> str:
|
||||
"""The run's stop for lack of space (its no_space event), in words, ""
|
||||
for another stop: read once, when the run ends."""
|
||||
if state.no_space is None:
|
||||
return ""
|
||||
needed, free = state.no_space
|
||||
dest = (state.dest or Path(".")).absolute()
|
||||
card = any((mount == dest or mount in dest.parents) and card_system(mount)
|
||||
for mount in _mounted_cards())
|
||||
return f"The {'card' if card else 'drive'} is full: {match[1]} needed, {match[2]} free."
|
||||
return (f"The {'card' if card else 'drive'} is full: {format_size(needed)} needed, "
|
||||
f"{format_size(free)} free.")
|
||||
|
||||
|
||||
def _tui_sources(state: TuiState, installed: int, missing: int, wrong: int = 0,
|
||||
@@ -107,7 +100,7 @@ def _outcome_counts(state: TuiState) -> _OutcomeCounts:
|
||||
if _offline_only() and not offline_failed else 0)
|
||||
up_to_date = summary.get("up_to_date", 0)
|
||||
total = (state.download or {}).get("files", 0)
|
||||
space = "" if summary else _space_words(state)
|
||||
space = "" if summary else state.full_drive
|
||||
errors = f", {len(failed)} failed" if failed else ""
|
||||
return _OutcomeCounts(summary, installed, failed, offline_failed, left, up_to_date, total,
|
||||
space, errors)
|
||||
@@ -427,7 +420,7 @@ def tui_keeps_log(state: TuiState) -> bool:
|
||||
return True
|
||||
# A full card is said in words on the screen: its log adds nothing.
|
||||
return (bool(state.log) and state.code not in (0, 130, None)
|
||||
and _space_stop(state) is None)
|
||||
and not state.full_drive)
|
||||
|
||||
|
||||
def _removal_text(state: TuiState) -> list:
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from installer.destination import _last_name
|
||||
from installer.from_folders import MAX_SCANNED_FILES
|
||||
from installer.frontend_folders import _retroarch_config_at, save_where_words
|
||||
from installer.frontend_folders import save_where_words
|
||||
from installer.install_record import record_changes, record_says
|
||||
from installer.manifest import GAME_DATA, OTHER_SYSTEMS
|
||||
from installer.offline import LOCAL, _offline_only, offline_named, offline_undo
|
||||
@@ -48,6 +48,7 @@ from installer.tui_choice import (
|
||||
_tui_tally,
|
||||
games_plan_words,
|
||||
games_where,
|
||||
space_needed,
|
||||
tui_systems,
|
||||
tui_verbose,
|
||||
)
|
||||
@@ -284,7 +285,7 @@ def _plan_lines(check: dict, dest: Path | None, state: TuiState) -> list:
|
||||
_styled(headline, "title"),
|
||||
_styled(f"BIOS folder: {_short_path(_plan_folder(state, dest), state.home)}", "path"),
|
||||
]
|
||||
found_in = _retroarch_config_at(dest) if dest is not None else None
|
||||
found_in = state.facts.get("config") if dest is not None else None
|
||||
if found_in:
|
||||
# Right under the folder it names: after the save lines it read as
|
||||
# naming them.
|
||||
@@ -315,8 +316,8 @@ def _plan_lines(check: dict, dest: Path | None, state: TuiState) -> list:
|
||||
free = state.facts.get("free")
|
||||
if free is not None:
|
||||
lines.append(_detail(f"Free space: {format_size(free)}"))
|
||||
if check["bytes_needed"] > free:
|
||||
lines.append(space_words(check["bytes_needed"], free, _on_its_card(state)))
|
||||
if space_needed(check) > free:
|
||||
lines.append(space_words(space_needed(check), free, _on_its_card(state)))
|
||||
backup = _plan_backups(check, state, fig)
|
||||
misplaced = _tui_misplaced(state) if check is state.check else []
|
||||
if misplaced:
|
||||
|
||||
@@ -21,6 +21,7 @@ from installer.tui_actions import (
|
||||
)
|
||||
from installer.tui_choice import _needed
|
||||
from installer.tui_commands import TUI_ACTION_RUNS
|
||||
from installer.tui_outcome import full_drive_words
|
||||
from installer.tui_paint import _styled
|
||||
from installer.tui_rows import tui_rows
|
||||
|
||||
@@ -118,6 +119,8 @@ def _take_check_event(state: TuiState, kind: str | None, event: dict) -> None:
|
||||
state.saves = event
|
||||
elif kind == "data" and state.check is not None:
|
||||
state.check["data_bytes"] = event["bytes"]
|
||||
elif kind == "space" and state.check is not None:
|
||||
state.check["space_bytes"] = event["bytes"]
|
||||
elif kind == "check":
|
||||
state.check = event
|
||||
elif kind == "file":
|
||||
@@ -135,6 +138,8 @@ def _take_dry_event(state: TuiState, kind: str | None, event: dict) -> None:
|
||||
state.dry_saves = event
|
||||
elif kind == "data" and state.dry is not None:
|
||||
state.dry["data_bytes"] = event["bytes"]
|
||||
elif kind == "space" and state.dry is not None:
|
||||
state.dry["space_bytes"] = event["bytes"]
|
||||
elif kind == "check":
|
||||
state.dry = event
|
||||
elif kind == "file" and event.get("state") != "present":
|
||||
@@ -172,6 +177,9 @@ def _take_event(state: TuiState, event: dict) -> None:
|
||||
if _take_action_event(state, event):
|
||||
return
|
||||
kind = event.get("event")
|
||||
if kind == "no_space":
|
||||
state.no_space = (event["bytes_needed"], event["bytes_free"])
|
||||
return
|
||||
if kind == "checking" and state.run in ("check", "install"):
|
||||
state.reading = (event["files_done"], event["files_total"])
|
||||
elif kind == "games_reading" and state.run in ("check", "install"):
|
||||
@@ -309,6 +317,8 @@ def tui_receive(state: TuiState, message: tuple) -> list[tuple]:
|
||||
state.running = False
|
||||
state.tail = [line for line in tail if not line.startswith("RetroBIOS ")]
|
||||
tail = state.tail
|
||||
state.full_drive = full_drive_words(state)
|
||||
state.no_space = None
|
||||
if state.run in TUI_ACTION_RUNS:
|
||||
return _action_ended(state, code, tail)
|
||||
if state.run == "check":
|
||||
|
||||
@@ -6,17 +6,14 @@ from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.cards import _doubt_kinds, _mount_name, _mounted_cards, share_doubt
|
||||
from installer.cards import _doubt_kinds, _mount_name, _mounted_cards
|
||||
from installer.choices import recorded_axes
|
||||
from installer.cores import CORE_PLATFORMS
|
||||
from installer.destination import _card_what, blank_cards_of, doubt_cards, mounted_cards_of
|
||||
from installer.destination import _card_what
|
||||
from installer.handheld_app import APP_OFFER, APP_OFFER_SHORT
|
||||
from installer.host_fs import _is_dir
|
||||
from installer.install_record import record_day
|
||||
from installer.invocation import offline_requested
|
||||
from installer.line_folder import _said_with, folder_drives, share_targets
|
||||
from installer.manifest import GAME_DATA
|
||||
from installer.offline import LOCAL, _offline_only
|
||||
from installer.offline import LOCAL
|
||||
from installer.plan import CONFIRM_FROM_BYTES
|
||||
from installer.plan_words import cores_words
|
||||
from installer.platforms import TARGET_PLATFORMS, _tui_system_label, system_title
|
||||
@@ -75,6 +72,7 @@ from installer.tui_commands import (
|
||||
tui_flags,
|
||||
tui_record_kept,
|
||||
)
|
||||
from installer.tui_folder_scan import FolderScan
|
||||
from installer.tui_paint import _short_path
|
||||
from installer.tui_state import TUI_MAX_WIDTH, TuiRow, _matches
|
||||
|
||||
@@ -126,27 +124,20 @@ def _setup_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
return rows + [TuiRow("another", "Another setup or folder")]
|
||||
|
||||
|
||||
def _card_screen_rows(state: TuiState, rows: list[TuiRow],
|
||||
bound: tuple[str, str]) -> list[TuiRow]:
|
||||
def _card_screen_rows(state: TuiState, rows: list[TuiRow], scan: FolderScan) -> list[TuiRow]:
|
||||
"""The folder rows of a setup that runs from a card."""
|
||||
# Only the cards whose own files say they run the system: A on the
|
||||
# first mount wrote Onion's layout on a muOS card.
|
||||
mounts = (state.cards if state.cards is not None
|
||||
else mounted_cards_of(bound[0], state.platform))
|
||||
cards = [TuiRow("card", f"{_mount_name(mount)} ({_card_what(mount)})", value=mount)
|
||||
for mount in mounts]
|
||||
cards = [TuiRow("card", f"{_mount_name(mount)} ({what})", value=mount)
|
||||
for mount, what in scan.cards]
|
||||
# A drive this system and another both fit is its card, as --dest
|
||||
# takes it: "No KNULLI card is mounted" sat beside it.
|
||||
doubtful = [mount for mount in doubt_cards(state.platform) if mount not in mounts]
|
||||
cards += [TuiRow("card", f"{_mount_name(mount)} (could be "
|
||||
f"{_doubt_kinds(share_doubt(mount)[0])})", value=mount)
|
||||
for mount in doubtful]
|
||||
mounts = [*mounts, *doubtful]
|
||||
cards += [TuiRow("card", f"{_mount_name(mount)} (could be {kinds})", value=mount)
|
||||
for mount, kinds in scan.doubtful]
|
||||
# On the device itself its folder is found, and no card is looked for.
|
||||
here = state.folder_default is not None and state.folder_kind == "found"
|
||||
blank = [] if here else [
|
||||
TuiRow("card", f"{_mount_name(mount)} ({_card_what(mount)})", value=mount)
|
||||
for mount in blank_cards_of(bound[0], state.platform) if mount not in mounts]
|
||||
blank = [] if here else [TuiRow("card", f"{_mount_name(mount)} ({what})", value=mount)
|
||||
for mount, what in scan.blank]
|
||||
rescan = [] if cards or here else [TuiRow("rescan", "Look again")]
|
||||
if blank:
|
||||
# A blank drive is listed for a system that fills its card when
|
||||
@@ -158,15 +149,14 @@ def _card_screen_rows(state: TuiState, rows: list[TuiRow],
|
||||
|
||||
|
||||
def _folder_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
"""The rows of the BIOS folder question."""
|
||||
"""The rows of the BIOS folder question, from the drives last looked for."""
|
||||
rows = [TuiRow("default", "Use this folder")] if state.folder_default else []
|
||||
bound = _tui_card_bound(state)
|
||||
scan = state.folder_scan or FolderScan()
|
||||
if state.folder_kind == "share":
|
||||
# The drives mounted here first, each one's bios folder: the
|
||||
# share drive of a Batocera card or disk in a reader.
|
||||
rows += [TuiRow("share", label, value=folder)
|
||||
for label, folder in share_targets(state.platform)]
|
||||
if not bound:
|
||||
rows += [TuiRow("share", label, value=folder) for label, folder in scan.shares]
|
||||
if not _tui_card_bound(state):
|
||||
# The drives mounted here, as line mode numbers them at the same
|
||||
# question, each by the BIOS folder its system reads, after the
|
||||
# Windows side's usual folder under WSL.
|
||||
@@ -175,14 +165,10 @@ def _folder_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
# Every row whose folder is missing says so, in both modes: the
|
||||
# Windows row alone did.
|
||||
drives = [] if state.folder_kind == "share" else [
|
||||
TuiRow("drive", label if _is_dir(folder) else _said_with(label,
|
||||
"does not exist yet"),
|
||||
value=folder)
|
||||
for label, folder in folder_drives(state.os_type, state.platform,
|
||||
state.folder_kind == "usual")]
|
||||
TuiRow("drive", label, value=folder) for label, folder in scan.drives]
|
||||
return rows + [TuiRow("browse", "Browse for a folder"),
|
||||
TuiRow("type", "Type a path")] + drives
|
||||
return _card_screen_rows(state, rows, bound)
|
||||
return _card_screen_rows(state, rows, scan)
|
||||
|
||||
|
||||
def _browse_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
@@ -256,6 +242,11 @@ def _core_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
return rows + _CHECKLIST_END
|
||||
|
||||
|
||||
def _tui_offline_only(state: TuiState) -> bool:
|
||||
"""Without the internet and without a pack: what is not here cannot come."""
|
||||
return state.offline and LOCAL.pack is None
|
||||
|
||||
|
||||
def _confirm_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
"""The rows of the confirm screen."""
|
||||
if state.running or state.dry is None:
|
||||
@@ -264,7 +255,7 @@ def _confirm_screen_rows(state: TuiState) -> list[TuiRow]:
|
||||
# Counted again, every file is in place: Install wrote nothing
|
||||
# and said Done.
|
||||
return [TuiRow("close", "Close"), TuiRow("back", "Back")]
|
||||
if _offline_only() and not _dry_copies(state):
|
||||
if _tui_offline_only(state) and not _dry_copies(state):
|
||||
# The plan's rule: Install would only fail every file.
|
||||
return [TuiRow("back", "Back")]
|
||||
return [TuiRow("install", "Install"), TuiRow("back", "Back")]
|
||||
@@ -339,7 +330,7 @@ def _plan_rows(state: TuiState) -> list[TuiRow]:
|
||||
label = (f"{TUI_INSTALL_ROW} {format_size(size)}" if size >= CONFIRM_FROM_BYTES
|
||||
else TUI_INSTALL_ROW)
|
||||
rows = [TuiRow("install", label)]
|
||||
if _offline_only() and not _plan_copies(state, check):
|
||||
if _tui_offline_only(state) and not _plan_copies(state, check):
|
||||
# Nothing here to copy, and the network refused: Install would
|
||||
# only fail every file, in this folder or another.
|
||||
rows = []
|
||||
@@ -589,8 +580,8 @@ def _option_rows(state: TuiState) -> list[TuiRow]:
|
||||
# and the focus stays on the row just changed.
|
||||
how = [TuiRow("offline", "Without the internet: "
|
||||
+ ("yes, a pack is read" if LOCAL.pack is not None
|
||||
else _yes(offline_requested())), "--offline")]
|
||||
if not LOCAL.offline:
|
||||
else _yes(state.offline)), "--offline")]
|
||||
if LOCAL.pack is None and not state.offline:
|
||||
# From a pack, or offline, nothing is downloaded.
|
||||
how.append(TuiRow("jobs", f"Parallel downloads: {state.jobs}", "--jobs"))
|
||||
see = [TuiRow("preview", "Preview the file list", "--dry-run"),
|
||||
|
||||
@@ -6,11 +6,11 @@ import textwrap
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from installer.cards import _GAMES_PART_CARDS, card_setup, setup_bios_folder
|
||||
from installer.cards import _GAMES_PART_CARDS, card_setup
|
||||
from installer.destination import card_where
|
||||
from installer.detect_os import detected_shown
|
||||
from installer.embedded import CARD_PLATFORMS, _a
|
||||
from installer.line_folder import drives_left_out, share_words, side_name, unproven_words
|
||||
from installer.line_folder import share_words, side_name
|
||||
from installer.manifest import OTHER_SYSTEMS
|
||||
from installer.offline import LOCAL
|
||||
from installer.outcome import _SHORT_DEFINITIONS
|
||||
@@ -113,8 +113,10 @@ def _aligned_devices(rows: list[TuiRow], width: int) -> list[TuiRow]:
|
||||
def _view_setup(state: TuiState, width: int, height: int) -> tuple:
|
||||
rows = tui_rows(state)
|
||||
focus = rows[min(state.focus.get("setup", 0), len(rows) - 1)]
|
||||
after = ([f"BIOS folder: {shown_path(setup_bios_folder(*state.setups[focus.value][:2]))}"]
|
||||
if focus.action == "setup" else [])
|
||||
after = []
|
||||
if focus.action == "setup":
|
||||
plat, path, _label = state.setups[focus.value]
|
||||
after.append(f"BIOS folder: {shown_path(state.setup_folders[plat, path])}")
|
||||
before = ["Found on this machine:" if state.setups
|
||||
else "A drive here could be either of these:" if state.doubts
|
||||
else "Nothing was found here."]
|
||||
@@ -208,7 +210,7 @@ def _view_folder(state: TuiState, width: int, height: int) -> tuple:
|
||||
before = [f"No usual {name} folder here: browse for it or type it."]
|
||||
notes: list = []
|
||||
if not bound and state.folder_kind != "share":
|
||||
notes = [note for note in (drives_left_out(state.platform), unproven_words()) if note]
|
||||
notes = list(state.folder_scan.notes) if state.folder_scan else []
|
||||
body = _fitted_compose(state, width, height, before, notes,
|
||||
tui_rows(state), _status_after(state), state.refused)
|
||||
return (title, body, ("A/Enter Choose", "B/Esc Back", "? Help"))
|
||||
|
||||
@@ -3,7 +3,6 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import codecs
|
||||
import contextlib
|
||||
import errno
|
||||
import functools
|
||||
import io
|
||||
@@ -20,10 +19,18 @@ from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, TextIO
|
||||
|
||||
from installer.cards import _SHARE_FOLDERS, _mounted_cards, card_bound, card_platform, share_doubt
|
||||
from installer.cards import (
|
||||
_SHARE_FOLDERS,
|
||||
_mounted_cards,
|
||||
card_bound,
|
||||
card_platform,
|
||||
setup_folders,
|
||||
share_doubt,
|
||||
)
|
||||
from installer.console import QUIT_CODE
|
||||
from installer.destination import card_choice, dest_default
|
||||
from installer.detect_frontends import detect_frontends
|
||||
from installer.detection_notes import DETECTION_NOTES, detection_held
|
||||
from installer.detect_os import _enter_wsl, _wsl_dest, detect_os, detected_os
|
||||
from installer.from_folders import _open_local_sources, from_folder_problem
|
||||
from installer.host_fs import _DETECTION_REFUSED, refused_words
|
||||
@@ -135,19 +142,19 @@ def _tui_take_args(state: TuiState, args: argparse.Namespace) -> None:
|
||||
|
||||
def _tui_detect(state: TuiState, os_type: str) -> None:
|
||||
"""The setups and cards found here, and what detection said."""
|
||||
captured = io.StringIO()
|
||||
with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
|
||||
start = len(DETECTION_NOTES)
|
||||
with detection_held():
|
||||
state.setups, state.mounted_setups = found_setups(os_type)
|
||||
frontends = detect_frontends(os_type)
|
||||
state.setup_folders = setup_folders(state.setups)
|
||||
# Said on the normal screen before this one covered it, and kept
|
||||
# above the list: a status line under 18 setups was never drawn.
|
||||
state.refused = [refused_words(folder, why, _short_path(folder, state.home))
|
||||
for folder, why in _DETECTION_REFUSED]
|
||||
unsaid = {refused_words(*refused) for refused in _DETECTION_REFUSED}
|
||||
if "esde" in frontends:
|
||||
state.notes.append(TUI_ESDE_NOTE)
|
||||
state.notes += [line.strip() for line in captured.getvalue().splitlines()
|
||||
if line.strip() and line.strip() not in unsaid]
|
||||
state.notes += [line.strip() for note in DETECTION_NOTES[start:]
|
||||
for line in note.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def _start_on_platform(state: TuiState, args: argparse.Namespace, plat: str,
|
||||
@@ -458,11 +465,23 @@ def _closing_lines(state: TuiState) -> list[str]:
|
||||
for line in state.error)]
|
||||
if state.exit_code == 0:
|
||||
return [f"RetroBIOS: everything is in place in {state.dest}."]
|
||||
if state.quit_asked:
|
||||
if _quit_closing(state):
|
||||
return [TUI_QUIT_WORDS]
|
||||
return ["RetroBIOS: stopped. Nothing was installed."]
|
||||
|
||||
|
||||
def _quit_closing(state: TuiState) -> bool:
|
||||
"""Whether the screen closes on the quit the user asked for: no install
|
||||
ran, no result, error or crash to report, and the exit not a success."""
|
||||
if state.screen not in ("result", "details") and state.download is not None:
|
||||
return False
|
||||
if state.screen in ("crashed", "error", "result"):
|
||||
return False
|
||||
if state.screen == "details" and "result" in state.stack:
|
||||
return False
|
||||
return state.exit_code != 0 and state.quit_asked
|
||||
|
||||
|
||||
TUI_QUIT_WORDS = "RetroBIOS: quit. Nothing was installed."
|
||||
|
||||
|
||||
@@ -479,8 +498,10 @@ def _terminal_words(lines: list[str]) -> list[str]:
|
||||
|
||||
|
||||
def tui_quit_chosen(state: TuiState) -> bool:
|
||||
"""Whether the screen ended on a quit the user chose, nothing installed."""
|
||||
return tui_farewell(state) == [TUI_QUIT_WORDS]
|
||||
"""Whether the screen ended on a quit the user chose, nothing installed:
|
||||
read from the state, so a version note after the quit line changes
|
||||
nothing."""
|
||||
return not state.idle_closed and _quit_closing(state)
|
||||
|
||||
|
||||
CTRL_Z_NO_SHELL = ("Ctrl-Z is ignored: no shell started this installer, and none could "
|
||||
@@ -610,14 +631,14 @@ class _TuiSession:
|
||||
kind, state, inbox = effect[0], self.state, self.inbox
|
||||
if kind == "fetch":
|
||||
threading.Thread(target=_tui_fetch_games,
|
||||
args=(effect[1], inbox, self.buffer, state.dest,
|
||||
args=(effect[1], inbox, state.dest,
|
||||
state.games_choice not in ("user", "cli", "record")),
|
||||
daemon=True).start()
|
||||
elif kind == "app":
|
||||
threading.Thread(target=_tui_put_app, args=(effect[1], inbox),
|
||||
daemon=True).start()
|
||||
elif kind == "targets":
|
||||
threading.Thread(target=_tui_fetch_targets, args=(effect[1], inbox, self.buffer),
|
||||
threading.Thread(target=_tui_fetch_targets, args=(effect[1], inbox),
|
||||
daemon=True).start()
|
||||
elif kind == "pack":
|
||||
inbox.put(("pack_opened", effect[1],
|
||||
|
||||
@@ -6,8 +6,11 @@ import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from installer.invocation import offline_requested
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from installer.handheld_app import CardApp
|
||||
from installer.tui_folder_scan import FolderScan
|
||||
from installer.tui_input import TuiHits
|
||||
|
||||
|
||||
@@ -83,6 +86,9 @@ class TuiState:
|
||||
self.now: float = time.monotonic()
|
||||
# (platform, folder, label) for each setup found here.
|
||||
self.setups: list = []
|
||||
# The BIOS folder each setup announces, keyed by (platform, folder):
|
||||
# read once when the setups are found, never by a frame.
|
||||
self.setup_folders: dict = {}
|
||||
# (platform, card) of each mounted drive whose files fit two systems
|
||||
# (share_doubt): offered under each, never taken for one.
|
||||
self.doubts: list = []
|
||||
@@ -128,8 +134,9 @@ class TuiState:
|
||||
# help and the bar say how to tap only then.
|
||||
self.mouse: bool = False
|
||||
self.list_top: dict = {}
|
||||
# The mounted cards of that system, as last looked for.
|
||||
self.cards: list | None = None
|
||||
# The drives the folder screen lists, as last looked for: read when
|
||||
# it opens and on Look again, never by a frame.
|
||||
self.folder_scan: FolderScan | None = None
|
||||
# (width and text, lines) of the last pager wrapped.
|
||||
self.pager_cache: tuple | None = None
|
||||
self.path_text: str = ""
|
||||
@@ -278,12 +285,21 @@ class TuiState:
|
||||
self.code: int | None = None
|
||||
self.stopping: bool = False
|
||||
self.tail: list = []
|
||||
# The run's stop for lack of space in words, read when it ended: the
|
||||
# result screen looked through the mounted drives on every frame.
|
||||
self.full_drive: str = ""
|
||||
# Needed and free bytes, from the no_space event of the run going on.
|
||||
self.no_space: tuple[int, int] | None = None
|
||||
self.log: str = ""
|
||||
self.exit_code: int | None = None
|
||||
# The RetroBIOS app on the card the BIOS folder is on: asked for
|
||||
# (--add-app, the options), what putting it did (the app event),
|
||||
# and the card, read once per folder.
|
||||
self.add_app: bool = False
|
||||
# Without the internet: read from --offline or the variable when the
|
||||
# screens start, changed by the option. The 'offline' effect writes
|
||||
# it for the runs, and the check is stale whenever it moves.
|
||||
self.offline: bool = offline_requested()
|
||||
self.app: dict | None = None
|
||||
self.app_running: bool = False
|
||||
self.card_for: Path | None = None
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"unsearched",
|
||||
"detect",
|
||||
"error",
|
||||
"no_space",
|
||||
"scanned",
|
||||
"version",
|
||||
"board",
|
||||
@@ -29,6 +30,7 @@
|
||||
"check",
|
||||
"declared",
|
||||
"data",
|
||||
"space",
|
||||
"found",
|
||||
"unreadable",
|
||||
"saves",
|
||||
@@ -61,6 +63,9 @@
|
||||
{
|
||||
"$ref": "#/$defs/error"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/no_space"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/scanned"
|
||||
},
|
||||
@@ -106,6 +111,9 @@
|
||||
{
|
||||
"$ref": "#/$defs/data"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/space"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/found"
|
||||
},
|
||||
@@ -267,6 +275,36 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"no_space": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"event",
|
||||
"platform",
|
||||
"folder",
|
||||
"bytes_needed",
|
||||
"bytes_free"
|
||||
],
|
||||
"properties": {
|
||||
"event": {
|
||||
"const": "no_space"
|
||||
},
|
||||
"platform": {
|
||||
"type": "string"
|
||||
},
|
||||
"folder": {
|
||||
"type": "string"
|
||||
},
|
||||
"bytes_needed": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"bytes_free": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
"scanned": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
@@ -779,6 +817,27 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"space": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"event",
|
||||
"platform",
|
||||
"bytes"
|
||||
],
|
||||
"properties": {
|
||||
"event": {
|
||||
"const": "space"
|
||||
},
|
||||
"platform": {
|
||||
"type": "string"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
"found": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
||||
@@ -618,8 +618,20 @@
|
||||
"description": "RetroDECK: the requirement wording, which is free text"
|
||||
},
|
||||
"component": {
|
||||
"type": "string",
|
||||
"description": "RetroDECK: the component whose manifest declares this file"
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 2,
|
||||
"uniqueItems": true
|
||||
}
|
||||
],
|
||||
"description": "RetroDECK: the component whose manifest declares this file, or the components whose manifests each declare it with the same hashes and requirement"
|
||||
},
|
||||
"alt_paths": {
|
||||
"type": "array",
|
||||
|
||||
@@ -242,8 +242,34 @@ def step3b_software_heritage(entry: dict) -> bytes | None:
|
||||
return None
|
||||
|
||||
|
||||
def archive_org_by_sha1(sha1: str) -> bytes | None:
|
||||
"""The first archive.org file whose metadata names sha1, read and checked.
|
||||
|
||||
The member is chosen by its recorded sha1, never by its name: an item
|
||||
may store the dump under any path (bios/SCPH1001.BIN for scph1001.bin).
|
||||
"""
|
||||
search = ("https://archive.org/advancedsearch.php?q="
|
||||
f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5")
|
||||
docs = _get_json(search).get("response", {}).get("docs", [])
|
||||
for doc in docs:
|
||||
identifier = doc.get("identifier")
|
||||
if not identifier:
|
||||
continue
|
||||
files = _get_json(f"https://archive.org/metadata/{identifier}/files").get("result", [])
|
||||
for item in files:
|
||||
if str(item.get("sha1", "")).lower() != sha1:
|
||||
continue
|
||||
url = (f"https://archive.org/download/{identifier}/"
|
||||
f"{urllib.parse.quote(item['name'])}")
|
||||
data = _get(url, timeout=60)
|
||||
if data is not None and hashlib.sha1(data).hexdigest() == sha1:
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def step4_search_archive_org(entry: dict) -> bytes | None:
|
||||
"""Search archive.org firmware collections by direct download."""
|
||||
"""Search archive.org firmware collections by direct download, then
|
||||
every item by each accepted sha1."""
|
||||
name = entry["name"]
|
||||
|
||||
for collection_id in ARCHIVE_ORG_COLLECTIONS:
|
||||
@@ -252,21 +278,8 @@ def step4_search_archive_org(entry: dict) -> bytes | None:
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
|
||||
sha1s = sorted(parse_hash_list(entry.get("sha1")))
|
||||
if not sha1s:
|
||||
return None
|
||||
# Each accepted revision is a query of its own: archive.org matches one.
|
||||
sha1 = " OR ".join(f"sha1:{value}" for value in sha1s)
|
||||
|
||||
search_url = (
|
||||
"https://archive.org/advancedsearch.php?q="
|
||||
f"{urllib.parse.quote(sha1)}&output=json&rows=1"
|
||||
)
|
||||
|
||||
docs = _get_json(search_url).get("response", {}).get("docs", [])
|
||||
identifier = docs[0].get("identifier") if docs else None
|
||||
if identifier:
|
||||
data = _get(f"https://archive.org/download/{identifier}/{name}")
|
||||
for sha1 in sorted(parse_hash_list(entry.get("sha1"))):
|
||||
data = archive_org_by_sha1(sha1)
|
||||
if data is not None and verify_content(data, entry):
|
||||
return data
|
||||
return None
|
||||
@@ -435,7 +448,7 @@ def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int:
|
||||
data = step3b_software_heritage(entry)
|
||||
where = "Software Heritage"
|
||||
if data is None:
|
||||
data, where = _archive_org_by_sha1(sha1), "archive.org"
|
||||
data, where = archive_org_by_sha1(sha1), "archive.org"
|
||||
if data is None:
|
||||
note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else ""
|
||||
print(f" {sha1}: not found{note}")
|
||||
@@ -448,25 +461,6 @@ def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int:
|
||||
return 1 if missing else 0
|
||||
|
||||
|
||||
def _archive_org_by_sha1(sha1: str) -> bytes | None:
|
||||
"""The first archive.org file whose metadata names sha1, read and checked."""
|
||||
search = ("https://archive.org/advancedsearch.php?q="
|
||||
f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5")
|
||||
docs = _get_json(search).get("response", {}).get("docs", [])
|
||||
for doc in docs:
|
||||
identifier = doc.get("identifier")
|
||||
files = _get_json(f"https://archive.org/metadata/{identifier}/files").get("result", [])
|
||||
for item in files:
|
||||
if str(item.get("sha1", "")).lower() != sha1:
|
||||
continue
|
||||
url = (f"https://archive.org/download/{identifier}/"
|
||||
f"{urllib.parse.quote(item['name'])}")
|
||||
data = _get(url, timeout=60)
|
||||
if data is not None and hashlib.sha1(data).hexdigest() == sha1:
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md"
|
||||
|
||||
|
||||
|
||||
@@ -319,3 +319,24 @@ def build_report(
|
||||
"out_of_scope": out_of_scope,
|
||||
}
|
||||
return report
|
||||
|
||||
|
||||
def print_missing(entry: dict, derived: dict[str, dict]) -> None:
|
||||
"""One missing dump, with what derives it, reads it and holds it."""
|
||||
label = entry.get("description") or entry["name"]
|
||||
source = derived.get(entry.get("sha1", ""))
|
||||
if source:
|
||||
print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} "
|
||||
f"of {' + '.join(source['from'])}")
|
||||
else:
|
||||
print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}")
|
||||
for need in entry.get("needed_by", []):
|
||||
print(f" needed by {need['emulator']} as {need['name']} "
|
||||
f"({'required' if need['required'] else 'optional'}, "
|
||||
f"matched by {need['by']})")
|
||||
for hit in entry.get("romsets", []):
|
||||
versions = hit["dats"][0] if len(hit["dats"]) == 1 else (
|
||||
f"{hit['dats'][0]} to {hit['dats'][-1]}"
|
||||
)
|
||||
print(f" in {hit['source']} {hit['archive']} as "
|
||||
f"{hit['member']} ({versions})")
|
||||
@@ -32,162 +32,15 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collection.gitrestore import GitFailed
|
||||
from collection.integrity import check
|
||||
from core.cli import add_repo_inputs
|
||||
from core.hashing import file_digest, git_blob_sha
|
||||
from model.largefiles import load_registered_paths
|
||||
|
||||
MISREAD = "misread"
|
||||
RESTORED = "restored"
|
||||
FLAGGED = "flagged"
|
||||
SKIPPED = "skipped"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
path: str
|
||||
verdict: str # misread, restored, flagged, skipped
|
||||
reason: str
|
||||
expected: str
|
||||
found: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Report:
|
||||
checked: int = 0
|
||||
findings: list[Finding] = field(default_factory=list)
|
||||
|
||||
def counts(self) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for f in self.findings:
|
||||
counts[f.verdict] = counts.get(f.verdict, 0) + 1
|
||||
return counts
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"checked": self.checked,
|
||||
"counts": self.counts(),
|
||||
"findings": [f.__dict__ for f in self.findings],
|
||||
}
|
||||
|
||||
@property
|
||||
def clean(self) -> bool:
|
||||
return all(f.verdict in (MISREAD, RESTORED) for f in self.findings)
|
||||
|
||||
|
||||
class GitFailed(RuntimeError):
|
||||
"""A git command failed: its empty output says nothing about the file."""
|
||||
|
||||
|
||||
def git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
||||
"""Run git in root. A failure raises: an unreadable index read as an empty
|
||||
status made a session's working change look unmodified, and --apply wrote
|
||||
HEAD's bytes over it."""
|
||||
done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False)
|
||||
if done.returncode:
|
||||
message = done.stderr.decode(errors="replace").strip()
|
||||
raise GitFailed(f"git {' '.join(args)} exited {done.returncode}: {message}")
|
||||
return done
|
||||
|
||||
|
||||
def head_blob(root: Path, path: str) -> str:
|
||||
"""The blob HEAD records for path, empty when HEAD has none."""
|
||||
out = git(root, "ls-tree", "HEAD", "--", path).stdout.decode()
|
||||
parts = out.split()
|
||||
return parts[2] if len(parts) >= 3 and parts[1] == "blob" else ""
|
||||
|
||||
|
||||
def modified_for_git(root: Path, path: str) -> bool:
|
||||
return bool(git(root, "status", "--porcelain", "--", path).stdout.strip())
|
||||
|
||||
|
||||
def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str:
|
||||
"""Write the blob's bytes over path, after checking them. Empty on success."""
|
||||
data = git(root, "cat-file", "blob", blob).stdout
|
||||
object_id = git_blob_sha(data)
|
||||
if object_id != blob:
|
||||
return f"blob read back as {object_id[:12]}, not {blob[:12]}"
|
||||
if hashlib.sha1(data).hexdigest() != expected:
|
||||
return "HEAD holds other bytes than database.json records"
|
||||
target = root / path
|
||||
handle, scratch = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.")
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as out:
|
||||
out.write(data)
|
||||
os.chmod(scratch, target.stat().st_mode & 0o777)
|
||||
os.replace(scratch, target)
|
||||
except OSError:
|
||||
if os.path.exists(scratch):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
return ""
|
||||
|
||||
|
||||
def check(
|
||||
root: Path,
|
||||
db: dict,
|
||||
apply: bool,
|
||||
hasher: Callable[[Path], str] = file_digest,
|
||||
) -> Report:
|
||||
"""Hash every database path, confirm each mismatch, repair what may be."""
|
||||
ignored = set(load_registered_paths(root / ".gitignore"))
|
||||
report = Report()
|
||||
for key, entry in sorted(db.get("files", {}).items(), key=lambda kv: kv[1]["path"]):
|
||||
path = entry["path"]
|
||||
expected = str(entry.get("sha1") or key).lower()
|
||||
local = root / path
|
||||
if not local.is_file():
|
||||
continue # a release asset not fetched yet, verify reports it
|
||||
report.checked += 1
|
||||
first = hasher(local)
|
||||
if first == expected:
|
||||
continue
|
||||
second = hasher(local)
|
||||
if second != first:
|
||||
verdict = MISREAD if second == expected else FLAGGED
|
||||
report.findings.append(Finding(
|
||||
path, verdict, f"two reads disagree ({first[:12]}, {second[:12]})",
|
||||
expected, second))
|
||||
continue
|
||||
if path in ignored:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "gitignored large file, never repaired here", expected, first))
|
||||
continue
|
||||
blob = head_blob(root, path)
|
||||
if not blob:
|
||||
report.findings.append(Finding(path, FLAGGED, "not in HEAD", expected, first))
|
||||
continue
|
||||
if modified_for_git(root, path):
|
||||
report.findings.append(Finding(
|
||||
path, SKIPPED, "modified for git: a working change, left alone",
|
||||
expected, first))
|
||||
continue
|
||||
if not apply:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "bit flip, restorable from HEAD with --apply", expected, first))
|
||||
continue
|
||||
problem = restore_from_blob(root, path, blob, expected)
|
||||
if problem:
|
||||
report.findings.append(Finding(path, FLAGGED, problem, expected, first))
|
||||
continue
|
||||
after = hasher(local)
|
||||
if after == expected:
|
||||
report.findings.append(Finding(
|
||||
path, RESTORED, f"restored from blob {blob[:12]}", expected, first))
|
||||
else:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, f"restored but reads {after[:12]}", expected, after))
|
||||
return report
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -19,94 +19,10 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
from core.cli import add_repo_inputs
|
||||
from core.hashing import compute_hashes
|
||||
from core.sizes import size_text
|
||||
from resolve.directories import expand_directory_entries
|
||||
from model.registry import list_registered_platforms
|
||||
from model.database import load_database
|
||||
from model.profiles import load_emulator_profiles
|
||||
from model.platforms import load_platform_config
|
||||
from packs.crossref import FileConsumers
|
||||
|
||||
|
||||
def _entries(profile: dict, db: dict) -> list[dict]:
|
||||
files = [f for f in profile.get("files") or [] if isinstance(f, dict)]
|
||||
return expand_directory_entries(files, db, False) + [
|
||||
f for f in expand_directory_entries(files, db, True) if f not in files
|
||||
]
|
||||
|
||||
|
||||
def shipped_by_manifests(install_dir: Path) -> set[str]:
|
||||
"""Every sha1 an install manifest places, alternatives included."""
|
||||
shipped: set[str] = set()
|
||||
for path in sorted(install_dir.glob("*.json")):
|
||||
manifest = json.loads(path.read_text(encoding="utf-8"))
|
||||
for entry in manifest.get("files") or []:
|
||||
shipped.add(str(entry.get("sha1") or ""))
|
||||
shipped.update(str(a.get("sha1") or "") for a in entry.get("alternatives") or [])
|
||||
return shipped - {""}
|
||||
|
||||
|
||||
def bundled_only(db: dict, profiles: dict, platforms_dir: str, install_dir: Path) -> list[dict]:
|
||||
"""Collected files a bundled entry resolves to and nothing else needs."""
|
||||
consumers = FileConsumers(db)
|
||||
needed: set[str] = set(shipped_by_manifests(install_dir))
|
||||
for name in list_registered_platforms(platforms_dir):
|
||||
config = load_platform_config(name, platforms_dir)
|
||||
for system in config.get("systems", {}).values():
|
||||
for entry in system.get("files", []):
|
||||
sha1 = consumers.sha1_of(entry, entry.get("destination", ""))
|
||||
if sha1:
|
||||
needed.add(sha1)
|
||||
bundled: dict[str, set[str]] = {}
|
||||
for emulator, profile in profiles.items():
|
||||
if profile.get("type") == "alias":
|
||||
continue
|
||||
for entry in _entries(profile, db):
|
||||
sha1 = consumers.sha1_of(entry, entry.get("path") or "", owner=emulator)
|
||||
if not sha1:
|
||||
continue
|
||||
# A platform whose package leaves the file out (not_bundled_on:
|
||||
# AmberELEC's amiberry 7.1.1 has no AROS ROMs) brings it from
|
||||
# the collection.
|
||||
if entry.get("bundled") and not entry.get("not_bundled_on"):
|
||||
bundled.setdefault(sha1, set()).add(emulator)
|
||||
else:
|
||||
needed.add(sha1)
|
||||
files = db.get("files", {})
|
||||
rows = [
|
||||
{"sha1": sha1, "path": files[sha1]["path"], "size": files[sha1].get("size", 0),
|
||||
"emulators": sorted(emulators)}
|
||||
for sha1, emulators in sorted(bundled.items(), key=lambda kv: files[kv[0]]["path"])
|
||||
if sha1 not in needed and sha1 in files
|
||||
]
|
||||
return rows + other_copies(rows, Path(db.get("bios_dir") or "bios"))
|
||||
|
||||
|
||||
def other_copies(rows: list[dict], bios_dir: Path) -> list[dict]:
|
||||
"""The same bytes under other paths of the collection.
|
||||
|
||||
The database keeps one path per sha1, and the trees kept whole
|
||||
(NODEDUP: splitwolf's sprite directories, c64-emu's machine folders)
|
||||
hold the same file several times. Listing only the indexed path took
|
||||
five passes to empty splitwolf. A file is hashed only when its size is
|
||||
one a listed file has.
|
||||
"""
|
||||
by_size: dict[int, dict[str, dict]] = {}
|
||||
for row in rows:
|
||||
by_size.setdefault(int(row["size"]), {})[row["sha1"]] = row
|
||||
listed = {row["path"] for row in rows}
|
||||
found = []
|
||||
for path in sorted(bios_dir.rglob("*")):
|
||||
if not path.is_file() or path.is_symlink() or path.as_posix() in listed:
|
||||
continue
|
||||
same_size = by_size.get(path.stat().st_size)
|
||||
if not same_size:
|
||||
continue
|
||||
sha1 = compute_hashes(path, frozenset({"sha1"}))["sha1"]
|
||||
if sha1 in same_size:
|
||||
found.append({**same_size[sha1], "path": path.as_posix()})
|
||||
return found
|
||||
from packs.bundledonly import bundled_only
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -61,9 +61,6 @@ job runs it on a schedule.
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
@@ -77,34 +74,18 @@ if sys.version_info < (3, 9):
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import yaml
|
||||
|
||||
from unattended import worktree
|
||||
from core import hostguard
|
||||
from probes.profileedit import ProfileEditError
|
||||
from core.paths import REPO_ROOT
|
||||
from probes.campaign import Campaign
|
||||
from probes.campaignmodes import run_mode
|
||||
from probes.content import ROMFETCH_ENV
|
||||
from probes.gate import changed_profiles, gate
|
||||
from probes.host import CONTENT_FILE, Paths, Settings, host_lock
|
||||
from probes.reports import REVIEWED, open_findings, render_status, review_finding, status_report
|
||||
|
||||
|
||||
EXIT_REFUSED = 3
|
||||
|
||||
|
||||
def parse_budget(text: str) -> float:
|
||||
match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([smh]?)\s*", text or "")
|
||||
if not match:
|
||||
raise argparse.ArgumentTypeError(f"--budget {text!r}: a number with s, m or h")
|
||||
return float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600}[match[2]]
|
||||
from probes.host import CONTENT_FILE, parse_budget
|
||||
from probes.reports import REVIEWED
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Command line
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0],
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
@@ -155,109 +136,9 @@ def _parser() -> argparse.ArgumentParser:
|
||||
return parser
|
||||
|
||||
|
||||
def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Paths) -> int:
|
||||
updates: dict[str, object] = {}
|
||||
for item in args.set:
|
||||
name, sep, value = item.partition("=")
|
||||
if not sep or not name:
|
||||
parser.error(f"--set {item!r}: FIELD=YAML")
|
||||
updates[name] = yaml.safe_load(value)
|
||||
try:
|
||||
line = review_finding(paths.root, args.key, args.status, args.reason, updates,
|
||||
args.index)
|
||||
except (ValueError, ProfileEditError) as exc:
|
||||
print(f"campaign: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{line['status']} {line['key']} [{line['id']}]")
|
||||
return 0
|
||||
|
||||
|
||||
def _findings(args: argparse.Namespace, paths: Paths) -> int:
|
||||
lines = open_findings(paths.root, args.all)
|
||||
if args.json:
|
||||
print(json.dumps(lines, indent=2))
|
||||
for line in [] if args.json else lines:
|
||||
print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, "
|
||||
f"run shows {json.dumps(line['run_shows'])}. {line['statement']} "
|
||||
f"[{', '.join(line['evidence'])}]")
|
||||
return 0
|
||||
|
||||
|
||||
def _settings(args: argparse.Namespace) -> Settings:
|
||||
if args.command == "run":
|
||||
return Settings(budget=args.budget, max_load_wait=args.max_load_wait,
|
||||
min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb,
|
||||
romfetch=args.romfetch, network=not args.offline,
|
||||
allow_unsandboxed=args.allow_unsandboxed, bench=args.bench)
|
||||
if args.command == "references":
|
||||
return Settings(romfetch=args.romfetch, network=not args.offline,
|
||||
allow_unsandboxed=args.allow_unsandboxed)
|
||||
return Settings()
|
||||
|
||||
|
||||
def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) -> int:
|
||||
try:
|
||||
with host_lock(campaign.lock_path):
|
||||
listed = campaign.references(only, args.system, Path(args.png_dir))
|
||||
except hostguard.LockBusy as exc:
|
||||
print(f"campaign: deferred, {exc}", file=sys.stderr)
|
||||
return 75
|
||||
print(json.dumps(listed, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = _parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
paths = Paths.default()
|
||||
if args.command == "gate":
|
||||
return gate(paths.root, changed_profiles(paths.root))
|
||||
if args.command == "review":
|
||||
return _review(parser, args, paths)
|
||||
if args.command == "findings":
|
||||
return _findings(args, paths)
|
||||
settings = _settings(args)
|
||||
if args.command in ("run", "references"):
|
||||
paths.content_file = Path(args.content_file)
|
||||
campaign = Campaign(paths, settings)
|
||||
if args.command == "status":
|
||||
report = status_report(campaign)
|
||||
print(json.dumps(report, indent=2) if args.json else render_status(report))
|
||||
return 0
|
||||
only = {item.strip() for item in args.only.split(",") if item.strip()}
|
||||
if args.command == "references":
|
||||
return _references(campaign, args, only)
|
||||
if args.dry_run:
|
||||
campaign.run(only, args.system, dry_run=True)
|
||||
return 0
|
||||
return _run_pass(campaign, args, only, paths)
|
||||
|
||||
|
||||
def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int:
|
||||
campaign.dirty_at_start = set(worktree.changed_files(paths.root)) if args.commit else set()
|
||||
|
||||
def stop(signum: int, frame: object) -> None:
|
||||
# SIGTERM ends the pass like Ctrl-C: state saved, pass line written.
|
||||
raise KeyboardInterrupt
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
try:
|
||||
with host_lock(campaign.lock_path):
|
||||
current = campaign.run(only, args.system, commit_every=args.commit_every,
|
||||
commit=args.commit)
|
||||
except hostguard.LockBusy as exc:
|
||||
print(f"campaign: deferred, {exc}", file=sys.stderr)
|
||||
return 75
|
||||
counts, _, _ = campaign.counts()
|
||||
report = {"result": current.result, "detail": current.detail, "counts": counts,
|
||||
"records": len(current.records), "findings": current.findings}
|
||||
if current.result == "refused":
|
||||
# autorun raises an alert from this key of a job's report.
|
||||
report["alert"] = current.detail
|
||||
print(json.dumps(report))
|
||||
if current.result == "refused":
|
||||
return EXIT_REFUSED
|
||||
return 75 if current.result == "paused" else 0
|
||||
parser = build_parser()
|
||||
return run_mode(parser, parser.parse_args(argv))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -19,12 +19,14 @@ import os
|
||||
import sys
|
||||
from core.cli import InputMissing
|
||||
from core.paths import DATA_DIRS_FILE
|
||||
from model.registry import data_dir_registry_at
|
||||
from packs.datadirs import refresh_keys
|
||||
from scraper.buildbot_system import (
|
||||
check,
|
||||
pending,
|
||||
print_report,
|
||||
unanswered,
|
||||
update_changed,
|
||||
updated,
|
||||
)
|
||||
|
||||
|
||||
@@ -60,7 +62,11 @@ def main() -> None:
|
||||
print_report(report)
|
||||
|
||||
if args.update:
|
||||
failed = update_changed(report)
|
||||
# The registry checked is the one refreshed, read in this process:
|
||||
# a child run by relative path read the default registry, and failed
|
||||
# outside the repository root.
|
||||
registry = data_dir_registry_at(args.registry, required=True)
|
||||
failed = refresh_keys(registry, updated(report), force=True)
|
||||
if failed:
|
||||
print(f"ERROR: refresh failed for {', '.join(failed)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -29,190 +29,14 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
GENERATED = re.compile(
|
||||
r"^(database\.json|install/.*\.json|exports/.*\.json|README\.md|CONTRIBUTING\.md"
|
||||
r"|website/src/data/[^/]+\.json)$"
|
||||
)
|
||||
KEPT_TMP = ("acquire",)
|
||||
AUTOMATION_WORKTREE = Path(".cache") / "autorun" / "worktree"
|
||||
ALERT_GB = 100
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Decision:
|
||||
path: Path
|
||||
kind: str # worktree, tmp
|
||||
action: str # remove, keep
|
||||
reason: str
|
||||
|
||||
|
||||
def git(cwd: Path, *args: str, check: bool = True) -> str:
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(cwd), *args], capture_output=True, text=True, check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)}: {proc.stderr.strip()}")
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def main_checkout(cwd: Path) -> Path:
|
||||
"""The main checkout, also when run from inside a linked worktree."""
|
||||
common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir").strip()
|
||||
return Path(common).parent
|
||||
|
||||
|
||||
def busy_paths() -> set[str]:
|
||||
"""Every working directory and open file of every readable process."""
|
||||
found: set[str] = set()
|
||||
proc = Path("/proc")
|
||||
if not proc.is_dir():
|
||||
return found
|
||||
for pid in proc.iterdir():
|
||||
if not pid.name.isdigit():
|
||||
continue
|
||||
links = [pid / "cwd"]
|
||||
with contextlib.suppress(OSError):
|
||||
links += list((pid / "fd").iterdir())
|
||||
for link in links:
|
||||
try:
|
||||
found.add(os.readlink(link))
|
||||
except OSError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def inside(path: Path, root: Path) -> bool:
|
||||
return str(path) == str(root) or str(path).startswith(f"{root}/")
|
||||
|
||||
|
||||
def in_use(path: Path, busy: Iterable[str]) -> bool:
|
||||
root = str(path)
|
||||
prefix = f"{root}/"
|
||||
return any(b == root or b.startswith(prefix) for b in busy)
|
||||
|
||||
|
||||
def age_hours(path: Path, now: float) -> float:
|
||||
return (now - path.stat().st_mtime) / 3600
|
||||
|
||||
|
||||
def real_changes(worktree: Path) -> list[str]:
|
||||
"""Modified tracked paths that are neither deletions nor generated files."""
|
||||
out = git(worktree, "status", "--porcelain", "--untracked-files=no")
|
||||
paths = []
|
||||
for line in out.splitlines():
|
||||
if len(line) < 4 or line[:2].strip() == "D":
|
||||
continue
|
||||
path = line[3:].split(" -> ")[-1].strip('"')
|
||||
if not GENERATED.match(path):
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def linked_worktrees(repo: Path) -> list[Path]:
|
||||
"""Every linked worktree of the checkout, wherever it lives."""
|
||||
out = git(repo, "worktree", "list", "--porcelain")
|
||||
paths = [Path(line[len("worktree "):]) for line in out.splitlines()
|
||||
if line.startswith("worktree ")]
|
||||
return [p for p in paths if p != repo]
|
||||
|
||||
|
||||
def session_worktrees(repo: Path) -> list[Path]:
|
||||
"""Linked worktrees inside the checkout, the automation worktree aside."""
|
||||
keep = repo / AUTOMATION_WORKTREE
|
||||
return [p for p in linked_worktrees(repo) if inside(p, repo) and p != keep]
|
||||
|
||||
|
||||
def judge_worktree(path: Path, busy: Iterable[str], hours: float, now: float) -> Decision:
|
||||
if in_use(path, busy):
|
||||
return Decision(path, "worktree", "keep", "in use")
|
||||
age = age_hours(path, now)
|
||||
if age <= hours:
|
||||
return Decision(path, "worktree", "keep", f"{age:.0f}h recent")
|
||||
real = real_changes(path)
|
||||
if real:
|
||||
return Decision(path, "worktree", "keep", f"uncommitted code: {len(real)} files")
|
||||
return Decision(path, "worktree", "remove", f"{age:.0f}h old, clean")
|
||||
|
||||
|
||||
def judge_tmp(
|
||||
repo: Path, busy: Iterable[str], hours: float, now: float,
|
||||
worktrees: Iterable[Path] = (),
|
||||
) -> list[Decision]:
|
||||
tmp = repo / "tmp"
|
||||
if not tmp.is_dir():
|
||||
return []
|
||||
worktrees = list(worktrees)
|
||||
decisions = []
|
||||
for entry in sorted(tmp.iterdir()):
|
||||
if entry.name in KEPT_TMP or entry.name.endswith(".bundle"):
|
||||
action, reason = "keep", "backup"
|
||||
elif any(inside(w, entry) for w in worktrees):
|
||||
action, reason = "keep", "holds a worktree"
|
||||
elif age_hours(entry, now) <= hours:
|
||||
action, reason = "keep", "recent"
|
||||
elif in_use(entry, busy):
|
||||
action, reason = "keep", "in use"
|
||||
else:
|
||||
action, reason = "remove", "old"
|
||||
decisions.append(Decision(entry, "tmp", action, reason))
|
||||
return decisions
|
||||
|
||||
|
||||
def plan(repo: Path, busy: Iterable[str], hours: float, now: float) -> list[Decision]:
|
||||
busy = set(busy)
|
||||
worktrees = [judge_worktree(w, busy, hours, now) for w in session_worktrees(repo)
|
||||
if w.is_dir()]
|
||||
return worktrees + judge_tmp(repo, busy, hours, now, linked_worktrees(repo))
|
||||
|
||||
|
||||
def apply(repo: Path, decisions: Iterable[Decision]) -> list[str]:
|
||||
"""Carry out the removals, and return the failures."""
|
||||
failures = []
|
||||
removed_worktree = False
|
||||
for d in decisions:
|
||||
if d.action != "remove":
|
||||
continue
|
||||
if d.kind == "worktree":
|
||||
git(repo, "worktree", "unlock", str(d.path), check=False)
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(repo), "worktree", "remove", "--force", str(d.path)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
failures.append(f"{d.path}: {proc.stderr.strip()}")
|
||||
removed_worktree = True
|
||||
continue
|
||||
try:
|
||||
if d.path.is_dir() and not d.path.is_symlink():
|
||||
shutil.rmtree(d.path)
|
||||
else:
|
||||
d.path.unlink()
|
||||
except OSError as exc:
|
||||
failures.append(f"{d.path}: {exc}")
|
||||
if removed_worktree:
|
||||
git(repo, "worktree", "prune", check=False)
|
||||
return failures
|
||||
|
||||
|
||||
def disk_line(path: Path, alert_gb: float) -> tuple[str, bool]:
|
||||
usage = shutil.disk_usage(path)
|
||||
free, total = usage.free / 1024 ** 3, usage.total / 1024 ** 3
|
||||
low = free < alert_gb
|
||||
line = f"disk: {free:.0f} GB free of {total:.0f} GB"
|
||||
if low:
|
||||
line += f"\nALERT: free space under {alert_gb:.0f} GB"
|
||||
return line, low
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from core.gitclone import main_checkout
|
||||
from devtools.diskcleanup import ALERT_GB, apply, busy_paths, disk_line, inside, plan
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -246,7 +70,6 @@ def main() -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from core.cli import run_cli
|
||||
|
||||
run_cli(main)
|
||||
@@ -0,0 +1 @@
|
||||
"""The collection under bios/: its database, its duplicates and the integrity of its bytes."""
|
||||
@@ -0,0 +1,278 @@
|
||||
"""The alternate names platform YAMLs, emulator profiles and known groups give a held content."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from collection.declared import Declarations, hash_values
|
||||
from resolve.localfile import variant_base_name
|
||||
|
||||
|
||||
def _primary_names(entries: list) -> set[str]:
|
||||
return {str(fe.get("name", "")).lower() for fe in entries if isinstance(fe, dict)}
|
||||
|
||||
|
||||
def _own_aliases(file_entry: dict, primary_names: set[str]) -> list[str]:
|
||||
"""Aliases that name no other entry of the same profile."""
|
||||
name = str(file_entry.get("name", "")).lower()
|
||||
return [
|
||||
alias for alias in file_entry.get("aliases") or []
|
||||
if str(alias).lower() == name or str(alias).lower() not in primary_names
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _AliasBook:
|
||||
"""The alternate names collected so far, and what designates a content."""
|
||||
|
||||
files: dict
|
||||
md5_to_sha1: dict[str, str]
|
||||
name_to_sha1: dict[str, str]
|
||||
# The contents held under each name, every copy counted.
|
||||
holders: dict[str, set[str]]
|
||||
# The files a name designates once case is folded.
|
||||
families: dict[str, set[str]]
|
||||
# A name only .variants/ copies carry is not a primary's.
|
||||
named_primaries: set[str]
|
||||
aliases: dict[str, list[dict]] = field(default_factory=dict)
|
||||
|
||||
def add(self, name: str, matched_sha1: str) -> None:
|
||||
if not name or name in self.named_primaries:
|
||||
return
|
||||
if matched_sha1 not in self.aliases:
|
||||
self.aliases[matched_sha1] = []
|
||||
existing = {a["name"] for a in self.aliases[matched_sha1]}
|
||||
if name not in existing:
|
||||
self.aliases[matched_sha1].append({"name": name, "path": ""})
|
||||
|
||||
|
||||
def _alias_book(files: dict, copies: dict | None) -> _AliasBook:
|
||||
"""Index the scanned files by md5, name and folded name."""
|
||||
md5_to_sha1 = {}
|
||||
name_to_sha1 = {}
|
||||
for sha1, entry in files.items():
|
||||
md5_to_sha1[entry["md5"]] = sha1
|
||||
name_to_sha1[entry["name"]] = sha1
|
||||
# The contents held under each name, every copy counted and not only the
|
||||
# primary: which copy of identical bytes is primary follows path order.
|
||||
# Keyed on primaries alone, project64's 64DD_IPL_v12_JPN.bin stopped
|
||||
# naming its content once 64DD_IPL.bin sorted first, and its aliases
|
||||
# 64dd_ipl_J.bin and 64DD_IPL_JP.n64 went with it.
|
||||
holders: dict[str, set[str]] = {}
|
||||
# The files a name designates once case is folded, as the resolver's
|
||||
# name step folds it, a primary and its own .variants/ counted as one
|
||||
# file. dosbox's SC-55 ROM2.BIN found Galaksija's ROM2.BIN the only
|
||||
# exact holder, and its alias ROM2_ST.BIN went to a 4 KiB BASIC ROM,
|
||||
# while SC-55's rom2.bin sat under the same folded name.
|
||||
families: dict[str, set[str]] = {}
|
||||
|
||||
def _hold(name: str, path: str, sha1: str) -> None:
|
||||
holders.setdefault(name, set()).add(sha1)
|
||||
directory = path.rpartition("/")[0].removesuffix("/.variants")
|
||||
families.setdefault(name.casefold(), set()).add(
|
||||
f"{directory}/{variant_base_name(name)}".casefold()
|
||||
)
|
||||
|
||||
for sha1, entry in files.items():
|
||||
_hold(entry["name"], entry["path"], sha1)
|
||||
for sha1, copy_list in (copies or {}).items():
|
||||
if sha1 in files:
|
||||
for copy in copy_list:
|
||||
_hold(copy["name"], copy["path"], sha1)
|
||||
|
||||
# A name only .variants/ copies carry is not a primary's: those copies are
|
||||
# the other revisions of whatever the name designates. Retroarch pins
|
||||
# bios_E.sms to v1.3, and with the name refused, Genesis Plus GX got the
|
||||
# first variant in index order, a 256 KB BIOS, by the name step.
|
||||
named_primaries = {
|
||||
entry["name"] for entry in files.values() if "/.variants/" not in entry["path"]
|
||||
}
|
||||
return _AliasBook(files, md5_to_sha1, name_to_sha1, holders, families, named_primaries)
|
||||
|
||||
|
||||
def _platform_aliases(book: _AliasBook, entries: list[dict]) -> None:
|
||||
"""Register the names platform YAMLs give a held content."""
|
||||
for file_entry in entries:
|
||||
name = file_entry.get("name", "")
|
||||
sha1 = file_entry.get("sha1", "")
|
||||
md5 = file_entry.get("md5", "")
|
||||
|
||||
# A zipped_file entry verifies a ROM INSIDE the archive, so its
|
||||
# hash describes the member and not the file the name designates.
|
||||
# Registering the name against that hash made d2fdc.zip an alias of
|
||||
# a loose 256-byte state-machine-16.rom, which three platforms were
|
||||
# then served in place of the archive.
|
||||
if file_entry.get("zipped_file"):
|
||||
continue
|
||||
|
||||
matched = None
|
||||
if sha1 and sha1 in book.files:
|
||||
matched = sha1
|
||||
elif md5 and md5 in book.md5_to_sha1:
|
||||
matched = book.md5_to_sha1[md5]
|
||||
|
||||
if matched:
|
||||
book.add(name, matched)
|
||||
|
||||
|
||||
def _profile_entry_aliases(
|
||||
book: _AliasBook,
|
||||
file_entry: dict,
|
||||
primary_names: set[str],
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None,
|
||||
) -> None:
|
||||
"""Register the aliases one profile entry gives the contents it designates."""
|
||||
entry_name = file_entry.get("name", "")
|
||||
entry_aliases = _own_aliases(file_entry, primary_names)
|
||||
# A profile may accept several revisions: each held one
|
||||
# is designated by the entry, none of them by guess.
|
||||
matched: set[str] = {
|
||||
value for value in hash_values(file_entry.get("sha1"))
|
||||
if value in book.files
|
||||
}
|
||||
matched |= {
|
||||
book.md5_to_sha1[value]
|
||||
for value in hash_values(file_entry.get("md5"))
|
||||
if value in book.md5_to_sha1
|
||||
}
|
||||
if matched:
|
||||
# Proven by content, the profile's own name designates
|
||||
# the file whatever the collection calls it.
|
||||
entry_aliases.insert(0, entry_name)
|
||||
if not entry_aliases:
|
||||
return
|
||||
if shadowed is not None:
|
||||
taken = [
|
||||
alias for alias in entry_aliases
|
||||
if alias != entry_name and alias in book.named_primaries
|
||||
]
|
||||
if taken:
|
||||
shadowed.append((entry_name, set(matched), taken))
|
||||
held = book.holders.get(entry_name, set())
|
||||
if (
|
||||
not matched
|
||||
and len(held) == 1
|
||||
and len(book.families[entry_name.casefold()]) == 1
|
||||
):
|
||||
# A name carried by several contents names none of them:
|
||||
# quasi88's disk.rom aliases went to whichever
|
||||
# disk.rom the scan met last, a Tandy CoCo ROM.
|
||||
matched = set(held)
|
||||
for sha in sorted(matched):
|
||||
for alias_name in entry_aliases:
|
||||
book.add(alias_name, sha)
|
||||
|
||||
|
||||
def _profile_aliases(
|
||||
book: _AliasBook,
|
||||
profiles: list[list[dict]],
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None,
|
||||
) -> None:
|
||||
"""Register the aliases emulator YAMLs give (aliases field on file entries)."""
|
||||
for entries in profiles:
|
||||
# A profile whose entries name each other (dosbox-x opens
|
||||
# MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry
|
||||
# aliases the other) states that ITS slot takes either name.
|
||||
# Indexed globally that became evidence for every emulator:
|
||||
# ScummVM's MT-32 slot received the CM-32L ROMs.
|
||||
primary_names = _primary_names(entries)
|
||||
for file_entry in entries:
|
||||
_profile_entry_aliases(book, file_entry, primary_names, shadowed)
|
||||
|
||||
|
||||
# Identical content named differently across platforms/cores
|
||||
KNOWN_ALIAS_GROUPS = [
|
||||
# ColecoVision - all these are the same 8KB BIOS
|
||||
["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"],
|
||||
# Game Boy - DMG boot ROM
|
||||
["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"],
|
||||
# Game Boy Color - CGB boot ROM
|
||||
["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"],
|
||||
# Super Game Boy
|
||||
["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"],
|
||||
["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"],
|
||||
["sgb1.program.rom", "SGB1.sfc/program.rom"],
|
||||
["sgb2.program.rom", "SGB2.sfc/program.rom"],
|
||||
# Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin
|
||||
# and nds_firmware.bin and checks their size only: the collection
|
||||
# answers those names with its DS dumps.
|
||||
["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"],
|
||||
["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"],
|
||||
["NDS_Lite_Firmware.bin", "nds_firmware.bin"],
|
||||
["dsi_sd_card.bin", "nds_sd_card.bin"],
|
||||
# MSX
|
||||
["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"],
|
||||
# NEC PC-98
|
||||
["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"],
|
||||
# Enterprise
|
||||
["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"],
|
||||
# ZX Spectrum
|
||||
["48.rom", "zx48.rom"],
|
||||
# SquirrelJME - all JARs are the same
|
||||
[
|
||||
"squirreljme.sqc",
|
||||
"squirreljme.jar",
|
||||
"squirreljme-fast.jar",
|
||||
"squirreljme-slow.jar",
|
||||
"squirreljme-slow-test.jar",
|
||||
"squirreljme-0.3.0.jar",
|
||||
"squirreljme-0.3.0-fast.jar",
|
||||
"squirreljme-0.3.0-slow.jar",
|
||||
"squirreljme-0.3.0-slow-test.jar",
|
||||
],
|
||||
# Arcade - FBNeo spectrum
|
||||
["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"],
|
||||
]
|
||||
|
||||
|
||||
def collect_all_aliases(
|
||||
files: dict,
|
||||
declared: Declarations,
|
||||
copies: dict | None = None,
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None = None,
|
||||
) -> dict:
|
||||
"""Collect alternate filenames from platform YAMLs, profiles, and known aliases.
|
||||
|
||||
Registers alternate names so generate_pack can resolve files stored under different names.
|
||||
``declared`` holds the platform and profile file entries.
|
||||
``copies`` maps a sha1 to the other files the scan found with that content.
|
||||
``shadowed`` receives, per profile entry, its name, the contents its hashes
|
||||
designate and the aliases a primary's name already carries.
|
||||
"""
|
||||
book = _alias_book(files, copies)
|
||||
_platform_aliases(book, declared.platform_entries)
|
||||
|
||||
# core-info is not read here: it was the only network call of a build
|
||||
# that must give the same database offline, and the one name it added
|
||||
# (gearcoleco's writer.rom) is a profile entry proven by its sha1, which
|
||||
# the profile pass below now registers.
|
||||
|
||||
_profile_aliases(book, declared.profile_entries, shadowed)
|
||||
|
||||
for group in KNOWN_ALIAS_GROUPS:
|
||||
matched_sha1 = None
|
||||
for name in group:
|
||||
if name in book.name_to_sha1:
|
||||
matched_sha1 = book.name_to_sha1[name]
|
||||
break
|
||||
if not matched_sha1:
|
||||
continue
|
||||
for name in group:
|
||||
book.add(name, matched_sha1)
|
||||
|
||||
return book.aliases
|
||||
|
||||
|
||||
def add_declared_aliases(
|
||||
files: dict,
|
||||
aliases: dict[str, list[dict]],
|
||||
shadowed: list[tuple[str, set[str], list[str]]],
|
||||
declared: Declarations,
|
||||
) -> None:
|
||||
"""Append to the scan's copies every alternate name the declarations give a held content."""
|
||||
found = collect_all_aliases(files, declared, aliases, shadowed)
|
||||
for sha1, name_list in found.items():
|
||||
for alias_entry in name_list:
|
||||
if sha1 not in aliases:
|
||||
aliases[sha1] = []
|
||||
aliases[sha1].append(alias_entry)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""The MAME clone map _mame_clones.json: where it lives, reading, merging and writing it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from core.artifacts import write_text_atomic
|
||||
|
||||
|
||||
def clone_map_path(bios_dir: str) -> str:
|
||||
"""The clone map beside the scanned tree.
|
||||
|
||||
That is where get_mame_clone_map() reads it for the real layout. A path
|
||||
relative to the working directory let a scan of a fixture tree rewrite
|
||||
the repository's own map.
|
||||
"""
|
||||
return os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json")
|
||||
|
||||
|
||||
def read_clone_map(clone_path: str) -> object:
|
||||
"""The clone map an earlier run wrote, {} when there is none."""
|
||||
# Read before anything is removed: the map is cumulative, and a run that
|
||||
# stopped on an unreadable one after deleting clones would lose them.
|
||||
try:
|
||||
with open(clone_path) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except json.JSONDecodeError as e:
|
||||
raise SystemExit(
|
||||
f"{clone_path} is not valid JSON ({e}). Restore it from git "
|
||||
"before deduplicating again"
|
||||
) from e
|
||||
|
||||
|
||||
def record_clone_map(
|
||||
mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool
|
||||
) -> None:
|
||||
"""Write the clone map, merged with what earlier runs recorded."""
|
||||
# A group is only visible while both copies are on disk, and this run
|
||||
# has just deleted the clone. Writing only what was seen this time
|
||||
# therefore erases every mapping an earlier run recorded, and the
|
||||
# canonical zip stops answering to the names it stands in for. The
|
||||
# older entries stay valid: their canonical file is still here.
|
||||
if not dry_run and isinstance(previous, dict):
|
||||
merged = dict(previous)
|
||||
merged.update(mame_clones)
|
||||
mame_clones = collapse_clone_chains(merged)
|
||||
if dry_run:
|
||||
print(f"\nWould write MAME clone map: {clone_path}")
|
||||
else:
|
||||
write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True))
|
||||
print(f"\nWrote MAME clone map: {clone_path}")
|
||||
print(
|
||||
f" {len(mame_clones)} canonical ZIPs with "
|
||||
f"{sum(len(v['clones']) for v in mame_clones.values())} clones"
|
||||
)
|
||||
|
||||
|
||||
def collapse_clone_chains(clone_map: dict[str, dict]) -> dict[str, dict]:
|
||||
"""Point every clone at a canonical archive that still exists.
|
||||
|
||||
The map is cumulative. When a later run finds that a canonical archive is
|
||||
itself a byte-identical copy of another and removes it, the entry that
|
||||
named it as canonical would send its clones to a file that is gone:
|
||||
sys68k_cpu21a pointed at sys68k_cpu21 after sys68k_cpu21 became a clone
|
||||
of sys68k_cpu20. Each such entry's clones move to the final canonical.
|
||||
"""
|
||||
owner = {
|
||||
clone: canonical
|
||||
for canonical, entry in clone_map.items()
|
||||
for clone in entry.get("clones", [])
|
||||
}
|
||||
|
||||
def final(name: str) -> str:
|
||||
seen = {name}
|
||||
while name in owner:
|
||||
name = owner[name]
|
||||
if name in seen:
|
||||
raise ValueError(f"clone map loops through {name}")
|
||||
seen.add(name)
|
||||
return name
|
||||
|
||||
collapsed: dict[str, dict] = {}
|
||||
for canonical, entry in clone_map.items():
|
||||
target = final(canonical)
|
||||
kept = collapsed.setdefault(target, {**clone_map.get(target, entry), "clones": []})
|
||||
names = set(kept["clones"]) | set(entry.get("clones", []))
|
||||
if target != canonical:
|
||||
names.add(canonical)
|
||||
names.discard(target)
|
||||
kept["clones"] = sorted(names)
|
||||
kept["total_copies"] = len(kept["clones"])
|
||||
return collapsed
|
||||
@@ -0,0 +1,77 @@
|
||||
"""The file entries the registered platforms and the emulator profiles declare, and their hash fields."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from core.cli import SourceUnreadable
|
||||
from model.profiles import source_yaml_paths
|
||||
from model.registry import list_registered_platforms
|
||||
from model.sources import source_yaml_file
|
||||
|
||||
|
||||
def hash_values(value: object) -> list[str]:
|
||||
"""A hash field as lowercase values, whether written alone or as a list."""
|
||||
if not value:
|
||||
return []
|
||||
values = value if isinstance(value, list) else str(value).split(",")
|
||||
return [str(v).strip().lower() for v in values if str(v).strip()]
|
||||
|
||||
|
||||
class UnreadableSource(Exception):
|
||||
"""Platform or profile files that do not parse, named one per line."""
|
||||
|
||||
def __init__(self, sources: list[str]) -> None:
|
||||
super().__init__("\n".join(sources))
|
||||
self.sources = sources
|
||||
|
||||
|
||||
@dataclass
|
||||
class Declarations:
|
||||
"""The file entries of every registered platform, and of each profile apart."""
|
||||
|
||||
platform_entries: list[dict] = field(default_factory=list)
|
||||
# One list per profile: an entry's aliases are judged against its own profile.
|
||||
profile_entries: list[list[dict]] = field(default_factory=list)
|
||||
|
||||
def entries(self) -> list[dict]:
|
||||
"""Every declared file entry, platforms first."""
|
||||
return self.platform_entries + [
|
||||
entry for entries in self.profile_entries for entry in entries
|
||||
]
|
||||
|
||||
|
||||
def _read_source(path: Path, unreadable: list[str]) -> dict | None:
|
||||
"""One platform or profile file, None and its name recorded when it does not read."""
|
||||
try:
|
||||
return source_yaml_file(path) or {}
|
||||
except SourceUnreadable as e:
|
||||
unreadable.append(str(e))
|
||||
except OSError as e:
|
||||
unreadable.append(f"{path}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def read_declarations(platforms_dir: Path, emulators_dir: Path) -> Declarations:
|
||||
"""Every file entry the registered platforms and the profiles declare.
|
||||
|
||||
A source that does not parse is reported and the run refused: written
|
||||
without it, the database lost every alias the file proves and the
|
||||
command exited 0 (dosbox-x's wqy fonts answered not_found).
|
||||
"""
|
||||
declared = Declarations()
|
||||
unreadable: list[str] = []
|
||||
if platforms_dir.is_dir():
|
||||
for name in list_registered_platforms(str(platforms_dir)):
|
||||
config = _read_source(platforms_dir / f"{name}.yml", unreadable)
|
||||
for system in ((config or {}).get("systems") or {}).values():
|
||||
declared.platform_entries.extend(system.get("files") or [])
|
||||
if emulators_dir.is_dir():
|
||||
for source in source_yaml_paths(emulators_dir):
|
||||
profile = _read_source(source, unreadable)
|
||||
if profile is not None:
|
||||
declared.profile_entries.append(profile.get("files") or [])
|
||||
if unreadable:
|
||||
raise UnreadableSource(unreadable)
|
||||
return declared
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Deduplication of bios/: one canonical file per content, the other copies removed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from collection.clonemap import clone_map_path, read_clone_map, record_clone_map
|
||||
from collection.duplicates import plan_group_removals, scan_duplicates
|
||||
from collection.scan import primary_rank
|
||||
from core.sizes import size_text
|
||||
|
||||
|
||||
def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]:
|
||||
"""Remove (or name, in a dry run) each copy beside the canonical file."""
|
||||
removed: list[str] = []
|
||||
for dup in true_dupes_to_remove:
|
||||
if dup == canonical:
|
||||
continue
|
||||
if not os.path.exists(dup):
|
||||
continue
|
||||
if dry_run:
|
||||
print(f" WOULD REMOVE: {dup}")
|
||||
else:
|
||||
try:
|
||||
os.remove(dup)
|
||||
except OSError as e:
|
||||
print(f" WARNING: cannot remove {dup}: {e}")
|
||||
continue
|
||||
# Clean up empty .variants/ directories
|
||||
parent = os.path.dirname(dup)
|
||||
if os.path.basename(parent) == ".variants" and not os.listdir(parent):
|
||||
os.rmdir(parent)
|
||||
removed.append(dup)
|
||||
return removed
|
||||
|
||||
|
||||
def _settle_group(
|
||||
paths: list[str],
|
||||
true_dupes_to_remove: list[str],
|
||||
clone_names: list[str],
|
||||
dry_run: bool,
|
||||
bios_dir: str,
|
||||
) -> dict:
|
||||
"""Keep the best copy of one content and remove the others.
|
||||
|
||||
Only the names the clone map records are MAME clones. A removed variant
|
||||
is one of the copies, and another name kept beside the canonical file
|
||||
is one an emulator looks for: printing either as a MAME clone named a
|
||||
file that stays, or a clone map entry that does not exist.
|
||||
"""
|
||||
def rank(path: str) -> tuple:
|
||||
return primary_rank(Path(path), Path(bios_dir))
|
||||
|
||||
# Find the best canonical across all paths
|
||||
all_paths = [p for p in paths if p not in true_dupes_to_remove]
|
||||
if not all_paths:
|
||||
# All copies were marked for removal: keep the best one
|
||||
all_paths_sorted = sorted(paths, key=rank)
|
||||
all_paths = [all_paths_sorted[0]]
|
||||
true_dupes_to_remove = [p for p in paths if p != all_paths[0]]
|
||||
|
||||
canonical = sorted(all_paths, key=rank)[0]
|
||||
canonical_name = os.path.basename(canonical)
|
||||
|
||||
all_names = set(os.path.basename(p) for p in paths)
|
||||
alias_names = sorted(all_names - {canonical_name})
|
||||
|
||||
size = os.path.getsize(canonical)
|
||||
removed = _remove_copies(canonical, true_dupes_to_remove, dry_run)
|
||||
|
||||
if alias_names or true_dupes_to_remove:
|
||||
action = "Would remove" if dry_run else "Removed"
|
||||
dn = os.path.basename(canonical)
|
||||
print(f" {dn} (keep: {canonical})")
|
||||
if true_dupes_to_remove:
|
||||
print(f" {action} {len(true_dupes_to_remove)} copies")
|
||||
if clone_names:
|
||||
print(f" MAME clones: {clone_names}")
|
||||
kept_names = sorted(
|
||||
{os.path.basename(p) for p in paths if p not in true_dupes_to_remove}
|
||||
- {canonical_name}
|
||||
)
|
||||
if kept_names:
|
||||
print(f" Kept under other names: {kept_names}")
|
||||
return {
|
||||
"canonical": canonical,
|
||||
"removed": removed,
|
||||
"aliases": alias_names,
|
||||
"saved": size * len(removed),
|
||||
}
|
||||
|
||||
|
||||
def _remove_empty_dirs(bios_dir: str) -> int:
|
||||
"""Remove the directories the removals left empty, bottom up."""
|
||||
empty_cleaned = 0
|
||||
for root, dirs, files in os.walk(bios_dir, topdown=False):
|
||||
if not files and not dirs and root != bios_dir:
|
||||
os.rmdir(root)
|
||||
empty_cleaned += 1
|
||||
return empty_cleaned
|
||||
|
||||
|
||||
def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
"""Remove true duplicates, map MAME device clones.
|
||||
|
||||
True duplicates (same name, different dirs): removes copies.
|
||||
MAME clones (different names, same content, same dir): creates mapping.
|
||||
|
||||
Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}}
|
||||
"""
|
||||
clone_path = clone_map_path(bios_dir)
|
||||
previous = read_clone_map(clone_path)
|
||||
|
||||
sha1_groups = scan_duplicates(bios_dir)
|
||||
results: dict[str, dict] = {}
|
||||
total_removed = 0
|
||||
total_saved = 0
|
||||
mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]}
|
||||
|
||||
for sha1, paths in sorted(sha1_groups.items()):
|
||||
if len(paths) <= 1:
|
||||
continue
|
||||
|
||||
group_clones: dict[str, dict] = {}
|
||||
true_dupes_to_remove = plan_group_removals(sha1, paths, group_clones, bios_dir)
|
||||
mame_clones.update(group_clones)
|
||||
|
||||
if not true_dupes_to_remove:
|
||||
continue
|
||||
|
||||
clone_names = [name for entry in group_clones.values() for name in entry["clones"]]
|
||||
settled = _settle_group(paths, true_dupes_to_remove, clone_names, dry_run, bios_dir)
|
||||
total_removed += len(settled["removed"])
|
||||
total_saved += settled.pop("saved")
|
||||
results[sha1] = settled
|
||||
|
||||
# Clean up empty directories
|
||||
empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir)
|
||||
|
||||
prefix = "Would remove" if dry_run else "Removed"
|
||||
print(f"\n{prefix}: {total_removed} files")
|
||||
print(
|
||||
f"Space {'to save' if dry_run else 'saved'}: {size_text(total_saved)}"
|
||||
)
|
||||
if not dry_run and empty_cleaned:
|
||||
print(f"Cleaned {empty_cleaned} empty directories")
|
||||
|
||||
if mame_clones:
|
||||
record_clone_map(mame_clones, previous, clone_path, dry_run)
|
||||
|
||||
return results
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Which files of bios/ hold the same content, and which of those copies may go."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from collection.scan import primary_rank
|
||||
from core.hashing import compute_hashes
|
||||
from model.nodedup import in_nodedup_dir
|
||||
|
||||
|
||||
def _is_mame_dir(path: str) -> bool:
|
||||
"""Check if a path is in a MAME-specific directory."""
|
||||
parts = Path(path).parts
|
||||
return "MAME" in parts or "Arcade" in parts
|
||||
|
||||
|
||||
def scan_duplicates(bios_dir: str) -> dict[str, list[str]]:
|
||||
"""Files grouped by SHA1, excluding no-dedup directories.
|
||||
|
||||
Two equal files have the same size, so only files that share a size are
|
||||
read, and for the sha1 alone: hashing the whole tree with every digest
|
||||
took 33 s for a scan that reads a quarter of it. A file alone at its
|
||||
size is in no group of two and is left out.
|
||||
"""
|
||||
by_size: dict[int, list[str]] = defaultdict(list)
|
||||
for root, _dirs, files in os.walk(bios_dir):
|
||||
for name in files:
|
||||
path = os.path.join(root, name)
|
||||
if in_nodedup_dir(path):
|
||||
continue
|
||||
by_size[os.path.getsize(path)].append(path)
|
||||
|
||||
sha1_to_paths: dict[str, list[str]] = defaultdict(list)
|
||||
for paths in by_size.values():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
for path in paths:
|
||||
sha1_to_paths[compute_hashes(path, frozenset({"sha1"}))["sha1"]].append(path)
|
||||
return sha1_to_paths
|
||||
|
||||
|
||||
def plan_group_removals(
|
||||
sha1: str, paths: list[str], mame_clones: dict, bios_dir: str
|
||||
) -> list[str]:
|
||||
"""Decide which copies of one content hash may go.
|
||||
|
||||
Two files with the same content are not automatically interchangeable.
|
||||
Same name in different directories is a true duplicate. Different names
|
||||
are only collapsible when they are MAME device clones, which is why the
|
||||
check is narrowed to zips under a MAME directory: anywhere else each
|
||||
name may be the one some emulator looks for.
|
||||
|
||||
Records clone groups in *mame_clones* and returns the paths to remove.
|
||||
"""
|
||||
def rank(path: str) -> tuple:
|
||||
return primary_rank(Path(path), Path(bios_dir))
|
||||
|
||||
# Separate by filename: same name = true duplicate, different name = clone
|
||||
by_name: dict[str, list[str]] = defaultdict(list)
|
||||
for p in paths:
|
||||
by_name[os.path.basename(p)].append(p)
|
||||
|
||||
# True duplicates: same filename in multiple directories
|
||||
true_dupes_to_remove: list[str] = []
|
||||
for name_paths in by_name.values():
|
||||
if len(name_paths) > 1:
|
||||
name_paths.sort(key=rank)
|
||||
true_dupes_to_remove.extend(name_paths[1:])
|
||||
|
||||
# A variant exists to hold a content its primary does not. Once another
|
||||
# file holds the same bytes, the copy under .variants/ answers nothing
|
||||
# the index does not already know, whatever its name or suffix: the
|
||||
# resolver finds the content by hash and writes it under the name the
|
||||
# destination asks for.
|
||||
remaining = [p for p in paths if p not in true_dupes_to_remove]
|
||||
variants = [p for p in remaining if ".variants" in Path(p).parts]
|
||||
if variants:
|
||||
holders = [p for p in remaining if p not in variants] or [
|
||||
min(variants, key=rank)
|
||||
]
|
||||
true_dupes_to_remove.extend(p for p in variants if p not in holders)
|
||||
|
||||
# Different filenames, same content. Outside a MAME directory each name
|
||||
# may be needed by a different emulator (64DD_IPL_US.n64, IPL_USA.n64)
|
||||
# and all are kept. Zips that all sit under MAME/Arcade are device
|
||||
# clones: one canonical stays, the clones go and the clone map records them.
|
||||
unique_names = sorted(by_name.keys())
|
||||
all_mame_zip = all(
|
||||
any(_is_mame_dir(p) for p in name_paths) for name_paths in by_name.values()
|
||||
) and all(n.endswith(".zip") for n in unique_names)
|
||||
if len(unique_names) > 1 and all_mame_zip:
|
||||
canonical_name = min(unique_names, key=len)
|
||||
clone_names = [n for n in unique_names if n != canonical_name]
|
||||
mame_clones[canonical_name] = {
|
||||
"sha1": sha1,
|
||||
"clones": clone_names,
|
||||
"total_copies": sum(len(by_name[n]) for n in clone_names),
|
||||
}
|
||||
true_dupes_to_remove.extend(p for n in clone_names for p in by_name[n])
|
||||
|
||||
return true_dupes_to_remove
|
||||
@@ -0,0 +1,59 @@
|
||||
"""What git records for a collection file, and restoring its bytes from the blob in HEAD."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from core.hashing import git_blob_sha
|
||||
|
||||
|
||||
class GitFailed(RuntimeError):
|
||||
"""A git command failed: its empty output says nothing about the file."""
|
||||
|
||||
|
||||
def git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
||||
"""Run git in root. A failure raises: an unreadable index read as an empty
|
||||
status made a session's working change look unmodified, and --apply wrote
|
||||
HEAD's bytes over it."""
|
||||
done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False)
|
||||
if done.returncode:
|
||||
message = done.stderr.decode(errors="replace").strip()
|
||||
raise GitFailed(f"git {' '.join(args)} exited {done.returncode}: {message}")
|
||||
return done
|
||||
|
||||
|
||||
def head_blob(root: Path, path: str) -> str:
|
||||
"""The blob HEAD records for path, empty when HEAD has none."""
|
||||
out = git(root, "ls-tree", "HEAD", "--", path).stdout.decode()
|
||||
parts = out.split()
|
||||
return parts[2] if len(parts) >= 3 and parts[1] == "blob" else ""
|
||||
|
||||
|
||||
def modified_for_git(root: Path, path: str) -> bool:
|
||||
return bool(git(root, "status", "--porcelain", "--", path).stdout.strip())
|
||||
|
||||
|
||||
def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str:
|
||||
"""Write the blob's bytes over path, after checking them. Empty on success."""
|
||||
data = git(root, "cat-file", "blob", blob).stdout
|
||||
object_id = git_blob_sha(data)
|
||||
if object_id != blob:
|
||||
return f"blob read back as {object_id[:12]}, not {blob[:12]}"
|
||||
if hashlib.sha1(data).hexdigest() != expected:
|
||||
return "HEAD holds other bytes than database.json records"
|
||||
target = root / path
|
||||
handle, scratch = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.")
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as out:
|
||||
out.write(data)
|
||||
os.chmod(scratch, target.stat().st_mode & 0o777)
|
||||
os.replace(scratch, target)
|
||||
except OSError:
|
||||
if os.path.exists(scratch):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
return ""
|
||||
@@ -0,0 +1,30 @@
|
||||
"""The digest cache a scan of bios/ reuses for files whose mtime and size did not move."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from core.artifacts import write_text_atomic
|
||||
|
||||
CACHE_DIR = ".cache"
|
||||
CACHE_FILE = os.path.join(CACHE_DIR, "db_cache.json")
|
||||
|
||||
|
||||
def load_cache(cache_path: str) -> dict:
|
||||
"""Load cache file if it exists."""
|
||||
try:
|
||||
with open(cache_path) as f:
|
||||
return json.load(f)
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_cache(cache_path: str, cache: dict) -> None:
|
||||
"""Save the cache whole or not at all.
|
||||
|
||||
Written in place, a crash while serializing left a truncated file that
|
||||
the next run read as empty and rehashed the collection from scratch.
|
||||
"""
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
write_text_atomic(cache_path, json.dumps(cache))
|
||||
@@ -0,0 +1,167 @@
|
||||
"""The secondary indexes of database.json: by hash, name, path tail, shadowed alias and proven name."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from collection.declared import hash_values
|
||||
|
||||
|
||||
def _path_suffixes(rel_path: str) -> list[str]:
|
||||
"""Every tail of a stored path that can answer a declared destination.
|
||||
|
||||
A destination and the tree meet on a tail, and which tail is unknowable
|
||||
from here: one profile writes GC/USA/IPL.bin, another writes the whole
|
||||
nand/.../00000000.app.romfs. Indexing only the tail after
|
||||
bios/Manufacturer/Console answered the first and never the second, so
|
||||
every same-named file collapsed onto one entry.
|
||||
|
||||
The bare filename is left out on purpose. by_name already holds it, and a
|
||||
name alone is the weakest evidence there is.
|
||||
|
||||
bios/Nintendo/GameCube/GC/USA/IPL.bin -> GC/USA/IPL.bin, USA/IPL.bin
|
||||
"""
|
||||
parts = [p for p in rel_path.replace("\\", "/").split("/") if p]
|
||||
if parts and parts[0] == "bios":
|
||||
parts = parts[1:]
|
||||
return ["/".join(parts[-depth:]) for depth in range(len(parts), 1, -1)]
|
||||
|
||||
|
||||
def _index_suffixes(
|
||||
by_path_suffix: dict[str, list[str]], path: str, name: str, sha1: str
|
||||
) -> None:
|
||||
"""File a content under every tail of one of its paths but its bare name."""
|
||||
for suffix in _path_suffixes(path):
|
||||
if suffix == name:
|
||||
continue
|
||||
held = by_path_suffix.setdefault(suffix, [])
|
||||
if sha1 not in held:
|
||||
held.append(sha1)
|
||||
|
||||
|
||||
def build_indexes(files: dict, aliases: dict) -> dict:
|
||||
"""Build secondary indexes for fast lookup."""
|
||||
by_md5: dict[str, str] = {}
|
||||
by_name: dict[str, list[str]] = {}
|
||||
by_crc32: dict[str, str] = {}
|
||||
by_sha256: dict[str, str] = {}
|
||||
by_path_suffix: dict[str, list[str]] = {}
|
||||
|
||||
for sha1, entry in files.items():
|
||||
by_md5[entry["md5"]] = sha1
|
||||
|
||||
name = entry["name"]
|
||||
if name not in by_name:
|
||||
by_name[name] = []
|
||||
by_name[name].append(sha1)
|
||||
|
||||
by_crc32[entry["crc32"]] = sha1
|
||||
by_sha256[entry["sha256"]] = sha1
|
||||
|
||||
# Path suffix index for regional variant resolution
|
||||
_index_suffixes(by_path_suffix, entry["path"], name, sha1)
|
||||
|
||||
# Add alias names to by_name index (aliases have different filenames for same SHA1)
|
||||
for sha1, alias_list in aliases.items():
|
||||
for alias in alias_list:
|
||||
name = alias["name"]
|
||||
if name not in by_name:
|
||||
by_name[name] = []
|
||||
if sha1 not in by_name[name]:
|
||||
by_name[name].append(sha1)
|
||||
# Also index alias paths in by_path_suffix
|
||||
_index_suffixes(by_path_suffix, alias["path"], name, sha1)
|
||||
|
||||
return {
|
||||
"by_md5": by_md5,
|
||||
"by_name": by_name,
|
||||
"by_crc32": by_crc32,
|
||||
"by_sha256": by_sha256,
|
||||
"by_path_suffix": by_path_suffix,
|
||||
}
|
||||
|
||||
|
||||
def shadowed_alias_index(
|
||||
shadowed: list[tuple[str, set[str], list[str]]], by_name: dict
|
||||
) -> dict[str, list[str]]:
|
||||
"""Profile aliases that a primary's name keeps out of by_name.
|
||||
|
||||
QUASI88 reads DISK.ROM as n88sub.rom, but DISK.ROM is the MSX disk ROM's
|
||||
own name, so by_name never points it at the PC-88 file. The resolver reads
|
||||
this index only where the system names a maker and no copy filed under
|
||||
that maker answers the name. An entry with no hash designates the content
|
||||
its own name holds alone in by_name.
|
||||
"""
|
||||
index: dict[str, set[str]] = {}
|
||||
for entry_name, matched, taken in shadowed:
|
||||
held = by_name.get(entry_name, [])
|
||||
designated = matched or (set(held) if len(held) == 1 else set())
|
||||
for alias in taken:
|
||||
fresh = designated - set(by_name.get(alias, []))
|
||||
if fresh:
|
||||
index.setdefault(alias, set()).update(fresh)
|
||||
return {alias: sorted(sha1s) for alias, sha1s in sorted(index.items())}
|
||||
|
||||
|
||||
def proven_name_index(
|
||||
files: dict, indexes: dict, declarations: list[dict]
|
||||
) -> dict[str, list[str]]:
|
||||
"""Names whose held primary no declaration proves, mapped to the primaries
|
||||
of the same directory that declarations of that name prove by hash.
|
||||
|
||||
A hashless entry takes a name's file by name alone. The collection files
|
||||
the DSi Panda devkit boot ROMs as dsi_bios7.bin and dsi_bios9.bin, with
|
||||
the eMMC key-Y zeroed, while every hash declared under those names
|
||||
designates a retail dump beside them: RetroBat and dsperate were served
|
||||
the devkit ROMs. Another revision kept in .variants/ is not a primary,
|
||||
and a dump filed elsewhere is another machine's file.
|
||||
"""
|
||||
by_hash = {
|
||||
"sha1": {sha1: sha1 for sha1 in files},
|
||||
"md5": indexes.get("by_md5", {}),
|
||||
"crc32": indexes.get("by_crc32", {}),
|
||||
"sha256": indexes.get("by_sha256", {}),
|
||||
}
|
||||
proven: dict[str, set[str]] = {}
|
||||
for entry in declarations:
|
||||
# A zipped_file hash is the member's, not the file the name designates.
|
||||
if not isinstance(entry, dict) or entry.get("zipped_file"):
|
||||
continue
|
||||
name = str(entry.get("name") or "").rsplit("/", 1)[-1]
|
||||
if not name:
|
||||
continue
|
||||
for kind, index in by_hash.items():
|
||||
for value in hash_values(entry.get(kind)):
|
||||
held = index.get(value)
|
||||
if held in files:
|
||||
proven.setdefault(name, set()).add(held)
|
||||
result: dict[str, list[str]] = {}
|
||||
for name, designated in sorted(proven.items()):
|
||||
primaries = {
|
||||
sha1 for sha1 in indexes.get("by_name", {}).get(name, [])
|
||||
if sha1 in files and "/.variants/" not in files[sha1]["path"]
|
||||
}
|
||||
if not primaries or primaries & designated:
|
||||
continue
|
||||
homes = {os.path.dirname(files[sha1]["path"]) for sha1 in primaries}
|
||||
beside = [
|
||||
sha1 for sha1 in designated
|
||||
if "/.variants/" not in files[sha1]["path"]
|
||||
and os.path.dirname(files[sha1]["path"]) in homes
|
||||
]
|
||||
if beside:
|
||||
result[name] = sorted(beside, key=lambda sha1: files[sha1]["path"])
|
||||
return result
|
||||
|
||||
|
||||
def database_indexes(
|
||||
files: dict,
|
||||
aliases: dict,
|
||||
shadowed: list[tuple[str, set[str], list[str]]],
|
||||
declarations: list[dict],
|
||||
) -> dict:
|
||||
"""Every index database.json publishes over the scanned files and their aliases."""
|
||||
indexes = build_indexes(files, aliases)
|
||||
indexes["by_shadowed_alias"] = shadowed_alias_index(shadowed, indexes["by_name"])
|
||||
indexes["by_proven_name"] = proven_name_index(files, indexes, declarations)
|
||||
return indexes
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Every file database.json names, hashed again, each confirmed bit flip repaired or flagged."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from collection.gitrestore import head_blob, modified_for_git, restore_from_blob
|
||||
from core.hashing import file_digest
|
||||
from model.largefiles import load_registered_paths
|
||||
|
||||
MISREAD = "misread"
|
||||
RESTORED = "restored"
|
||||
FLAGGED = "flagged"
|
||||
SKIPPED = "skipped"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
path: str
|
||||
verdict: str # misread, restored, flagged, skipped
|
||||
reason: str
|
||||
expected: str
|
||||
found: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Report:
|
||||
checked: int = 0
|
||||
findings: list[Finding] = field(default_factory=list)
|
||||
|
||||
def counts(self) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for f in self.findings:
|
||||
counts[f.verdict] = counts.get(f.verdict, 0) + 1
|
||||
return counts
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"checked": self.checked,
|
||||
"counts": self.counts(),
|
||||
"findings": [f.__dict__ for f in self.findings],
|
||||
}
|
||||
|
||||
@property
|
||||
def clean(self) -> bool:
|
||||
return all(f.verdict in (MISREAD, RESTORED) for f in self.findings)
|
||||
|
||||
|
||||
def check(
|
||||
root: Path,
|
||||
db: dict,
|
||||
apply: bool,
|
||||
hasher: Callable[[Path], str] = file_digest,
|
||||
) -> Report:
|
||||
"""Hash every database path, confirm each mismatch, repair what may be."""
|
||||
ignored = set(load_registered_paths(root / ".gitignore"))
|
||||
report = Report()
|
||||
for key, entry in sorted(db.get("files", {}).items(), key=lambda kv: kv[1]["path"]):
|
||||
path = entry["path"]
|
||||
expected = str(entry.get("sha1") or key).lower()
|
||||
local = root / path
|
||||
if not local.is_file():
|
||||
continue # a release asset not fetched yet, verify reports it
|
||||
report.checked += 1
|
||||
first = hasher(local)
|
||||
if first == expected:
|
||||
continue
|
||||
second = hasher(local)
|
||||
if second != first:
|
||||
verdict = MISREAD if second == expected else FLAGGED
|
||||
report.findings.append(Finding(
|
||||
path, verdict, f"two reads disagree ({first[:12]}, {second[:12]})",
|
||||
expected, second))
|
||||
continue
|
||||
if path in ignored:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "gitignored large file, never repaired here", expected, first))
|
||||
continue
|
||||
blob = head_blob(root, path)
|
||||
if not blob:
|
||||
report.findings.append(Finding(path, FLAGGED, "not in HEAD", expected, first))
|
||||
continue
|
||||
if modified_for_git(root, path):
|
||||
report.findings.append(Finding(
|
||||
path, SKIPPED, "modified for git: a working change, left alone",
|
||||
expected, first))
|
||||
continue
|
||||
if not apply:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "bit flip, restorable from HEAD with --apply", expected, first))
|
||||
continue
|
||||
problem = restore_from_blob(root, path, blob, expected)
|
||||
if problem:
|
||||
report.findings.append(Finding(path, FLAGGED, problem, expected, first))
|
||||
continue
|
||||
after = hasher(local)
|
||||
if after == expected:
|
||||
report.findings.append(Finding(
|
||||
path, RESTORED, f"restored from blob {blob[:12]}", expected, first))
|
||||
else:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, f"restored but reads {after[:12]}", expected, after))
|
||||
return report
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The database.json record: its fields, the sha1s a rebuild retires, and its write."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_if_changed
|
||||
from model import retired
|
||||
|
||||
|
||||
def database_record(files: dict, indexes: dict, bios_dir: str) -> dict:
|
||||
"""The database over the scanned files, stamped with the time of the build."""
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"total_files": len(files),
|
||||
"total_size": sum(entry["size"] for entry in files.values()),
|
||||
# The tree these paths belong to: dedup writes _mame_clones.json
|
||||
# beside it, and the resolver reads the map there, not at the repo root.
|
||||
"bios_dir": os.path.normpath(bios_dir),
|
||||
"files": files,
|
||||
"indexes": indexes,
|
||||
}
|
||||
|
||||
|
||||
def record_retired(output: Path, database: dict) -> int:
|
||||
"""Record beside the database the sha1s the rebuild drops from the one at output.
|
||||
|
||||
A sha1 the rebuild drops keeps its published address: the record
|
||||
beside the database says when it left and what holds its place.
|
||||
"""
|
||||
if not output.is_file():
|
||||
return 0
|
||||
previous = json.loads(output.read_text(encoding="utf-8"))
|
||||
return retired.update(
|
||||
retired.retired_path(output), previous, database,
|
||||
database["generated_at"][:10],
|
||||
)
|
||||
|
||||
|
||||
def write_database(output: str, database: dict) -> bool:
|
||||
"""Write the database unless only its timestamp moved, and say whether it was."""
|
||||
return write_if_changed(output, json.dumps(database, indent=2))
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The database entries of release assets the checkout does not hold, kept across a scan."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class DatabaseUnreadable(Exception):
|
||||
"""The previous database exists and is not JSON: its release-asset entries cannot be kept."""
|
||||
|
||||
|
||||
def load_gitignored_large_files(gitignore: str | Path) -> set[str]:
|
||||
"""The bios/ paths a .gitignore registers as release assets."""
|
||||
from model.largefiles import load_registered_paths
|
||||
|
||||
return set(load_registered_paths(gitignore))
|
||||
|
||||
|
||||
def read_database(db_path: str) -> dict | None:
|
||||
"""The previous database, None when there is none."""
|
||||
try:
|
||||
with open(db_path) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except json.JSONDecodeError as e:
|
||||
# An unreadable database is not an absent one: rewriting it from a
|
||||
# checkout without the release assets would drop every entry they
|
||||
# hold, and the manifests regenerated from it would omit them.
|
||||
raise DatabaseUnreadable(
|
||||
f"{db_path} is not valid JSON ({e}). Restore it from git "
|
||||
"or regenerate it on a checkout holding the release assets before "
|
||||
"scanning again"
|
||||
) from e
|
||||
|
||||
|
||||
def surviving_entries(existing_db: dict, files: dict, registered: set[str]) -> dict:
|
||||
"""The entries of the previous database a scan that missed their file keeps.
|
||||
|
||||
Files kept out of git live as assets of the large-files release, and
|
||||
.gitignore registers their paths. An entry survives only under that
|
||||
registered path: a bare name is shared by other files (pak0.pk3,
|
||||
history.db), and a path rewritten into the download cache is no longer
|
||||
one .gitignore knows, so the manifest would send the installer to the
|
||||
repository for it.
|
||||
"""
|
||||
# A path the scan just claimed holds known bytes. An older entry naming
|
||||
# the same path describes a revision that is no longer there, and keeping
|
||||
# it would publish a hash that contradicts the file it points at.
|
||||
scanned_paths = {entry.get("path", "") for entry in files.values()}
|
||||
return {
|
||||
sha1: entry
|
||||
for sha1, entry in existing_db.get("files", {}).items()
|
||||
if sha1 not in files
|
||||
and entry.get("path", "") in registered
|
||||
and entry.get("path", "") not in scanned_paths
|
||||
}
|
||||
|
||||
|
||||
def restore_release_assets(entries: dict, registered: set[str], *, offline: bool) -> None:
|
||||
"""Write each kept entry's asset back to its registered path, fetched only when online."""
|
||||
from model.largefiles import fetch_large_file, restore_verified
|
||||
|
||||
for sha1, entry in entries.items():
|
||||
path = entry.get("path", "")
|
||||
cached = fetch_large_file(
|
||||
path,
|
||||
expected_sha1=entry.get("sha1", ""),
|
||||
expected_md5=entry.get("md5", ""),
|
||||
offline=offline,
|
||||
registered=registered,
|
||||
)
|
||||
if cached and not os.path.exists(path):
|
||||
restore_verified(cached, path, sha1)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""The files that left database.json, read back through its git history."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from core.paths import REPO_ROOT
|
||||
from model.retired import FIRST_ADDRESSED, merge, retired_between
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True,
|
||||
check=True).stdout
|
||||
|
||||
|
||||
def backfill() -> dict[str, dict]:
|
||||
"""Every sha1 that left database.json in the commits since content
|
||||
addresses were published, with the day of the commit that dropped it."""
|
||||
revisions = [line.split() for line in _git(
|
||||
"log", "--reverse", "--format=%H %cs", f"{FIRST_ADDRESSED}^..HEAD", "--", "database.json",
|
||||
).splitlines() if line.strip()]
|
||||
records: dict[str, dict] = {}
|
||||
previous: dict | None = None
|
||||
for commit, day in revisions:
|
||||
current = json.loads(_git("show", f"{commit}:database.json"))
|
||||
if previous is not None:
|
||||
records = merge(records, retired_between(previous, current, day), current)
|
||||
previous = current
|
||||
return records
|
||||
@@ -0,0 +1,106 @@
|
||||
"""One database.json build: scan bios/, join aliases and provenance, write the record."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from collection.aliases import add_declared_aliases
|
||||
from collection.declared import UnreadableSource, read_declarations
|
||||
from collection.hashcache import CACHE_FILE, load_cache, save_cache
|
||||
from collection.indexes import database_indexes
|
||||
from collection.record import database_record, record_retired, write_database
|
||||
from collection.releaseassets import (
|
||||
DatabaseUnreadable,
|
||||
load_gitignored_large_files,
|
||||
read_database,
|
||||
restore_release_assets,
|
||||
surviving_entries,
|
||||
)
|
||||
from collection.scan import scan_bios_dir
|
||||
from model import retired
|
||||
from model.dumpcatalog import annotate_provenance, load_provenance_snapshots
|
||||
|
||||
# Database entries name paths relative to the working directory, and so does
|
||||
# the registry of release assets beside them.
|
||||
GITIGNORE = Path(".gitignore")
|
||||
|
||||
|
||||
def preserve_release_assets(files: dict, db_path: str, *, offline: bool) -> int:
|
||||
"""Keep the entries of release assets the scan missed, their files restored, and count them."""
|
||||
registered = load_gitignored_large_files(GITIGNORE)
|
||||
if not registered:
|
||||
return 0
|
||||
existing_db = read_database(db_path)
|
||||
if existing_db is None:
|
||||
return 0
|
||||
kept = surviving_entries(existing_db, files, registered)
|
||||
restore_release_assets(kept, registered, offline=offline)
|
||||
files.update(kept)
|
||||
return len(kept)
|
||||
|
||||
|
||||
def generate(args: argparse.Namespace) -> int:
|
||||
"""Scan bios/ and write the database, 1 when a declared source or the old database cannot be read."""
|
||||
bios_dir = Path(args.bios_dir)
|
||||
|
||||
# A forced run rehashes every file but keeps the previous digests to
|
||||
# check the new ones against.
|
||||
cache = load_cache(CACHE_FILE)
|
||||
|
||||
print(f"Scanning {bios_dir}/ ...")
|
||||
files, aliases, new_cache = scan_bios_dir(bios_dir, cache, args.force)
|
||||
|
||||
if not files:
|
||||
print("Warning: No BIOS files found", file=sys.stderr)
|
||||
|
||||
# Preserve entries for large files stored as release assets (.gitignore)
|
||||
try:
|
||||
preserved = preserve_release_assets(files, args.output, offline=args.offline)
|
||||
except DatabaseUnreadable as exc:
|
||||
print(exc, file=sys.stderr)
|
||||
return 1
|
||||
if preserved:
|
||||
print(f" Preserved {preserved} large file entries from existing database")
|
||||
|
||||
shadowed: list[tuple[str, set[str], list[str]]] = []
|
||||
try:
|
||||
declared = read_declarations(Path(args.platforms_dir), Path(args.emulators_dir))
|
||||
except UnreadableSource as exc:
|
||||
for source in exc.sources:
|
||||
print(f"Error: cannot read {source}", file=sys.stderr)
|
||||
print(f"Error: {args.output} not written", file=sys.stderr)
|
||||
return 1
|
||||
add_declared_aliases(files, aliases, shadowed, declared)
|
||||
|
||||
snapshots = load_provenance_snapshots(args.provenance_dir)
|
||||
provenance_counts = annotate_provenance(files, snapshots)
|
||||
|
||||
indexes = database_indexes(files, aliases, shadowed, declared.entries())
|
||||
database = database_record(files, indexes, args.bios_dir)
|
||||
total_size = database["total_size"]
|
||||
|
||||
output = Path(args.output)
|
||||
left = record_retired(output, database)
|
||||
if left:
|
||||
print(f" Left the collection: {left} files, recorded in "
|
||||
f"{retired.retired_path(output)}")
|
||||
|
||||
written = write_database(args.output, database)
|
||||
|
||||
save_cache(CACHE_FILE, new_cache)
|
||||
|
||||
alias_count = sum(len(v) for v in aliases.values())
|
||||
name_count = len(indexes["by_name"])
|
||||
status = "Generated" if written else "Unchanged"
|
||||
print(f"{status} {args.output}: {len(files)} files, {total_size:,} bytes total")
|
||||
print(f" Name index: {name_count} names ({alias_count} aliases)")
|
||||
if provenance_counts:
|
||||
matched = sum(1 for e in files.values() if "provenance" in e)
|
||||
per_source = ", ".join(
|
||||
f"{source} {count}" for source, count in sorted(provenance_counts.items())
|
||||
)
|
||||
print(f" Provenance: {matched} files catalog-matched ({per_source})")
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""The walk of bios/: which files count, their digests, and which copy of a content is primary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from core.hashing import compute_hashes
|
||||
from resolve.localfile import variant_base_name
|
||||
|
||||
SKIP_PATTERNS = {".git", ".github", "__pycache__", ".cache", ".DS_Store", "desktop.ini"}
|
||||
|
||||
# Every digest database.json publishes per file, in the order compute_hashes
|
||||
# returns them. The schema requires all five, so a cache entry missing any of
|
||||
# them cannot serve a database entry, and the order is fixed here so a warm
|
||||
# cache serialises an entry exactly like a fresh hash does.
|
||||
CACHED_HASHES = ("sha1", "md5", "sha256", "crc32", "adler32")
|
||||
|
||||
|
||||
def should_skip(path: Path) -> bool:
|
||||
"""Whether a path stays out of the collection.
|
||||
|
||||
Tooling directories and hidden files do. A hidden directory inside the
|
||||
collection does not: `.variants/` holds alternate dumps, and an engine
|
||||
tree can carry one of its own (C-Dogs SDL reads `data/.wolf3d/`).
|
||||
"""
|
||||
if any(part in SKIP_PATTERNS for part in path.parts):
|
||||
return True
|
||||
return path.name.startswith(".")
|
||||
|
||||
|
||||
def _canonical_name(filepath: Path) -> str:
|
||||
"""Get canonical filename, stripping .variants/ hash suffix."""
|
||||
if ".variants" in filepath.parts:
|
||||
return variant_base_name(filepath.name)
|
||||
return filepath.name
|
||||
|
||||
|
||||
def _settled_hashes(
|
||||
filepath: Path, cached: dict | None, mtime: float, size: int
|
||||
) -> dict:
|
||||
"""The file's digests, computed again when they contradict the cache.
|
||||
|
||||
A forced run rehashes everything, and this host has given a wrong SHA-1
|
||||
under load (DSi_Nand_USA.bin read as 834b140f, not ef08ae02). An entry
|
||||
whose mtime and size did not move but whose digest did is hashed a
|
||||
second time. A second reading that gives the cached value back settles it.
|
||||
Two readings that agree against it do not: the host has returned the same
|
||||
wrong digest twice in a row (62b100f2 for the same file), and a value
|
||||
taken then is cached and read back by every later run. A file rewritten
|
||||
in place moves its mtime, so the run stops instead of choosing.
|
||||
"""
|
||||
hashes = compute_hashes(filepath)
|
||||
if not cached or cached.get("mtime") != mtime or cached.get("size") != size:
|
||||
return hashes
|
||||
if cached.get("sha1") in (None, hashes["sha1"]):
|
||||
return hashes
|
||||
again = compute_hashes(filepath, cache=False)
|
||||
print(
|
||||
f" WARNING: {filepath}: sha1 read as {hashes['sha1'][:8]} then "
|
||||
f"{again['sha1'][:8]}, cached {cached['sha1'][:8]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if again["sha1"] == cached["sha1"]:
|
||||
return again
|
||||
raise RuntimeError(
|
||||
f"{filepath}: read as {again['sha1'][:8]}, cached as {cached['sha1'][:8]}, "
|
||||
"with the same mtime and size. Rerun when the host is idle, or "
|
||||
f"`touch {filepath}` if its bytes really changed."
|
||||
)
|
||||
|
||||
|
||||
def primary_rank(path: Path, bios_dir: Path) -> tuple:
|
||||
"""Rank of one copy of a content, the lowest being its path in the index.
|
||||
|
||||
A .variants/ copy yields to any other one. A copy in an emulator's own
|
||||
tree, bios/Other/<emulator>/, yields to one filed under its machine:
|
||||
ZEsarUX's sms.rom sorted before bios/Sega/Master System/, the resolver
|
||||
set it aside as another emulator's file, and Genesis Plus GX got a
|
||||
variant instead of v1.3. Equal copies follow the walk's order. The scan
|
||||
and the dedup both read this rank, so the copy the dedup keeps is the
|
||||
one the index names.
|
||||
"""
|
||||
parts = path.relative_to(bios_dir).parts
|
||||
return (".variants" in parts, len(parts) > 2 and parts[0] == "Other", parts)
|
||||
|
||||
|
||||
def _add_scanned(
|
||||
files: dict[str, dict],
|
||||
aliases: dict[str, list[dict]],
|
||||
filepath: Path,
|
||||
rel_path: str,
|
||||
size: int,
|
||||
hashes: dict,
|
||||
root: Path,
|
||||
) -> None:
|
||||
"""Record a scanned file as its content's primary, or as an alias of it."""
|
||||
sha1 = hashes["sha1"]
|
||||
entry = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
if sha1 not in files:
|
||||
files[sha1] = entry
|
||||
elif primary_rank(Path(rel_path), root) < primary_rank(Path(files[sha1]["path"]), root):
|
||||
aliases.setdefault(sha1, []).append(
|
||||
{"name": files[sha1]["name"], "path": files[sha1]["path"]}
|
||||
)
|
||||
files[sha1] = entry
|
||||
else:
|
||||
aliases.setdefault(sha1, []).append({"name": entry["name"], "path": rel_path})
|
||||
|
||||
|
||||
def _cached_hashes(cached: dict | None, mtime: float, size: int) -> dict | None:
|
||||
"""The cache's digests of a file that has not changed since."""
|
||||
if cached is None:
|
||||
return None
|
||||
fresh = cached.get("mtime") == mtime and cached.get("size") == size
|
||||
# Rebuilding the hash dict by hand dropped whichever digest the
|
||||
# list forgot, and the entry was then written back to the cache
|
||||
# without it, so the loss survived every later run. Requiring the
|
||||
# full set instead turns a partial cache entry into a miss, which
|
||||
# heals it.
|
||||
if fresh and all(name in cached for name in CACHED_HASHES):
|
||||
return {name: cached[name] for name in CACHED_HASHES}
|
||||
return None
|
||||
|
||||
|
||||
def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, dict]:
|
||||
"""Scan bios directory and compute hashes, using cache when possible."""
|
||||
files: dict[str, dict] = {}
|
||||
aliases: dict[str, list[dict]] = {}
|
||||
new_cache = {}
|
||||
root = Path(bios_dir.name)
|
||||
|
||||
for filepath in sorted(bios_dir.rglob("*")):
|
||||
if not filepath.is_file():
|
||||
continue
|
||||
if should_skip(filepath.relative_to(bios_dir)):
|
||||
continue
|
||||
|
||||
rel_path = str(filepath.relative_to(bios_dir.parent))
|
||||
stat = filepath.stat()
|
||||
mtime = stat.st_mtime
|
||||
size = stat.st_size
|
||||
cache_key = rel_path
|
||||
|
||||
hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size)
|
||||
if hashes is None:
|
||||
hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size)
|
||||
_add_scanned(files, aliases, filepath, rel_path, size, hashes, root)
|
||||
new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size}
|
||||
|
||||
return files, aliases, new_cache
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class GitRefused(RuntimeError):
|
||||
@@ -37,6 +38,17 @@ def required_git_lines(*args: str) -> list[str]:
|
||||
return _lines(result.stdout)
|
||||
|
||||
|
||||
def main_checkout(cwd: Path) -> Path:
|
||||
"""The main checkout of the clone holding cwd, also from a linked worktree,
|
||||
GitRefused when cwd is in no clone."""
|
||||
args = ("rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
result = _run(("-C", str(cwd), *args))
|
||||
if result.returncode:
|
||||
detail = result.stderr.strip() or f"exit {result.returncode}"
|
||||
raise GitRefused(f"git {' '.join(args)}: {detail}")
|
||||
return Path(result.stdout.strip()).parent
|
||||
|
||||
|
||||
# Where a clone with no remote naming the project keeps its main line, each
|
||||
# remote's names in the order tried.
|
||||
FALLBACK_REMOTES = ("upstream", "origin")
|
||||
|
||||
@@ -19,6 +19,10 @@ BIOS_DIR = "bios"
|
||||
DATA_DIRS_FILE = f"{PLATFORMS_DIR}/_data_dirs.yml"
|
||||
# Where generate_truth writes its models and diff_truth and export_native read them.
|
||||
TRUTH_DIR = "dist/truth"
|
||||
# The unattended runner's home, and the worktree it commits from, which disk
|
||||
# cleanup must never take for an idle session worktree.
|
||||
AUTORUN_DIR = ".cache/autorun"
|
||||
AUTORUN_WORKTREE = f"{AUTORUN_DIR}/worktree"
|
||||
|
||||
|
||||
def sanitize_pack_path(raw: str) -> str:
|
||||
|
||||
@@ -623,6 +623,8 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
|
||||
|
||||
A project published outside a forge (Altirra, mednafen, ePSXe) says its
|
||||
version on a download page: that page is the only release feed there is.
|
||||
None is a page the site answers absent. Offline, a page the cache never
|
||||
stored raises NotCachedError, as every other read of this module does.
|
||||
"""
|
||||
key = hashlib.sha256(url.encode()).hexdigest()
|
||||
target = Path(cache_dir) / "_pages" / f"{key}.txt"
|
||||
@@ -632,7 +634,7 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
|
||||
raw = target.read_text(encoding="utf-8")
|
||||
return None if raw == ABSENT else raw
|
||||
if offline:
|
||||
return None
|
||||
raise NotCachedError(f"{url} is not in the offline cache")
|
||||
text = http_text(url)
|
||||
write_cache(target, ABSENT if text is None else text)
|
||||
return text
|
||||
|
||||
@@ -1587,8 +1587,13 @@ def probe(args: argparse.Namespace) -> int:
|
||||
return _probe(args)
|
||||
|
||||
|
||||
def default_max_load(cpus: int | None = None) -> float:
|
||||
"""The load above which a run records nothing without --max-load: a quarter of the CPUs."""
|
||||
return (cpus if cpus is not None else os.cpu_count() or 1) / 4
|
||||
|
||||
|
||||
def _probe(args: argparse.Namespace) -> int:
|
||||
max_load = args.max_load if args.max_load is not None else (os.cpu_count() or 1) / 4
|
||||
max_load = args.max_load if args.max_load is not None else default_max_load()
|
||||
load_before = load_average()
|
||||
if args.record and load_before and load_before[0] > max_load:
|
||||
print(f"ERROR: load average {load_before[0]} exceeds {max_load}: the machine is busy, "
|
||||
|
||||
@@ -15,173 +15,20 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.cli import add_repo_inputs
|
||||
from core.text import count_text
|
||||
from model.cliargs import platform_arg, list_emulator_profiles, require_platform
|
||||
from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles
|
||||
from model.database import load_database
|
||||
from model.registry import list_registered_platforms, load_data_dir_registry
|
||||
from model.platforms import load_platform_config
|
||||
from model.cliargs import platform_arg
|
||||
from model.safeparse import require_yaml
|
||||
from resolve.standalone import standalone_set
|
||||
from resolve.launchers import (
|
||||
LauncherLayer,
|
||||
declared_destinations,
|
||||
launcher_unproven,
|
||||
)
|
||||
|
||||
from packs.crossref import (
|
||||
build_supplemental_index,
|
||||
cross_reference,
|
||||
global_report_scope,
|
||||
launcher_reads_not_held,
|
||||
platform_configs,
|
||||
profile_breakdown,
|
||||
)
|
||||
from packs.crossrefreport import run_gap_report
|
||||
|
||||
yaml = require_yaml()
|
||||
|
||||
|
||||
# The --json key of the launcher reads category, beside the emulator keys.
|
||||
LAUNCHER_READS_KEY = "_launcher_reads_not_held"
|
||||
# The --json key of the launcher records a config file does not prove.
|
||||
LAUNCHER_UNPROVEN_KEY = "_launcher_unproven"
|
||||
|
||||
|
||||
def print_launcher_unproven(rows: list[dict]) -> None:
|
||||
"""The launcher records resting on a config file the code does not prove.
|
||||
|
||||
Neither a pack, a manifest nor a severity reads them: each is listed
|
||||
with the links it lacks.
|
||||
"""
|
||||
if not rows:
|
||||
return
|
||||
platforms = sorted({r["platform"] for r in rows})
|
||||
print(f"\nLauncher records unproven: {len(rows)} across {count_text(len(platforms), 'platform')}")
|
||||
for platform in platforms:
|
||||
print(f"\n{platform}")
|
||||
for row in (r for r in rows if r["platform"] == platform):
|
||||
print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}")
|
||||
for link in row["missing"]:
|
||||
print(f" missing {link}")
|
||||
|
||||
|
||||
def print_launcher_reads(rows: list[dict]) -> None:
|
||||
"""The launcher reads gap category, after the profile gaps.
|
||||
|
||||
A name its reader declares unsourceable is listed apart, with the
|
||||
reason: it is no file left to find.
|
||||
"""
|
||||
unsourceable = [r for r in rows if r.get("unsourceable")]
|
||||
rows = [r for r in rows if not r.get("unsourceable")]
|
||||
platforms = sorted({r["platform"] for r in rows})
|
||||
print(f"\nLauncher reads, not held: {count_text(len(rows), 'name')} "
|
||||
f"across {count_text(len(platforms), 'platform')}")
|
||||
for platform in platforms:
|
||||
print(f"\n{platform}")
|
||||
for row in (r for r in rows if r["platform"] == platform):
|
||||
first = row["readers"][0]
|
||||
more = f" (+{count_text(len(row['readers']) - 1, 'record')})" if len(row["readers"]) > 1 else ""
|
||||
casing = f", held as {row['held_as']}" if row.get("held_as") else ""
|
||||
print(
|
||||
f" {row['name']} [{', '.join(row['emulators'])}, {first['kind']}, "
|
||||
f"{first['source_ref']}]{more}{casing}"
|
||||
)
|
||||
if not unsourceable:
|
||||
return
|
||||
platforms = sorted({r["platform"] for r in unsourceable})
|
||||
print(
|
||||
f"\nLauncher reads, unsourceable: {count_text(len(unsourceable), 'name')} "
|
||||
f"across {count_text(len(platforms), 'platform')}"
|
||||
)
|
||||
for row in unsourceable:
|
||||
print(
|
||||
f" {row['platform']}: {row['name']} [{', '.join(row['emulators'])}, "
|
||||
f"{row['readers'][0]['source_ref']}]: {row['unsourceable']}"
|
||||
)
|
||||
|
||||
|
||||
def print_report(
|
||||
report: dict, scope: str = "all emulators", show_clean: bool = False
|
||||
) -> None:
|
||||
"""Print a human-readable gap analysis report.
|
||||
|
||||
`scope` names what the totals cover: under --platform, the emulators
|
||||
that platform runs, not all of them. `show_clean` lists an emulator with
|
||||
nothing undeclared too: asked about by name, it was the whole answer and
|
||||
the report used to leave it out.
|
||||
"""
|
||||
print("Emulator vs Platform Gap Analysis")
|
||||
print("=" * 60)
|
||||
print("* marks a file the emulator requires")
|
||||
|
||||
total_gaps = 0
|
||||
totals: dict[str, int] = {"bios": 0, "data": 0, "large_file": 0, "missing": 0}
|
||||
# A runtime component bundled with its emulator is left out of the
|
||||
# collection by design, as verify and the gaps page say: not a file to find.
|
||||
bundled = 0
|
||||
|
||||
for _emu_name, data in sorted(report.items()):
|
||||
gaps = data["gaps"]
|
||||
if gaps == 0 and not show_clean:
|
||||
continue
|
||||
|
||||
# Counted once, for the heading and the total alike: a file installed
|
||||
# with its emulator is neither one to source nor one the pack brings,
|
||||
# held or not (validation.deliverable leaves it out of every pack).
|
||||
bundled_gaps = [g for g in data["gap_details"] if g.get("bundled")]
|
||||
emulator_bundled = len(bundled_gaps)
|
||||
counts = {key: data.get(f"gap_{key}", 0) for key in totals}
|
||||
for g in bundled_gaps:
|
||||
counts[g.get("source", "missing")] -= 1
|
||||
counts["bundled"] = emulator_bundled
|
||||
parts = [f"{count} {key}" for key, count in counts.items() if count]
|
||||
status = ", ".join(parts) if parts else "OK"
|
||||
|
||||
systems = ", ".join(data["systems"])
|
||||
print(f"\n{data['emulator']}" + (f" ({systems})" if systems else ""))
|
||||
print(f" {data['total_files']} files in profile: {profile_breakdown(data)}")
|
||||
print(f" Gaps: {status}")
|
||||
|
||||
for g in data["gap_details"]:
|
||||
req = "*" if g["required"] else " "
|
||||
src = g.get("source", "missing").upper()
|
||||
if g.get("bundled"):
|
||||
src = "BUNDLED"
|
||||
# One line per file: a note spanning lines fell to column 0
|
||||
# between entries and read as an emulator heading.
|
||||
note = f": {' '.join(str(g['note']).split())}" if g["note"] else ""
|
||||
archive_info = ""
|
||||
if g.get("archive"):
|
||||
fc = g.get("archive_file_count", 0)
|
||||
rc = g.get("archive_required_count", 0)
|
||||
archive_info = f" ({fc} files, {rc} required)"
|
||||
if g.get("alternatives") and not g.get("in_repo"):
|
||||
archive_info += f" (or {', '.join(g['alternatives'])})"
|
||||
print(f" {req} {g['name']} [{src}]{archive_info}{note}")
|
||||
|
||||
total_gaps += gaps
|
||||
for key in totals:
|
||||
totals[key] += counts[key]
|
||||
bundled += emulator_bundled
|
||||
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"Total: {total_gaps} undeclared files across {scope}")
|
||||
available = totals["bios"] + totals["data"] + totals["large_file"]
|
||||
print(f" {available} available (bios: {totals['bios']}, data: {totals['data']}, "
|
||||
f"large_file: {totals['large_file']})")
|
||||
print(f" {totals['missing']} missing (need to be sourced)")
|
||||
if bundled:
|
||||
print(f" {bundled} bundled with their emulator, not packed")
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis")
|
||||
add_repo_inputs(parser, "emulators", "platforms", "db")
|
||||
parser.add_argument("--emulator", "-e", help="Analyze single emulator")
|
||||
@@ -204,247 +51,9 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
return parser
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PlatformScope:
|
||||
"""The profiles a --platform run compares, and how the platform runs them."""
|
||||
|
||||
profiles: dict[str, dict]
|
||||
standalone_cores: set[str]
|
||||
config: dict
|
||||
relevant: set[str]
|
||||
run_anywhere: set[str]
|
||||
|
||||
|
||||
def _platform_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _PlatformScope:
|
||||
from model.targets import target_scope
|
||||
from resolve.cores import resolve_platform_cores
|
||||
|
||||
# A typo ended in a traceback where verify and slots name the closest
|
||||
# target, and is refused the way they refuse it.
|
||||
target_cores = target_scope(
|
||||
[args.platform], args.target, args.platforms_dir
|
||||
)[0].get(args.platform)
|
||||
config = load_platform_config(args.platform, args.platforms_dir)
|
||||
relevant = resolve_platform_cores(config, profiles, target_cores=target_cores)
|
||||
run_anywhere = (
|
||||
set(resolve_platform_cores(config, profiles)) if args.target else relevant
|
||||
)
|
||||
return _PlatformScope(
|
||||
{k: v for k, v in profiles.items() if k in relevant},
|
||||
standalone_set(config),
|
||||
config,
|
||||
relevant,
|
||||
run_anywhere,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _TreeScope:
|
||||
"""What a run compares: the profiles, the platforms whose lists and
|
||||
launchers they are measured against (None for every platform), and the
|
||||
standalone layout of those platforms."""
|
||||
|
||||
profiles: dict[str, dict]
|
||||
standalone_cores: set[str]
|
||||
selected: list[str] | None
|
||||
platform: _PlatformScope | None = None
|
||||
|
||||
|
||||
def _target_platforms_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _TreeScope:
|
||||
"""--target without --platform: every platform that has the target, each
|
||||
with the cores it builds for it, the way verify and generate_pack read
|
||||
--all --target. A target no platform has ends the run."""
|
||||
from model.targets import target_scope
|
||||
from resolve.cores import resolve_platform_cores
|
||||
from resolve.standalone import merged_standalone_set
|
||||
|
||||
cache, kept = target_scope(
|
||||
list_registered_platforms(args.platforms_dir), args.target, args.platforms_dir,
|
||||
is_all=True,
|
||||
)
|
||||
configs = {name: load_platform_config(name, args.platforms_dir) for name in kept}
|
||||
relevant: set[str] = set()
|
||||
for name, config in configs.items():
|
||||
relevant |= set(resolve_platform_cores(config, profiles, target_cores=cache.get(name)))
|
||||
return _TreeScope(
|
||||
{k: v for k, v in profiles.items() if k in relevant},
|
||||
merged_standalone_set(configs.values()),
|
||||
kept,
|
||||
)
|
||||
|
||||
|
||||
def _tree_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _TreeScope:
|
||||
"""The scope --platform, --target or neither asks for."""
|
||||
if args.platform:
|
||||
scope = _platform_scope(args, profiles)
|
||||
return _TreeScope(scope.profiles, scope.standalone_cores, [args.platform], scope)
|
||||
if args.target:
|
||||
return _target_platforms_scope(args, profiles)
|
||||
# The tree as every platform runs it: a profile some platform runs
|
||||
# standalone keeps its standalone entries. Laid out as libretro only,
|
||||
# eka2l1, dolphin and xenia-edge lost 133 files no platform declares.
|
||||
from resolve.standalone import merged_standalone_set
|
||||
|
||||
return _TreeScope(
|
||||
profiles,
|
||||
merged_standalone_set(
|
||||
load_platform_config(name, args.platforms_dir)
|
||||
for name in list_registered_platforms(args.platforms_dir)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _refuse_empty_scope(args: argparse.Namespace, emulator: str | None, tree: _TreeScope) -> None:
|
||||
"""Why the scope holds no profile, said before ending the run."""
|
||||
platform_scope = tree.platform
|
||||
if (emulator and args.target and platform_scope is not None
|
||||
and emulator in platform_scope.run_anywhere):
|
||||
raise SystemExit(
|
||||
f"ERROR: {emulator} is not built for {args.platform}'s "
|
||||
f"{args.target} target; {args.platform} runs it elsewhere "
|
||||
f"(drop --target to see its files)"
|
||||
)
|
||||
if emulator and args.platform:
|
||||
raise SystemExit(f"ERROR: {emulator} is not run by {args.platform}")
|
||||
if emulator:
|
||||
raise SystemExit(
|
||||
f"ERROR: no platform with the {args.target} target builds {emulator} "
|
||||
f"for it (drop --target to see its files)"
|
||||
)
|
||||
if args.target and not args.platform:
|
||||
print(f"No platform runs a profiled emulator on {args.target}.", file=sys.stderr)
|
||||
else:
|
||||
print(f"{args.platform or 'The tree'} runs no profiled emulator.", file=sys.stderr)
|
||||
|
||||
|
||||
def _launcher_rows(
|
||||
args: argparse.Namespace,
|
||||
selected: list[str] | None,
|
||||
db: dict,
|
||||
all_profiles: dict[str, dict],
|
||||
registry: dict,
|
||||
emulator: str | None,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""The names a launcher reads that the collection lacks, and the
|
||||
launcher records nothing proves."""
|
||||
# Counted apart from the profile gaps: a name only a launcher reads is
|
||||
# reported, not yet judged.
|
||||
launcher_reads = launcher_reads_not_held(
|
||||
{
|
||||
name: load_platform_config(name, args.platforms_dir)
|
||||
for name in (selected or list_registered_platforms(args.platforms_dir))
|
||||
},
|
||||
db, all_profiles, registry, emulator or "",
|
||||
)
|
||||
|
||||
unproven = [
|
||||
row for row in launcher_unproven(
|
||||
{
|
||||
name: load_platform_config(name, args.platforms_dir)
|
||||
for name in (selected or list_registered_platforms(args.platforms_dir))
|
||||
},
|
||||
all_profiles,
|
||||
)
|
||||
if not emulator or any(
|
||||
emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles))
|
||||
for part in row["emulator"].split(", ")
|
||||
)
|
||||
]
|
||||
return launcher_reads, unproven
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args()
|
||||
from model.cliargs import work_from_repo_root
|
||||
|
||||
work_from_repo_root(args, parser, ["emulators_dir", "platforms_dir", "db"])
|
||||
if args.list_emulators:
|
||||
ignored = [flag for flag, on in (
|
||||
("--emulator", args.emulator), ("--platform", args.platform),
|
||||
("--all", args.all), ("--target", args.target), ("--json", args.json),
|
||||
) if on]
|
||||
if ignored:
|
||||
parser.error(f"--list-emulators does not apply {', '.join(ignored)}")
|
||||
list_emulator_profiles(args.emulators_dir)
|
||||
return
|
||||
if args.platform and args.all:
|
||||
parser.error("--platform and --all are mutually exclusive")
|
||||
if args.platform:
|
||||
require_platform(args.platform, args.platforms_dir)
|
||||
|
||||
import contextlib
|
||||
|
||||
from packs.datadirs import hold_data_dirs
|
||||
|
||||
# Files resolve against data/: the trees stay put until the process
|
||||
# ends, which releases the hold.
|
||||
held = contextlib.ExitStack()
|
||||
registry = load_data_dir_registry(args.platforms_dir)
|
||||
hold_data_dirs(held, registry)
|
||||
|
||||
profiles = load_emulator_profiles(args.emulators_dir)
|
||||
# Every profile's names and aliases, whatever --emulator or --platform keeps.
|
||||
all_profiles = profiles
|
||||
emulator = args.emulator
|
||||
if emulator:
|
||||
# A typo answered "No emulator profiles found" with exit 0.
|
||||
try:
|
||||
((emulator, _),) = select_emulator_profiles(
|
||||
[args.emulator],
|
||||
load_emulator_profiles(args.emulators_dir, skip_aliases=False),
|
||||
)
|
||||
except ProfileSelectionError as exc:
|
||||
raise SystemExit(f"ERROR: {exc}") from None
|
||||
profiles = {k: v for k, v in profiles.items() if k == emulator}
|
||||
|
||||
tree = _tree_scope(args, profiles)
|
||||
profiles = tree.profiles
|
||||
platform_scope = tree.platform
|
||||
if not profiles:
|
||||
_refuse_empty_scope(args, emulator, tree)
|
||||
return
|
||||
|
||||
selected = tree.selected
|
||||
db = load_database(args.db)
|
||||
declared, global_scope = global_report_scope(
|
||||
platform_configs(args.platforms_dir, selected), db)
|
||||
global_scope["standalone_cores"] = tree.standalone_cores
|
||||
data_names = build_supplemental_index()
|
||||
report = cross_reference(
|
||||
profiles, declared, db, data_names, **global_scope,
|
||||
platform=(
|
||||
platform_scope.config.get("_key", args.platform) if platform_scope else ""
|
||||
),
|
||||
# What the platform's launchers open, as verify and the builder read it.
|
||||
launcher_layer=LauncherLayer(
|
||||
platform_scope.config, profiles, platform_scope.relevant, db,
|
||||
declared_destinations(platform_scope.config),
|
||||
) if platform_scope else None,
|
||||
)
|
||||
|
||||
launcher_reads, unproven = _launcher_rows(
|
||||
args, selected, db, all_profiles, registry, emulator,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(
|
||||
{**report, LAUNCHER_READS_KEY: launcher_reads, LAUNCHER_UNPROVEN_KEY: unproven},
|
||||
indent=2,
|
||||
))
|
||||
return
|
||||
if emulator:
|
||||
scope = emulator
|
||||
elif args.platform:
|
||||
scope = f"the emulators {args.platform} runs"
|
||||
elif args.target:
|
||||
scope = f"the emulators built for {args.target}"
|
||||
else:
|
||||
scope = "all emulators"
|
||||
print_report(report, scope, show_clean=bool(args.emulator))
|
||||
print_launcher_reads(launcher_reads)
|
||||
print_launcher_unproven(unproven)
|
||||
parser = build_parser()
|
||||
run_gap_report(parser.parse_args(), parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -21,330 +21,12 @@ After dedup, run generate_db.py --force to rebuild database indexes.
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.hashing import compute_hashes
|
||||
from core.sizes import size_text
|
||||
from collection.dedup import deduplicate
|
||||
from core.cli import add_repo_inputs, require_directory
|
||||
from core.artifacts import write_text_atomic
|
||||
from model.nodedup import in_nodedup_dir
|
||||
|
||||
|
||||
def path_priority(path: str) -> tuple:
|
||||
"""Lower score = better candidate to keep as canonical.
|
||||
|
||||
Prefers: shorter path, non-variant, non-MAME (system-specific over generic).
|
||||
"""
|
||||
parts = Path(path).parts
|
||||
is_variant = ".variants" in parts
|
||||
is_mame = "MAME" in parts
|
||||
is_arcade = "Arcade" in parts
|
||||
return (is_variant, is_mame, is_arcade, len(parts), path)
|
||||
|
||||
|
||||
def _is_mame_dir(path: str) -> bool:
|
||||
"""Check if a path is in a MAME-specific directory."""
|
||||
parts = Path(path).parts
|
||||
return "MAME" in parts or "Arcade" in parts
|
||||
|
||||
|
||||
def scan_duplicates(bios_dir: str) -> dict[str, list[str]]:
|
||||
"""Files grouped by SHA1, excluding no-dedup directories.
|
||||
|
||||
Two equal files have the same size, so only files that share a size are
|
||||
read, and for the sha1 alone: hashing the whole tree with every digest
|
||||
took 33 s for a scan that reads a quarter of it. A file alone at its
|
||||
size is in no group of two and is left out.
|
||||
"""
|
||||
by_size: dict[int, list[str]] = defaultdict(list)
|
||||
for root, _dirs, files in os.walk(bios_dir):
|
||||
for name in files:
|
||||
path = os.path.join(root, name)
|
||||
if in_nodedup_dir(path):
|
||||
continue
|
||||
by_size[os.path.getsize(path)].append(path)
|
||||
|
||||
sha1_to_paths: dict[str, list[str]] = defaultdict(list)
|
||||
for paths in by_size.values():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
for path in paths:
|
||||
sha1_to_paths[compute_hashes(path, frozenset({"sha1"}))["sha1"]].append(path)
|
||||
return sha1_to_paths
|
||||
|
||||
|
||||
def _plan_group_removals(
|
||||
sha1: str, paths: list[str], mame_clones: dict
|
||||
) -> list[str]:
|
||||
"""Decide which copies of one content hash may go.
|
||||
|
||||
Two files with the same content are not automatically interchangeable.
|
||||
Same name in different directories is a true duplicate. Different names
|
||||
are only collapsible when they are MAME device clones, which is why the
|
||||
check is narrowed to zips under a MAME directory: anywhere else each
|
||||
name may be the one some emulator looks for.
|
||||
|
||||
Records clone groups in *mame_clones* and returns the paths to remove.
|
||||
"""
|
||||
true_dupes_to_remove: list[str] = []
|
||||
# Separate by filename: same name = true duplicate, different name = clone
|
||||
by_name: dict[str, list[str]] = defaultdict(list)
|
||||
for p in paths:
|
||||
by_name[os.path.basename(p)].append(p)
|
||||
|
||||
# True duplicates: same filename in multiple directories
|
||||
true_dupes_to_remove = []
|
||||
for name_paths in by_name.values():
|
||||
if len(name_paths) > 1:
|
||||
name_paths.sort(key=path_priority)
|
||||
true_dupes_to_remove.extend(name_paths[1:])
|
||||
|
||||
# A variant exists to hold a content its primary does not. Once another
|
||||
# file holds the same bytes, the copy under .variants/ answers nothing
|
||||
# the index does not already know, whatever its name or suffix: the
|
||||
# resolver finds the content by hash and writes it under the name the
|
||||
# destination asks for.
|
||||
remaining = [p for p in paths if p not in true_dupes_to_remove]
|
||||
variants = [p for p in remaining if ".variants" in Path(p).parts]
|
||||
if variants:
|
||||
holders = [p for p in remaining if p not in variants] or [
|
||||
min(variants, key=path_priority)
|
||||
]
|
||||
true_dupes_to_remove.extend(p for p in variants if p not in holders)
|
||||
|
||||
# Different filenames, same content: need special handling
|
||||
unique_names = sorted(by_name.keys())
|
||||
if len(unique_names) > 1:
|
||||
# Check if these are all in MAME/Arcade dirs AND all ZIPs
|
||||
all_mame_zip = all(
|
||||
any(_is_mame_dir(p) for p in name_paths)
|
||||
for name_paths in by_name.values()
|
||||
) and all(n.endswith(".zip") for n in unique_names)
|
||||
if all_mame_zip:
|
||||
# MAME device clones: different ZIP names, same ROM content
|
||||
# Keep one canonical, remove clones, record in clone map
|
||||
canonical_name = min(unique_names, key=len)
|
||||
clone_names = sorted(n for n in unique_names if n != canonical_name)
|
||||
if clone_names:
|
||||
mame_clones[canonical_name] = {
|
||||
"sha1": sha1,
|
||||
"clones": clone_names,
|
||||
"total_copies": sum(len(by_name[n]) for n in clone_names),
|
||||
}
|
||||
for clone_name in clone_names:
|
||||
for p in by_name[clone_name]:
|
||||
true_dupes_to_remove.append(p)
|
||||
else:
|
||||
# Non-MAME different names (e.g., 64DD_IPL_US.n64 vs IPL_USA.n64)
|
||||
# Keep ALL: each name may be needed by a different emulator
|
||||
# Only remove true duplicates (same name in multiple dirs)
|
||||
pass
|
||||
|
||||
return true_dupes_to_remove
|
||||
|
||||
|
||||
def _read_clone_map(clone_path: str) -> object:
|
||||
"""The clone map an earlier run wrote, {} when there is none."""
|
||||
# Read before anything is removed: the map is cumulative, and a run that
|
||||
# stopped on an unreadable one after deleting clones would lose them.
|
||||
try:
|
||||
with open(clone_path) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except json.JSONDecodeError as e:
|
||||
raise SystemExit(
|
||||
f"{clone_path} is not valid JSON ({e}). Restore it from git "
|
||||
"before deduplicating again"
|
||||
) from e
|
||||
|
||||
|
||||
def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]:
|
||||
"""Remove (or name, in a dry run) each copy beside the canonical file."""
|
||||
removed: list[str] = []
|
||||
for dup in true_dupes_to_remove:
|
||||
if dup == canonical:
|
||||
continue
|
||||
if not os.path.exists(dup):
|
||||
continue
|
||||
if dry_run:
|
||||
print(f" WOULD REMOVE: {dup}")
|
||||
else:
|
||||
try:
|
||||
os.remove(dup)
|
||||
except OSError as e:
|
||||
print(f" WARNING: cannot remove {dup}: {e}")
|
||||
continue
|
||||
# Clean up empty .variants/ directories
|
||||
parent = os.path.dirname(dup)
|
||||
if os.path.basename(parent) == ".variants" and not os.listdir(parent):
|
||||
os.rmdir(parent)
|
||||
removed.append(dup)
|
||||
return removed
|
||||
|
||||
|
||||
def _settle_group(paths: list[str], true_dupes_to_remove: list[str], dry_run: bool) -> dict:
|
||||
"""Keep the best copy of one content and remove the others."""
|
||||
# Find the best canonical across all paths
|
||||
all_paths = [p for p in paths if p not in true_dupes_to_remove]
|
||||
if not all_paths:
|
||||
# All copies were marked for removal: keep the best one
|
||||
all_paths_sorted = sorted(paths, key=path_priority)
|
||||
all_paths = [all_paths_sorted[0]]
|
||||
true_dupes_to_remove = [p for p in paths if p != all_paths[0]]
|
||||
|
||||
canonical = sorted(all_paths, key=path_priority)[0]
|
||||
canonical_name = os.path.basename(canonical)
|
||||
|
||||
all_names = set(os.path.basename(p) for p in paths)
|
||||
alias_names = sorted(all_names - {canonical_name})
|
||||
|
||||
size = os.path.getsize(canonical)
|
||||
removed = _remove_copies(canonical, true_dupes_to_remove, dry_run)
|
||||
|
||||
if alias_names or true_dupes_to_remove:
|
||||
action = "Would remove" if dry_run else "Removed"
|
||||
dn = os.path.basename(canonical)
|
||||
print(f" {dn} (keep: {canonical})")
|
||||
if true_dupes_to_remove:
|
||||
print(f" {action} {len(true_dupes_to_remove)} copies")
|
||||
if alias_names:
|
||||
print(f" MAME clones: {alias_names}")
|
||||
return {
|
||||
"canonical": canonical,
|
||||
"removed": removed,
|
||||
"aliases": alias_names,
|
||||
"saved": size * len(removed),
|
||||
}
|
||||
|
||||
|
||||
def _remove_empty_dirs(bios_dir: str) -> int:
|
||||
"""Remove the directories the removals left empty, bottom up."""
|
||||
empty_cleaned = 0
|
||||
for root, dirs, files in os.walk(bios_dir, topdown=False):
|
||||
if not files and not dirs and root != bios_dir:
|
||||
os.rmdir(root)
|
||||
empty_cleaned += 1
|
||||
return empty_cleaned
|
||||
|
||||
|
||||
def _record_clone_map(
|
||||
mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool
|
||||
) -> None:
|
||||
"""Write the clone map, merged with what earlier runs recorded."""
|
||||
# A group is only visible while both copies are on disk, and this run
|
||||
# has just deleted the clone. Writing only what was seen this time
|
||||
# therefore erases every mapping an earlier run recorded, and the
|
||||
# canonical zip stops answering to the names it stands in for. The
|
||||
# older entries stay valid: their canonical file is still here.
|
||||
if not dry_run and isinstance(previous, dict):
|
||||
merged = dict(previous)
|
||||
merged.update(mame_clones)
|
||||
mame_clones = collapse_clone_chains(merged)
|
||||
if dry_run:
|
||||
print(f"\nWould write MAME clone map: {clone_path}")
|
||||
else:
|
||||
write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True))
|
||||
print(f"\nWrote MAME clone map: {clone_path}")
|
||||
print(
|
||||
f" {len(mame_clones)} canonical ZIPs with "
|
||||
f"{sum(len(v['clones']) for v in mame_clones.values())} clones"
|
||||
)
|
||||
|
||||
|
||||
def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
"""Remove true duplicates, map MAME device clones.
|
||||
|
||||
True duplicates (same name, different dirs): removes copies.
|
||||
MAME clones (different names, same content, same dir): creates mapping.
|
||||
|
||||
Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}}
|
||||
"""
|
||||
# Beside the scanned tree, where get_mame_clone_map() reads it for
|
||||
# the real layout. A path relative to the working directory let a
|
||||
# scan of a fixture tree rewrite the repository's own map.
|
||||
clone_path = os.path.join(
|
||||
os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json"
|
||||
)
|
||||
previous = _read_clone_map(clone_path)
|
||||
|
||||
sha1_groups = scan_duplicates(bios_dir)
|
||||
results: dict[str, dict] = {}
|
||||
total_removed = 0
|
||||
total_saved = 0
|
||||
mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]}
|
||||
|
||||
for sha1, paths in sorted(sha1_groups.items()):
|
||||
if len(paths) <= 1:
|
||||
continue
|
||||
|
||||
true_dupes_to_remove = _plan_group_removals(sha1, paths, mame_clones)
|
||||
|
||||
if not true_dupes_to_remove:
|
||||
continue
|
||||
|
||||
settled = _settle_group(paths, true_dupes_to_remove, dry_run)
|
||||
total_removed += len(settled["removed"])
|
||||
total_saved += settled.pop("saved")
|
||||
results[sha1] = settled
|
||||
|
||||
# Clean up empty directories
|
||||
empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir)
|
||||
|
||||
prefix = "Would remove" if dry_run else "Removed"
|
||||
print(f"\n{prefix}: {total_removed} files")
|
||||
print(
|
||||
f"Space {'to save' if dry_run else 'saved'}: {size_text(total_saved)}"
|
||||
)
|
||||
if not dry_run and empty_cleaned:
|
||||
print(f"Cleaned {empty_cleaned} empty directories")
|
||||
|
||||
if mame_clones:
|
||||
_record_clone_map(mame_clones, previous, clone_path, dry_run)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def collapse_clone_chains(clone_map: dict[str, dict]) -> dict[str, dict]:
|
||||
"""Point every clone at a canonical archive that still exists.
|
||||
|
||||
The map is cumulative. When a later run finds that a canonical archive is
|
||||
itself a byte-identical copy of another and removes it, the entry that
|
||||
named it as canonical would send its clones to a file that is gone:
|
||||
sys68k_cpu21a pointed at sys68k_cpu21 after sys68k_cpu21 became a clone
|
||||
of sys68k_cpu20. Each such entry's clones move to the final canonical.
|
||||
"""
|
||||
owner = {
|
||||
clone: canonical
|
||||
for canonical, entry in clone_map.items()
|
||||
for clone in entry.get("clones", [])
|
||||
}
|
||||
|
||||
def final(name: str) -> str:
|
||||
seen = {name}
|
||||
while name in owner:
|
||||
name = owner[name]
|
||||
if name in seen:
|
||||
raise ValueError(f"clone map loops through {name}")
|
||||
seen.add(name)
|
||||
return name
|
||||
|
||||
collapsed: dict[str, dict] = {}
|
||||
for canonical, entry in clone_map.items():
|
||||
target = final(canonical)
|
||||
kept = collapsed.setdefault(target, {**clone_map.get(target, entry), "clones": []})
|
||||
names = set(kept["clones"]) | set(entry.get("clones", []))
|
||||
if target != canonical:
|
||||
names.add(canonical)
|
||||
names.discard(target)
|
||||
kept["clones"] = sorted(names)
|
||||
kept["total_copies"] = len(kept["clones"])
|
||||
return collapsed
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -1 +1 @@
|
||||
"""The repository's own rules: commit messages and the checks CI runs on a pull request."""
|
||||
"""The repository's own tooling: commit rules, pull request checks, the test runner, disk cleanup, the bios/ migration."""
|
||||
@@ -0,0 +1,260 @@
|
||||
"""The Manufacturer/Console folder a legacy BIOS path belongs to, read from its name and folder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
BIOS_FILE_MAP = {
|
||||
"panafz": ("3DO Company", "3DO"),
|
||||
"goldstar.bin": ("3DO Company", "3DO"),
|
||||
"sanyotry.bin": ("3DO Company", "3DO"),
|
||||
"3do_arcade_saot.bin": ("3DO Company", "3DO"),
|
||||
"3dobios.zip": ("3DO Company", "3DO"),
|
||||
"cpc464.rom": ("Amstrad", "CPC"),
|
||||
"cpc664.rom": ("Amstrad", "CPC"),
|
||||
"cpc6128.rom": ("Amstrad", "CPC"),
|
||||
"neogeo.zip": ("SNK", "Neo Geo"),
|
||||
"pgm.zip": ("Arcade", "Arcade"),
|
||||
"skns.zip": ("Arcade", "Arcade"),
|
||||
"bubsys.zip": ("Arcade", "Arcade"),
|
||||
"cchip.zip": ("Arcade", "Arcade"),
|
||||
"decocass.zip": ("Arcade", "Arcade"),
|
||||
"isgsm.zip": ("Arcade", "Arcade"),
|
||||
"midssio.zip": ("Arcade", "Arcade"),
|
||||
"nmk004.zip": ("Arcade", "Arcade"),
|
||||
"ym2608.zip": ("Arcade", "Arcade"),
|
||||
"qsound.zip": ("Arcade", "Arcade"),
|
||||
"ATARIBAS.ROM": ("Atari", "400-800"),
|
||||
"ATARIOSA.ROM": ("Atari", "400-800"),
|
||||
"ATARIOSB.ROM": ("Atari", "400-800"),
|
||||
"ATARIXL.ROM": ("Atari", "400-800"),
|
||||
"BB01R4_OS.ROM": ("Atari", "400-800"),
|
||||
"XEGAME.ROM": ("Atari", "400-800"),
|
||||
"5200.rom": ("Atari", "5200"),
|
||||
"7800 BIOS (U).rom": ("Atari", "7800"),
|
||||
"7800 BIOS (E).rom": ("Atari", "7800"),
|
||||
"lynxboot.img": ("Atari", "Lynx"),
|
||||
"tos.img": ("Atari", "ST"),
|
||||
"colecovision.rom": ("Coleco", "ColecoVision"),
|
||||
"coleco.rom": ("Coleco", "ColecoVision"),
|
||||
"kick33180.A500": ("Commodore", "Amiga"),
|
||||
"kick34005.A500": ("Commodore", "Amiga"),
|
||||
"kick34005.CDTV": ("Commodore", "Amiga"),
|
||||
"kick37175.A500": ("Commodore", "Amiga"),
|
||||
"kick37350.A600": ("Commodore", "Amiga"),
|
||||
"kick39106.A1200": ("Commodore", "Amiga"),
|
||||
"kick39106.A4000": ("Commodore", "Amiga"),
|
||||
"kick40060.CD32": ("Commodore", "Amiga"),
|
||||
"kick40060.CD32.ext": ("Commodore", "Amiga"),
|
||||
"kick40063.A600": ("Commodore", "Amiga"),
|
||||
"kick40068.A1200": ("Commodore", "Amiga"),
|
||||
"kick40068.A4000": ("Commodore", "Amiga"),
|
||||
"sl31253.bin": ("Fairchild", "Channel F"),
|
||||
"sl31254.bin": ("Fairchild", "Channel F"),
|
||||
"sl90025.bin": ("Fairchild", "Channel F"),
|
||||
"prboom.wad": ("Id Software", "Doom"),
|
||||
"ecwolf.pk3": ("Id Software", "Wolfenstein 3D"),
|
||||
"MacII.ROM": ("Apple", "Macintosh II"),
|
||||
"MacIIx.ROM": ("Apple", "Macintosh II"),
|
||||
"vMac.ROM": ("Apple", "Macintosh II"),
|
||||
"o2rom.bin": ("Magnavox", "Odyssey2"),
|
||||
"g7400.bin": ("Philips", "Videopac+"),
|
||||
"jopac.bin": ("Philips", "Videopac+"),
|
||||
"exec.bin": ("Mattel", "Intellivision"),
|
||||
"grom.bin": ("Mattel", "Intellivision"),
|
||||
"ECS.bin": ("Mattel", "Intellivision"),
|
||||
"IVOICE.BIN": ("Mattel", "Intellivision"),
|
||||
"MSX.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2EXT.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2P.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2PEXT.ROM": ("Microsoft", "MSX"),
|
||||
"syscard1.pce": ("NEC", "PC Engine"),
|
||||
"syscard2.pce": ("NEC", "PC Engine"),
|
||||
"syscard2u.pce": ("NEC", "PC Engine"),
|
||||
"syscard3.pce": ("NEC", "PC Engine"),
|
||||
"syscard3u.pce": ("NEC", "PC Engine"),
|
||||
"gexpress.pce": ("NEC", "PC Engine"),
|
||||
"pcfx.rom": ("NEC", "PC-FX"),
|
||||
"disksys.rom": ("Nintendo", "Famicom Disk System"),
|
||||
"gba_bios.bin": ("Nintendo", "Game Boy Advance"),
|
||||
"gb_bios.bin": ("Nintendo", "Game Boy"),
|
||||
"dmg_boot.bin": ("Nintendo", "Game Boy"),
|
||||
"gbc_bios.bin": ("Nintendo", "Game Boy Color"),
|
||||
"BS-X.bin": ("Nintendo", "Satellaview"),
|
||||
"sgb_bios.bin": ("Nintendo", "Super Game Boy"),
|
||||
"sgb_boot.bin": ("Nintendo", "Super Game Boy"),
|
||||
"sgb2_boot.bin": ("Nintendo", "Super Game Boy"),
|
||||
"SGB1.sfc": ("Nintendo", "Super Game Boy"),
|
||||
"SGB2.sfc": ("Nintendo", "Super Game Boy"),
|
||||
"bios7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"bios9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"firmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosnds7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosnds9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"dsfirmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosdsi7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosdsi9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"dsifirmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"bios.min": ("Nintendo", "Pokemon Mini"),
|
||||
"64DD_IPL.bin": ("Nintendo", "Nintendo 64DD"),
|
||||
"dc_boot.bin": ("Sega", "Dreamcast"),
|
||||
"dc_flash.bin": ("Sega", "Dreamcast"),
|
||||
"bios.gg": ("Sega", "Game Gear"),
|
||||
"bios_E.sms": ("Sega", "Master System"),
|
||||
"bios_J.sms": ("Sega", "Master System"),
|
||||
"bios_U.sms": ("Sega", "Master System"),
|
||||
"bios_CD_E.bin": ("Sega", "Mega CD"),
|
||||
"bios_CD_J.bin": ("Sega", "Mega CD"),
|
||||
"bios_CD_U.bin": ("Sega", "Mega CD"),
|
||||
"bios_MD.bin": ("Sega", "Mega Drive"),
|
||||
"mpr-17933.bin": ("Sega", "Saturn"),
|
||||
"mpr-18811-mx.ic1": ("Sega", "Saturn"),
|
||||
"mpr-19367-mx.ic1": ("Sega", "Saturn"),
|
||||
"saturn_bios.bin": ("Sega", "Saturn"),
|
||||
"sega_101.bin": ("Sega", "Saturn"),
|
||||
"stvbios.zip": ("Sega", "Saturn"),
|
||||
"scph1001.bin": ("Sony", "PlayStation"),
|
||||
"SCPH1001.BIN": ("Sony", "PlayStation"),
|
||||
"scph5500.bin": ("Sony", "PlayStation"),
|
||||
"scph5501.bin": ("Sony", "PlayStation"),
|
||||
"scph5502.bin": ("Sony", "PlayStation"),
|
||||
"scph7001.bin": ("Sony", "PlayStation"),
|
||||
"scph101.bin": ("Sony", "PlayStation"),
|
||||
"ps1_rom.bin": ("Sony", "PlayStation"),
|
||||
"psxonpsp660.bin": ("Sony", "PlayStation"),
|
||||
"PSXONPSP660.BIN": ("Sony", "PlayStation Portable"),
|
||||
"scummvm.zip": ("ScummVM", "ScummVM"),
|
||||
"MT32_CONTROL.ROM": ("Roland", "MT-32"),
|
||||
"MT32_PCM.ROM": ("Roland", "MT-32"),
|
||||
}
|
||||
|
||||
PATH_PREFIX_MAP = {
|
||||
"neocd/": ("SNK", "Neo Geo CD"),
|
||||
"dc/": ("Sega", "Dreamcast"),
|
||||
"np2kai/": ("NEC", "PC-98"),
|
||||
"quasi88/": ("NEC", "PC-98"),
|
||||
"keropi/": ("Sharp", "X68000"),
|
||||
"xmil/": ("Sharp", "X1"),
|
||||
"fuse/": ("Sinclair", "ZX Spectrum"),
|
||||
"vice/": ("Commodore", "C128"),
|
||||
"bk/": ("Elektronika", "BK"),
|
||||
"dragon/": ("Dragon", "Dragon"),
|
||||
"oricutron/": ("Tangerine", "Oric"),
|
||||
"trs80coco/": ("Tandy", "CoCo"),
|
||||
"ti994a/": ("Texas Instruments", "TI-99"),
|
||||
"gamecube/": ("Nintendo", "GameCube"),
|
||||
"Mupen64plus/": ("Nintendo", "Nintendo 64DD"),
|
||||
"ps2/": ("Sony", "PlayStation 2"),
|
||||
"fmtowns/": ("Fujitsu", "FM Towns"),
|
||||
"mame/": ("Arcade", "MAME"),
|
||||
"fbneo/": ("Arcade", "Arcade"),
|
||||
"saves/3ds/": ("Nintendo", "3DS"),
|
||||
"saves/citra-emu/": ("Nintendo", "3DS"),
|
||||
"saves/dolphin-emu/": ("Nintendo", "Wii"),
|
||||
"saves/xbox/": ("Microsoft", "Xbox"),
|
||||
"cemu/": ("Nintendo", "Wii U"),
|
||||
"wsh57/": ("Other", "Misc"),
|
||||
"Machines/COL - ColecoVision/": ("Coleco", "ColecoVision"),
|
||||
"Machines/Shared Roms/": ("Microsoft", "MSX"),
|
||||
"Sony - PlayStation 2/": ("Sony", "PlayStation 2"),
|
||||
"Sony - PlayStation/": ("Sony", "PlayStation"),
|
||||
}
|
||||
|
||||
SKIP_FILES = {
|
||||
"README.md",
|
||||
".gitignore",
|
||||
"desktop.ini",
|
||||
"telemetry_id",
|
||||
"citra_log.txt",
|
||||
}
|
||||
SKIP_EXTENSIONS = {".txt", ".log", ".pem", ".nvm", ".ctg", ".exe", ".bat", ".sh"}
|
||||
|
||||
|
||||
ARCADE_ROM_PREFIXES = (
|
||||
"roms/fba/",
|
||||
"roms/fbneo/",
|
||||
"roms/mame/",
|
||||
"roms/mame-libretro/",
|
||||
"roms/neogeo/",
|
||||
"roms/naomi/",
|
||||
"roms/atomiswave/",
|
||||
"roms/macintosh/",
|
||||
)
|
||||
|
||||
|
||||
def _strip_branch_prefix(filepath: str) -> str | None:
|
||||
"""The path below its bios/ or arcade roms/ folder, None for any other
|
||||
roms/ path."""
|
||||
if filepath.startswith("roms/") and not filepath.startswith(ARCADE_ROM_PREFIXES):
|
||||
return None
|
||||
for prefix in ("bios/", "BIOS/", *ARCADE_ROM_PREFIXES):
|
||||
if filepath.startswith(prefix):
|
||||
return filepath[len(prefix) :]
|
||||
return filepath
|
||||
|
||||
|
||||
def _classify_by_name(name: str, filepath: str) -> tuple[str, str] | None:
|
||||
if name in BIOS_FILE_MAP:
|
||||
return BIOS_FILE_MAP[name]
|
||||
|
||||
for prefix, target in BIOS_FILE_MAP.items():
|
||||
if name.lower().startswith(prefix.lower()) and len(prefix) > 3:
|
||||
return target
|
||||
|
||||
if name.startswith("tos") and name.endswith(".img"):
|
||||
return ("Atari", "ST")
|
||||
|
||||
if name.startswith("kick") and (name.endswith(".rom") or "." in name):
|
||||
return ("Commodore", "Amiga")
|
||||
|
||||
if name.startswith("amiga-"):
|
||||
return ("Commodore", "Amiga")
|
||||
|
||||
if name.upper().startswith("SCPH"):
|
||||
if "70004" in name or "39001" in name or "30004" in name or "10000" in name:
|
||||
return ("Sony", "PlayStation 2")
|
||||
return ("Sony", "PlayStation")
|
||||
|
||||
if name.endswith(".zip") and filepath.startswith(("roms/", "BIOS/")):
|
||||
return ("Arcade", "Arcade")
|
||||
return None
|
||||
|
||||
|
||||
def classify_file(filepath: str) -> tuple[str, str] | None:
|
||||
"""Determine (Manufacturer, Console) for a file path from a branch.
|
||||
|
||||
Returns None if the file should be skipped.
|
||||
"""
|
||||
name = os.path.basename(filepath)
|
||||
|
||||
if name in SKIP_FILES:
|
||||
return None
|
||||
ext = os.path.splitext(name)[1].lower()
|
||||
if ext in SKIP_EXTENSIONS:
|
||||
return None
|
||||
|
||||
clean = _strip_branch_prefix(filepath)
|
||||
if clean is None:
|
||||
return None
|
||||
|
||||
for prefix, target in PATH_PREFIX_MAP.items():
|
||||
if clean.startswith(prefix):
|
||||
return target
|
||||
|
||||
return _classify_by_name(name, filepath)
|
||||
|
||||
|
||||
def get_subpath(filepath: str) -> str:
|
||||
"""Get the sub-path within the console directory (for nested files like neocd/*)."""
|
||||
clean = filepath
|
||||
for prefix in ("bios/", "BIOS/"):
|
||||
if clean.startswith(prefix):
|
||||
clean = clean[len(prefix) :]
|
||||
break
|
||||
|
||||
for prefix in PATH_PREFIX_MAP:
|
||||
if clean.startswith(prefix):
|
||||
return clean[len(prefix) :]
|
||||
|
||||
return os.path.basename(filepath)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""The move of a flat BIOS tree and of the legacy branches' files into bios/Manufacturer/Console/."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from acquire.fetch import LEGACY_BRANCHES, legacy_branch_blob, legacy_branch_files
|
||||
from core.hashing import file_digest
|
||||
from devtools.biosclassify import classify_file, get_subpath
|
||||
|
||||
SYSTEM_MAP = {
|
||||
"3DO Company, The - 3DO": ("3DO Company", "3DO"),
|
||||
"Arcade": ("Arcade", "Arcade"),
|
||||
"Atari - 400-800": ("Atari", "400-800"),
|
||||
"Atari - 5200": ("Atari", "5200"),
|
||||
"Atari - 7800": ("Atari", "7800"),
|
||||
"Atari - Lynx": ("Atari", "Lynx"),
|
||||
"Atari - ST": ("Atari", "ST"),
|
||||
"Coleco - ColecoVision": ("Coleco", "ColecoVision"),
|
||||
"Commodore - Amiga": ("Commodore", "Amiga"),
|
||||
"Fairchild Channel F": ("Fairchild", "Channel F"),
|
||||
"Id Software - Doom": ("Id Software", "Doom"),
|
||||
"J2ME": ("Java", "J2ME"),
|
||||
"MacII": ("Apple", "Macintosh II"),
|
||||
"Magnavox - Odyssey2": ("Magnavox", "Odyssey2"),
|
||||
"Mattel - Intellivision": ("Mattel", "Intellivision"),
|
||||
"Microsoft - MSX": ("Microsoft", "MSX"),
|
||||
"NEC - PC Engine - TurboGrafx 16 - SuperGrafx": ("NEC", "PC Engine"),
|
||||
"NEC - PC-98": ("NEC", "PC-98"),
|
||||
"NEC - PC-FX": ("NEC", "PC-FX"),
|
||||
"Nintendo - Famicom Disk System": ("Nintendo", "Famicom Disk System"),
|
||||
"Nintendo - Game Boy Advance": ("Nintendo", "Game Boy Advance"),
|
||||
"Nintendo - GameCube": ("Nintendo", "GameCube"),
|
||||
"Nintendo - Gameboy": ("Nintendo", "Game Boy"),
|
||||
"Nintendo - Gameboy Color": ("Nintendo", "Game Boy Color"),
|
||||
"Nintendo - Nintendo 64DD": ("Nintendo", "Nintendo 64DD"),
|
||||
"Nintendo - Nintendo DS": ("Nintendo", "Nintendo DS"),
|
||||
"Nintendo - Nintendo Entertainment System": ("Nintendo", "NES"),
|
||||
"Nintendo - Pokemon Mini": ("Nintendo", "Pokemon Mini"),
|
||||
"Nintendo - Satellaview": ("Nintendo", "Satellaview"),
|
||||
"Nintendo - SuFami Turbo": ("Nintendo", "SuFami Turbo"),
|
||||
"Nintendo - Super Game Boy": ("Nintendo", "Super Game Boy"),
|
||||
"Nintendo - Super Nintendo Entertainment System": ("Nintendo", "SNES"),
|
||||
"Phillips - Videopac+": ("Philips", "Videopac+"),
|
||||
"SNK - NeoGeo CD": ("SNK", "Neo Geo CD"),
|
||||
"ScummVM": ("ScummVM", "ScummVM"),
|
||||
"Sega - Dreamcast": ("Sega", "Dreamcast"),
|
||||
"Sega - Game Gear": ("Sega", "Game Gear"),
|
||||
"Sega - Master System - Mark III": ("Sega", "Master System"),
|
||||
"Sega - Mega CD - Sega CD": ("Sega", "Mega CD"),
|
||||
"Sega - Mega Drive - Genesis": ("Sega", "Mega Drive"),
|
||||
"Sega - Saturn": ("Sega", "Saturn"),
|
||||
"Sharp - X1": ("Sharp", "X1"),
|
||||
"Sharp - X68000": ("Sharp", "X68000"),
|
||||
"Sinclair - ZX Spectrum": ("Sinclair", "ZX Spectrum"),
|
||||
"Sony - PlayStation": ("Sony", "PlayStation"),
|
||||
"Sony - PlayStation Portable": ("Sony", "PlayStation Portable"),
|
||||
"Wolfenstein 3D": ("Id Software", "Wolfenstein 3D"),
|
||||
}
|
||||
|
||||
|
||||
def sha1_blob(data: bytes) -> str:
|
||||
"""Compute SHA1 hash of raw bytes."""
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
||||
|
||||
def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set[str]) -> int:
|
||||
"""Extract BIOS files from all branches into the target structure."""
|
||||
extracted = 0
|
||||
|
||||
for branch in LEGACY_BRANCHES:
|
||||
files = legacy_branch_files(branch)
|
||||
if files is None:
|
||||
print(f" Branch {branch} not found, skipping")
|
||||
continue
|
||||
print(f"\n Branch '{branch}': {len(files)} files")
|
||||
|
||||
branch_extracted = 0
|
||||
for filepath in files:
|
||||
classification = classify_file(filepath)
|
||||
if classification is None:
|
||||
continue
|
||||
|
||||
manufacturer, console = classification
|
||||
dest_dir = target / manufacturer / console
|
||||
dest = dest_dir / get_subpath(filepath)
|
||||
|
||||
content = legacy_branch_blob(branch, filepath)
|
||||
if content is None:
|
||||
continue
|
||||
|
||||
file_hash = sha1_blob(content)
|
||||
|
||||
if file_hash in existing_hashes:
|
||||
continue
|
||||
|
||||
label = "NEW"
|
||||
if dest.exists():
|
||||
if file_digest(dest) == file_hash:
|
||||
existing_hashes.add(file_hash)
|
||||
continue
|
||||
dest = dest_dir / ".variants" / f"{dest.name}.{file_hash[:8]}"
|
||||
if dest.exists():
|
||||
continue
|
||||
label = "VARIANT"
|
||||
|
||||
if not dry_run:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(content)
|
||||
print(f" {label}: {filepath} -> {dest.relative_to(target)}")
|
||||
existing_hashes.add(file_hash)
|
||||
branch_extracted += 1
|
||||
|
||||
print(f" -> {branch_extracted} new files from {branch}")
|
||||
extracted += branch_extracted
|
||||
|
||||
return extracted
|
||||
|
||||
|
||||
def migrate_local(
|
||||
source: Path, target: Path, dry_run: bool,
|
||||
) -> tuple[int, int, list[tuple[Path, str]], set[str]]:
|
||||
"""Migrate files from local flat structure to Manufacturer/Console hierarchy."""
|
||||
moved = 0
|
||||
skipped = 0
|
||||
errors: list[tuple[Path, str]] = []
|
||||
existing_hashes: set[str] = set()
|
||||
|
||||
for old_dir_name, (manufacturer, console) in sorted(SYSTEM_MAP.items()):
|
||||
old_path = source / old_dir_name
|
||||
if not old_path.is_dir():
|
||||
continue
|
||||
|
||||
new_path = target / manufacturer / console
|
||||
files = [f for f in old_path.iterdir() if f.is_file()]
|
||||
|
||||
if not files:
|
||||
continue
|
||||
|
||||
print(f" {old_dir_name}/ -> bios/{manufacturer}/{console}/")
|
||||
|
||||
if not dry_run:
|
||||
new_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for f in files:
|
||||
dest = new_path / f.name
|
||||
if dest.exists():
|
||||
print(f" SKIP (exists): {f.name}")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
print(f" COPY: {f.name}")
|
||||
else:
|
||||
try:
|
||||
shutil.copy2(str(f), str(dest))
|
||||
except OSError as e:
|
||||
errors.append((f, str(e)))
|
||||
print(f" ERROR: {f.name}: {e}")
|
||||
continue
|
||||
|
||||
existing_hashes.add(file_digest(f))
|
||||
moved += 1
|
||||
|
||||
return moved, skipped, errors, existing_hashes
|
||||
|
||||
|
||||
def unmapped_directories(source: Path) -> list[str]:
|
||||
"""Folders of the source that no system maps and that are not the repository's own."""
|
||||
known = set(SYSTEM_MAP.keys()) | {
|
||||
"bios",
|
||||
"scripts",
|
||||
"platforms",
|
||||
"schemas",
|
||||
".github",
|
||||
".cache",
|
||||
".git",
|
||||
"README.md",
|
||||
".gitignore",
|
||||
}
|
||||
return [d.name for d in sorted(source.iterdir())
|
||||
if d.name not in known and not d.name.startswith(".") and d.is_dir()]
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Which idle session worktrees and tmp/ entries can go, their removal, and the free space left."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import AUTORUN_WORKTREE
|
||||
|
||||
GENERATED = re.compile(
|
||||
r"^(database\.json|install/.*\.json|exports/.*\.json|README\.md|CONTRIBUTING\.md"
|
||||
r"|website/src/data/[^/]+\.json)$"
|
||||
)
|
||||
KEPT_TMP = ("acquire",)
|
||||
ALERT_GB = 100
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Decision:
|
||||
path: Path
|
||||
kind: str # worktree, tmp
|
||||
action: str # remove, keep
|
||||
reason: str
|
||||
|
||||
|
||||
def git(cwd: Path, *args: str, check: bool = True) -> str:
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(cwd), *args], capture_output=True, text=True, check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)}: {proc.stderr.strip()}")
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def busy_paths() -> set[str]:
|
||||
"""Every working directory and open file of every readable process."""
|
||||
found: set[str] = set()
|
||||
proc = Path("/proc")
|
||||
if not proc.is_dir():
|
||||
return found
|
||||
for pid in proc.iterdir():
|
||||
if not pid.name.isdigit():
|
||||
continue
|
||||
links = [pid / "cwd"]
|
||||
with contextlib.suppress(OSError):
|
||||
links += list((pid / "fd").iterdir())
|
||||
for link in links:
|
||||
try:
|
||||
found.add(os.readlink(link))
|
||||
except OSError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def inside(path: Path, root: Path) -> bool:
|
||||
return str(path) == str(root) or str(path).startswith(f"{root}/")
|
||||
|
||||
|
||||
def in_use(path: Path, busy: Iterable[str]) -> bool:
|
||||
root = str(path)
|
||||
prefix = f"{root}/"
|
||||
return any(b == root or b.startswith(prefix) for b in busy)
|
||||
|
||||
|
||||
def age_hours(path: Path, now: float) -> float:
|
||||
return (now - path.stat().st_mtime) / 3600
|
||||
|
||||
|
||||
def real_changes(worktree: Path) -> list[str]:
|
||||
"""Modified tracked paths that are neither deletions nor generated files."""
|
||||
out = git(worktree, "status", "--porcelain", "--untracked-files=no")
|
||||
paths = []
|
||||
for line in out.splitlines():
|
||||
if len(line) < 4 or line[:2].strip() == "D":
|
||||
continue
|
||||
path = line[3:].split(" -> ")[-1].strip('"')
|
||||
if not GENERATED.match(path):
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def linked_worktrees(repo: Path) -> list[Path]:
|
||||
"""Every linked worktree of the checkout, wherever it lives."""
|
||||
out = git(repo, "worktree", "list", "--porcelain")
|
||||
paths = [Path(line[len("worktree "):]) for line in out.splitlines()
|
||||
if line.startswith("worktree ")]
|
||||
return [p for p in paths if p != repo]
|
||||
|
||||
|
||||
def session_worktrees(repo: Path) -> list[Path]:
|
||||
"""Linked worktrees inside the checkout, the automation worktree aside."""
|
||||
keep = repo / AUTORUN_WORKTREE
|
||||
return [p for p in linked_worktrees(repo) if inside(p, repo) and p != keep]
|
||||
|
||||
|
||||
def judge_worktree(path: Path, busy: Iterable[str], hours: float, now: float) -> Decision:
|
||||
if in_use(path, busy):
|
||||
return Decision(path, "worktree", "keep", "in use")
|
||||
age = age_hours(path, now)
|
||||
if age <= hours:
|
||||
return Decision(path, "worktree", "keep", f"{age:.0f}h recent")
|
||||
real = real_changes(path)
|
||||
if real:
|
||||
return Decision(path, "worktree", "keep", f"uncommitted code: {len(real)} files")
|
||||
return Decision(path, "worktree", "remove", f"{age:.0f}h old, clean")
|
||||
|
||||
|
||||
def judge_tmp(
|
||||
repo: Path, busy: Iterable[str], hours: float, now: float,
|
||||
worktrees: Iterable[Path] = (),
|
||||
) -> list[Decision]:
|
||||
tmp = repo / "tmp"
|
||||
if not tmp.is_dir():
|
||||
return []
|
||||
worktrees = list(worktrees)
|
||||
decisions = []
|
||||
for entry in sorted(tmp.iterdir()):
|
||||
if entry.name in KEPT_TMP or entry.name.endswith(".bundle"):
|
||||
action, reason = "keep", "backup"
|
||||
elif any(inside(w, entry) for w in worktrees):
|
||||
action, reason = "keep", "holds a worktree"
|
||||
elif age_hours(entry, now) <= hours:
|
||||
action, reason = "keep", "recent"
|
||||
elif in_use(entry, busy):
|
||||
action, reason = "keep", "in use"
|
||||
else:
|
||||
action, reason = "remove", "old"
|
||||
decisions.append(Decision(entry, "tmp", action, reason))
|
||||
return decisions
|
||||
|
||||
|
||||
def plan(repo: Path, busy: Iterable[str], hours: float, now: float) -> list[Decision]:
|
||||
busy = set(busy)
|
||||
worktrees = [judge_worktree(w, busy, hours, now) for w in session_worktrees(repo)
|
||||
if w.is_dir()]
|
||||
return worktrees + judge_tmp(repo, busy, hours, now, linked_worktrees(repo))
|
||||
|
||||
|
||||
def apply(repo: Path, decisions: Iterable[Decision]) -> list[str]:
|
||||
"""Carry out the removals, and return the failures."""
|
||||
failures = []
|
||||
removed_worktree = False
|
||||
for d in decisions:
|
||||
if d.action != "remove":
|
||||
continue
|
||||
if d.kind == "worktree":
|
||||
git(repo, "worktree", "unlock", str(d.path), check=False)
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(repo), "worktree", "remove", "--force", str(d.path)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
failures.append(f"{d.path}: {proc.stderr.strip()}")
|
||||
removed_worktree = True
|
||||
continue
|
||||
try:
|
||||
if d.path.is_dir() and not d.path.is_symlink():
|
||||
shutil.rmtree(d.path)
|
||||
else:
|
||||
d.path.unlink()
|
||||
except OSError as exc:
|
||||
failures.append(f"{d.path}: {exc}")
|
||||
if removed_worktree:
|
||||
git(repo, "worktree", "prune", check=False)
|
||||
return failures
|
||||
|
||||
|
||||
def disk_line(path: Path, alert_gb: float) -> tuple[str, bool]:
|
||||
usage = shutil.disk_usage(path)
|
||||
free, total = usage.free / 1024 ** 3, usage.total / 1024 ** 3
|
||||
low = free < alert_gb
|
||||
line = f"disk: {free:.0f} GB free of {total:.0f} GB"
|
||||
if low:
|
||||
line += f"\nALERT: free space under {alert_gb:.0f} GB"
|
||||
return line, low
|
||||
@@ -0,0 +1,147 @@
|
||||
"""The test suite run one module per process: the order, each run, the reruns and the timings kept."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT as ROOT
|
||||
|
||||
TESTS = ROOT / "tests"
|
||||
WORK = ROOT / "tmp" / "test-runs"
|
||||
DURATIONS = ROOT / "tmp" / "test-durations.json"
|
||||
# The pty and site-build tests time themselves out under load: more than a
|
||||
# third of the cores at once made them fail for no other reason.
|
||||
DEFAULT_JOBS = max(1, min(6, (os.cpu_count() or 2) // 3))
|
||||
|
||||
# Lines of a failed module's tracebacks printed in the summary.
|
||||
FAILURE_LINES = 200
|
||||
_RAN = re.compile(r"^Ran (\d+) tests? in ([\d.]+)s$", re.M)
|
||||
_COUNTS = re.compile(r"(failures|errors|skipped|expected failures|unexpected successes)=(\d+)")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
module: str
|
||||
code: int
|
||||
seconds: float
|
||||
tests: int = 0
|
||||
failures: int = 0
|
||||
errors: int = 0
|
||||
skipped: int = 0
|
||||
log: Path | None = None
|
||||
crashed_then: int | None = None
|
||||
|
||||
@property
|
||||
def passed(self) -> bool:
|
||||
return self.code == 0 if self.crashed_then is None else self.crashed_then == 0
|
||||
|
||||
|
||||
def modules() -> list[str]:
|
||||
return sorted(f"tests.{path.stem}" for path in TESTS.glob("test_*.py"))
|
||||
|
||||
|
||||
def load_durations() -> dict[str, float]:
|
||||
try:
|
||||
data = json.loads(DURATIONS.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"note: {DURATIONS} not read ({exc}), modules weighed by size", file=sys.stderr)
|
||||
return {}
|
||||
return {str(name): float(value) for name, value in data.items()
|
||||
if isinstance(value, (int, float))}
|
||||
|
||||
|
||||
def weight(module: str, durations: dict[str, float]) -> float:
|
||||
"""Seconds the module took last time, else its size as a stand-in."""
|
||||
if module in durations:
|
||||
return durations[module]
|
||||
path = TESTS / f"{module.split('.', 1)[1]}.py"
|
||||
return path.stat().st_size / 2000 if path.exists() else 0.0
|
||||
|
||||
|
||||
def parse(result: Result, text: str) -> None:
|
||||
ran = _RAN.findall(text)
|
||||
if ran:
|
||||
result.tests = int(ran[-1][0])
|
||||
tail = text[text.rfind("\nRan "):] if "\nRan " in text else text
|
||||
for name, count in _COUNTS.findall(tail):
|
||||
if name == "failures":
|
||||
result.failures = int(count)
|
||||
elif name == "errors":
|
||||
result.errors = int(count)
|
||||
elif name == "skipped":
|
||||
result.skipped = int(count)
|
||||
|
||||
|
||||
def run_module(module: str, env: dict[str, str], logs: Path) -> Result:
|
||||
scratch = WORK / "scratch" / module
|
||||
scratch.mkdir(parents=True, exist_ok=True)
|
||||
log = logs / f"{module}.log"
|
||||
started = time.monotonic()
|
||||
with log.open("w", encoding="utf-8") as out:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-m", "unittest", module], cwd=ROOT, stdout=out,
|
||||
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
||||
env={**env, "RETROBIOS_TEST_SCRATCH": str(scratch)}, check=False,
|
||||
)
|
||||
result = Result(module, proc.returncode, time.monotonic() - started, log=log)
|
||||
parse(result, log.read_text(encoding="utf-8", errors="replace"))
|
||||
return result
|
||||
|
||||
|
||||
def run_all(order: Iterable[str], jobs: int, env: dict[str, str], logs: Path,
|
||||
say: Callable[[str], None]) -> list[Result]:
|
||||
"""Every module, `jobs` at a time, each failure said as it ends."""
|
||||
results: list[Result] = []
|
||||
with ThreadPoolExecutor(max_workers=jobs) as pool:
|
||||
running = [pool.submit(run_module, name, env, logs) for name in order]
|
||||
for done in as_completed(running):
|
||||
result = done.result()
|
||||
results.append(result)
|
||||
if result.code != 0:
|
||||
why = f"signal {-result.code}" if result.code < 0 else "failed"
|
||||
say(f" {why}: {result.module} ({result.seconds:.0f} s)")
|
||||
return results
|
||||
|
||||
|
||||
def rerun_crashed(results: Iterable[Result], env: dict[str, str], logs: Path,
|
||||
say: Callable[[str], None]) -> None:
|
||||
"""A module a signal killed is the host's doing until it fails alone."""
|
||||
for result in results:
|
||||
if result.code < 0:
|
||||
say(f" again, alone: {result.module}")
|
||||
again = run_module(result.module, env, logs)
|
||||
result.crashed_then = again.code
|
||||
result.tests, result.failures, result.errors, result.skipped = (
|
||||
again.tests, again.failures, again.errors, again.skipped)
|
||||
|
||||
|
||||
def save_durations(durations: dict[str, float], results: Iterable[Result]) -> None:
|
||||
"""The timings of this run over the previous ones, a crashed run left out."""
|
||||
timed = {**durations, **{r.module: round(r.seconds, 1) for r in results if r.code >= 0}}
|
||||
DURATIONS.write_text(json.dumps(timed, indent=1, sort_keys=True), encoding="utf-8")
|
||||
|
||||
|
||||
def failure_excerpt(log: Path) -> list[str]:
|
||||
"""The tracebacks unittest wrote in a module's log, at most a page."""
|
||||
text = log.read_text(encoding="utf-8", errors="replace")
|
||||
start = text.find("\n" + "=" * 70)
|
||||
shown = (text[start:] if start >= 0 else text).strip().splitlines()
|
||||
lines = shown[:FAILURE_LINES]
|
||||
if len(shown) > FAILURE_LINES:
|
||||
lines.append(f"... {len(shown) - FAILURE_LINES} more lines in the log")
|
||||
return lines
|
||||
|
||||
|
||||
def say(line: str) -> None:
|
||||
print(line, flush=True)
|
||||
@@ -10,7 +10,6 @@ Usage:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from core.paths import TRUTH_DIR
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
@@ -18,170 +17,14 @@ import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.cli import add_repo_inputs
|
||||
from core.paths import TRUTH_DIR
|
||||
from exporter.diffreport import format_markdown, format_terminal
|
||||
from exporter.truthdiff import NoDiffInput, platform_diff
|
||||
from model.cliargs import platform_arg, selected_platforms
|
||||
from model.platforms import load_platform_config, native_layer
|
||||
from model.safeparse import require_yaml, yaml_load
|
||||
from model.targets import truth_target_dir
|
||||
from resolve.truth import diff_platform_truth
|
||||
|
||||
yaml = require_yaml()
|
||||
|
||||
|
||||
def _load_truth(truth_dir: str, platform: str) -> dict | None:
|
||||
path = os.path.join(truth_dir, f"{platform}.yml")
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return yaml_load(f) or {}
|
||||
|
||||
|
||||
def _where(entry: dict) -> str:
|
||||
"""Where a diffed entry sits: one name can be declared at several paths."""
|
||||
return entry.get("destination") or entry["name"]
|
||||
|
||||
|
||||
_TOTAL_LABELS = (
|
||||
("total_missing", "missing"),
|
||||
("total_extra_phantom", "unpaired"),
|
||||
("total_extra_unprofiled", "unprofiled"),
|
||||
("total_hash_mismatch", "hash"),
|
||||
("total_required_mismatch", "required"),
|
||||
)
|
||||
|
||||
_DIVERGENCE_LABELS = (
|
||||
("missing", "MISSING"),
|
||||
("extra_phantom", "UNPAIRED"),
|
||||
("extra_unprofiled", "UNPROF"),
|
||||
("hash_mismatch", "HASH"),
|
||||
("required_mismatch", "REQ"),
|
||||
)
|
||||
|
||||
|
||||
def _terminal_divergence(sys_id: str, div: dict) -> list[str]:
|
||||
labels = [f"{label}:{len(div[key])}" for key, label in _DIVERGENCE_LABELS if div.get(key)]
|
||||
lines = [f" {sys_id}: {' '.join(labels)}"]
|
||||
lines.extend(
|
||||
f" + {_where(m)} [{', '.join(m.get('cores', []))}]"
|
||||
for m in div.get("missing", [])
|
||||
)
|
||||
lines.extend(
|
||||
f" ~ {_where(h)} {h['hash_type']}: "
|
||||
f"{h['truth_' + h['hash_type']]} != {h['scraped_' + h['hash_type']]}"
|
||||
for h in div.get("hash_mismatch", [])
|
||||
)
|
||||
lines.extend(
|
||||
f" - {_where(p)} (no profile entry of this system matches it)"
|
||||
for p in div.get("extra_phantom", [])
|
||||
)
|
||||
lines.extend(
|
||||
f" ? {_where(u)} (unprofiled cores)"
|
||||
for u in div.get("extra_unprofiled", [])
|
||||
)
|
||||
lines.extend(
|
||||
f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}"
|
||||
for r in div.get("required_mismatch", [])
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
def _format_terminal(report: dict) -> str:
|
||||
lines: list[str] = []
|
||||
platform = report.get("platform", "unknown")
|
||||
s = report["summary"]
|
||||
|
||||
lines.append(f"=== {platform} ===")
|
||||
lines.append(
|
||||
f" {s['systems_compared']} systems compared: "
|
||||
f"{s['systems_fully_covered']} full, "
|
||||
f"{s['systems_partially_covered']} partial, "
|
||||
f"{s['systems_uncovered']} uncovered"
|
||||
)
|
||||
|
||||
totals = [f"{s[key]} {label}" for key, label in _TOTAL_LABELS if s[key]]
|
||||
if totals:
|
||||
lines.append(f" divergences: {', '.join(totals)}")
|
||||
else:
|
||||
lines.append(" no divergences")
|
||||
|
||||
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
||||
lines.extend(_terminal_divergence(sys_id, div))
|
||||
|
||||
uncovered = report.get("uncovered_systems", [])
|
||||
if uncovered:
|
||||
lines.append(f" uncovered ({len(uncovered)}): {', '.join(uncovered)}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _markdown_divergence(sys_id: str, div: dict) -> list[str]:
|
||||
lines = [f"## {sys_id}", ""]
|
||||
for m in div.get("missing", []):
|
||||
refs = ""
|
||||
if m.get("source_refs"):
|
||||
refs = " " + " ".join(f"`{r}`" for r in m["source_refs"])
|
||||
lines.append(f"- **Add** `{_where(m)}`{refs}")
|
||||
lines.extend(
|
||||
f"- **Fix hash** `{_where(h)}` {h['hash_type']}: "
|
||||
f"`{h['truth_' + h['hash_type']]}` != `{h['scraped_' + h['hash_type']]}`"
|
||||
for h in div.get("hash_mismatch", [])
|
||||
)
|
||||
# Evidence, not a request: an entry leaves a platform's file only on
|
||||
# proof (export_native's removal_candidates). A core can read a
|
||||
# file its profile does not pair with this declaration.
|
||||
lines.extend(
|
||||
f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it "
|
||||
"by path, name or hash"
|
||||
for p in div.get("extra_phantom", [])
|
||||
)
|
||||
lines.extend(
|
||||
f"- **Unpaired** `{_where(u)}`: some cores of this platform "
|
||||
"have no profile yet"
|
||||
for u in div.get("extra_unprofiled", [])
|
||||
)
|
||||
lines.extend(
|
||||
f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}"
|
||||
for r in div.get("required_mismatch", [])
|
||||
)
|
||||
lines.append("")
|
||||
return lines
|
||||
|
||||
|
||||
def _format_markdown(report: dict) -> str:
|
||||
lines: list[str] = []
|
||||
platform = report.get("platform", "unknown")
|
||||
s = report["summary"]
|
||||
|
||||
lines.append(f"# {platform}")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
f"**{s['systems_compared']}** systems compared | "
|
||||
f"**{s['systems_fully_covered']}** full | "
|
||||
f"**{s['systems_partially_covered']}** partial | "
|
||||
f"**{s['systems_uncovered']}** uncovered"
|
||||
)
|
||||
lines.append(
|
||||
f"**{s['total_missing']}** missing | "
|
||||
f"**{s['total_extra_phantom']}** unpaired | "
|
||||
f"**{s['total_extra_unprofiled']}** unprofiled | "
|
||||
f"**{s['total_hash_mismatch']}** hash | "
|
||||
f"**{s['total_required_mismatch']}** required"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
||||
lines.extend(_markdown_divergence(sys_id, div))
|
||||
|
||||
uncovered = report.get("uncovered_systems", [])
|
||||
if uncovered:
|
||||
lines.append("## Uncovered systems")
|
||||
lines.append("")
|
||||
lines.extend(f"- {u}" for u in uncovered)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Compare scraped vs truth YAMLs")
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument(
|
||||
@@ -213,12 +56,16 @@ def main() -> None:
|
||||
help="read the models generate_truth --target wrote, each under the "
|
||||
"target as its platform files it",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = build_parser().parse_args()
|
||||
|
||||
platforms = selected_platforms(args)
|
||||
|
||||
reports: list[dict] = []
|
||||
formatter = _format_markdown if args.format == "markdown" else _format_terminal
|
||||
formatter = format_markdown if args.format == "markdown" else format_terminal
|
||||
compared = 0
|
||||
|
||||
for platform in platforms:
|
||||
@@ -226,21 +73,11 @@ def main() -> None:
|
||||
truth_target_dir(args.truth_dir, [platform], args.target, args.platforms_dir)
|
||||
if args.target else args.truth_dir
|
||||
)
|
||||
truth = _load_truth(truth_dir, platform)
|
||||
if truth is None:
|
||||
print(f"skip {platform}: no truth YAML in {truth_dir}/", file=sys.stderr)
|
||||
continue
|
||||
|
||||
try:
|
||||
# What the platform's own file declares: our shared groups,
|
||||
# mirrors and curated additions are not theirs to be credited.
|
||||
scraped = native_layer(load_platform_config(platform, args.platforms_dir))
|
||||
except FileNotFoundError:
|
||||
print(f"skip {platform}: no scraped config", file=sys.stderr)
|
||||
report = platform_diff(platform, truth_dir, args.platforms_dir)
|
||||
except NoDiffInput as exc:
|
||||
print(f"skip {platform}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
report = diff_platform_truth(truth, scraped)
|
||||
report["platform"] = platform
|
||||
compared += 1
|
||||
|
||||
if args.json_output:
|
||||
|
||||
@@ -21,327 +21,18 @@ import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.hashing import compute_hashes, parse_sha256sums
|
||||
from core.paths import REPO_ROOT
|
||||
from core.sizes import size_text
|
||||
from core.text import count_text
|
||||
from core.upstream import UpstreamError, forge_headers, open_retrying
|
||||
from core.upstream import UpstreamError
|
||||
from core.ziptools import safe_extract_zip
|
||||
from packs.parts import part_of
|
||||
from model.releaserecord import PACK_SUFFIX, RECORD, load_record, match_key, pack_label, recorded_pack
|
||||
|
||||
DEFAULT_API = "https://api.github.com"
|
||||
REPO = "Abdess/retrobios"
|
||||
CHECKSUMS_ASSET = "SHA256SUMS.txt"
|
||||
STAGING_PREFIX = ".retrobios-download-"
|
||||
MAX_CHECKSUMS_BYTES = 1 << 20
|
||||
CHUNK = 1 << 20
|
||||
|
||||
_VOLUME_RE = re.compile(rf"^(?P<base>.+{re.escape(PACK_SUFFIX)})\.(?P<index>\d+)$")
|
||||
_LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
|
||||
|
||||
|
||||
def _checked_url(value: str, label: str) -> str:
|
||||
"""Refuse a URL that is neither HTTPS nor loopback.
|
||||
|
||||
This endpoint names the assets and, through them, the bytes that land in
|
||||
the BIOS directory, so it is the trust anchor of the whole download.
|
||||
Plain HTTP to loopback stays allowed: it is how this is tested end to end.
|
||||
"""
|
||||
parsed = urllib.parse.urlparse(value)
|
||||
if parsed.scheme == "https":
|
||||
return value.rstrip("/")
|
||||
host = (parsed.hostname or "").lower()
|
||||
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
|
||||
return value.rstrip("/")
|
||||
print(f"Error: {label} must use HTTPS, got {value!r}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
API = _checked_url(os.environ.get("RETROBIOS_API", DEFAULT_API), "RETROBIOS_API")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pack:
|
||||
"""A platform pack: one asset, or the files it was published in.
|
||||
|
||||
`joined` says the files are byte ranges of one archive. `expected_parts`
|
||||
is the count a part's own name declares, so a release that lists fewer
|
||||
is recognised before anything is downloaded.
|
||||
"""
|
||||
|
||||
name: str
|
||||
platform: str
|
||||
parts: tuple[dict, ...]
|
||||
size: int
|
||||
joined: bool = False
|
||||
expected_parts: int = 1
|
||||
|
||||
|
||||
# A release publishes packs for the setups most people download. The others
|
||||
# are served file by file by the installer.
|
||||
NO_PACK_HINT = (
|
||||
"A setup without a pack is served by the installer:\n"
|
||||
" curl -fsSL https://abdess.github.io/retrobios/i | sh -s -- --platform <name>"
|
||||
)
|
||||
|
||||
|
||||
def get_latest_release() -> dict:
|
||||
"""Fetch latest release info from GitHub API."""
|
||||
url = f"{API}/repos/{REPO}/releases/latest"
|
||||
# The anonymous quota is 60 calls an hour per address. The token goes to
|
||||
# GitHub's API only: RETROBIOS_API can name any host.
|
||||
headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0")
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
|
||||
try:
|
||||
return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404:
|
||||
print("No releases found. The repository may not have any releases yet.")
|
||||
sys.exit(1)
|
||||
raise
|
||||
|
||||
|
||||
def group_packs(release: dict) -> list[Pack]:
|
||||
"""Group release assets into packs, the files of one pack folded together."""
|
||||
groups: dict[str, list[tuple[int, dict]]] = {}
|
||||
joined: set[str] = set()
|
||||
expected: dict[str, int] = {}
|
||||
for asset in release.get("assets", []):
|
||||
name = asset["name"]
|
||||
volume = _VOLUME_RE.match(name)
|
||||
part = part_of(name)
|
||||
if volume:
|
||||
groups.setdefault(volume["base"], []).append((int(volume["index"]), asset))
|
||||
joined.add(volume["base"])
|
||||
elif part:
|
||||
base, index, count = part
|
||||
groups.setdefault(base, []).append((index, asset))
|
||||
expected[base] = count
|
||||
elif name.endswith(PACK_SUFFIX):
|
||||
groups.setdefault(name, []).append((0, asset))
|
||||
|
||||
packs = []
|
||||
for base, volumes in sorted(groups.items()):
|
||||
parts = tuple(asset for _, asset in sorted(volumes, key=lambda v: v[0]))
|
||||
packs.append(
|
||||
Pack(
|
||||
name=base,
|
||||
platform=pack_label(base),
|
||||
parts=parts,
|
||||
size=sum(part.get("size", 0) for part in parts),
|
||||
joined=base in joined,
|
||||
expected_parts=expected.get(base, len(parts)),
|
||||
)
|
||||
)
|
||||
return packs
|
||||
|
||||
|
||||
def list_platforms(release: dict) -> list[str]:
|
||||
"""List available platform packs from release assets."""
|
||||
return sorted(pack.platform for pack in group_packs(release))
|
||||
|
||||
|
||||
def find_pack(release: dict, platform: str) -> Pack | None:
|
||||
"""Find the pack for a platform name.
|
||||
|
||||
release.json names the platforms each pack serves, and is read when it
|
||||
records this release. Otherwise the platform is matched against the pack
|
||||
names, the shortest first: RetroArch_v1.22.2 is the full pack, and
|
||||
RetroArch_v1.22.2_AndroidArm64V8A one target's.
|
||||
"""
|
||||
packs = group_packs(release)
|
||||
record = load_record(REPO_ROOT / RECORD)
|
||||
if record.get("tag") and record.get("tag") == release.get("tag_name"):
|
||||
name = recorded_pack(platform, record)
|
||||
return next((pack for pack in packs if pack.name == name), None)
|
||||
needle = match_key(platform)
|
||||
if not needle:
|
||||
return None
|
||||
matches = [pack for pack in packs if needle in match_key(pack.name)]
|
||||
return min(matches, key=lambda pack: (len(match_key(pack.name)), pack.name), default=None)
|
||||
|
||||
|
||||
def fetch_checksums(release: dict) -> dict[str, str]:
|
||||
"""Read the published SHA-256 of each pack, keyed by archive name."""
|
||||
for asset in release.get("assets", []):
|
||||
if asset["name"] != CHECKSUMS_ASSET:
|
||||
continue
|
||||
url = _checked_url(asset["browser_download_url"], "asset URL")
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "retrobios-downloader/1.0"}
|
||||
)
|
||||
body = open_retrying(
|
||||
req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
|
||||
).decode("utf-8", "replace")
|
||||
# A file that is not sha256sum output refuses the download: read
|
||||
# leniently, a `*name` line matched nothing and the pack went
|
||||
# unchecked.
|
||||
try:
|
||||
return parse_sha256sums(body)
|
||||
except ValueError as exc:
|
||||
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
|
||||
return {}
|
||||
|
||||
|
||||
def download_file(
|
||||
url: str, dest: Path, expected_size: int = 0, label: str = ""
|
||||
) -> None:
|
||||
"""Download a file with progress indication.
|
||||
|
||||
core.upstream.open_retrying asks again after a dropped connection, a
|
||||
stream cut midway or a 5xx, and waits out a rate limit: each attempt
|
||||
writes `dest` from its first byte.
|
||||
"""
|
||||
url = _checked_url(url, "asset URL")
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "retrobios-downloader/1.0"}
|
||||
)
|
||||
|
||||
# A redrawn bar only on a terminal: written to a log, 32,768 redraws of a
|
||||
# 2 GiB part made one line of nearly 3 MB.
|
||||
live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
|
||||
|
||||
def save(resp: http.client.HTTPResponse) -> int:
|
||||
total = int(resp.headers.get("Content-Length", expected_size))
|
||||
downloaded = 0
|
||||
shown = -1
|
||||
with open(dest, "wb") as f:
|
||||
while chunk := resp.read(65536):
|
||||
f.write(chunk)
|
||||
downloaded += len(chunk)
|
||||
if total > 0 and live:
|
||||
pct = downloaded * 100 // total
|
||||
if pct != shown:
|
||||
shown = pct
|
||||
columns = shutil.get_terminal_size((80, 24)).columns
|
||||
line = _progress_line(label, downloaded, total, columns)
|
||||
print(f"\r\033[K{line}", end="", flush=True)
|
||||
return downloaded
|
||||
|
||||
downloaded = open_retrying(req, save, 300)
|
||||
if live:
|
||||
print()
|
||||
else:
|
||||
print(f" {label}{downloaded:,} bytes")
|
||||
if expected_size and downloaded != expected_size:
|
||||
raise ValueError(f"downloaded {downloaded} bytes, expected {expected_size}")
|
||||
|
||||
|
||||
def _progress_line(label: str, done: int, total: int, columns: int) -> str:
|
||||
"""One physical line shorter than the terminal: a wrapped line leaves a
|
||||
copy of itself on every redraw, since \\r goes back one row only. The
|
||||
bar shrinks first, then goes."""
|
||||
pct = done * 100 // total
|
||||
figures = f" {pct}% ({size_text(done)}/{size_text(total)})"
|
||||
room = min(50, columns - 1 - len(f" {label}[]") - len(figures))
|
||||
if room < 10:
|
||||
return f" {label}{figures.strip()}"[: columns - 1]
|
||||
filled = room * pct // 100
|
||||
return f" {label}[{'=' * filled}{' ' * (room - filled)}]{figures}"
|
||||
|
||||
|
||||
def join_volumes(parts: list[Path], dest: Path) -> None:
|
||||
"""Concatenate split volumes into one archive, streaming."""
|
||||
with open(dest, "wb") as out:
|
||||
for part in parts:
|
||||
with open(part, "rb") as src:
|
||||
shutil.copyfileobj(src, out, CHUNK)
|
||||
|
||||
|
||||
def make_staging(dest: Path) -> Path:
|
||||
"""Return a staging directory of this run's own, on the destination volume.
|
||||
|
||||
A pack is gigabytes and that is the filesystem the user picked for them:
|
||||
the system temp directory is a RAM disk on the appliances these packs
|
||||
target. The name is unique per run because two downloads into one BIOS
|
||||
folder used to share a fixed path, so whichever finished first removed the
|
||||
other's archive mid-transfer and the second died on the missing file with
|
||||
nothing installed.
|
||||
"""
|
||||
return Path(tempfile.mkdtemp(prefix=STAGING_PREFIX, dir=dest))
|
||||
|
||||
|
||||
def _check(archive: Path, checksums: dict[str, str]) -> None:
|
||||
"""Compare a downloaded file with its published SHA-256, when there is one."""
|
||||
expected = checksums.get(archive.name)
|
||||
if not expected:
|
||||
print(f"No checksum published for {archive.name}, skipping.")
|
||||
return
|
||||
print(f"Checking {archive.name}...")
|
||||
actual = compute_hashes(str(archive))["sha256"].lower()
|
||||
if actual != expected:
|
||||
archive.unlink()
|
||||
print(
|
||||
f"Error: checksum mismatch for {archive.name}\n"
|
||||
f" expected {expected}\n got {actual}\n"
|
||||
"Download the parts again: a truncated part gives this.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_pack(pack: Pack, staging: Path, checksums: dict[str, str]) -> list[Path]:
|
||||
"""Download a pack and return the archives to extract, each one checked."""
|
||||
if len(pack.parts) != pack.expected_parts:
|
||||
print(
|
||||
f"Error: the release lists {len(pack.parts)} of "
|
||||
f"{pack.expected_parts} parts of {pack.name}.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
staging.mkdir(parents=True, exist_ok=True)
|
||||
volumes = []
|
||||
for index, part in enumerate(pack.parts, start=1):
|
||||
label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else ""
|
||||
target = staging / part["name"]
|
||||
print(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...")
|
||||
download_file(part["browser_download_url"], target, part.get("size", 0), label)
|
||||
volumes.append(target)
|
||||
|
||||
if pack.joined:
|
||||
archive = staging / pack.name
|
||||
print(f"Joining {len(volumes)} parts into {pack.name}...")
|
||||
join_volumes(volumes, archive)
|
||||
for volume in volumes:
|
||||
volume.unlink()
|
||||
volumes = [archive]
|
||||
|
||||
if not checksums:
|
||||
print(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.")
|
||||
return volumes
|
||||
for archive in volumes:
|
||||
_check(archive, checksums)
|
||||
return volumes
|
||||
|
||||
|
||||
def show_info(platform: str, release: dict) -> None:
|
||||
"""Show pack information for a platform."""
|
||||
pack = find_pack(release, platform)
|
||||
if not pack:
|
||||
print(f"Platform '{platform}' not found in release.")
|
||||
print("Available:", ", ".join(list_platforms(release)))
|
||||
print(NO_PACK_HINT)
|
||||
sys.exit(1)
|
||||
|
||||
print(f" Platform: {pack.platform}")
|
||||
print(f" File: {pack.name}")
|
||||
print(f" Parts: {count_text(len(pack.parts), 'part')}")
|
||||
print(f" Size: {pack.size:,} bytes ({size_text(pack.size)})")
|
||||
for part in pack.parts:
|
||||
print(f" {part['name']} ({part.get('size', 0):,} bytes)")
|
||||
from release.latest import get_latest_release
|
||||
from release.packfetch import fetch_checksums, fetch_pack, make_staging
|
||||
from release.packgroups import find_pack, list_platforms
|
||||
from release.packinfo import exit_without_pack, show_info
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -405,10 +96,7 @@ To check files already in place, use: python install.py --check
|
||||
|
||||
pack = find_pack(release, args.platform)
|
||||
if not pack:
|
||||
print(f"Platform '{args.platform}' not found in release.")
|
||||
print("Available:", ", ".join(list_platforms(release)))
|
||||
print(NO_PACK_HINT)
|
||||
sys.exit(1)
|
||||
exit_without_pack(args.platform, release)
|
||||
|
||||
dest = Path(os.path.expanduser(args.dest))
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||