NSP script: game files whose extension is in capitals are found and packed, an NSZ or XCZ too

A folder with `Game [id].NSP` stopped with "no NSP with a readable title ID" on any Mac volume
(LNPANDY/NX2Apple#554): Path.glob('*.nsp') compares case-sensitively on every POSIX system, a
case-insensitive volume included. The same globs let a dump folder win over `Game.NSP` beside it and
missed `Game.NUP`. files_with_suffix lists a folder's files by their lowercased extension for every scan
of the inputs, and is where AppleDouble files are dropped.

nsz has the limit of its own: it skips a capital extension and exits 0 with no output, after resolving
any symlink. A compressed file in capitals goes to it as a hard link with a lowercase extension in its
temporary folder, or as a copy where there can be none (another volume, exFAT). A package beside a
compressed one is found in the folder's listing, so it wins on a case-sensitive volume too. A folder named
like a package no longer stops the scan with IsADirectoryError.

Co-authored-by: v0lumehi <[email protected]>
This commit is contained in:
seeddsandv0lumehi committed 2026-11-04 20:58:40 +08:00
1 parent d17e0ca536
commit 7dc00e4d2b
7 files changed
+110 -11

No files matched your search

+1
View File
@@ -82,6 +82,7 @@ Game-specific findings. The general host changes they led to are listed under [F
## Found on this game
- [A game file whose extension is in capitals is not found](../../../docs/reference/packing.md#a-game-file-whose-extension-is-in-capitals-is-not-found) (2026-11-04, LNPANDY/NX2Apple#554): its `.NSP` stopped the build on a Mac.
- [macOS Game Mode holds the GPU at its lowest clock](../../../docs/reference/frame-rate.md#macos-game-mode-holds-the-gpu-at-its-lowest-clock) (2026-11-04, #349): the Mac's fall to 30 fps at 338 MHz; a new Mac app opts out, a re-packed one needs the Game Overlay switch once.
- [A regress run stops when another app takes the key window](../../../docs/reference/frame-rate.md#a-regress-run-stops-when-another-app-takes-the-key-window): the route's intermittent "hang" was the game paused out of focus (resolved).
- [Old per-shader cache entries grew a game's build folder with each chain change](../../../docs/reference/shaders.md#old-per-shader-cache-entries-grew-a-games-build-folder-with-each-chain-change) (2026-11-03, #1033): 12 GB of earlier chains' entries in `cas/shader`.
+30
View File
@@ -49,6 +49,8 @@ class Nsz(unittest.TestCase):
self.assertEqual(staged.resolve(), self.keys.resolve())
self.assertEqual(staged.read_text(), 'test keys\n')
self.runs.append(src.name)
if src.suffix not in nsp.COMPRESSED: return # the real nsz: PathTools.isCompressedGame takes a lowercase extension only, skips anything else and exits 0 with no output
self.assertEqual(src, src.resolve()) # and it resolves a symlink before it looks at the extension
(out / (src.stem + nsp.COMPRESSED[src.suffix])).write_bytes(b'partial' if self.fail_conversion else b'nsp of ' + src.name.encode())
if self.fail_conversion: raise nsp.BuildError('nsz exit code 1')
@@ -89,6 +91,34 @@ class Nsz(unittest.TestCase):
self.assertEqual(fam['base'].read_bytes(), b'nsp of Game [v0].xcz')
self.assertFalse((fam['base'].parent / 'partial').exists())
def test_extension_in_capitals_is_converted(self):
self.upd.unlink()
for capitals, lower, made in (('.NSZ', '.nsz', '.nsp'), ('.XCZ', '.xcz', '.xci')):
with self.subTest(capitals=capitals):
src = self.base.with_suffix(capitals); self.base.rename(src); content = src.read_bytes()
app, fam = nsp.scan_nsps(self.tmp)
self.assertEqual(fam['base'], src)
fam = nsp.decompress_nsz(self.tmp, app, fam, self.keys, {})
self.assertEqual(fam['base'], self.tmp / f'{APP:016X}_build' / 'nsp' / f'Game [v0]{made}')
self.assertEqual(fam['base'].read_bytes(), f'nsp of Game [v0]{lower}'.encode())
self.assertEqual((sorted(p.name for p in self.tmp.iterdir() if p.is_file()), src.read_bytes()), ([src.name], content)) # the player's file stays as it was
self.assertFalse((fam['base'].parent / 'partial').exists())
src.rename(self.base)
def test_extension_in_capitals_without_a_hard_link(self): # another volume, exFAT
self.upd.unlink(); src = self.base.with_suffix('.NSZ'); self.base.rename(src)
app, fam = nsp.scan_nsps(self.tmp)
with mock.patch.object(os, 'link', side_effect=OSError('no hard links')):
fam = nsp.decompress_nsz(self.tmp, app, fam, self.keys, {})
self.assertEqual(fam['base'].read_bytes(), b'nsp of Game [v0].nsz')
self.assertTrue(src.is_file())
def test_lowercase_extension_is_given_as_it_is(self):
self.upd.unlink()
with mock.patch.object(os, 'link') as link: nsp.decompress_nsz(self.tmp, *nsp.scan_nsps(self.tmp), self.keys, {})
link.assert_not_called()
self.assertEqual(self.runs, [self.base.name])
def test_failed_conversion_is_not_kept(self):
app, fam = nsp.scan_nsps(self.tmp); self.fail_conversion = True
with self.assertRaises(nsp.BuildError): nsp.decompress_nsz(self.tmp, app, fam, self.keys, {})
+40
View File
@@ -46,6 +46,46 @@ class Scan(unittest.TestCase):
self.assertEqual(nsp.scan_nsps(self.tmp)[1]['base'], base)
self.assertEqual(self.said, [])
def test_extension_in_any_letter_case(self): # `Game [id].NSP` (a download, a card dump): glob('*.nsp') missed it on every POSIX system, a case-insensitive Mac volume too (LNPANDY/NX2Apple#554)
base = self.tmp / f'Game [{APP:016X}][v0].NSP'; pfs0(base, [f'{APP:016x}0000000000000011.tik'])
upd = self.tmp / f'Update [{APP | 0x800:016X}][v65536].Nsp'; pfs0(upd, [])
dlc = self.tmp / f'DLC [{APP + 0x1001:016X}].XCI'; dlc.write_bytes(bytes(0x100) + b'HEAD' + bytes(0x100))
app, fam = nsp.scan_nsps(self.tmp)
self.assertEqual((app, fam['base'], [p for _, p in fam['updates']], [p for _, _, p in fam['dlc']]), (APP, base, [upd], [dlc]))
def test_compressed_extension_in_capitals_counts(self): # its conversion: test_nsp_nsz
nsz = self.tmp / f'Game [{APP:016X}].NSZ'; pfs0(nsz, [f'{APP:016x}0000000000000011.tik'])
self.assertEqual(nsp.scan_nsps(self.tmp)[1]['base'], nsz)
def test_package_beside_a_compressed_one_wins_in_any_letter_case(self): # read from the listing: Game.nsp, which with_suffix would look for, is not on a case-sensitive volume
for packed, compressed in (('.NSP', '.NSZ'), ('.NSP', '.nsz'), ('.nsp', '.NSZ'), ('.XCI', '.XCZ')):
with self.subTest(packed=packed, compressed=compressed):
self.said.clear()
base = self.tmp / f'Game [{APP:016X}]{packed}'; pfs0(base, [f'{APP:016x}0000000000000011.tik'])
nsz = self.tmp / f'Game [{APP:016X}]{compressed}'; pfs0(nsz, [f'{APP:016x}0000000000000011.tik'])
self.assertEqual(nsp.scan_nsps(self.tmp)[1]['base'], base)
self.assertEqual(self.said, [f'skipping {nsz.name}: {base.name} is beside it'])
base.unlink(); nsz.unlink()
def test_folder_named_like_a_package_is_not_one(self):
(self.tmp / 'old.nsp').mkdir()
base = self.tmp / f'Game [{APP:016X}].nsp'; pfs0(base, [f'{APP:016x}0000000000000011.tik'])
self.assertEqual(nsp.scan_nsps(self.tmp)[1]['base'], base)
def test_nup_in_capitals(self):
nup = self.tmp / 'Game.NUP'; nup.write_bytes(b'NUP\0')
self.assertEqual(nsp.nup_file(self.tmp), nup)
(self.tmp / '._Game.NSP').write_bytes(b'\0\x05\x16\x07') # an AppleDouble file is not a package
self.assertEqual(nsp.nup_file(self.tmp), nup)
pfs0(self.tmp / 'Game.NSP', ['x.nca'])
self.assertIsNone(nsp.nup_file(self.tmp)) # a package in capitals counts as a package, so no NUP is looked for
def test_dump_with_a_package_in_capitals_beside_it(self):
(self.tmp / 'base/exefs').mkdir(parents=True); (self.tmp / 'base/romfs').mkdir(); (self.tmp / 'base/exefs/main.npdm').write_bytes(b'x')
self.assertTrue(nsp.dump_folder(self.tmp))
pfs0(self.tmp / 'Game.NSP', ['x.nca'])
self.assertFalse(nsp.dump_folder(self.tmp)) # the package is what the player asked for
def test_missing_final_name_terminator(self):
for extension in ('.nsp', '.nsz'):
with self.subTest(extension=extension):
+1
View File
@@ -28,6 +28,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the NSP script or any module tool stops on `main`: `compressed with zstd (NSO flag bit 7), which this loader does not decode yet`; with the decoder but without its package, `ZBIC (zstd) segments need the zbic package (python3 -m pip install zbic)`. → [ZBIC-compressed NSO segments](../reference/packing.md#zbic-compressed-nso-segments)
- `FATAL open <folder>/subsdk1.fixups.tsv` right after the host starts, or `build_ipa.sh` stops with `no rewritten module …/subsdk1`, for a version that has no such module. → [A version without one of the profile's modules stops the host at boot](../reference/packing.md#a-version-without-one-of-the-profiles-modules-stops-the-host-at-boot)
- `[RED] no NSP with a readable title ID in <folder>`, although the keys open the package (the launcher's key check passes). Renaming the file to `Game [0100XXXXXXXXXXXX].nsp` makes the build go on. → [An NSP without a ticket or a title ID in its name stops with "no NSP with a readable title ID"](../reference/packing.md#an-nsp-without-a-ticket-or-a-title-id-in-its-name-stops-with-no-nsp-with-a-readable-title-id)
- `[RED] no NSP with a readable title ID in <folder>` for a folder holding `Game [0100XXXXXXXXXXXX].NSP`, on any Mac volume; renaming it to `.nsp` makes the build go on. A dump folder beside `Game.NSP` is packed instead of the package, and `Game.NUP` is not found. A `Game.NSZ` stops with `nsz made no Game.nsp`. → [A game file whose extension is in capitals is not found](../reference/packing.md#a-game-file-whose-extension-is-in-capitals-is-not-found)
- a game folder holding one merged package (`[Base + Update + DLC].nsp`, or a 1G+1U cartridge dump with no update NSP beside it) stops with `no base game NSP found`, or packs the base game alone (v0) without its update and DLC; when the base game's own build cannot be packed (Mario Kart 8 Deluxe 1.0.0's `main` is 32-bit), the build stops there. → [A merged NSP (base game, update and DLC in one file) packs as one title](../reference/packing.md#a-merged-nsp-base-game-update-and-dlc-in-one-file-packs-as-one-title)
- the NSP script stops at its rewrite stage with `FileNotFoundError: … extract/v0/ExeFS/subsdk1` while packing a version the profile was not brought up on; the extraction has every other module. → [A derived profile loads only the modules its version ships](../reference/packing.md#a-derived-profile-loads-only-the-modules-its-version-ships)
- `nx_extract` stops with exit code 134 and `Unhandled exception. LibHac.Common.Keys.MissingKeyException: Unable to decrypt NCA section.` with `Key Name: key_area_key_application_<NN>` (or `titlekek_<NN>`), after any NSZ conversion, the build ID lookup or the survey. An NSZ converted with such keys is written anyway: `nsz -D` warns `master_key_<NN> missing … This will lead to corrupted output.` and exits 0. → [Keys older than the game stop the extraction with an unhandled MissingKeyException](../reference/packing.md#keys-older-than-the-game-stop-the-extraction-with-an-unhandled-missingkeyexception)
+1 -1
View File
@@ -445,7 +445,7 @@ When the output goes to a file or a pipe, the script prints a plain line instead
`--progress json` is for a program that shows the build (a GUI): stdout carries one JSON object per line, each with `ev` and the time `t`. The events are `stage` (`k`, `n`, `name`, `step`), `step`, `progress` (`done`, `total`, `unit`, `est`, `note`, `frac`, `eta`, `elapsed`; `null` while unknown), `stage_end` (`ok`, `summary`, `elapsed`) and `say` (`msg`: every message, errors and a failed step's log tail included). A count change goes out at most every 0.5 s, any other change at once. This mode never asks for the NSP folder or the keys; argument errors and an unexpected error's traceback still go to stderr. `dm/tools/tests/test_nsp_progress.py` tests it without game files, keys or Xcode (`python3 -m unittest discover -s dm/tools/tests`).
A file in the NSP folder counts only when its header is an NSP's or an XCI's (whatever its name says); others are skipped with a line. The NSP folder may be on an exFAT or FAT drive: the AppleDouble `._<name>` files macOS writes there are skipped quietly, and removing a folder tolerates entries that vanish meanwhile ([exFAT drives](reference/packing.md#a-game-folder-on-an-exfat-drive-reads-one-update-as-two-or-fails-to-remove-a-folder)). Everything it writes stays in the NSP folder: intermediate files and logs in `<id>_build/`, the IPA next to the NSPs; `--work-dir <folder>` puts the build folder at that path instead, and the IPA (or Mac app) then defaults to the folder holding it (`-o` names it either way). The survey of a game without a profile still goes to the NSP folder (`<title ID>_survey/`); the NSZ conversions go to the build folder's `nsp/`. NSZ and XCZ files are converted with `nsz -D` (from the `nsz` package in the Python running the script, else an nsz 5.0 or later executable on PATH, `nsz` or the release binary `nsz-cli-macos-arm64`, given the keys with `--keys`) into the build folder's `nsp/` (`<title ID>_build/nsp/`, or under `--work-dir`), through a temporary folder so that only a conversion nsz finished is used, and reused while the source keeps its name, size and modification time; `nsz -D` reports an NCA hash mismatch but goes on, so a damaged file is caught by nx_extract's own hash check (`--allow-damaged`). The keys selected by `-k` are linked temporarily as `keys.txt` for nsz's import-time lookup ([NSZ keys](reference/packing.md#nsz-decompression-rejects---keys)). The extracted game files stay in `<id>_build/extract/` for the next build; `--no-keep-extracted` (`KEEP_EXTRACTED = False` in Spyder) deletes them at the end. It exits with 0 when done and 1 on an error. The app's bundle ID is `org.nxnative.<base game title ID>` (for example `org.nxnative.0100a6301214e000`), and its version is the game's display version: the update's when an update is packed, else the base game's (Engage 2.0.0); `--app-name` / `--bundle-id` (or `APP_NAME` / `BUNDLE_ID` in Spyder) override the name and ID.
A file in the NSP folder counts only when its header is an NSP's or an XCI's (whatever its name says); others are skipped with a line. Its extension may be in any letter case ([capitals](reference/packing.md#a-game-file-whose-extension-is-in-capitals-is-not-found)). The NSP folder may be on an exFAT or FAT drive: the AppleDouble `._<name>` files macOS writes there are skipped quietly, and removing a folder tolerates entries that vanish meanwhile ([exFAT drives](reference/packing.md#a-game-folder-on-an-exfat-drive-reads-one-update-as-two-or-fails-to-remove-a-folder)). Everything it writes stays in the NSP folder: intermediate files and logs in `<id>_build/`, the IPA next to the NSPs; `--work-dir <folder>` puts the build folder at that path instead, and the IPA (or Mac app) then defaults to the folder holding it (`-o` names it either way). The survey of a game without a profile still goes to the NSP folder (`<title ID>_survey/`); the NSZ conversions go to the build folder's `nsp/`. NSZ and XCZ files are converted with `nsz -D` (from the `nsz` package in the Python running the script, else an nsz 5.0 or later executable on PATH, `nsz` or the release binary `nsz-cli-macos-arm64`, given the keys with `--keys`) into the build folder's `nsp/` (`<title ID>_build/nsp/`, or under `--work-dir`), through a temporary folder so that only a conversion nsz finished is used, and reused while the source keeps its name, size and modification time; `nsz -D` reports an NCA hash mismatch but goes on, so a damaged file is caught by nx_extract's own hash check (`--allow-damaged`). The keys selected by `-k` are linked temporarily as `keys.txt` for nsz's import-time lookup ([NSZ keys](reference/packing.md#nsz-decompression-rejects---keys)). The extracted game files stay in `<id>_build/extract/` for the next build; `--no-keep-extracted` (`KEEP_EXTRACTED = False` in Spyder) deletes them at the end. It exits with 0 when done and 1 on an error. The app's bundle ID is `org.nxnative.<base game title ID>` (for example `org.nxnative.0100a6301214e000`), and its version is the game's display version: the update's when an update is packed, else the base game's (Engage 2.0.0); `--app-name` / `--bundle-id` (or `APP_NAME` / `BUNDLE_ID` in Spyder) override the name and ID.
The game language (`--language`, `LANGUAGE`; English by default) is what `nn::oe::GetDesiredLanguage` returns. As on the console, it must be one the game's control data lists (`SupportedLanguageFlag`, `nacp.py --languages`); the packed version's control data counts, since an update may add languages. The same language for another region stands in (`en-GB` for `en-US`, `es` for `es-419`, `fr` for `fr-CA`, `pt` for `pt-BR`, and back). A language the game lacks stops the build with the game's list; English, the default, falls back to the game's first language.
On the device, environment switches go in `Documents/env.txt` (one `KEY=VALUE` per line), and game files are also accepted at `Documents/romfs`.
+7
View File
@@ -189,6 +189,13 @@
- **Fix:** with neither, `title_of` asks the package: `nx_extract <prod.keys> --title <package>` opens it, decrypts the header of each meta NCA with the keys' `header_key` and prints the lowest title ID (the base game's before its update's or a DLC's). It works for NSP, NSZ (the meta NCA is not compressed), XCI and XCZ, and runs only when the ticket and the tag are both missing, so the common cases stay a read of the file name table. `nx_extract` is built into a temporary folder for it, since the build folder is named after the title ID. Key values are never printed.
- **Found on:** NX2Apple, [LNPANDY/NX2Apple#177](https://github.com/LNPANDY/NX2Apple/issues/177) ([Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md), whose base NSP has no ticket). Applies to every game.
### A game file whose extension is in capitals is not found
- **Symptom:** `[RED] no NSP with a readable title ID in <folder>` for a folder holding `Game [0100XXXXXXXXXXXX].NSP`, on any Mac volume; renaming it to `.nsp` makes the build go on. A dump folder beside `Game.NSP` is packed instead of the package, and `Game.NUP` is not found. A `Game.NSZ` stops with `nsz made no Game.nsp`.
- **Cause:** the script listed the folder with `Path.glob('*.nsp')`, which compares case-sensitively on every POSIX system, a case-insensitive Mac volume included. nsz has the same limit of its own: `PathTools.isCompressedGame` takes only a lowercase extension, and nsz skips anything else and exits 0 with no output. It resolves a symlink before it looks.
- **Fix:** `files_with_suffix` lists a folder's files by their lowercased extension, for every scan of the inputs, and a package beside a compressed one is found in that listing. A compressed file in capitals goes to nsz as a hard link with a lowercase extension in its temporary folder, or as a copy where there can be none (another volume, exFAT), so the player's file stays as it is.
- **Found on:** NX2Apple, [LNPANDY/NX2Apple#554](https://github.com/LNPANDY/NX2Apple/issues/554) ([Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md)). Applies to every game.
### A merged NSP (base game, update and DLC in one file) packs as one title
- **Symptom:** a game folder holding one merged package (`[Base + Update + DLC].nsp`, or a 1G+1U cartridge dump with no update NSP beside it) stops with `no base game NSP found`, or packs the base game alone (v0) without its update and DLC; when the base game's own build cannot be packed (Mario Kart 8 Deluxe 1.0.0's `main` is 32-bit), the build stops there.
+30 -10
View File
@@ -530,6 +530,14 @@ def version_of(path):
COMPRESSED = {'.nsz': '.nsp', '.xcz': '.xci'} # nsz's compressed NSP / XCI and what nsz -D makes of them
PACKAGE_SUFFIXES = ('.nsp', '.xci', '.nsz', '.xcz')
def files_with_suffix(folder, *suffixes):
"""The files of folder whose extension is one of suffixes in any letter case (`Game [id].NSP` from a download or a card dump): Path.glob('*.nsp') compares case-sensitively on every
POSIX system, a case-insensitive Mac volume included. An AppleDouble file does not count: on an exFAT / FAT drive macOS keeps a file's extended attributes (a download's quarantine
flag) in `._<name>`, one beside each game file"""
return sorted(p for p in folder.iterdir() if p.suffix.lower() in suffixes and not p.name.startswith('._') and p.is_file())
def extract_flags(app): # nx_extract's options shared by its extraction calls: the application to read (--app), the program of a multi-program application and a damaged NSP.
@@ -552,14 +560,14 @@ def scan_nsps(nsp_dir, from_package=None, contents_of=None, want=None):
if low == 0: f['base'] = p
elif low == 0x800: f['updates'].append((version, p))
else: f['dlc'].append((tid, version, p))
for p in sorted([*nsp_dir.glob('*.nsp'), *nsp_dir.glob('*.xci'), *nsp_dir.glob('*.nsz'), *nsp_dir.glob('*.xcz')]): # a base game may be a cartridge dump (.xci: Monster Hunter Rise); nx_extract reads its secure partition
if p.name.startswith('._'): continue # an AppleDouble file: on an exFAT / FAT drive macOS keeps a file's extended attributes (a download's quarantine flag) in `._<name>`, one beside each game file; is_package would skip it too, with a line for each
packages = files_with_suffix(nsp_dir, *PACKAGE_SUFFIXES) # a base game may be a cartridge dump (.xci: Monster Hunter Rise); nx_extract reads its secure partition
for p in packages:
if p.stat().st_size == 0: # an empty file left by an incomplete download (the Zelda BotW folder holds a 0-byte DLC NSP next to the complete (1).nsp)
say(f'skipping an empty file: {p.name}'); continue
if not is_package(p): # title_of falls back to the name's [title ID]: without this, any file with a game's extension and tag counted as one of its packages
say(f'skipping {p.name}: neither an NSP (PFS0) nor an XCI (HEAD at 0x100)'); continue
if p.suffix in COMPRESSED and p.with_suffix(COMPRESSED[p.suffix]).exists():
say(f'skipping {p.name}: {p.with_suffix(COMPRESSED[p.suffix]).name} is beside it'); continue
beside = next((q for q in packages if q.suffix.lower() == COMPRESSED.get(p.suffix.lower()) and q.stem.lower() == p.stem.lower()), None) # from the listing: `Game.NSP` is beside `Game.nsz` on a case-sensitive volume too
if beside: say(f'skipping {p.name}: {beside.name} is beside it'); continue
if contents_of and is_merged(p):
cs = [(t, i, v) for t, i, v in contents_of(p) or () if t in ('Application', 'Patch', 'AddOnContent')]
if cs:
@@ -608,12 +616,24 @@ def nsz_command(env):
raise BuildError(f'NSZ / XCZ files need the nsz tool in the current Python ({sys.executable}: pip install nsz) or an nsz 5.0 or later executable on PATH ({" or ".join(NSZ_EXECUTABLES)}){detail}')
def nsz_source(p, tmp):
"""The path of p to give nsz -D. nsz takes only a lowercase extension (anything else it skips and exits 0 with no output) and resolves a symlink before looking, so a name in capitals
goes as a hard link with a lowercase extension in tmp, or as a copy where there can be none (another volume, exFAT). The limit is nsz's own, in its PathTools.isCompressedGame"""
src = p.resolve()
if p.suffix == p.suffix.lower(): return src
(tmp / 'source').mkdir()
lower = tmp / 'source' / (p.stem + p.suffix.lower())
try: os.link(src, lower)
except OSError: shutil.copyfile(src, lower)
return lower.resolve()
def decompress_nsz(nsp_dir, app, fam, keys, env, work=None):
"""NSZ / XCZ files of fam converted once with nsz -D into <build folder>/nsp/ (work, the --work-dir folder, else <title ID>_build in the NSP folder); returns fam with the converted files in their place. nsz writes into an empty temporary folder
and the file is moved into nsp/ only when nsz exits 0, so a partial one is never taken for a whole one; a conversion is reused while its source has the same name, size and
modification time. nsz -D prints an NCA hash mismatch but goes on and exits 0: nx_extract's hash check catches a damaged file (ALLOW_DAMAGED)"""
paths = [fam['base']] + [p for _, p in fam['updates']] + [p for _, _, p in fam['dlc']]
todo = list(dict.fromkeys(p for p in paths if p.suffix in COMPRESSED)) # a merged package is the base game, the update and DLC: converted once
todo = list(dict.fromkeys(p for p in paths if p.suffix.lower() in COMPRESSED)) # a merged package is the base game, the update and DLC: converted once
if not todo: return fam
nsz, keys_opt = nsz_command(env), []
if nsz[0] != sys.executable: keys_opt = ['--keys', keys.resolve()] # a standalone nsz looks for keys beside itself, not in cwd: it takes them by --keys (nsz_command)
@@ -621,7 +641,7 @@ def decompress_nsz(nsp_dir, app, fam, keys, env, work=None):
PROG.plan(1); PROG.stage('decompress NSZ', done=0, total=len(todo))
conv, made = {}, 0
for i, p in enumerate(todo):
dst = out / (p.stem + COMPRESSED[p.suffix]); keyfile = dst.with_name(dst.name + '.key')
dst = out / (p.stem + COMPRESSED[p.suffix.lower()]); keyfile = dst.with_name(dst.name + '.key')
st = p.stat(); key = fingerprint(p.name, st.st_size, st.st_mtime_ns)
if not (dst.is_file() and reused(keyfile, key) is not None):
PROG.set(done=i, step=p.name)
@@ -630,7 +650,7 @@ def decompress_nsz(nsp_dir, app, fam, keys, env, work=None):
try:
# nsz 4.6.1 loads keys.txt beside argv[0] at import time; with argv[0] = 'nsz' that is cwd. That release has no --keys option.
(tmp / 'keys.txt').symlink_to(keys.resolve())
run([*nsz, *keys_opt, '-D', '-o', tmp, p.resolve()], log, env=env, cwd=tmp)
run([*nsz, *keys_opt, '-D', '-o', tmp, nsz_source(p, tmp)], log, env=env, cwd=tmp)
if not (tmp / dst.name).is_file(): raise BuildError(f'nsz made no {dst.name} (full output: {log})')
(tmp / dst.name).rename(dst)
finally: rmtree(tmp)
@@ -1154,15 +1174,15 @@ def extract_html(nx, keys, dst, base, upd, logs, app):
def dump_folder(folder): # a folder of the game's files (pack_dump.py), with no game package beside them: NSPs in the folder are what the player asked for
return pack_dump.is_dump(folder) and not any(p for g in ('*.nsp', '*.xci', '*.nsz', '*.xcz') for p in folder.glob(g) if not p.name.startswith('._'))
return pack_dump.is_dump(folder) and not files_with_suffix(folder, *PACKAGE_SUFFIXES)
def nup_file(path): # the NUP to pack: path when it is a .nup file, else the one .nup in the folder when no game package is beside it; None when there is none
if path.is_file():
if not pack_nup.is_nup(path): raise BuildError(f'not a folder or a NUP file: {path}')
return path
if any(p for g in ('*.nsp', '*.xci', '*.nsz', '*.xcz') for p in path.glob(g) if not p.name.startswith('._')): return None
nups = sorted(p for p in path.glob('*.nup') if not p.name.startswith('._') and pack_nup.is_nup(p))
if files_with_suffix(path, *PACKAGE_SUFFIXES): return None
nups = [p for p in files_with_suffix(path, '.nup') if pack_nup.is_nup(p)]
if len(nups) > 1: raise BuildError(f'more than one NUP in {path}: {", ".join(p.name for p in nups)}; keep one game per folder, or give the .nup file to pack in place of the folder')
return nups[0] if nups else None