Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Failure rows for keys, game files and the build's own steps

v0lumehi68117907ddaf
diff --git a/frontend-qt/nspb_qt/build_failure.py b/frontend-qt/nspb_qt/build_failure.py
index 984f7c2d..a5622231 100644
--- a/frontend-qt/nspb_qt/build_failure.py
+++ b/frontend-qt/nspb_qt/build_failure.py
@@ -21,6 +21,10 @@ OTHER_METAL = 'otherMetal'
SHADER_REGRESSION = 'shaderRegression'
DAMAGED_NSP = 'damagedNSP'
A32_PROGRAM = 'a32Program'
+KEYS = 'keys'
+SEVERAL_GAMES = 'severalGames'
+NO_TITLE_ID = 'noTitleID'
+DISK_FULL = 'diskFull'
UNKNOWN = 'unknown'
# (id, kind, regular expression searched in the log)
@@ -34,6 +38,11 @@ TABLE: list[tuple[str, str, str]] = [
('shaders.regression', SHADER_REGRESSION, r'a change to the translation chain broke them'),
('nsp.damaged', DAMAGED_NSP, r"files fail the NCA's hash check"),
('arm32.program', A32_PROGRAM, r'is a 32-bit ARM program'),
+ ('keys.missing', KEYS, r'(?m)^\[RED\] no such file: '),
+ ('games.several', SEVERAL_GAMES, r'more than one game in the folder, keep one game per folder'),
+ ('games.noTitleID', NO_TITLE_ID, r'no NSP with a readable title ID in '),
+ ('disk.low', DISK_FULL, r'less than [0-9]+ GB free on the volume of '),
+ ('disk.full', DISK_FULL, r'No space left on device'),
]
# The script's override for a stop, offered as "Build anyway". The others cannot be built around.
@@ -43,7 +52,10 @@ OVERRIDE_FLAGS = {
DAMAGED_NSP: '--allow-damaged',
}
-KINDS = [ROSETTA, TRANSLATOR, IOS_SDK, CLT_SELECTED, OTHER_METAL, SHADER_REGRESSION, DAMAGED_NSP, A32_PROGRAM]
+KINDS = [ROSETTA, TRANSLATOR, IOS_SDK, CLT_SELECTED, OTHER_METAL, SHADER_REGRESSION, DAMAGED_NSP, A32_PROGRAM,
+ KEYS, SEVERAL_GAMES, NO_TITLE_ID, DISK_FULL]
+# The Swift app has four more rows that no log line sets (a drive that is gone, a signing team, a device transfer):
+# they belong to the Mac launcher's install on a device and to /Volumes, which this front end does not have.
_A32_NAME = re.compile(r'^(?:\[RED\] )?(.+?) \([0-9A-Fa-f]{16}\) is a 32-bit ARM program', re.M)
@@ -52,6 +64,7 @@ _A32_NAME = re.compile(r'^(?:\[RED\] )?(.+?) \([0-9A-Fa-f]{16}\) is a 32-bit ARM
class Failure:
kind: str
game: str | None = None # a32Program: the game, when the message names it
+ detail: str | None = None # diskFull: the GB the script says it needs. noTitleID: the folder it names
@property
def what_key(self) -> str:
@@ -66,13 +79,28 @@ class Failure:
return OVERRIDE_FLAGS.get(self.kind)
-def classify(log: str) -> Failure:
- """UNKNOWN when no row matches: the caller then keeps showing the last line of the log."""
+def _detail(kind: str, log: str) -> str | None:
+ if kind == DISK_FULL: # "less than 40 GB free on the volume of /Volumes/X/..."
+ m = re.search(r'less than ([0-9]+) GB free', log)
+ return m.group(1) if m else None
+ if kind == NO_TITLE_ID: # "no NSP with a readable title ID in /path"
+ m = re.search(r'(?m)no NSP with a readable title ID in (.+)$', log)
+ return m.group(1).strip() if m else None
+ return None
+
+
+def classify(log: str, keys_readable: bool | None = None) -> Failure:
+ """UNKNOWN when no row matches: the caller then keeps showing the last line of the log.
+
+ keys_readable: what the window knows of the keys file (False = gone or unreadable). The script's own line for a missing
+ file is a row of the table, and nx_extract says nothing of its own about a file it cannot read."""
for _id, kind, pattern in TABLE:
if re.search(pattern, log):
m = _A32_NAME.search(log) if kind == A32_PROGRAM else None
name = m.group(1).strip() if m else None
- return Failure(kind, None if name in (None, '', '?') else name)
+ return Failure(kind, None if name in (None, '', '?') else name, _detail(kind, log))
+ if keys_readable is False:
+ return Failure(KEYS)
return Failure(UNKNOWN)
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index 1e251d41..ea04024a 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -709,6 +709,28 @@ TABLE: dict[str, tuple[str, str, str]] = {
'fail.confirm.go': ('仍然构建', 'Build anyway', 'Build anyway'),
'fail.confirm.cancel': ('取消', 'Cancel', 'Cancel'),
'fail.override.note': ('仍然构建:这一次构建加上 %@(已确认,不会保存)', 'Build anyway: this build adds %@ (confirmed, not saved)', 'Build anyway: this build adds %@ (confirmed, not saved)'),
+ 'fail.keys.what': ('找不到密钥文件,或者无法读取它。', "The keys file was not found or can't be read.", 'Nyckelfilen hittades inte eller går inte att läsa.'),
+ 'fail.keys.next': ('请重新选择你的 prod.keys。如果它在外接硬盘上,请先连接硬盘,然后再构建。', 'Choose your prod.keys again. If it is on an external drive, connect the drive first. Then build again.', 'Välj din prod.keys igen. Ligger den på en extern disk ansluter du disken först. Bygg sedan igen.'),
+ 'fail.keys.button': ('选择密钥文件', 'Choose keys file', 'Välj nyckelfil'),
+ 'fail.severalGames.what': ('这个文件夹里有不止一个游戏。', 'The folder holds more than one game.', 'Mappen innehåller fler än ett spel.'),
+ 'fail.severalGames.next': ('每次构建只能处理一个文件夹里的一个游戏。请把其他游戏移出这个文件夹,或把这个游戏的文件放进单独的文件夹,然后再构建。', "A build takes one game per folder. Move the other games out of the folder or put this game's files in a folder of their own, then build again.", 'Ett bygge tar ett spel per mapp. Flytta de andra spelen ur mappen eller lägg det här spelets filer i en egen mapp. Bygg sedan igen.'),
+ 'fail.noTitleID.what': ('文件夹里的安装包都读不出标题 ID:包里没有票据,文件名里也没有 [标题 ID]。', 'No package in the folder has a title ID the build can read: none has a ticket inside and none has [title ID] in its file name.', 'Inget paket i mappen har ett titel-ID som bygget kan läsa: inget har en biljett i paketet och inget har [titel-ID] i filnamnet.'),
+ 'fail.noTitleID.next': ('请把文件改名,加上它的标题 ID,例如 Game Name [0100XXXXXXXXXXXX].nsp,并使用这个安装包自己的 ID,因为本体、更新和 DLC 各有各的 ID。然后再构建。\\n也可能是文件夹里没有 .nsp、.xci、.nsz 或 .xcz 文件(分卷或压缩包,例如 .00、.rar,不会被读取),或者文件还在 iCloud 里没有下载。点「显示文件夹」可以查看。', 'Rename the file to include its title ID, like Game Name [0100XXXXXXXXXXXX].nsp, using the ID of that exact package, since the base game, an update and DLC each have their own. Then build again.\\nIt can also be that the folder has no .nsp, .xci, .nsz or .xcz files (split or archived parts such as .00 or .rar are not read), or that the files are still in iCloud and not downloaded. Choose Show folder to check.', 'Byt namn på filen så att den innehåller sitt titel-ID, till exempel Game Name [0100XXXXXXXXXXXX].nsp, med ID:t för just det paketet, eftersom basspelet, en uppdatering och DLC har varsitt. Bygg sedan igen.\\nDet kan också vara att mappen saknar .nsp-, .xci-, .nsz- eller .xcz-filer (delade eller arkiverade delar som .00 eller .rar läses inte), eller att filerna ligger kvar i iCloud och inte är nedladdade. Välj Visa mapp för att kontrollera.'),
+ 'fail.driveMissing.what': ('存放游戏文件的硬盘没有连接。', 'The drive with your game files is not connected.', 'Disken med dina spelfiler är inte ansluten.'),
+ 'fail.driveMissing.whatNamed': ('存放游戏文件的硬盘“%@”没有连接。', 'The drive “%@” with your game files is not connected.', 'Disken ”%@” med dina spelfiler är inte ansluten.'),
+ 'fail.driveMissing.next': ('请连接硬盘,等它出现在访达里,然后再构建。', 'Connect the drive and wait until it shows up in the Finder, then build again.', 'Anslut disken och vänta tills den syns i Finder. Bygg sedan igen.'),
+ 'fail.diskFull.what': ('构建时硬盘的可用空间用完了。', 'The drive ran out of free space for the build.', 'Disken fick slut på ledigt utrymme under bygget.'),
+ 'fail.diskFull.whatNeeds': ('可用空间不足,构建在这块硬盘上至少需要 %@ GB。', 'There is not enough free space. The build needs at least %@ GB on the drive.', 'Det finns för lite ledigt utrymme. Bygget behöver minst %@ GB på disken.'),
+ 'fail.diskFull.next': ('请释放存放构建文件夹的硬盘空间,也就是游戏文件旁边以 _build 结尾的那个文件夹。游戏菜单里的「释放空间」会清除已完成的构建不再需要的内容。然后再构建。', "Free up space on the drive that holds the build folder, the one ending in _build beside your game files. Free space in a game's menu removes what a finished build no longer needs. Then build again.", 'Frigör utrymme på disken som innehåller byggmappen, den som slutar på _build bredvid dina spelfiler. Frigör utrymme i ett spels meny tar bort det som ett färdigt bygge inte längre behöver. Bygg sedan igen.'),
+ 'fail.teamTaken.what': ('这个游戏的 App ID 已注册给另一个 Apple 团队。', "The game's app ID is registered to another Apple team.", 'Spelets app-ID är registrerat hos ett annat Apple-team.'),
+ 'fail.teamTaken.next': ('Xcode 对你的团队拒绝了它,用你的团队专属的 ID 变体也不行。请打开 Xcode > 设置 > 账户,登录以前安装这个游戏的那个 Apple ID,或者在这里选另一个签名团队,然后再构建。', "Xcode refused it for your team, also with your team's own variant of the ID. Open Xcode > Settings > Accounts and sign in with the Apple ID that installed this game before, or choose a different signing team here. Then build again.", 'Xcode nekade det för ditt team, även med teamets egen variant av ID:t. Öppna Xcode > Inställningar > Konton och logga in med det Apple-ID som installerade spelet tidigare, eller välj ett annat signeringsteam här. Bygg sedan igen.'),
+ 'fail.noSigningAccount.what': ('Xcode 里没有所选团队的签名账户。', 'Xcode has no signing account for the chosen team.', 'Xcode har inget signeringskonto för det valda teamet.'),
+ 'fail.noSigningAccount.next': ('请打开 Xcode > 设置 > 账户,登录你的 Apple ID,确认团队已列出,然后再构建。免费的 Apple ID 就够用,证书由 Xcode 自己创建。', 'Open Xcode > Settings > Accounts, sign in with your Apple ID and make sure the team is listed, then build again. A free Apple ID is enough and Xcode creates the certificate itself.', 'Öppna Xcode > Inställningar > Konton, logga in med ditt Apple-ID och kontrollera att teamet finns i listan. Bygg sedan igen. Ett gratis Apple-ID räcker och Xcode skapar certifikatet själv.'),
+ 'fail.deviceTransfer.what': ('把游戏发送到设备失败。', 'Sending the game to the device failed.', 'Det gick inte att skicka spelet till enheten.'),
+ 'fail.deviceTransfer.next': ('请解锁 iPhone 或 iPad,如果出现提示就点「信任」,检查数据线并确认设备保持连接,然后重试。', 'Unlock the iPhone or iPad and tap Trust if it asks, check the cable and that the device stays connected, then try again.', 'Lås upp iPhone eller iPad och tryck på Lita på om den frågar. Kontrollera kabeln och att enheten förblir ansluten. Försök sedan igen.'),
+ 'fail.showFolder': ('显示文件夹', 'Show folder', 'Visa mapp'),
+ 'fail.openXcode': ('打开 Xcode', 'Open Xcode', 'Öppna Xcode'),
+ 'fail.retry': ('重试', 'Try again', 'Försök igen'),
'dep.metal.other': ('%@(测试用的是 %@)', '%@ (tested: %@)', '%@ (tested: %@)'),
'dep.fix.metalPin': ('这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.'),
'msg.exitCode': ('退出码 %d', 'exit code %d', 'slutkod %d'),
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index a27838c0..16b05870 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -1138,7 +1138,7 @@ class Model(QObject):
# on its own sent a reporter looking for a log that was not on screen (#52)
last = getattr(self, '_last_error', '')
note = self.t('msg.buildFailedReason', last) if last else self.t('msg.buildFailed')
- known = bf.classify(self.log_tail)
+ known = bf.classify(self.log_tail, keys_readable=self._keys_readable())
if known.kind != bf.UNKNOWN: # a known early stop: the window explains it and offers the next step
self.failure = known
note = self.failure_what(known)
@@ -1151,8 +1151,34 @@ class Model(QObject):
"""The first sentence of a failure's hint (it names the game of a 32-bit program when the message does)."""
if f.kind == bf.A32_PROGRAM and f.game:
return self.t('fail.a32Program.whatNamed', f.game)
+ if f.kind == bf.DISK_FULL and f.detail:
+ return self.t('fail.diskFull.whatNeeds', f.detail)
return self.t(f.what_key)
+ def _keys_readable(self) -> bool | None:
+ """Whether the chosen keys file can be opened: None when none is chosen."""
+ if not self.keys_path:
+ return None
+ try:
+ with open(self.keys_path, 'rb'):
+ return True
+ except OSError:
+ return False
+
+ def failure_folder(self, f: 'bf.Failure') -> str:
+ """The folder "Show folder" opens: the one with the game files, else the one the message names. For a full disk the
+ build folder (`<title ID>_build`) when it is there, since that is where the space went."""
+ game_dir = str(Path(self.base_path).parent) if self.base_path else ''
+ folder = game_dir or (f.detail if f.kind == bf.NO_TITLE_ID else '') or ''
+ if f.kind == bf.DISK_FULL and game_dir:
+ try:
+ built = sorted(p.name for p in Path(game_dir).iterdir() if p.name.endswith('_build') and p.is_dir())
+ except OSError:
+ built = []
+ if built:
+ folder = str(Path(game_dir, built[0]))
+ return folder
+
def fix_failure(self, f: 'bf.Failure') -> None:
"""The failure card's fix buttons run the dependency rows' own fixes (install_dep, as Settings does)."""
if f.kind == bf.TRANSLATOR:
diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.py
index 6309c7ed..e2c3deeb 100644
--- a/frontend-qt/nspb_qt/ui.py
+++ b/frontend-qt/nspb_qt/ui.py
@@ -7,8 +7,8 @@ from __future__ import annotations
from pathlib import Path
-from PySide6.QtCore import Qt
-from PySide6.QtGui import QFontDatabase
+from PySide6.QtCore import Qt, QUrl
+from PySide6.QtGui import QDesktopServices, QFontDatabase
from PySide6.QtWidgets import (
QFileDialog, QFrame, QGridLayout, QHBoxLayout, QLabel, QMainWindow,
QProgressBar, QPushButton, QScrollArea, QSizePolicy, QTextEdit, QVBoxLayout, QWidget,
@@ -352,7 +352,9 @@ class MainWindow(QMainWindow):
self.failure_box.hide()
outer.addWidget(self.failure_box)
- _FIX_BUTTONS = {'translator': 'fail.translator.button', 'iosSDK': 'fail.iosSDK.button'}
+ _FIX_BUTTONS = {'translator': 'fail.translator.button', 'iosSDK': 'fail.iosSDK.button',
+ 'keys': 'fail.keys.button', 'severalGames': 'fail.showFolder', 'noTitleID': 'fail.showFolder',
+ 'diskFull': 'fail.showFolder'}
def _show_failure(self) -> None:
f = self.m.failure
@@ -370,8 +372,17 @@ class MainWindow(QMainWindow):
self.failure_box.show()
def _fix_failure(self) -> None:
- if self.m.failure is not None:
- self.m.fix_failure(self.m.failure)
+ f = self.m.failure
+ if f is None:
+ return
+ if f.kind == 'keys':
+ self._choose_input('keys') # the same picker as the keys row
+ elif f.kind in ('severalGames', 'noTitleID', 'diskFull'):
+ folder = self.m.failure_folder(f)
+ if folder:
+ QDesktopServices.openUrl(QUrl.fromLocalFile(folder))
+ else:
+ self.m.fix_failure(f)
def _build_anyway(self) -> None:
"""Asks first: the dialog states the risk. Nothing is armed until the player agrees."""
diff --git a/frontend-qt/tests/test_build_failure_hints.py b/frontend-qt/tests/test_build_failure_hints.py
index d20d91a1..8524114f 100644
--- a/frontend-qt/tests/test_build_failure_hints.py
+++ b/frontend-qt/tests/test_build_failure_hints.py
@@ -7,6 +7,8 @@ pattern, shared with the Swift tests. A sync of scripts/ or dm/ that rewords a m
"""
from __future__ import annotations
+import errno
+import importlib.util
import json
import os
import re
@@ -47,6 +49,9 @@ class Classifier(unittest.TestCase):
"""A sync that rewords a message must fail here, not turn a hint into the raw last line."""
for f in FIXTURES:
with self.subTest(pattern=f['id']):
+ if f['source'] == 'errno': # the system's own text, not the script's
+ self.assertEqual(os.strerror(errno.ENOSPC), f['fragment'])
+ continue
there = f['fragment'] in (ROOT / f['source']).read_text(encoding='utf-8')
if f.get('pending_sync'):
self.assertFalse(there, f"{f['id']} is in {f['source']} now: remove pending_sync ({f['pending_sync']}) from the fixture")
@@ -81,6 +86,55 @@ class Classifier(unittest.TestCase):
self.assertEqual(flags, bf.OVERRIDE_FLAGS)
+class Rows(unittest.TestCase):
+ """The rows of issue #141: what sets each one, and that the text names the action."""
+
+ def test_each_row_appears_for_its_log_line(self):
+ for pid, kind in (('keys.missing', bf.KEYS), ('games.several', bf.SEVERAL_GAMES), ('games.noTitleID', bf.NO_TITLE_ID),
+ ('disk.low', bf.DISK_FULL), ('disk.full', bf.DISK_FULL)):
+ self.assertEqual(bf.classify(fixture(pid)['text']).kind, kind, pid)
+ self.assertEqual(bf.classify('copying: no such file: x').kind, bf.UNKNOWN)
+
+ def test_details(self):
+ self.assertEqual(bf.classify(fixture('disk.low')['text']).detail, fixture('disk.low')['gb'])
+ self.assertIsNone(bf.classify(fixture('disk.full')['text']).detail)
+ log = 'skipping an empty file: a.nsp\n' + fixture('games.noTitleID')['text'] + '\n'
+ self.assertEqual(bf.classify(log).detail, fixture('games.noTitleID')['folder'])
+
+ def test_a_keys_file_that_cannot_be_read_is_known_from_the_file(self):
+ log = '[RED] nx_extract exit code 1 (full output: /w/extract.log)'
+ self.assertEqual(bf.classify(log, keys_readable=False).kind, bf.KEYS)
+ self.assertEqual(bf.classify(log, keys_readable=True).kind, bf.UNKNOWN)
+ self.assertEqual(bf.classify('[RED] the iOS SDK is not installed', keys_readable=False).kind, bf.IOS_SDK)
+
+ def test_the_text_names_the_action(self):
+ words = {bf.KEYS: ['Choose your prod.keys again'], bf.SEVERAL_GAMES: ['Move the other games'],
+ bf.NO_TITLE_ID: ['Rename the file', '0100XXXXXXXXXXXX', 'exact package', 'iCloud', 'Show folder'],
+ bf.DISK_FULL: ['Free up space', '_build']}
+ for kind, ws in words.items():
+ en = TABLE[f'fail.{kind}.next'][1]
+ for w in ws:
+ self.assertIn(w, en, kind)
+ for key in ('fail.showFolder', 'fail.keys.button', 'fail.diskFull.whatNeeds'):
+ self.assertIn(key, TABLE)
+ self.assertTrue(TABLE[key][2] and TABLE[key][2] != TABLE[key][1], key) # Swedish present
+
+ @unittest.skipIf(importlib.util.find_spec('PySide6') is None, 'PySide6 is not installed')
+ def test_show_folder_opens_the_game_folder_and_for_a_full_disk_the_build_folder(self):
+ import tempfile
+ from nspb_qt.model import Model
+ m = Model()
+ with tempfile.TemporaryDirectory() as d:
+ m.base_path = str(Path(d, 'game.nsp'))
+ self.assertEqual(m.failure_folder(bf.Failure(bf.NO_TITLE_ID, detail='/x')), d)
+ self.assertEqual(m.failure_folder(bf.Failure(bf.DISK_FULL)), d)
+ Path(d, '0100F2C0115B6000_build').mkdir()
+ self.assertEqual(m.failure_folder(bf.Failure(bf.DISK_FULL)), str(Path(d, '0100F2C0115B6000_build')))
+ m.base_path = ''
+ self.assertEqual(m.failure_folder(bf.Failure(bf.NO_TITLE_ID, detail='/x/y')), '/x/y')
+ self.assertIn('40 GB', m.failure_what(bf.Failure(bf.DISK_FULL, detail='40')))
+
+
class Override(unittest.TestCase):
BASE = ['-m', 'x', '/in', '-k', '/k', '--progress', 'lines']
diff --git a/frontend/Sources/NSPortBuilder/BuildFailure.swift b/frontend/Sources/NSPortBuilder/BuildFailure.swift
index 6291b522..7498b526 100644
--- a/frontend/Sources/NSPortBuilder/BuildFailure.swift
+++ b/frontend/Sources/NSPortBuilder/BuildFailure.swift
@@ -5,7 +5,12 @@ import Foundation
/// the log, cut to 200 characters. The classifier reads the whole log tail, because for a damaged NSP the
/// last line is only "nx_extract exit code 3" and the message is a few lines above it.
enum BuildFailureKind: String, CaseIterable {
- case rosetta, translator, iosSDK, cltSelected, otherMetal, shaderRegression, damagedNSP, a32Program, unknown
+ case rosetta, translator, iosSDK, cltSelected, otherMetal, shaderRegression, damagedNSP, a32Program
+ /// The inputs: the keys file, the game folder, a drive that is gone.
+ case keys, severalGames, noTitleID, driveMissing
+ /// The build's and the install's own steps.
+ case diskFull, teamTaken, noSigningAccount, deviceTransfer
+ case unknown
/// The script's override for this stop, offered as "Build anyway". Only these three have one that the launcher
/// may offer: the others cannot be built around (a 32-bit program, a missing SDK).
@@ -26,6 +31,9 @@ enum BuildFailureKind: String, CaseIterable {
struct BuildFailure: Equatable {
var kind: BuildFailureKind
var gameName: String? // a32Program: the game, when the message names it
+ /// What the message adds to its row: the GB a full disk needs (diskFull), the drive's name (driveMissing), the folder
+ /// of "no NSP with a readable title ID" (noTitleID).
+ var detail: String? = nil
}
enum BuildFailureClassifier {
@@ -44,16 +52,72 @@ enum BuildFailureClassifier {
("shaders.regression", .shaderRegression, "a change to the translation chain broke them"),
("nsp.damaged", .damagedNSP, "files fail the NCA's hash check"),
("arm32.program", .a32Program, "is a 32-bit ARM program"),
+ ("keys.missing", .keys, "(?m)^\\[RED\\] no such file: "),
+ ("games.several", .severalGames, "more than one game in the folder, keep one game per folder"),
+ ("games.noTitleID", .noTitleID, "no NSP with a readable title ID in "),
+ ("disk.low", .diskFull, "less than [0-9]+ GB free on the volume of "),
+ ("disk.full", .diskFull, "No space left on device"),
]
+ /// What the launcher itself knows when the log says nothing it can use. The keys file and the game files are checked
+ /// first: a drive that is not connected makes every later message ("not a folder", a dangling link) a consequence.
+ struct Inputs {
+ var keysPath = ""
+ var paths: [String] = [] // the picked game files and the game folder
+ var volumes = "/Volumes"
+ var isReadable: (String) -> Bool = { FileManager.default.isReadableFile(atPath: $0) }
+ }
+
/// `unknown` when no row matches: the caller then keeps showing the last line of the log.
- static func classify(_ log: String) -> BuildFailure {
+ static func classify(_ log: String, inputs: Inputs = Inputs()) -> BuildFailure {
+ for path in [inputs.keysPath] + inputs.paths where !path.isEmpty && GameLibrary.onUnmountedVolume(path, volumes: inputs.volumes) {
+ let prefix = inputs.volumes.hasSuffix("/") ? inputs.volumes : inputs.volumes + "/"
+ let name = path.dropFirst(prefix.count).split(separator: "/").first.map(String.init)
+ return BuildFailure(kind: .driveMissing, gameName: nil, detail: name)
+ }
for row in table where log.range(of: row.pattern, options: .regularExpression) != nil {
- return BuildFailure(kind: row.kind, gameName: row.kind == .a32Program ? gameName(in: log) : nil)
+ return BuildFailure(kind: row.kind, gameName: row.kind == .a32Program ? gameName(in: log) : nil, detail: detail(of: row.kind, in: log))
}
+ // The keys file is gone or cannot be read: nx_extract stops with an exit code and no line of its own for it.
+ if !inputs.keysPath.isEmpty, !inputs.isReadable(inputs.keysPath) { return BuildFailure(kind: .keys, gameName: nil) }
return BuildFailure(kind: .unknown, gameName: nil)
}
+ private static func detail(of kind: BuildFailureKind, in log: String) -> String? {
+ switch kind {
+ case .diskFull: // "less than 40 GB free on the volume of /Volumes/X/..."
+ guard let r = log.range(of: #"less than [0-9]+ GB free"#, options: .regularExpression) else { return nil }
+ return log[r].split(separator: " ").dropFirst(2).first.map(String.init)
+ case .noTitleID: // "no NSP with a readable title ID in /path"
+ guard let r = log.range(of: #"(?m)no NSP with a readable title ID in (.+)$"#, options: .regularExpression),
+ let at = log[r].range(of: " in ") else { return nil }
+ return String(log[r][at.upperBound...]).trimmingCharacters(in: .whitespaces)
+ default: return nil
+ }
+ }
+
+ /// A step of the install on a device that failed, with the tool's last error line. The sign step's own retry (the team's
+ /// variant of the bundle ID) has run already when this is called.
+ enum InstallStep { case sign, install, copy }
+
+ /// nil when the launcher has no better words than the tool's own line. `teamListed`: whether the chosen team is still one
+ /// the Mac knows (an account signed in to Xcode, or a development certificate in the keychain).
+ static func classifyInstall(_ step: InstallStep, error: String, teamListed: Bool) -> BuildFailure? {
+ if error.contains("No space left on device") { return BuildFailure(kind: .diskFull, gameName: nil) }
+ switch step {
+ case .sign:
+ if signingTeamTaken(error) { return BuildFailure(kind: .teamTaken, gameName: nil) }
+ return teamListed ? nil : BuildFailure(kind: .noSigningAccount, gameName: nil)
+ case .install, .copy:
+ return BuildFailure(kind: .deviceTransfer, gameName: nil)
+ }
+ }
+
+ /// xcodebuild's words when the app's identifier is registered to another team.
+ static func signingTeamTaken(_ error: String) -> Bool {
+ error.contains("cannot be registered to your development team") || error.contains("No profiles for 'org.nxnative.")
+ }
+
/// "<name> (<title ID>) is a 32-bit ARM program": the name is "?" when the extraction has none.
static func gameName(in log: String) -> String? {
guard let r = log.range(of: #"(?m)^(?:\[RED\] )?.+? \([0-9A-Fa-f]{16}\) is a 32-bit ARM program"#, options: .regularExpression) else { return nil }
diff --git a/frontend/Sources/NSPortBuilder/BuildFailureView.swift b/frontend/Sources/NSPortBuilder/BuildFailureView.swift
index 5830a513..fe97188f 100644
--- a/frontend/Sources/NSPortBuilder/BuildFailureView.swift
+++ b/frontend/Sources/NSPortBuilder/BuildFailureView.swift
@@ -41,6 +41,14 @@ struct BuildFailureCard: View {
fix(kind, "fail.iosSDK.button")
case .cltSelected:
if BuildModel.installedXcode() != nil { fix(kind, "fail.cltSelected.button") }
+ case .keys:
+ fix(kind, "fail.keys.button")
+ case .severalGames, .noTitleID, .diskFull:
+ fix(kind, "fail.showFolder")
+ case .teamTaken, .noSigningAccount:
+ if BuildModel.installedXcode() != nil { fix(kind, "fail.openXcode") }
+ case .deviceTransfer:
+ fix(kind, "fail.retry")
default: EmptyView()
}
if kind.overrideFlag != nil {
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 44445a9a..2a450bd7 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -164,6 +164,11 @@ final class BuildModel: ObservableObject {
}
private var bundleID = "" // from the script's "bundle ID:" line
var xcrunPath = "/usr/bin/xcrun" // tests stand in for xcodebuild and devicectl
+ var volumesRoot = "/Volumes" // where external drives are mounted
+ var teamsProvider: () -> [SigningTeam] = { DeviceTools.teams() } // the teams the Mac knows, read when a signing step fails
+ var chooseKeys: (() -> Void)? // tests stand in for the file picker
+ var revealFolder: (URL) -> Void = { NSWorkspace.shared.open($0) }
+ var openApp: (URL) -> Void = { NSWorkspace.shared.openApplication(at: $0, configuration: NSWorkspace.OpenConfiguration()) }
/// This iPhone build goes straight to a device.
var installsDirectly: Bool { target != "mac-app" && !installDevice.isEmpty && !signingTeam.isEmpty }
@@ -1258,15 +1263,32 @@ final class BuildModel: ObservableObject {
/// A failed build's log read for the script's known early stops: the card under the build button then says what
/// happened and what to do. An unknown stop leaves the note (the last line of the log) as it is.
func noteFailure() {
- let f = BuildFailureClassifier.classify(logTail)
+ let f = BuildFailureClassifier.classify(logTail, inputs: failureInputs())
guard f.kind != .unknown else { failure = nil; return }
failure = f
doneNote = failureWhat(f)
}
+ /// What the classifier may check besides the log: the keys file and where the game files are.
+ func failureInputs() -> BuildFailureClassifier.Inputs {
+ BuildFailureClassifier.Inputs(keysPath: keysPath, paths: ([basePath, updatePath, gameDir] + dlcPaths).filter { !$0.isEmpty },
+ volumes: volumesRoot)
+ }
+
+ /// A failed step of an install on a device, as a card when the launcher can say more than the tool's line.
+ /// Called after `finishInstall`, which put the tool's own error into the note.
+ func noteInstallFailure(_ step: BuildFailureClassifier.InstallStep, error: String) {
+ let listed = teamsProvider().contains { $0.id == signingTeam }
+ guard let f = BuildFailureClassifier.classifyInstall(step, error: error, teamListed: listed) else { failure = nil; return }
+ failure = f
+ doneNote = failureWhat(f)
+ }
+
/// The first sentence of a failure's hint (it names the game of a 32-bit program when the message does).
func failureWhat(_ f: BuildFailure) -> String {
if f.kind == .a32Program, let name = f.gameName { return String(format: t("fail.a32Program.whatNamed"), name) }
+ if f.kind == .driveMissing, let name = f.detail { return String(format: t("fail.driveMissing.whatNamed"), name) }
+ if f.kind == .diskFull, let gb = f.detail { return String(format: t("fail.diskFull.whatNeeds"), gb) }
return t(f.kind.whatKey)
}
@@ -1302,13 +1324,41 @@ final class BuildModel: ObservableObject {
if let xcode = Self.installedXcode() {
installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Self.selectXcodeCmd(xcode)))
}
+ case .keys:
+ if let chooseKeys { chooseKeys() } else { pickFiles(kind: .keys) } // the same picker as the keys row
+ case .severalGames, .noTitleID, .diskFull:
+ showFailureFolder()
+ case .teamTaken, .noSigningAccount:
+ openXcode()
+ case .deviceTransfer:
+ startBuild()
default: break
}
}
+ /// The folder the failure is about, in the Finder: the folder of the game files, else the one the message names. For a full
+ /// disk the build folder (`<title ID>_build`, beside the game files) when it is there, since that is where the space went.
+ func showFailureFolder() {
+ guard let f = failure else { return }
+ var folder = gameDir.isEmpty ? (f.detail ?? "") : gameDir
+ if f.kind == .diskFull, !gameDir.isEmpty {
+ let built = ((try? FileManager.default.contentsOfDirectory(atPath: gameDir)) ?? []).sorted().first { $0.hasSuffix("_build") }
+ if let built { folder = gameDir + "/" + built }
+ }
+ guard !folder.isEmpty else { return }
+ revealFolder(URL(fileURLWithPath: folder))
+ }
+
+ /// Xcode itself: its Settings > Accounts is where a team is signed in, and Xcode has no address that opens that pane.
+ func openXcode() {
+ guard let app = Self.installedXcode() else { return }
+ openApp(URL(fileURLWithPath: app))
+ }
+
/// Whether the card's fix button is already running its command.
func fixBusy(_ kind: BuildFailureKind) -> Bool {
- deps.first { $0.id == (kind == .translator ? "dotnet" : "xcode") }?.installing ?? false
+ guard [.translator, .iosSDK, .cltSelected].contains(kind) else { return false }
+ return deps.first { $0.id == (kind == .translator ? "dotnet" : "xcode") }?.installing ?? false
}
/// (file count, bytes) of a RomFS tree — the reuse fingerprint's content part.
@@ -1743,7 +1793,10 @@ final class BuildModel: ObservableObject {
guard FileManager.default.fileExists(atPath: app) else { return finishInstall(String(format: t("dev.noProject"), shortPath(app))) }
runTool(id: 1002, name: String(format: t("dev.installStage"), name),
[xcrun, "devicectl", "device", "install", "app", "--device", device, app], step: Self.installStep) { error in
- if let error { return self.finishInstall(String(format: self.t("dev.installFailed"), error)) }
+ if let error {
+ self.finishInstall(String(format: self.t("dev.installFailed"), error))
+ return self.noteInstallFailure(.install, error: error)
+ }
guard let bundle = NSDictionary(contentsOfFile: app + "/Info.plist")?["CFBundleIdentifier"] as? String else {
return self.finishInstall(String(format: self.t("dev.noProject"), self.shortPath(app + "/Info.plist")))
}
@@ -1754,7 +1807,10 @@ final class BuildModel: ObservableObject {
let copy = {
self.runTool(id: 1003, name: String(format: self.t("dev.copyStage"), name),
Self.archiveCopy(xcrun: xcrun, device: device, bundle: bundle, archive: archive, titleID: tid), step: Self.installStep) { error in
- if let error { return self.finishInstall(String(format: self.t("dev.copyFailed"), error)) }
+ if let error {
+ self.finishInstall(String(format: self.t("dev.copyFailed"), error))
+ return self.noteInstallFailure(.copy, error: error)
+ }
self.installedOn = device
self.installedAppPath = app
self.finishInstall(nil)
@@ -1795,10 +1851,7 @@ final class BuildModel: ObservableObject {
}
let appID = "org.nxnative." + (Self.titleID(self.basePath).map { String(format: "%016llX", $0) } ?? "game").lowercased()
let teamVariant = "org.nxnative." + appID.split(separator: ".").last!.appending(".\(team)")
- func taken(_ e: String?) -> Bool {
- guard let e else { return false }
- return e.contains("cannot be registered to your development team") || e.contains("No profiles for 'org.nxnative.")
- }
+ func taken(_ e: String?) -> Bool { e.map(BuildFailureClassifier.signingTeamTaken) ?? false }
self.runTool(id: 1001, name: String(format: self.t("dev.signStage"), name), sign(), step: Self.xcodeStep) { firstError in
if let firstError, taken(firstError) {
// Once more under this team's own identifier, and the log says why the first try failed.
@@ -1806,6 +1859,7 @@ final class BuildModel: ObservableObject {
self.runTool(id: 1001, name: String(format: self.t("dev.signStage"), name), sign(["PRODUCT_BUNDLE_IDENTIFIER=" + teamVariant]), step: Self.xcodeStep) { retryError in
if let retryError, !retryError.isEmpty {
self.finishInstall(String(format: self.t("dev.signFailed"), retryError))
+ self.noteInstallFailure(.sign, error: retryError)
} else {
self.installBuiltApp(app: derived + "/Build/Products/Release-iphoneos/DmIOS.app", archive: archive, device: device, xcrun: xcrun)
}
@@ -1814,6 +1868,7 @@ final class BuildModel: ObservableObject {
}
if let firstError, !firstError.isEmpty {
self.finishInstall(String(format: self.t("dev.signFailed"), firstError))
+ self.noteInstallFailure(.sign, error: firstError)
} else {
self.installBuiltApp(app: derived + "/Build/Products/Release-iphoneos/DmIOS.app", archive: archive, device: device, xcrun: xcrun)
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 36f8dbf2..f5acba13 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -862,6 +862,28 @@ enum L10n {
"Cancel"),
"fail.override.note": ("仍然构建:这一次构建加上 %@(已确认,不会保存)",
"Build anyway: this build adds %@ (confirmed, not saved)"),
+ "fail.keys.what": ("找不到密钥文件,或者无法读取它。", "The keys file was not found or can't be read."),
+ "fail.keys.next": ("请重新选择你的 prod.keys。如果它在外接硬盘上,请先连接硬盘,然后再构建。", "Choose your prod.keys again. If it is on an external drive, connect the drive first. Then build again."),
+ "fail.keys.button": ("选择密钥文件", "Choose keys file"),
+ "fail.severalGames.what": ("这个文件夹里有不止一个游戏。", "The folder holds more than one game."),
+ "fail.severalGames.next": ("每次构建只能处理一个文件夹里的一个游戏。请把其他游戏移出这个文件夹,或把这个游戏的文件放进单独的文件夹,然后再构建。", "A build takes one game per folder. Move the other games out of the folder or put this game's files in a folder of their own, then build again."),
+ "fail.noTitleID.what": ("文件夹里的安装包都读不出标题 ID:包里没有票据,文件名里也没有 [标题 ID]。", "No package in the folder has a title ID the build can read: none has a ticket inside and none has [title ID] in its file name."),
+ "fail.noTitleID.next": ("请把文件改名,加上它的标题 ID,例如 Game Name [0100XXXXXXXXXXXX].nsp,并使用这个安装包自己的 ID,因为本体、更新和 DLC 各有各的 ID。然后再构建。\n也可能是文件夹里没有 .nsp、.xci、.nsz 或 .xcz 文件(分卷或压缩包,例如 .00、.rar,不会被读取),或者文件还在 iCloud 里没有下载。点「显示文件夹」可以查看。", "Rename the file to include its title ID, like Game Name [0100XXXXXXXXXXXX].nsp, using the ID of that exact package, since the base game, an update and DLC each have their own. Then build again.\nIt can also be that the folder has no .nsp, .xci, .nsz or .xcz files (split or archived parts such as .00 or .rar are not read), or that the files are still in iCloud and not downloaded. Choose Show folder to check."),
+ "fail.driveMissing.what": ("存放游戏文件的硬盘没有连接。", "The drive with your game files is not connected."),
+ "fail.driveMissing.whatNamed": ("存放游戏文件的硬盘“%@”没有连接。", "The drive “%@” with your game files is not connected."),
+ "fail.driveMissing.next": ("请连接硬盘,等它出现在访达里,然后再构建。", "Connect the drive and wait until it shows up in the Finder, then build again."),
+ "fail.diskFull.what": ("构建时硬盘的可用空间用完了。", "The drive ran out of free space for the build."),
+ "fail.diskFull.whatNeeds": ("可用空间不足,构建在这块硬盘上至少需要 %@ GB。", "There is not enough free space. The build needs at least %@ GB on the drive."),
+ "fail.diskFull.next": ("请释放存放构建文件夹的硬盘空间,也就是游戏文件旁边以 _build 结尾的那个文件夹。游戏菜单里的「释放空间」会清除已完成的构建不再需要的内容。然后再构建。", "Free up space on the drive that holds the build folder, the one ending in _build beside your game files. Free space in a game's menu removes what a finished build no longer needs. Then build again."),
+ "fail.teamTaken.what": ("这个游戏的 App ID 已注册给另一个 Apple 团队。", "The game's app ID is registered to another Apple team."),
+ "fail.teamTaken.next": ("Xcode 对你的团队拒绝了它,用你的团队专属的 ID 变体也不行。请打开 Xcode > 设置 > 账户,登录以前安装这个游戏的那个 Apple ID,或者在这里选另一个签名团队,然后再构建。", "Xcode refused it for your team, also with your team's own variant of the ID. Open Xcode > Settings > Accounts and sign in with the Apple ID that installed this game before, or choose a different signing team here. Then build again."),
+ "fail.noSigningAccount.what": ("Xcode 里没有所选团队的签名账户。", "Xcode has no signing account for the chosen team."),
+ "fail.noSigningAccount.next": ("请打开 Xcode > 设置 > 账户,登录你的 Apple ID,确认团队已列出,然后再构建。免费的 Apple ID 就够用,证书由 Xcode 自己创建。", "Open Xcode > Settings > Accounts, sign in with your Apple ID and make sure the team is listed, then build again. A free Apple ID is enough and Xcode creates the certificate itself."),
+ "fail.deviceTransfer.what": ("把游戏发送到设备失败。", "Sending the game to the device failed."),
+ "fail.deviceTransfer.next": ("请解锁 iPhone 或 iPad,如果出现提示就点「信任」,检查数据线并确认设备保持连接,然后重试。", "Unlock the iPhone or iPad and tap Trust if it asks, check the cable and that the device stays connected, then try again."),
+ "fail.showFolder": ("显示文件夹", "Show folder"),
+ "fail.openXcode": ("打开 Xcode", "Open Xcode"),
+ "fail.retry": ("重试", "Try again"),
"dep.metal.other": ("%@(测试用的是 %@)",
"%@ (tested: %@)"),
"dep.fix.metalPin": ("这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。",
@@ -1582,6 +1604,28 @@ enum L10n {
"section.tools": "Byggverktyg",
"section.app": "App",
"build.setup": "Slutför inställningen",
+ "fail.keys.what": "Nyckelfilen hittades inte eller går inte att läsa.",
+ "fail.keys.next": "Välj din prod.keys igen. Ligger den på en extern disk ansluter du disken först. Bygg sedan igen.",
+ "fail.keys.button": "Välj nyckelfil",
+ "fail.severalGames.what": "Mappen innehåller fler än ett spel.",
+ "fail.severalGames.next": "Ett bygge tar ett spel per mapp. Flytta de andra spelen ur mappen eller lägg det här spelets filer i en egen mapp. Bygg sedan igen.",
+ "fail.noTitleID.what": "Inget paket i mappen har ett titel-ID som bygget kan läsa: inget har en biljett i paketet och inget har [titel-ID] i filnamnet.",
+ "fail.noTitleID.next": "Byt namn på filen så att den innehåller sitt titel-ID, till exempel Game Name [0100XXXXXXXXXXXX].nsp, med ID:t för just det paketet, eftersom basspelet, en uppdatering och DLC har varsitt. Bygg sedan igen.\nDet kan också vara att mappen saknar .nsp-, .xci-, .nsz- eller .xcz-filer (delade eller arkiverade delar som .00 eller .rar läses inte), eller att filerna ligger kvar i iCloud och inte är nedladdade. Välj Visa mapp för att kontrollera.",
+ "fail.driveMissing.what": "Disken med dina spelfiler är inte ansluten.",
+ "fail.driveMissing.whatNamed": "Disken ”%@” med dina spelfiler är inte ansluten.",
+ "fail.driveMissing.next": "Anslut disken och vänta tills den syns i Finder. Bygg sedan igen.",
+ "fail.diskFull.what": "Disken fick slut på ledigt utrymme under bygget.",
+ "fail.diskFull.whatNeeds": "Det finns för lite ledigt utrymme. Bygget behöver minst %@ GB på disken.",
+ "fail.diskFull.next": "Frigör utrymme på disken som innehåller byggmappen, den som slutar på _build bredvid dina spelfiler. Frigör utrymme i ett spels meny tar bort det som ett färdigt bygge inte längre behöver. Bygg sedan igen.",
+ "fail.teamTaken.what": "Spelets app-ID är registrerat hos ett annat Apple-team.",
+ "fail.teamTaken.next": "Xcode nekade det för ditt team, även med teamets egen variant av ID:t. Öppna Xcode > Inställningar > Konton och logga in med det Apple-ID som installerade spelet tidigare, eller välj ett annat signeringsteam här. Bygg sedan igen.",
+ "fail.noSigningAccount.what": "Xcode har inget signeringskonto för det valda teamet.",
+ "fail.noSigningAccount.next": "Öppna Xcode > Inställningar > Konton, logga in med ditt Apple-ID och kontrollera att teamet finns i listan. Bygg sedan igen. Ett gratis Apple-ID räcker och Xcode skapar certifikatet själv.",
+ "fail.deviceTransfer.what": "Det gick inte att skicka spelet till enheten.",
+ "fail.deviceTransfer.next": "Lås upp iPhone eller iPad och tryck på Lita på om den frågar. Kontrollera kabeln och att enheten förblir ansluten. Försök sedan igen.",
+ "fail.showFolder": "Visa mapp",
+ "fail.openXcode": "Öppna Xcode",
+ "fail.retry": "Försök igen",
]
static func string(_ key: String, _ lang: Lang) -> String {
diff --git a/frontend/Tests/Fixtures/build_failures.json b/frontend/Tests/Fixtures/build_failures.json
index c0966742..7ff1a6ca 100644
--- a/frontend/Tests/Fixtures/build_failures.json
+++ b/frontend/Tests/Fixtures/build_failures.json
@@ -62,5 +62,42 @@
"fragment": "is a 32-bit ARM program",
"game": "Some Game",
"text": "[RED] Some Game (0100ABCD00000000) is a 32-bit ARM program (main.npdm: the 64-bit instruction flag is clear): Apple silicon cannot run 32-bit ARM code, and this repository runs a game's own AArch64 code, so it cannot be ported"
+ },
+ {
+ "id": "keys.missing",
+ "kind": "keys",
+ "source": "scripts/build_ipa_from_nsp.py",
+ "fragment": "no such file: {keys}",
+ "text": "[RED] no such file: /Volumes/Keys/prod.keys"
+ },
+ {
+ "id": "games.several",
+ "kind": "severalGames",
+ "source": "scripts/build_ipa_from_nsp.py",
+ "fragment": "more than one game in the folder, keep one game per folder",
+ "text": "[RED] more than one game in the folder, keep one game per folder: 0100000000010000, 01006F8002326000"
+ },
+ {
+ "id": "games.noTitleID",
+ "kind": "noTitleID",
+ "source": "scripts/build_ipa_from_nsp.py",
+ "fragment": "no NSP with a readable title ID in",
+ "text": "[RED] no NSP with a readable title ID in /Users/x/Games/Zelda",
+ "folder": "/Users/x/Games/Zelda"
+ },
+ {
+ "id": "disk.low",
+ "kind": "diskFull",
+ "source": "scripts/build_ipa_from_nsp.py",
+ "fragment": "GB free on the volume of {work}",
+ "text": "[RED] less than 40 GB free on the volume of /Volumes/NX/Zelda/0100F2C0115B6000_build",
+ "gb": "40"
+ },
+ {
+ "id": "disk.full",
+ "kind": "diskFull",
+ "source": "errno",
+ "fragment": "No space left on device",
+ "text": "[RED] OSError: [Errno 28] No space left on device"
}
-]
\ No newline at end of file
+]
diff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift
new file mode 100644
index 00000000..bec2c714
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift
@@ -0,0 +1,203 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// The failure rows for keys, game files and the build's own steps (issue #141): what sets each one, that its text names the
+/// action, and that its button does it. The log lines are the script's real messages (Tests/Fixtures/build_failures.json).
+final class BuildFailureRowsTests: XCTestCase {
+ func fixture(_ id: String) throws -> BuildFailureTests.Fixture {
+ try XCTUnwrap(BuildFailureTests().fixtures().first { $0.id == id }, id)
+ }
+
+ func tempFolder() throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("nspb-rows-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ addTeardownBlock { try? FileManager.default.removeItem(at: url) }
+ return url
+ }
+
+ // ---- what sets each row
+
+ func testTheKeysFileMissingFromTheScriptsMessage() throws {
+ let f = BuildFailureClassifier.classify(try fixture("keys.missing").text)
+ XCTAssertEqual(f.kind, .keys)
+ // only the script's own line: the words inside another line are not it
+ XCTAssertEqual(BuildFailureClassifier.classify("copying: no such file: x").kind, .unknown)
+ }
+
+ func testTheKeysFileThatCannotBeReadIsKnownFromTheFileNotFromTheLog() throws {
+ let dir = try tempFolder(), keys = dir.appendingPathComponent("prod.keys")
+ try Data("header_key = 00".utf8).write(to: keys)
+ let log = "[RED] nx_extract exit code 1 (full output: /w/extract.log)"
+ var inputs = BuildFailureClassifier.Inputs(keysPath: keys.path, paths: [], volumes: dir.path)
+ XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: inputs).kind, .unknown, "a readable file is not the cause")
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: keys.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: keys.path) }
+ if getuid() != 0 { XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: inputs).kind, .keys) }
+ inputs.isReadable = { _ in false }
+ XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: inputs).kind, .keys)
+ XCTAssertEqual(BuildFailureClassifier.classify("[RED] the iOS SDK is not installed", inputs: inputs).kind, .iosSDK, "a known stop keeps its own row")
+ }
+
+ func testSeveralGamesAndNoTitleID() throws {
+ XCTAssertEqual(BuildFailureClassifier.classify(try fixture("games.several").text).kind, .severalGames)
+ let none = try fixture("games.noTitleID")
+ // after the key check passed, with the script's skip notes above the stop (#177)
+ let log = "skipping an empty file: a.nsp\nskipping b.nsp: neither an NSP (PFS0) nor an XCI (HEAD at 0x100)\n" + none.text + "\n"
+ let f = BuildFailureClassifier.classify(log)
+ XCTAssertEqual(f.kind, .noTitleID)
+ XCTAssertEqual(f.detail, none.folder)
+ }
+
+ func testAFullDiskNamesTheSizeWhenTheScriptDoes() throws {
+ let low = BuildFailureClassifier.classify(try fixture("disk.low").text)
+ XCTAssertEqual(low, BuildFailure(kind: .diskFull, gameName: nil, detail: try fixture("disk.low").gb))
+ XCTAssertEqual(BuildFailureClassifier.classify(try fixture("disk.full").text), BuildFailure(kind: .diskFull, gameName: nil, detail: nil))
+ let m = BuildModel()
+ XCTAssertTrue(m.failureWhat(low).contains("40 GB"), m.failureWhat(low))
+ XCTAssertFalse(m.failureWhat(BuildFailure(kind: .diskFull, gameName: nil)).contains("GB"))
+ }
+
+ func testADriveThatIsNotConnectedComesBeforeTheMessagesItCauses() throws {
+ let volumes = try tempFolder()
+ let gone = volumes.path + "/Games/Zelda/zelda.nsp"
+ let log = try fixture("games.noTitleID").text
+ let f = BuildFailureClassifier.classify(log, inputs: .init(keysPath: "", paths: [gone], volumes: volumes.path))
+ XCTAssertEqual(f, BuildFailure(kind: .driveMissing, gameName: nil, detail: "Games"))
+ try FileManager.default.createDirectory(at: volumes.appendingPathComponent("Games"), withIntermediateDirectories: true)
+ XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "", paths: [gone], volumes: volumes.path)).kind, .noTitleID, "the drive is there")
+ XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "/Users/x/prod.keys", paths: ["/Users/x/g.nsp"], volumes: volumes.path)).kind, .noTitleID, "a path off /Volumes is no drive")
+ XCTAssertTrue(BuildModel().failureWhat(f).contains("“Games”"))
+ }
+
+ func testTheInstallStepsThatFailedBecomeRows() {
+ let taken = "error: Failed to register bundle identifier. The app identifier \"org.nxnative.x\" cannot be registered to your development team."
+ XCTAssertEqual(BuildFailureClassifier.classifyInstall(.sign, error: taken, teamListed: true)?.kind, .teamTaken)
+ XCTAssertEqual(BuildFailureClassifier.classifyInstall(.sign, error: "error: No profiles for 'org.nxnative.x' were found", teamListed: true)?.kind, .teamTaken)
+ XCTAssertEqual(BuildFailureClassifier.classifyInstall(.sign, error: "error: something", teamListed: false)?.kind, .noSigningAccount)
+ XCTAssertNil(BuildFailureClassifier.classifyInstall(.sign, error: "error: something", teamListed: true), "the tool's line stays")
+ for step in [BuildFailureClassifier.InstallStep.install, .copy] {
+ XCTAssertEqual(BuildFailureClassifier.classifyInstall(step, error: "ERROR: The device is not connected. (com.apple.dt.CoreDeviceError error 4)", teamListed: true)?.kind, .deviceTransfer)
+ }
+ XCTAssertEqual(BuildFailureClassifier.classifyInstall(.copy, error: "No space left on device", teamListed: true)?.kind, .diskFull)
+ }
+
+ // ---- the text names the action
+
+ func testEveryRowSaysWhatToDoNext() {
+ let next: [(BuildFailureKind, [String])] = [
+ (.keys, ["Choose your prod.keys again", "build again"]),
+ (.severalGames, ["Move the other games", "folder of their own"]),
+ (.noTitleID, ["Rename the file", "0100XXXXXXXXXXXX", "exact package", ".nsp, .xci, .nsz or .xcz", ".00 or .rar", "iCloud", "Show folder"]),
+ (.driveMissing, ["Connect the drive"]),
+ (.diskFull, ["Free up space", "_build"]),
+ (.teamTaken, ["Xcode > Settings > Accounts"]),
+ (.noSigningAccount, ["Xcode > Settings > Accounts"]),
+ (.deviceTransfer, ["Unlock", "Trust", "cable", "try again"]),
+ ]
+ for (kind, words) in next {
+ let en = L10n.table[kind.nextKey]?.en ?? ""
+ for w in words { XCTAssertTrue(en.contains(w), "\(kind): \"\(w)\" is not in \"\(en)\"") }
+ }
+ }
+
+ func testTheNewRowsAreInAllThreeLanguagesWithoutSemicolonsOrTheProductName() {
+ var keys = ["fail.showFolder", "fail.openXcode", "fail.retry", "fail.keys.button", "fail.driveMissing.whatNamed", "fail.diskFull.whatNeeds"]
+ let kinds = BuildFailureTests.stateKinds.union([.keys, .severalGames, .noTitleID, .diskFull])
+ for k in BuildFailureKind.allCases where kinds.contains(k) { keys += [k.whatKey, k.nextKey] }
+ for key in keys {
+ let row = L10n.table[key]
+ XCTAssertNotNil(row, key)
+ let sv = L10n.sv[key]
+ XCTAssertNotNil(sv, "\(key) has no Swedish text")
+ XCTAssertNotEqual(sv, row?.en, "\(key) has the English text in the Swedish column")
+ for text in [row?.zh ?? "", row?.en ?? "", sv ?? ""] {
+ XCTAssertFalse(text.isEmpty, key)
+ XCTAssertFalse(text.contains(";") || text.contains("\u{FF1B}"), "\(key) has a semicolon")
+ XCTAssertFalse(text.localizedCaseInsensitiveContains("NX2Apple"), key)
+ }
+ XCTAssertNotEqual(row?.zh, row?.en, key)
+ XCTAssertTrue(row?.zh.unicodeScalars.contains { $0.value >= 0x4E00 } ?? false, "\(key) has no Chinese")
+ }
+ }
+
+ // ---- the card and its buttons
+
+ func testAFailedBuildShowsTheRowForItsLogLine() throws {
+ for (id, kind) in [("keys.missing", BuildFailureKind.keys), ("games.several", .severalGames), ("games.noTitleID", .noTitleID), ("disk.low", .diskFull), ("disk.full", .diskFull)] {
+ let m = BuildModel()
+ m.logTail = try fixture(id).text + "\n"
+ m.noteFailure()
+ XCTAssertEqual(m.failure?.kind, kind, id)
+ XCTAssertEqual(m.doneNote, m.failureWhat(m.failure!), id)
+ }
+ }
+
+ func testTheKeysButtonOpensTheKeysPicker() {
+ let m = BuildModel()
+ var opened = 0
+ m.chooseKeys = { opened += 1 }
+ m.failure = BuildFailure(kind: .keys, gameName: nil)
+ m.fixBuildFailure(.keys)
+ XCTAssertEqual(opened, 1)
+ }
+
+ func testShowFolderRevealsTheGameFolderAndForAFullDiskTheBuildFolder() throws {
+ let dir = try tempFolder()
+ let m = BuildModel()
+ var shown: [String] = []
+ m.revealFolder = { shown.append($0.path) }
+ m.gameDir = dir.path
+ m.failure = BuildFailure(kind: .noTitleID, gameName: nil, detail: "/elsewhere")
+ m.fixBuildFailure(.noTitleID)
+ m.failure = BuildFailure(kind: .severalGames, gameName: nil)
+ m.fixBuildFailure(.severalGames)
+ XCTAssertEqual(shown, [dir.path, dir.path])
+ shown = []
+ m.failure = BuildFailure(kind: .diskFull, gameName: nil)
+ m.fixBuildFailure(.diskFull)
+ XCTAssertEqual(shown, [dir.path], "no build folder yet")
+ try FileManager.default.createDirectory(at: dir.appendingPathComponent("0100F2C0115B6000_build"), withIntermediateDirectories: true)
+ shown = []
+ m.fixBuildFailure(.diskFull)
+ XCTAssertEqual(shown, [dir.path + "/0100F2C0115B6000_build"])
+ shown = []
+ m.gameDir = ""
+ m.failure = BuildFailure(kind: .noTitleID, gameName: nil, detail: "/Users/x/Games/Zelda")
+ m.fixBuildFailure(.noTitleID)
+ XCTAssertEqual(shown, ["/Users/x/Games/Zelda"], "the folder the message names")
+ }
+
+ func testAnInstallStepThatFailedShowsItsRow() {
+ let m = BuildModel()
+ m.signingTeam = "TEAM123456"
+ m.teamsProvider = { [SigningTeam(id: "TEAM123456", identity: "")] }
+ m.noteInstallFailure(.sign, error: "error: Failed to register bundle identifier: cannot be registered to your development team")
+ XCTAssertEqual(m.failure?.kind, .teamTaken)
+ XCTAssertEqual(m.doneNote, m.t("fail.teamTaken.what"))
+ m.teamsProvider = { [] }
+ m.noteInstallFailure(.sign, error: "error: x")
+ XCTAssertEqual(m.failure?.kind, .noSigningAccount)
+ m.noteInstallFailure(.install, error: "ERROR: The device is not connected.")
+ XCTAssertEqual(m.failure?.kind, .deviceTransfer)
+ m.teamsProvider = { [SigningTeam(id: "TEAM123456", identity: "")] }
+ m.failure = BuildFailure(kind: .teamTaken, gameName: nil)
+ m.noteInstallFailure(.sign, error: "error: x")
+ XCTAssertNil(m.failure, "an unknown signing error leaves the tool's line")
+ }
+
+ func testTryAgainStartsANewBuildAndClearsTheCard() {
+ let m = BuildModel()
+ m.failure = BuildFailure(kind: .deviceTransfer, gameName: nil)
+ m.fixBuildFailure(.deviceTransfer) // no repository here: the build stops at once, but it has started and dropped the old card
+ XCTAssertNil(m.failure)
+ }
+
+ func testTheXcodeButtonOpensXcodeWhenItIsInstalled() {
+ let m = BuildModel()
+ var opened: [URL] = []
+ m.openApp = { opened.append($0) }
+ m.failure = BuildFailure(kind: .teamTaken, gameName: nil)
+ m.fixBuildFailure(.teamTaken)
+ if let xcode = BuildModel.installedXcode() { XCTAssertEqual(opened, [URL(fileURLWithPath: xcode)]) } else { XCTAssertTrue(opened.isEmpty) }
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
index 1a696c74..f0f33c18 100644
--- a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift
@@ -7,7 +7,7 @@ import XCTest
final class BuildFailureTests: XCTestCase {
struct Fixture: Decodable {
let id: String, kind: String, source: String, fragment: String, text: String
- let game: String?
+ let game: String?, folder: String?, gb: String?
}
static let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
@@ -31,12 +31,19 @@ final class BuildFailureTests: XCTestCase {
func testEveryKindIsReachable() {
let kinds = Set(BuildFailureClassifier.table.map(\.kind))
- for k in BuildFailureKind.allCases where k != .unknown { XCTAssertTrue(kinds.contains(k), "\(k)") }
+ for k in BuildFailureKind.allCases where k != .unknown && !Self.stateKinds.contains(k) { XCTAssertTrue(kinds.contains(k), "\(k)") }
}
+ /// The rows that no log line sets: the launcher's own state (a drive, a team) or the step that failed (the install).
+ static let stateKinds: Set<BuildFailureKind> = [.driveMissing, .teamTaken, .noSigningAccount, .deviceTransfer]
+
/// A sync of scripts/ or dm/ that rewords a message must fail here, not turn a hint into the raw last line.
func testTheVendoredScriptsStillSayWhatThePatternsExpect() throws {
for f in try fixtures() {
+ if f.source == "errno" { // the system's own text, not the script's
+ XCTAssertEqual(String(cString: strerror(ENOSPC)), f.fragment, f.id)
+ continue
+ }
let source = try String(contentsOf: Self.root.appendingPathComponent(f.source), encoding: .utf8)
let there = source.contains(f.fragment)
XCTAssertTrue(there, "\(f.id): \(f.source) no longer contains \"\(f.fragment)\": update the pattern and the fixture")
@@ -72,7 +79,8 @@ final class BuildFailureTests: XCTestCase {
func testEveryHintIsInBothLanguagesWithoutSemicolons() {
var keys = ["fail.section", "fail.buildAnyway", "fail.confirm.title", "fail.confirm.go", "fail.confirm.cancel", "fail.override.note",
"fail.a32Program.whatNamed", "fail.translator.button", "fail.iosSDK.button", "fail.cltSelected.button",
- "dep.metal.other", "dep.fix.metalPin"]
+ "dep.metal.other", "dep.fix.metalPin", "fail.showFolder", "fail.openXcode", "fail.retry", "fail.keys.button",
+ "fail.driveMissing.whatNamed", "fail.diskFull.whatNeeds"]
for k in BuildFailureKind.allCases where k != .unknown {
keys += [k.whatKey, k.nextKey]
if k.overrideFlag != nil { keys.append("fail.\(k.rawValue).risk") }
@@ -140,7 +148,7 @@ final class BuildFailureTests: XCTestCase {
func testAStopWithoutAnOverrideCannotBeBuiltAnyway() {
let m = BuildModel()
- for k in [BuildFailureKind.rosetta, .translator, .iosSDK, .cltSelected, .a32Program] {
+ for k in BuildFailureKind.allCases where k.overrideFlag == nil {
m.failure = BuildFailure(kind: k, gameName: nil)
m.requestBuildAnyway()
XCTAssertNil(m.confirmingOverride, "\(k)")
@@ -241,12 +249,14 @@ final class BuildFailureTests: XCTestCase {
window.orderOut(nil)
}
for (name, kind, lang) in [("hint-other-metal", BuildFailureKind.otherMetal, Lang.en), ("hint-ios-sdk", .iosSDK, .en), ("hint-damaged-nsp", .damagedNSP, .en),
- ("hint-other-metal-zh", .otherMetal, .zh)] {
+ ("hint-other-metal-zh", .otherMetal, .zh)]
+ + [BuildFailureKind.keys, .severalGames, .noTitleID, .driveMissing, .diskFull, .teamTaken, .noSigningAccount, .deviceTransfer].flatMap { k in
+ [("row-\(k.rawValue)", k, Lang.en), ("row-\(k.rawValue)-zh", k, Lang.zh)] } {
let m = BuildModel()
m.lang = lang
- m.failure = BuildFailure(kind: kind, gameName: nil)
+ m.failure = BuildFailure(kind: kind, gameName: nil, detail: kind == .diskFull ? "40" : kind == .driveMissing ? "Games" : nil)
m.doneNote = m.failureWhat(m.failure!)
- try capture(name, width: 760, height: 250, ZStack(alignment: .top) {
+ try capture(name, width: 760, height: kind == .noTitleID ? 380 : 250, ZStack(alignment: .top) {
LauncherPalette.background
BuildFailureCard(m: m).padding(24)
})