Skip to content

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

Move the pure logic out of BuildModel into NXCore (#387)

v0lumehi69dccea0eb5c
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.md
index bfbe6481..fa67c331 100644
--- a/frontend/ARCHITECTURE.md
+++ b/frontend/ARCHITECTURE.md
@@ -13,10 +13,11 @@ The plan and the steps are in [LNPANDY/NX2Apple#387](https://github.com/LNPANDY/
## Where it stands
-Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. The rest still lives in the app target and moves with the later steps.
+Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. The rest still lives in the app target and moves with the later steps.
- `BuildModel` is the model of the whole launcher and reaches into every layer, so the files that use it cannot leave the app target yet. It no longer owns the language: it holds the `Localizer` it was given and forwards `lang` and `t()` to it, for the text it writes itself (alerts, status, failures).
-- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader.
+- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. What reads `MetalPin`, `EngineLayout` or `OnboardingDefaults` (`detectDepsSync`, `metalDep`, `needsIOSPlatform`) and the handling of the build's JSON events stay in `BuildModel` until the later store steps.
+- `NXCoreTests` tests `NXCore` alone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.
- `NXModel` holds `Localizer`: `lang` and `t()`. The app creates one with each `BuildModel`, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.
- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildModel` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards. `BuildModel` is not `@MainActor` yet, so it reaches the log through `BuildLog.onMain`.
- `NXLauncher` holds the views and styles that do not need `BuildModel`: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.
diff --git a/frontend/Package.swift b/frontend/Package.swift
index 04a93cc7..db1e9f36 100644
--- a/frontend/Package.swift
+++ b/frontend/Package.swift
@@ -12,6 +12,8 @@ let package = Package(
.target(name: "NXModel", dependencies: ["NXCore"], path: "Sources/NXModel"),
.target(name: "NXLauncher", dependencies: ["NXModel", "NXCore"], path: "Sources/NXLauncher"),
.executableTarget(name: "NX2Apple", dependencies: ["NXLauncher", "NXModel", "NXCore"], path: "Sources/NX2Apple"),
+ // Tests of the pure logic: they link NXCore only, so they run without SwiftUI.
+ .testTarget(name: "NXCoreTests", dependencies: ["NXCore"]),
.testTarget(name: "NX2AppleTests", dependencies: ["NX2Apple", "NXLauncher", "NXModel", "NXCore"])
],
swiftLanguageModes: [.v5]
diff --git a/frontend/Sources/NX2Apple/BuildFailureView.swift b/frontend/Sources/NX2Apple/BuildFailureView.swift
index 2ba30486..ff0a79f8 100644
--- a/frontend/Sources/NX2Apple/BuildFailureView.swift
+++ b/frontend/Sources/NX2Apple/BuildFailureView.swift
@@ -53,7 +53,7 @@ struct BuildFailureCard: View {
case .iosSDK:
fix(kind, "fail.iosSDK.button")
case .cltSelected:
- if BuildModel.installedXcode() != nil { fix(kind, "fail.cltSelected.button") }
+ if Toolchain.installedXcode() != nil { fix(kind, "fail.cltSelected.button") }
case .keys:
fix(kind, "fail.keys.button")
case .severalGames, .noTitleID, .diskFull:
@@ -61,7 +61,7 @@ struct BuildFailureCard: View {
case .cloudFolder:
fix(kind, "fail.cloudFolder.button")
case .teamTaken, .noSigningAccount:
- if BuildModel.installedXcode() != nil { fix(kind, "fail.openXcode") }
+ if Toolchain.installedXcode() != nil { fix(kind, "fail.openXcode") }
case .deviceTransfer, .devicePairing:
fix(kind, "fail.retry")
case .shellDataIncomplete:
diff --git a/frontend/Sources/NX2Apple/BuildNotifications.swift b/frontend/Sources/NX2Apple/BuildNotifications.swift
index 4adbbad8..53e1d07c 100644
--- a/frontend/Sources/NX2Apple/BuildNotifications.swift
+++ b/frontend/Sources/NX2Apple/BuildNotifications.swift
@@ -1,5 +1,6 @@
import AppKit
import Combine
+import NXCore
import UserNotifications
// A notification when a build finishes or fails (issue #64): a build takes long enough that people switch
@@ -90,7 +91,7 @@ final class BuildNotifier: NSObject, ObservableObject, UNUserNotificationCenterD
}
private func post(_ outcome: BuildNotice.Outcome, m: BuildModel, library: GameLibrary) {
- let titleID = BuildModel.titleID(m.basePath).map { String(format: "%016llX", $0) } ?? ""
+ let titleID = TitleID.parse(m.basePath).map { String(format: "%016llX", $0) } ?? ""
let game = library.games.first { $0.titleID == titleID }
let name = game?.name ?? GameLibrary.title(for: m.basePath, repo: m.repoPath, titleID: titleID)
let text = BuildNotice.text(outcome, game: name, target: m.target, device: m.installedOn.isEmpty ? nil : m.deviceName(m.installedOn), m.t)
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swift
index 12fedce3..9a231efb 100644
--- a/frontend/Sources/NX2Apple/ContentView.swift
+++ b/frontend/Sources/NX2Apple/ContentView.swift
@@ -15,55 +15,7 @@ import NXModel
// MARK: - Pieces
-struct Stage: Identifiable {
- let id: Int // k, the stage number in the script's own plan
- var name: String
- var state: StepState = .running
- var detail: String = ""
- var percent: Double? = nil
- var started: Date? = nil // when the stage began here: its clock runs while the count may stand still
- var eta: Double? = nil // the script's estimate of the seconds left, as of etaAt
- var etaAt: Date? = nil
-
- /// A stage's name in the launcher's language. The script names its stages in English (PROG.stage in
- /// build_ipa_from_nsp.py): stage.<name> in the table, "extract <name>" and "<API> shader capture" with their
- /// part kept; a name the table does not know (a newer script's) is shown as the script wrote it.
- static func localizedName(_ name: String, _ t: (String) -> String) -> String {
- func known(_ key: String) -> String? { let s = t(key); return s == key ? nil : s }
- let key = "stage." + name.lowercased().replacingOccurrences(of: "[^a-z0-9]+", with: "_", options: .regularExpression)
- .trimmingCharacters(in: CharacterSet(charactersIn: "_"))
- if let s = known(key) { return s }
- if name.hasPrefix("extract "), let f = known("stage.extract") { return String(format: f, String(name.dropFirst("extract ".count))) }
- if name.hasSuffix(" shader capture"), let f = known("stage.capture") { return String(format: f, String(name.dropLast(" shader capture".count))) }
- return name
- }
-
- /// "3:42" since the stage began, then "1 min left" while the script's estimate, counted down from when it came,
- /// lasts: the estimate only arrives with a new count, so one taken as it was would stand still with the count.
- func clock(at now: Date, left: String) -> String {
- var parts: [String] = []
- if let started {
- let t = max(0, Int(now.timeIntervalSince(started)))
- parts.append(t >= 3600 ? String(format: "%d:%02d:%02d", t / 3600, t / 60 % 60, t % 60) : String(format: "%d:%02d", t / 60, t % 60))
- }
- if let eta, let etaAt {
- let remaining = eta - now.timeIntervalSince(etaAt)
- if remaining >= 1 { parts.append(String(format: left, BuildModel.duration(remaining))) }
- }
- return parts.joined(separator: " · ")
- }
-}
-
-enum StepState: Equatable {
- case pending, running, done, failed
- var icon: String {
- switch self {
- case .pending: return "circle"
- case .running: return "spinner"
- case .done: return "checkmark.circle.fill"
- case .failed: return "xmark.octagon.fill"
- }
- }
+extension StepState {
var color: Color {
switch self {
case .pending: return .gray
@@ -74,9 +26,6 @@ enum StepState: Equatable {
}
}
-/// One of the four things the user points at.
-enum InputKind { case base, update, dlc, keys }
-
struct Slot: Identifiable {
let id: String
let kind: InputKind
@@ -671,7 +620,7 @@ final class BuildModel: ObservableObject {
append("$ python3 tools/engine.py sync\n")
var tail = "" // what failureKind reads when the sync stops (only touched on the main queue)
DispatchQueue.global().async {
- let py = chosen.isEmpty ? Self.findPython().path : chosen
+ let py = chosen.isEmpty ? Toolchain.findPython().path : chosen
let ok = EngineLayout.runSync(repo: repo, python: py) { line in
DispatchQueue.main.async { self.append(line + "\n"); tail = String((tail + line + "\n").suffix(4000)) }
}
@@ -1008,7 +957,7 @@ final class BuildModel: ObservableObject {
/// pruning the build folders this pipeline itself writes so a rescan is not slow.
func scan(folder: String) {
gameDir = folder
- let found = Self.classify(Self.inputFiles(in: folder))
+ let found = GameInputs.classify(GameInputs.inputFiles(in: folder))
updateSlot("base") { $0.paths = found.base.map { [$0] } ?? []; $0.problem = found.base == nil ? "data.noBase" : "" }
updateSlot("update") { $0.paths = found.update.map { [$0] } ?? []; $0.problem = ""; $0.note = updateNote(found) }
updateSlot("dlc") { $0.paths = found.dlc; $0.problem = "" }
@@ -1018,115 +967,14 @@ final class BuildModel: ObservableObject {
}
}
- /// What a set of files holds for the four slots (`classify`).
- struct FoundInputs: Equatable {
- var base: String?
- var update: String?
- var dlc: [String] = []
- var keys: String?
- /// How many updates the files held and the version of the one taken (the newest), for the update row's note.
- var updateCount = 0
- var updateVersion = 0
- var anyGame: Bool { base != nil || update != nil || !dlc.isEmpty }
- static func == (a: Self, b: Self) -> Bool {
- a.base == b.base && a.update == b.update && a.dlc == b.dlc && a.keys == b.keys
- }
- }
-
/// The update row's note when the files held several updates: which one was taken and why one is enough.
- func updateNote(_ found: FoundInputs) -> String {
+ func updateNote(_ found: GameInputs.Found) -> String {
guard found.update != nil, found.updateCount > 1 else { return "" }
return String(format: t("data.updateNewest"), found.updateVersion, found.updateCount)
}
- /// The files under a folder, pruning the build folders this pipeline itself writes so a rescan is not slow.
- nonisolated static func inputFiles(in folder: String) -> [String] {
- let fm = FileManager.default
- var files: [String] = []
- var seen = 0
- let enumerator = fm.enumerator(atPath: folder)
- while let rel = enumerator?.nextObject() as? String {
- if seen > 8000 { break } // a pathological tree should not hang the picker
- seen += 1
- let name = (rel as NSString).lastPathComponent
- if name.hasPrefix(".") { continue }
- let path = folder + "/" + rel
- var isDir: ObjCBool = false
- guard fm.fileExists(atPath: path, isDirectory: &isDir) else { continue }
- let low = name.lowercased()
- if isDir.boolValue {
- // the pipeline's own output, and anything hidden: never walk back into those
- if low == "archive" || low == "xcode" || low.hasSuffix("_build") || low.hasSuffix("_survey") { enumerator?.skipDescendants() }
- continue
- }
- files.append(path)
- }
- return files
- }
-
- /// NSP/XCI (and their compressed NSZ/XCZ) sorted by the title ID in the file name, plus the first prod.keys.
- /// Shared by Choose game folder and files dropped on the Builds page.
- nonisolated static func classify(_ files: [String]) -> FoundInputs {
- var base: [(String, Int)] = [], update: [(String, Int, Int)] = [], dlc: [String] = []
- var found = FoundInputs()
- for path in files {
- let name = (path as NSString).lastPathComponent
- let low = name.lowercased()
- if name.hasPrefix("._") { continue } // an AppleDouble file macOS writes beside every real file on exFAT/FAT drives: its name carries the same [title ID], so counting it made one update read as two
- if found.keys == nil && (low == "prod.keys" || low.hasSuffix(".keys")) { found.keys = path; continue }
- guard ["nsp", "xci", "nsz", "xcz"].contains((low as NSString).pathExtension) else { continue }
- let size = (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? Int ?? 0
- guard size > 0 else { continue } // an incomplete download leaves 0-byte files behind
- guard let tid = titleID(name) else { continue } // a name without a title ID cannot be classified
- switch tid & 0xFFF {
- case 0: base.append((path, size))
- case 0x800: update.append((path, size, updateVersion(name)))
- default: dlc.append(path)
- }
- }
- // several bases happen when a folder holds a repack beside the original: the largest wins
- found.base = base.sorted { $0.1 > $1.1 }.first?.0
- // a folder that holds other games too: only the update and add-on content of the chosen base game count
- if let app = found.base.flatMap({ titleID(($0 as NSString).lastPathComponent) }).map({ $0 & ~0xFFF }) {
- update = update.filter { titleID(($0.0 as NSString).lastPathComponent).map(owner) == app }
- dlc = dlc.filter { titleID(($0 as NSString).lastPathComponent).map(owner) == app }
- }
- // several updates: the newest version is the one a profile would pack (an update contains the earlier ones)
- let newest = update.sorted { $0.2 > $1.2 }.first
- found.update = newest?.0
- found.updateCount = update.count
- found.updateVersion = newest?.2 ?? 0
- found.dlc = dlc.sorted()
- return found
- }
-
- /// The base game's title ID (low 12 bits clear) a title ID belongs to, as build_ipa_from_nsp.py reads it:
- /// 0x000 is a base game, 0x800 its update, anything else add-on content in the block above the base.
- nonisolated static func owner(_ tid: UInt64) -> UInt64 {
- let low = tid & 0xFFF
- return low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)
- }
-
- /// Why a file does not fit the row it was put in, judged by the title ID in its name.
- enum RowMismatch: Equatable { case notBase(UInt64), notUpdate(UInt64), notDLC(UInt64), otherGame }
-
- /// A file whose name carries no title ID fits every row (the build script reads the ID from the package).
- /// `base` is the selected base game's file name, when it carries one.
- nonisolated static func rowMismatch(_ kind: InputKind, name: String, base: String?) -> RowMismatch? {
- guard kind != .keys, let tid = titleID(name) else { return nil }
- let low = tid & 0xFFF
- switch kind {
- case .base: if low != 0 { return .notBase(tid) }
- case .update: if low != 0x800 { return .notUpdate(tid) }
- case .dlc: if low == 0 || low == 0x800 { return .notDLC(tid) }
- case .keys: break
- }
- if kind != .base, let b = base.flatMap(titleID), owner(tid) != b & ~0xFFF { return .otherGame }
- return nil
- }
-
/// The row's message for a rejected file, as a finished sentence in the current language.
- func rowProblemText(_ mismatch: RowMismatch, name: String) -> String {
+ func rowProblemText(_ mismatch: GameInputs.RowMismatch, name: String) -> String {
func hex(_ tid: UInt64) -> String { String(format: "%016llX", tid) }
switch mismatch {
case .notBase(let tid): return String(format: t("data.rowNotBase"), name, hex(tid))
@@ -1136,38 +984,12 @@ final class BuildModel: ObservableObject {
}
}
- /// The version in a file name, 0 when absent: `[v65536]` first, then the `_v65536` / ` v65536` token the
- /// eShop-style names use (`01007EF00011E800_v1114112_038ff9df0888.nsp`). Picks the newest of several updates.
- nonisolated static func updateVersion(_ name: String) -> Int {
- for pattern in [#"\[v(\d+)\]"#, #"(?:^|[_ ])v(\d+)(?=$|[_ .\-)\]])"#] {
- if let v = firstGroup(pattern, in: name), let n = Int(v) { return n }
- }
- return 0
- }
-
- nonisolated private static func firstGroup(_ pattern: String, in name: String) -> String? {
- guard let re = try? NSRegularExpression(pattern: pattern) else { return nil }
- let ns = name as NSString
- guard let m = re.firstMatch(in: name, range: NSRange(location: 0, length: ns.length)) else { return nil }
- return ns.substring(with: m.range(at: 1))
- }
-
- /// What the Choose… dialog of a row offers. The compressed NSZ / XCZ are accepted by the build
- /// script like their plain forms. DLC ships as NSP (or NSZ), never as a cartridge image.
- nonisolated static func allowedFileTypes(for kind: InputKind) -> [String] {
- switch kind {
- case .base, .update: return ["nsp", "xci", "nsz", "xcz"]
- case .dlc: return ["nsp", "nsz"]
- case .keys: return ["keys"]
- }
- }
-
func pickFiles(kind: InputKind) {
let p = NSOpenPanel()
p.canChooseDirectories = false
p.canChooseFiles = true
p.allowsMultipleSelection = (kind == .dlc)
- p.allowedFileTypes = Self.allowedFileTypes(for: kind)
+ p.allowedFileTypes = GameInputs.allowedFileTypes(for: kind)
switch kind {
case .dlc:
p.message = t("data.dlcPanelMessage")
@@ -1187,7 +1009,7 @@ final class BuildModel: ObservableObject {
var fitting: [String] = [], problem = ""
for path in picked {
let name = (path as NSString).lastPathComponent
- if let why = Self.rowMismatch(kind, name: name, base: baseName) {
+ if let why = GameInputs.rowMismatch(kind, name: name, base: baseName) {
if problem.isEmpty { problem = rowProblemText(why, name: name) }
} else { fitting.append(path) }
}
@@ -1203,32 +1025,6 @@ final class BuildModel: ObservableObject {
func clear(_ id: String) { updateSlot(id) { $0.paths = []; $0.problem = "" } }
- /// The title ID in a file name: `[0100F2C0115B6000]` first, else a bare 16-digit ID that starts with 01 as a token
- /// (start of the name or after `_`, space, `-`, `.`, `(`, `[`). Only the file name counts, so a full path works and a folder named with an ID never
- /// stands in for the file (#382). Like `01007EF00011E000_v0_420d1c5034ab.nsp`.
- nonisolated static func titleID(_ path: String) -> UInt64? {
- let name = (path as NSString).lastPathComponent
- let found = firstGroup(#"\[([0-9A-Fa-f]{16})\]"#, in: name)
- ?? firstGroup(#"(?:^|[_ \-.(\[])(01[0-9A-Fa-f]{14})(?![0-9A-Fa-f])"#, in: name)
- return found.flatMap { UInt64($0, radix: 16) }
- }
-
- /// The name of a game's work folder and output (`<key>_build`, `<key>.app`). The title ID in the file name when there
- /// is one, so `<ID>_build` stays what the library looks for. Else the file name without its extension, cut to letters,
- /// digits, `-` and `_`, plus a short hash of the full name: two games never share a folder (and so a shader cache),
- /// the same file name always gets the same one (a rebuild reuses its cache). Never a constant.
- nonisolated static func buildKey(_ path: String) -> String {
- let name = (path as NSString).lastPathComponent
- if let id = titleID(name) { return String(format: "%016llX", id) }
- let stem = (name as NSString).deletingPathExtension
- var hash: UInt32 = 2166136261 // FNV-1a, stable across runs (Hashable is seeded per launch)
- for byte in stem.utf8 { hash = (hash ^ UInt32(byte)) &* 16777619 }
- let clean = String(stem.unicodeScalars.map { c in
- c.isASCII && (CharacterSet.alphanumerics.contains(c) || c == "-" || c == "_") ? Character(c) : "_"
- }).prefix(40)
- return (clean.isEmpty ? "game" : String(clean)) + "-" + String(format: "%08x", hash)
- }
-
var repoOK: Bool { Self.isRepo(repoPath) }
/// A clone has .git; a GitHub "Download ZIP" copy does not (everything builds, but there is
/// nothing to fetch or pull — the update buttons hide and the note says to re-download instead).
@@ -1260,7 +1056,7 @@ final class BuildModel: ObservableObject {
// runs on a background queue and startBuild() can beat it — for a moment pythonPath is
// empty, and the old fallback was Apple's /usr/bin/python3 (3.9), which the script then
// rejected with "require Python 3.12 or newer" whatever the machine actually had (#53).
- let py = pythonPath.isEmpty ? Self.findPython().path : pythonPath
+ let py = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath
// engine/ is the only engine and is stale or missing (#214): make it, then start again
if EngineLayout.needsSyncBeforeBuild(repoPath) {
syncEngine { ok in
@@ -1293,10 +1089,10 @@ final class BuildModel: ObservableObject {
// exactly as build_ipa_from_nsp.py:445 reads it: the low 12 bits are 0x000 for a base game,
// 0x800 for its update, and anything else is add-on content below the base.
var staged = allPaths
- if let base = Self.titleID((basePath as NSString).lastPathComponent) {
+ if let base = TitleID.parse((basePath as NSString).lastPathComponent) {
let app = base & ~0xFFF
for f in unpicked {
- guard let tid = Self.titleID(f) else { continue }
+ guard let tid = TitleID.parse(f) else { continue }
let low = tid & 0xFFF
let owner = low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)
guard owner == app else { continue }
@@ -1305,7 +1101,7 @@ final class BuildModel: ObservableObject {
staged.append(baseDir + "/" + f)
}
}
- let tidHex = Self.buildKey(basePath)
+ let tidHex = TitleID.buildKey(basePath)
let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"
// The build's signing step refuses the attributes a cloud folder adds, after the long steps: stop here instead.
if cloudFolderCheck(workDir) {
@@ -1344,7 +1140,7 @@ final class BuildModel: ObservableObject {
let e = ($0 as NSString).pathExtension.lowercased()
return e == "nsz" || e == "xcz"
}
- if compressed, !Self.runOK(py, ["-c", "import nsz"]) {
+ if compressed, !Toolchain.runOK(py, ["-c", "import nsz"]) {
say(t("msg.installingNsz"))
let r = Self.runCaptured([py, "-m", "pip", "install", "nsz"],
env: ["PATH": Self.toolPath(python: py),
@@ -1406,7 +1202,7 @@ final class BuildModel: ObservableObject {
var denv: [String: String] = ["PATH": Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: py),
"USER": NSUserName(), "HOME": NSHomeDirectory(), "LANG": "en_US.UTF-8",
"TMPDIR": NSTemporaryDirectory()]
- if let droot = Self.dotnetRoot(for: dotnetPath.isEmpty ? "dotnet" : dotnetPath) {
+ if let droot = Toolchain.dotnetRoot(for: dotnetPath.isEmpty ? "dotnet" : dotnetPath) {
denv["DOTNET_ROOT"] = droot // both variables carry the same root, as the apphost checks the arch-specific one first
denv["DOTNET_ROOT_ARM64"] = droot
}
@@ -1451,7 +1247,7 @@ final class BuildModel: ObservableObject {
self.cleanupStaging()
} else {
// The game's archive, then its framework into the one shared app on the device
- let tid = Self.buildKey(self.basePath)
+ let tid = TitleID.buildKey(self.basePath)
let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension
let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)
self.packArchive(workDir: self.effectiveWorkDir) {
@@ -1468,7 +1264,7 @@ final class BuildModel: ObservableObject {
// points at the log: "Build failed (exit code 1)" with nothing else sent a
// reporter looking for a log that a short window had below the fold (#52)
self.doneNote = String(format: self.t("msg.buildFailed"), status.terminationStatus)
- if let last = Self.lastMeaningfulLine(self.logTail) {
+ if let last = BuildProgress.lastMeaningfulLine(self.logTail) {
self.doneNote = String(format: self.t("msg.buildFailedReason"), last)
}
self.noteFailure()
@@ -1576,10 +1372,10 @@ final class BuildModel: ObservableObject {
case .translator:
if let d = deps.first(where: { $0.id == "dotnet" }) { installDep(d) }
case .iosSDK:
- installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Self.iosPlatformCmd))
+ installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.iosPlatformCmd))
case .cltSelected:
- if let xcode = Self.installedXcode() {
- installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Self.selectXcodeCmd(xcode)))
+ if let xcode = Toolchain.installedXcode() {
+ installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.selectXcodeCmd(xcode)))
}
case .zbic:
if let d = deps.first(where: { $0.id == "python" }) { installDep(d) } // the venv install, which now names zbic
@@ -1614,7 +1410,7 @@ final class BuildModel: ObservableObject {
/// 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 }
+ guard let app = Toolchain.installedXcode() else { return }
openApp(URL(fileURLWithPath: app))
}
@@ -1687,17 +1483,6 @@ final class BuildModel: ObservableObject {
// MARK: Output parsing
- /// The last line of the log that says something: not blank, not a progress event. Used for the
- /// failure note, where the exit code on its own is not actionable (issue #52).
- static func lastMeaningfulLine(_ log: String) -> String? {
- for line in log.split(separator: "\n", omittingEmptySubsequences: true).reversed() {
- let s = line.trimmingCharacters(in: .whitespaces)
- if s.isEmpty || s.hasPrefix("{") { continue } // a --progress json event
- return String(s.prefix(200))
- }
- return nil
- }
-
private func say(_ s: String) { append(s + "\n") }
private func append(_ s: String) { BuildLog.onMain { log.append(s) } }
@@ -1722,7 +1507,7 @@ final class BuildModel: ObservableObject {
}
append(line + "\n")
noteChainChange(line)
- guard let s = Self.parseStage(line) else { return }
+ guard let s = BuildProgress.parseStage(line) else { return }
if let i = stages.firstIndex(where: { $0.id == s.k }) {
if !s.name.isEmpty { stages[i].name = Stage.localizedName(s.name, t) }
if s.state != .pending { stages[i].state = s.state }
@@ -1768,12 +1553,12 @@ final class BuildModel: ObservableObject {
stage { $0.detail = step; $0.percent = nil; $0.eta = nil }
case "progress":
let fraction = (e["frac"] as? NSNumber)?.doubleValue
- let detail = Self.progressDetail(e)
+ let detail = BuildProgress.progressDetail(e)
let eta = (e["eta"] as? NSNumber)?.doubleValue
stage { $0.percent = fraction.map { $0 * 100 }; $0.detail = detail; $0.eta = eta; $0.etaAt = eta == nil ? nil : Date() }
case "stage_end":
let ok = e["ok"] as? Bool ?? true, summary = e["summary"] as? String ?? ""
- let elapsed = Self.duration((e["elapsed"] as? NSNumber)?.doubleValue ?? 0)
+ let elapsed = BuildProgress.duration((e["elapsed"] as? NSNumber)?.doubleValue ?? 0)
append("\(ok ? "✓" : "✗") \(e["name"] as? String ?? "") (\(elapsed))" + (summary.isEmpty ? "" : ": \(summary)") + "\n")
stage { $0.state = ok ? .done : .failed; $0.detail = summary; $0.percent = ok ? 100 : $0.percent; $0.eta = nil }
case "say":
@@ -1784,67 +1569,6 @@ final class BuildModel: ObservableObject {
}
}
- /// "splitting · 1.2 / 3.4 GB", "1,203 / 19,592 shaders", "2,301 files": the step and the count (the time left is the Stage's clock).
- nonisolated static func progressDetail(_ e: [String: Any]) -> String {
- let step = e["step"] as? String ?? "", unit = e["unit"] as? String ?? "", note = e["note"] as? String ?? ""
- let done = (e["done"] as? NSNumber)?.doubleValue, total = (e["total"] as? NSNumber)?.doubleValue
- let estimate = (e["est"] as? Bool ?? false) ? "~" : ""
- var count = ""
- if let done {
- if unit == "B" {
- let bytes = { (v: Double) in ByteCountFormatter.string(fromByteCount: Int64(v), countStyle: .file) }
- count = total.map { "\(bytes(done)) / \(estimate)\(bytes($0))" } ?? bytes(done)
- } else {
- let number = { (v: Double) in NumberFormatter.localizedString(from: NSNumber(value: Int(v)), number: .decimal) }
- count = (total.map { "\(number(done)) / \(estimate)\(number($0))" } ?? number(done)) + (unit.isEmpty ? "" : " \(unit)")
- }
- }
- return [step, count, note].filter { !$0.isEmpty }.joined(separator: " · ")
- }
-
- nonisolated static func duration(_ seconds: Double) -> String {
- // Formatted by hand, not DateComponentsFormatter: the formatter follows the system
- // locale, so a Chinese macOS wrote "4秒" into a log whose every other line was English
- // (and the test that pinned "4s" failed on any non-English machine). The abbreviations
- // are the interface language's, via the same string table as everything else.
- let s = max(Int(seconds.rounded(.up)), 1)
- if s >= 3600 {
- let h = s / 3600, m = (s % 3600) / 60
- return h > 0 && m > 0 ? "\(h)h \(m)m" : "\(h)h"
- }
- if s >= 60 {
- let m = s / 60, sec = s % 60
- return sec > 0 ? "\(m)m \(sec)s" : "\(m)m"
- }
- return "\(s)s"
- }
-
- nonisolated static func parseStage(_ line: String) -> (k: Int, name: String, state: StepState, detail: String, percent: Double?)? {
- guard let re = try? NSRegularExpression(pattern: #"\[(\d+)/(\d+)\] (.+)$"#) else { return nil }
- let ns = line as NSString
- guard let m = re.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { return nil }
- guard let k = Int(ns.substring(with: m.range(at: 1))) else { return nil }
- var rest = ns.substring(with: m.range(at: 3))
-
- if let pct = rest.range(of: #"(\d+)%"#, options: .regularExpression) {
- let v = Double(rest[pct].dropLast()) ?? 0
- var name = String(rest[..<pct.lowerBound]).trimmingCharacters(in: CharacterSet(charactersIn: " :·"))
- if let dot = name.range(of: " · ", options: .backwards) { name = String(name[..<dot.lowerBound]) }
- let after = String(rest[pct.upperBound...]).trimmingCharacters(in: CharacterSet(charactersIn: ", :"))
- return (k, name, .running, after, v)
- }
- let ok = line.contains("✓"), bad = line.contains("✗")
- if ok || bad {
- var detail = ""
- if let r = rest.range(of: "): ") { detail = String(rest[r.upperBound...]); rest = String(rest[..<r.lowerBound]) + ")" }
- if let r = rest.range(of: " (", options: .backwards) { rest = String(rest[..<r.lowerBound]) }
- return (k, rest, bad ? .failed : .done, detail, 100)
- }
- if rest.hasSuffix(" …") { rest = String(rest.dropLast(2)) }
- if let dot = rest.range(of: " · ", options: .backwards), !rest.hasPrefix("survey") { rest = String(rest[..<dot.lowerBound]) }
- return (k, rest, .running, "", nil)
- }
-
// MARK: Archive
/// The DLC images ride along: with the slim default the build script leaves them in the work folder
@@ -1891,7 +1615,7 @@ final class BuildModel: ObservableObject {
// exposes on an external drive) then needs no renaming, and several games' folders can sit
// side by side in one app.
let gamesRoot = (outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) + "/games"
- let tid = Self.buildKey(basePath)
+ let tid = TitleID.buildKey(basePath)
// games/<id>/ holds romfs.img and aoc/ side by side: main.m's per-game lookup takes the
// image, and the host mounts DLC from aoc/<index>.img (hle_fs.c aoc_dir). One folder, which
// the user copies to the phone or keeps on an external drive as a whole.
@@ -2022,7 +1746,7 @@ final class BuildModel: ObservableObject {
running = true
if dataOnly { failure = nil; done = false; doneNote = "" }
shellRetry = (framework, titleID, name, archive)
- let python = pythonPath.isEmpty ? Self.findPython().path : pythonPath
+ let python = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath
let root = shellRoot
var installer = ShellInstaller(xcrun: xcrunPath, repo: repoPath, python: python, root: root, device: installDevice, team: signingTeam)
installer.deviceName = deviceName(installDevice)
@@ -2116,7 +1840,7 @@ final class BuildModel: ObservableObject {
}
running = true
runTool(id: 1004, name: String(format: t("dev.reinstallStage"), deviceName(device)),
- Self.reinstallCommand(xcrun: xcrunPath, device: device, app: app), step: Self.installStep) { error in
+ Self.reinstallCommand(xcrun: xcrunPath, device: device, app: app), step: BuildProgress.installStep) { error in
if let error {
// The app is still on the device: a failed reinstall is a note, not a failed build
self.running = false
@@ -2157,14 +1881,14 @@ final class BuildModel: ObservableObject {
// The shared app is signed again under the identifier shell.json holds, so the device keeps its Documents
let command = ShellInstall.buildCommand(xcrun: xcrun, root: shell.root, device: device, team: team, bundleID: bundle)
runTool(id: 1006, name: String(format: t("dev.resignStage"), name),
- command, step: Self.xcodeStep) { error in
+ command, step: BuildProgress.xcodeStep) { error in
if let error, !error.isEmpty {
self.running = false
self.doneNote = String(format: self.t("dev.resignFailed"), error)
then?(); return
}
self.runTool(id: 1007, name: String(format: self.t("dev.installStage"), name),
- Self.reinstallCommand(xcrun: xcrun, device: device, app: app), step: Self.installStep) { installError in
+ Self.reinstallCommand(xcrun: xcrun, device: device, app: app), step: BuildProgress.installStep) { installError in
self.running = false
if let installError {
self.doneNote = String(format: self.t("dev.installFailed"), installError)
@@ -2232,19 +1956,6 @@ final class BuildModel: ObservableObject {
return name.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: ":", with: "_") + ".ipa"
}
- /// What xcodebuild is doing, from the actions it prints.
- nonisolated static func xcodeStep(_ line: String) -> (detail: String, percent: Double?)? {
- let actions = [("CompileC ", "compiling"), ("SwiftCompile ", "compiling"), ("Ld ", "linking"),
- ("PhaseScriptExecution ", "copying resources"), ("CodeSign ", "signing"), ("ProcessProductPackaging ", "provisioning")]
- return actions.first { line.hasPrefix($0.0) }.map { ($0.1, nil) }
- }
-
- /// devicectl's install progress ("… 45%").
- nonisolated static func installStep(_ line: String) -> (detail: String, percent: Double?)? {
- guard let range = line.range(of: #"(\d{1,3})%"#, options: .regularExpression), let n = Double(line[range].dropLast()) else { return nil }
- return ("installing", min(n, 100))
- }
-
/// One of Xcode's tools as a stage of the build: in its own process group (Stop ends it), its output in the log,
/// its progress in the stage. `then` gets nil on success, else the last error line.
private func runTool(id: Int, name: String, _ command: [String], step: @escaping (String) -> (detail: String, percent: Double?)?,
@@ -2326,428 +2037,6 @@ final class BuildModel: ObservableObject {
// MARK: Dependencies
- struct Dep: Identifiable {
- let id: String
- let name: String // an L10n key
- let hint: String // an L10n key
- var present: Bool
- var installing = false
- var detail = ""
- var lastError = "" // the tool's own first error line after a failed install (brew's, pip's)
- var fixHint = "" // an L10n key: what to type or click, chosen from that line
- var actionLabel = "" // an L10n key for the button when the action is not a plain install ("Fix")
- var warning = false // present, but with a caveat the row's error and hint lines explain (the Metal compiler is not the tested one)
- let installCmd: [String] // run via bash; empty = manual (Xcode from the App Store)
- }
-
- /// A GUI app does not inherit the shell's PATH, so look where the tools actually
- /// live instead of trusting `which` — that is why .NET (in ~/.dotnet) and the
- /// Python packages (in /usr/local/bin/python3, not /usr/bin/python3) used to show
- /// as missing while a terminal could see them.
- nonisolated static func runOK(_ tool: String, _ args: [String], env: [String: String]? = nil) -> Bool {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: tool)
- p.arguments = args
- if let env { p.environment = env }
- p.standardOutput = Pipe(); p.standardError = Pipe()
- p.standardInput = FileHandle.nullDevice
- do { try p.run() } catch { return false }
- p.waitUntilExit()
- return p.terminationStatus == 0
- }
-
- nonisolated static func firstExisting(_ paths: [String]) -> String? {
- paths.first { FileManager.default.isExecutableFile(atPath: $0) }
- }
-
- /// The Python that actually has lz4/capstone/fontTools/zbic/backports.zstd — the one
- /// the build must run under, not whatever /usr/bin/python3 happens to be.
- /// The minimum the build scripts need. /usr/bin/python3 is 3.9 on a stock Mac and has none of
- /// the packages; picking it made a build fail with a syntax error deep inside the script
- /// (an f-string only 3.12 can parse) instead of a clear message here.
- ///
- /// 3.12 is the script's own floor, not a guess: build_ipa_from_nsp.py:1911 raises "Direct
- /// RomFS image builds require Python 3.12 or newer". This said 3.9 — the comment above even
- /// said 3.12 — so findPython() was happy to return Apple's 3.9 and the build then died inside
- /// the script with a message the user could not act on (issue #53).
- nonisolated static let minPython = (3, 12)
-
- /// The Homebrew formulae the dependency check offers, with the localization key of each row. The repo-root
- /// Brewfile lists the same formulae (BrewfileTests keeps the two equal).
- /// `binary` is the file the formula puts in the Homebrew bin folder (glslang installs glslangValidator, which the
- /// NSP script's environment check requires).
- nonisolated static let brewDeps: [(formula: String, binary: String, key: String)] = [
- ("xcodegen", "xcodegen", "dep.xcodegen"),
- ("zstd", "zstd", "dep.zstd"),
- ("spirv-cross", "spirv-cross", "dep.spirv"),
- ("glslang", "glslangValidator", "dep.glslang"),
- ]
-
- /// The interpreter probe: lz4 / capstone / fontTools / zbic always, and zstd from either source —
- /// `compression.zstd` is built in from Python 3.14 and `backports.zstd` (which declares
- /// Python < 3.14) is the only option before that. Requiring the backport unconditionally
- /// rejected an otherwise working Homebrew Python 3.15 (issue #1).
- /// zbic is required although only a game with system 22.0.0+ modules (ZBIC segments, Nintendo's zstd variant) needs it:
- /// the launcher cannot know that before the extraction, and the build stops late without it (issue #251).
- /// nsz is deliberately not required here: it is only needed for NSZ / XCZ dumps, and the
- /// pipeline says so by name when one shows up. The venv installs it anyway so that a player
- /// who downloads a compressed dump never meets that error.
- nonisolated static let importProbe = """
- import lz4, capstone, fontTools, zbic
- try:
- from compression import zstd
- except ImportError:
- from backports import zstd
- """
-
- /// The interpreter the packages are installed into when no system Python has them. A venv
- /// rather than `pip install --user`: Homebrew's Python is externally managed (PEP 668) and
- /// refuses --user, and this leaves the user's environment untouched. Injectable so tests can
- /// use a scratch directory.
- nonisolated static var venvDir = NSHomeDirectory() + "/Library/Application Support/NS Port Builder/venv"
-
- nonisolated static func venvPython() -> String { venvDir + "/bin/python3" }
-
- /// Where uv keeps the Pythons it installs (`uv python install`): the shims in `~/.local/bin`
- /// and the store the real binaries live in, which `UV_PYTHON_INSTALL_DIR` moves. A uv user
- /// often has neither python.org's framework nor Homebrew, and a GUI launch's PATH is
- /// /usr/bin:/bin:/usr/sbin:/sbin, so neither `which` nor the locations below see them: a
- /// working uv Python 3.12 was reported as "No Python 3.12 or newer found". Injectable so a
- /// test can point them at a scratch tree.
- nonisolated static var uvShimDir = NSHomeDirectory() + "/.local/bin"
- nonisolated static var uvPythonRoot: String = {
- let dir = ProcessInfo.processInfo.environment["UV_PYTHON_INSTALL_DIR"] ?? ""
- return dir.isEmpty ? NSHomeDirectory() + "/.local/share/uv/python" : dir
- }()
-
- /// Where mise and asdf keep the Pythons they install, and mise's shims. `MISE_DATA_DIR` and
- /// `ASDF_DATA_DIR` move them. A GUI launch's PATH does not include the shims directory, so a
- /// Python managed by either was not found at all (issue #113). Injectable for tests.
- nonisolated static var miseDataDir: String = {
- let dir = ProcessInfo.processInfo.environment["MISE_DATA_DIR"] ?? ""
- return dir.isEmpty ? NSHomeDirectory() + "/.local/share/mise" : dir
- }()
- nonisolated static var asdfDataDir: String = {
- let dir = ProcessInfo.processInfo.environment["ASDF_DATA_DIR"] ?? ""
- return dir.isEmpty ? NSHomeDirectory() + "/.asdf" : dir
- }()
-
- nonisolated static func importsOK(_ py: String) -> Bool {
- runOK(py, ["-c", importProbe], env: ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: py)) { $1 })
- }
-
- /// backports.zstd declares Python < 3.14, so it is only installed where it is needed.
- /// nsz is always installed: NSZ / XCZ dumps are accepted by the pipeline now, and a player who
- /// downloads one should not have to run pip by hand (it is a few hundred KB).
- nonisolated static func pipPackages(_ version: (Int, Int)) -> [String] {
- version < (3, 14) ? ["lz4", "capstone", "fonttools", "zbic", "backports.zstd", "nsz"]
- : ["lz4", "capstone", "fonttools", "zbic", "nsz"]
- }
-
- /// Create the venv (reusing an existing one) and install the packages into it. Returns the
- /// combined output so a failure can be shown instead of swallowed — the pip output used to go
- /// to a pipe nobody read, and `externally-managed-environment` never reached the user.
- nonisolated static func makeVenv(base: String) -> (ok: Bool, log: String) {
- var log = ""
- func run(_ exe: String, _ args: [String]) -> Bool {
- let p = Process(); p.executableURL = URL(fileURLWithPath: exe); p.arguments = args
- let out = Pipe(), err = Pipe()
- p.standardOutput = out; p.standardError = err; p.standardInput = FileHandle.nullDevice
- p.environment = ["PATH": toolPath(python: base), "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: base)) { $1 }
- do { try p.run() } catch { log += "could not start \(exe): \(error.localizedDescription)\n"; return false }
- // both pipes are drained on this thread (before waitUntilExit, so the child cannot
- // block on a full pipe), and the log string keeps a single owner
- let outData = out.fileHandleForReading.readDataToEndOfFile()
- let errData = err.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
- log += String(data: outData, encoding: .utf8) ?? ""
- log += String(data: errData, encoding: .utf8) ?? ""
- return p.terminationStatus == 0
- }
- let vpy = venvPython()
- // An existing venv below minPython (built from Apple's 3.9 by an older app, issue #75) is
- // moved aside and rebuilt: pip into it would "succeed" and the build would still fail.
- // Moved, never deleted, because the folder is the user's. Only when a usable base exists,
- // so a Mac with no new Python keeps its old venv instead of losing it for nothing.
- if FileManager.default.isExecutableFile(atPath: vpy), pythonVersion(vpy).map({ $0 < minPython }) ?? true {
- guard let interp = venvBase(preferred: base), interp != vpy else {
- return (false, log + "\(venvDir) is older than Python \(minPython.0).\(minPython.1) and no newer Python was found to rebuild it from\n")
- }
- let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-")
- let aside = venvDir + ".old-" + stamp
- do { try FileManager.default.moveItem(atPath: venvDir, toPath: aside) } catch {
- return (false, log + "could not move \(venvDir) aside: \(error.localizedDescription)\n")
- }
- log += "moved the old venv (Python below \(minPython.0).\(minPython.1)) to \(aside)\n"
- }
- if !FileManager.default.isExecutableFile(atPath: vpy) {
- // findPython() returns the venv path it hopes to create when no interpreter was
- // found, and the panel hands that to this function. It cannot be a base: `-m venv`
- // failed with "could not start …" and the Python row never recovered.
- guard let interp = venvBase(preferred: base) else {
- return (false, log + "no Python \(minPython.0).\(minPython.1) or newer to create \(venvDir) from\n")
- }
- if interp != base { log += "\(base) is not a usable interpreter; using \(interp)\n" }
- log += "$ \(interp) -m venv \(venvDir)\n"
- try? FileManager.default.createDirectory(atPath: (venvDir as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
- guard run(interp, ["-m", "venv", venvDir]) else { return (false, log + "venv creation failed\n") }
- }
- let pkgs = pipPackages(pythonVersion(vpy) ?? minPython).joined(separator: " ")
- log += "$ \(vpy) -m pip install \(pkgs)\n"
- let ok = run(vpy, ["-m", "pip", "install"] + pipPackages(pythonVersion(vpy) ?? minPython))
- return (ok && importsOK(vpy), log)
- }
-
- /// "3.12.4" → (3, 12). nil when the interpreter cannot be run.
- nonisolated static func pythonVersion(_ path: String) -> (Int, Int)? {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: path)
- p.arguments = ["-c", "import sys; print('%d.%d' % sys.version_info[:2])"]
- p.environment = ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: path)) { $1 }
- let pipe = Pipe()
- p.standardOutput = pipe; p.standardError = Pipe()
- p.standardInput = FileHandle.nullDevice
- guard (try? p.run()) != nil else { return nil }
- p.waitUntilExit()
- guard p.terminationStatus == 0 else { return nil }
- let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
- let parts = out.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ".")
- guard parts.count == 2, let a = Int(parts[0]), let b = Int(parts[1]) else { return nil }
- return (a, b)
- }
-
- /// The interpreter to create the venv from. `preferred` is what the panel picked; when
- /// findPython() found nothing that is the venv path it hopes to create, which cannot be a
- /// base (see makeVenv). So a base that does not run at the required version falls back to
- /// the newest candidate that does. nil when this Mac has no such interpreter at all.
- nonisolated static func venvBase(preferred: String) -> String? {
- if FileManager.default.isExecutableFile(atPath: preferred),
- let v = pythonVersion(preferred), v >= minPython {
- return preferred
- }
- return pythonCandidates().first {
- FileManager.default.isExecutableFile(atPath: $0)
- && (pythonVersion($0).map { $0 >= minPython } ?? false)
- }
- }
-
- /// The `python3` / `python3.x` names in a directory, newest version first.
- nonisolated static func pythonNames(in dir: String, matching pattern: String) -> [String] {
- let names = (try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? []
- return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }
- .sorted { $0.compare($1, options: .numeric) == .orderedDescending }
- }
-
- /// uv's managed Pythons: the shims in `uvShimDir` and every install under `uvPythonRoot`
- /// (`cpython-3.12.13-macos-aarch64-none/bin/python3.12`). A uv user often has neither
- /// python.org's framework nor Homebrew, and a GUI launch's PATH does not contain
- /// `~/.local/bin`, so nothing else on this Mac finds them.
- nonisolated static func uvPythonCandidates() -> [String] {
- var out = pythonNames(in: uvShimDir, matching: #"^python3(\.\d+)?$"#).map { uvShimDir + "/" + $0 }
- let installs = (try? FileManager.default.contentsOfDirectory(atPath: uvPythonRoot)) ?? []
- for d in installs.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
- let bin = uvPythonRoot + "/" + d + "/bin"
- out += pythonNames(in: bin, matching: #"^python3(\.\d+)?$"#).map { bin + "/" + $0 }
- }
- return out
- }
-
- /// Pythons managed by mise (installs, then its shims) and asdf (installs only: an asdf shim is
- /// a script that needs `asdf` on the PATH, which a GUI launch lacks). Only the interpreter
- /// names are taken, never `python3-config` and the other files that share the folder.
- nonisolated static func versionManagerPythonCandidates() -> [String] {
- var out: [String] = []
- let strict = #"^python3(\.\d+)?$"#
- for root in [miseDataDir + "/installs/python", asdfDataDir + "/installs/python"] {
- let installs = (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? []
- for d in installs.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
- let bin = root + "/" + d + "/bin"
- out += pythonNames(in: bin, matching: strict).map { bin + "/" + $0 }
- }
- }
- let shims = miseDataDir + "/shims"
- out += pythonNames(in: shims, matching: strict).map { shims + "/" + $0 }
- return out
- }
-
- /// Every interpreter a build could run under, best first: python.org's framework, Homebrew,
- /// /usr/local, uv's store, mise and asdf, then whatever `which` can see. Probed by hand because a GUI app
- /// does not inherit the shell's PATH — the same reason .NET (in ~/.dotnet) used to show as
- /// missing while a terminal saw it.
- nonisolated static func pythonCandidates() -> [String] {
- var cands: [String] = []
- let fw = "/Library/Frameworks/Python.framework/Versions"
- if let vers = try? FileManager.default.contentsOfDirectory(atPath: fw) {
- for v in vers.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
- cands.append(fw + "/" + v + "/bin/python3")
- }
- }
- cands += ["/opt/homebrew/bin/python3", "/usr/local/bin/python3", "/usr/bin/python3"]
- // Homebrew's [email protected] is always python3.x, but the bare python3 link exists only for
- // the formula that is linked: a 3.12 beside an unlinked default would go unseen.
- for dir in ["/opt/homebrew/bin", "/usr/local/bin"] {
- cands += pythonNames(in: dir, matching: #"^python3\.\d+$"#).map { dir + "/" + $0 }
- }
- cands += uvPythonCandidates()
- cands += versionManagerPythonCandidates()
- let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/which")
- p.arguments = ["-a", "python3"]
- let pipe = Pipe()
- p.standardOutput = pipe; p.standardError = Pipe()
- p.standardInput = FileHandle.nullDevice
- if (try? p.run()) != nil {
- p.waitUntilExit()
- let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
- cands += out.split(separator: "\n").map(String.init)
- }
- return cands
- }
-
- /// Every python3 on this Mac, newest-looking first, each tried for a usable version and the
- /// packages. Returns the one to build with, plus why the others were rejected for the message.
- nonisolated static func findPython(resources: URL? = BundledTools.resources) -> (path: String, ok: Bool) {
- // The release app's own Python (BundledTools.swift) has every package and is the one the build is tested with: it wins over
- // any Python on this Mac and needs no venv. One that does not run (a damaged copy) falls through to the search below
- // (uv's Pythons, the other candidates, then the venv).
- if let bundled = BundledTools.python(in: resources), pythonVersion(bundled).map({ $0 >= minPython }) == true, importsOK(bundled) {
- return (bundled, true)
- }
- var seen = Set<String>()
- var fallback: (String, (Int, Int))? = nil // newest with an acceptable version but no packages
- for c in pythonCandidates() where !c.isEmpty && seen.insert(c).inserted {
- guard FileManager.default.isExecutableFile(atPath: c), let v = pythonVersion(c) else { continue }
- guard v >= minPython else { continue }
- if importsOK(c) { return (c, true) }
- if fallback == nil || v > fallback!.1 { fallback = (c, v) }
- }
- // No system interpreter has the packages: the venv (existing, or created by 安装) is next.
- let vpy = venvPython()
- // A venv below minPython is not ready however complete its packages are: an older app
- // version made it from Apple's 3.9, and the build script refuses that (issue #75). It
- // falls through to the candidates above, or to the row saying the Python is too old.
- if FileManager.default.isExecutableFile(atPath: vpy), let v = pythonVersion(vpy), v >= minPython {
- if importsOK(vpy) { return (vpy, true) }
- return (vpy, false) // exists but incomplete: 安装 finishes it
- }
- return (fallback?.0 ?? vpy, false)
- }
-
- /// The runtime root of a dotnet installation, parsed from `dotnet --list-runtimes`. It cannot
- /// be assumed to be the binary's directory: Homebrew's /opt/homebrew/bin/dotnet is a symlink
- /// into Cellar, and the runtime lives in …/libexec, so a hardcoded ~/.dotnet left the apphost
- /// without a runtime and nx_extract died with exit code 131 (issue #2).
- nonisolated static func parseDotnetRoot(_ listRuntimes: String) -> String? {
- for ln in listRuntimes.split(separator: "\n") {
- guard ln.hasPrefix("Microsoft.NETCore.App"), let a = ln.firstIndex(of: "["), let b = ln.lastIndex(of: "]") else { continue }
- let p = String(ln[ln.index(after: a)..<b])
- for suffix in ["/shared/Microsoft.NETCore.App", "\\shared\\Microsoft.NETCore.App"] where p.hasSuffix(suffix) {
- return String(p.dropLast(suffix.count))
- }
- return p
- }
- return nil
- }
-
- nonisolated static func dotnetRoot(for dotnet: String) -> String? {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: dotnet)
- p.arguments = ["--list-runtimes"]
- let pipe = Pipe()
- p.standardOutput = pipe; p.standardError = Pipe(); p.standardInput = FileHandle.nullDevice
- p.environment = ["HOME": NSHomeDirectory(), "PATH": "/usr/bin:/bin", "TMPDIR": NSTemporaryDirectory()]
- guard (try? p.run()) != nil else { return nil }
- p.waitUntilExit()
- guard p.terminationStatus == 0 else { return nil }
- let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
- // No directory fallback: for Homebrew's symlink layout the binary's directory is not the root,
- // and a wrong DOTNET_ROOT is worse than none (the apphost stops searching once it is set).
- // When this returns nil the pipeline derives and verifies a root itself.
- return parseDotnetRoot(out)
- }
-
- nonisolated static func findDotnet() -> (path: String, ok: Bool) {
- let cands = [NSHomeDirectory() + "/.dotnet/dotnet",
- "/usr/local/share/dotnet/dotnet",
- "/opt/homebrew/bin/dotnet",
- "/usr/local/bin/dotnet"]
- if let d = firstExisting(cands) {
- // the extractor targets net10.0, so an SDK (not just a runtime) is needed
- let ok = runOK(d, ["--list-sdks"], env: ["DOTNET_ROOT": (d as NSString).deletingLastPathComponent,
- "PATH": "/usr/bin:/bin", "HOME": NSHomeDirectory(),
- "TMPDIR": NSTemporaryDirectory()])
- return (d, ok)
- }
- return ("dotnet", false)
- }
-
- /// Whether the selected developer directory exists (`xcode-select -p`), which is the same
- /// source of truth xcodebuild and xcrun use — so an Xcode beta, a custom location, or a
- /// Command Line Tools-only setup is reported for what it is instead of "no Xcode".
- nonisolated static func developerDir() -> String? {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")
- p.arguments = ["-p"]
- let pipe = Pipe()
- p.standardOutput = pipe
- p.standardError = FileHandle.nullDevice
- do { try p.run() } catch { return nil }
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
- guard p.terminationStatus == 0,
- let dir = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
- !dir.isEmpty else { return nil }
- var isDir: ObjCBool = false
- return FileManager.default.fileExists(atPath: dir, isDirectory: &isDir) && isDir.boolValue ? dir : nil
- }
-
- nonisolated static func developerDirExists() -> Bool { developerDir() != nil }
-
- /// An Xcode.app that is installed but not selected: an App Store download arrives as
- /// /Applications/Xcode.app and stays unused until someone opens it or points xcode-select at
- /// it, so `xcode-select -p` keeps saying CommandLineTools and xcodebuild fails later.
- nonisolated static func installedXcode() -> String? {
- for app in ["/Applications/Xcode.app", "/Applications/Xcode-beta.app"]
- where FileManager.default.isExecutableFile(atPath: app + "/Contents/Developer/usr/bin/xcodebuild") {
- return app
- }
- let apps = (try? FileManager.default.contentsOfDirectory(atPath: "/Applications")) ?? []
- for name in apps.sorted() where name.hasPrefix("Xcode") && name.hasSuffix(".app") {
- let app = "/Applications/" + name
- if FileManager.default.isExecutableFile(atPath: app + "/Contents/Developer/usr/bin/xcodebuild") { return app }
- }
- return nil
- }
-
- /// What the Xcode row is looking at: the selected developer directory, the Xcode that is only
- /// installed, and whether the iOS SDK answers. Pure, so the four cases are tested.
- enum XcodeState: Equatable {
- case ready
- case noIOSSDK(selected: String) // Xcode selected, its iOS platform not downloaded
- case commandLineToolsOnly(xcode: String) // Xcode.app installed, xcode-select still on the CLT
- case notInstalled
- }
-
- nonisolated static func xcodeState(selected: String?, xcodeApp: String?, iosSDK: Bool) -> XcodeState {
- if let selected, selected.contains(".app/Contents/Developer") {
- return iosSDK ? .ready : .noIOSSDK(selected: selected)
- }
- if let xcodeApp { return .commandLineToolsOnly(xcode: xcodeApp) }
- return iosSDK ? .ready : .notInstalled // a CLT whose xcrun does answer the SDK is usable
- }
-
- /// The commands that fetch Xcode's two downloadable parts; the setup panel and the guided setup run the same ones.
- nonisolated static let metalToolchainCmd = ["/usr/bin/xcodebuild", "-downloadComponent", "MetalToolchain"]
- nonisolated static let iosPlatformCmd = ["/usr/bin/xcodebuild", "-downloadPlatform", "iOS"]
-
- /// One admin prompt runs both steps: switch the toolchain to this Xcode, then let it finish its first launch (license and
- /// components) - a fresh App Store download has neither. The Xcode row and the failure card run the same command.
- nonisolated static func selectXcodeCmd(_ xcode: String) -> [String] {
- let script = "xcode-select -s '" + xcode + "/Contents/Developer' && xcodebuild -runFirstLaunch"
- let apple = "do shell script \"" + script.replacingOccurrences(of: "\"", with: "\\\"") + "\" with administrator privileges"
- return ["/usr/bin/osascript", "-e", apple]
- }
-
/// Whether the xcode row asks for the iOS SDK. Always, as before, unless the guided setup stored a Mac-only choice
/// and builds are for the Mac: upstream no longer needs the iOS SDK for a Mac build (c464cb24).
nonisolated static func needsIOSPlatform(defaults: UserDefaults = .standard) -> Bool {
@@ -2756,49 +2045,11 @@ final class BuildModel: ObservableObject {
return BuildTarget.normalized(defaults.string(forKey: "buildTarget")) != BuildTarget.mac
}
- /// The rows for the build tools (xcodegen, zstd, spirv-cross, glslangValidator) and the Homebrew row they may need.
- /// A tool the app carries counts as present and says "bundled"; otherwise Homebrew's copy counts (`installed` answers
- /// a binary name with its path in a Homebrew folder, or nil). The Homebrew row appears only when some tool is neither
- /// bundled nor installed (with a bundle; with none the row stays, as before): it is the way to get that one.
- nonisolated static func toolDeps(resources: URL?, installed: (String) -> String?, brew: String?) -> [Dep] {
- var rows: [Dep] = []
- var needsBrew = false, anyBundled = false
- for (pkg, binary, key) in brewDeps {
- let bundled = BundledTools.tool(binary, in: resources) != nil
- let path = bundled ? nil : installed(binary)
- if !bundled && path == nil { needsBrew = true }
- if bundled { anyBundled = true }
- // A bundled tool is named by the tool; "brew: …" says where a Homebrew copy comes from, so it stays for the rows that
- // refer to one (installed there, or missing with the install button)
- rows.append(Dep(id: "brew:" + pkg, name: bundled ? "dep.tool." + binary : key, hint: key + ".hint", present: bundled || path != nil,
- detail: bundled ? "dep.bundled" : (path ?? ""),
- installCmd: [(brew ?? "/opt/homebrew/bin/brew"), "install", pkg]))
- }
- guard needsBrew || !anyBundled else { return rows } // without a bundle the row is always there, as it was
- return [Dep(id: "brew", name: "dep.brew", hint: "dep.brew.hint", present: brew != nil,
- installCmd: ["/bin/bash", "-c",
- "NONINTERACTIVE=1 /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""])] + rows
- }
-
- /// First line of a tool's output (the Metal compiler's version line), nil when it does not run or says nothing.
- nonisolated static func firstOutputLine(_ tool: String, _ args: [String]) -> String? {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: tool)
- p.arguments = args
- let out = Pipe()
- p.standardOutput = out; p.standardError = Pipe(); p.standardInput = FileHandle.nullDevice
- do { try p.run() } catch { return nil }
- let data = out.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
- guard p.terminationStatus == 0 else { return nil }
- return String(decoding: data, as: UTF8.self).split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
- }
-
/// The Metal toolchain row. A compiler that does not run is the missing-toolchain row with its install button. One that differs from the
/// lock's pin is a warning and not a blocker: the row stays present, and its error and hint lines (the install failures' fields) say that
/// NVN games will stop. Pure over its inputs, so tests give it version strings.
nonisolated static func metalDep(runs: Bool, lock: String?, now: [String: String?], needsIOS: Bool) -> Dep {
- var dep = Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint", present: runs, installCmd: metalToolchainCmd)
+ var dep = Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint", present: runs, installCmd: Toolchain.metalToolchainCmd)
guard runs, let lock, let m = MetalPin.mismatches(lock: lock, now: now, iOS: needsIOS).first else { return dep }
dep.warning = true
dep.detail = "dep.metal.other:" + m.now + ":" + m.pinned
@@ -2815,69 +2066,59 @@ final class BuildModel: ObservableObject {
// xcodebuild. Ask for the SDK version itself — that is the check that matches the name.
// And ask xcode-select where Xcode is, not a fixed path: a beta lives at
// /Applications/Xcode-beta.app and the hard-coded check called that "no Xcode" (#21).
- let selected = Self.developerDir()
- let xcodeApp = Self.installedXcode()
- let sdkenv = runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"])
+ let selected = Toolchain.developerDir()
+ let xcodeApp = Toolchain.installedXcode()
+ let sdkenv = Toolchain.runOK("/usr/bin/xcrun", ["--sdk", "iphoneos", "--show-sdk-version"])
// A Mac-only setup does not need the iOS platform (onboarding's platform choice, #120); a
// Mac build still needs a selected Xcode, so the CommandLineTools state is reported either way.
- switch Self.xcodeState(selected: selected, xcodeApp: xcodeApp, iosSDK: !needsIOS || sdkenv) {
+ switch Toolchain.xcodeState(selected: selected, xcodeApp: xcodeApp, iosSDK: !needsIOS || sdkenv) {
case .ready:
out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []))
case .noIOSSDK:
out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,
- detail: "dep.xcode.noSDK", installCmd: iosPlatformCmd))
+ detail: "dep.xcode.noSDK", installCmd: Toolchain.iosPlatformCmd))
case .commandLineToolsOnly(let xcode):
out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,
detail: "dep.xcode.notSelected", actionLabel: "dep.xcode.fix",
- installCmd: selectXcodeCmd(xcode)))
+ installCmd: Toolchain.selectXcodeCmd(xcode)))
case .notInstalled:
out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: []))
}
- let macMetal = firstOutputLine("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])
+ let macMetal = Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])
let lock = repo.isEmpty ? nil : try? String(contentsOfFile: EngineLayout.root(repo) + "/" + MetalPin.lockPath, encoding: .utf8)
- let iosMetal = needsIOS && lock != nil ? firstOutputLine("/usr/bin/xcrun", ["-sdk", "iphoneos", "metal", "--version"]) : nil
+ let iosMetal = needsIOS && lock != nil ? Toolchain.firstOutputLine("/usr/bin/xcrun", ["-sdk", "iphoneos", "metal", "--version"]) : nil
out.append(metalDep(runs: macMetal != nil, lock: lock, now: ["macosx": macMetal, "iphoneos": iosMetal], needsIOS: needsIOS))
- out += toolDeps(resources: BundledTools.resources,
- installed: { firstExisting(["/opt/homebrew/bin/\($0)", "/usr/local/bin/\($0)"]) },
- brew: firstExisting(["/opt/homebrew/bin/brew", "/usr/local/bin/brew"]))
+ out += Toolchain.toolDeps(resources: BundledTools.resources,
+ installed: { Toolchain.firstExisting(["/opt/homebrew/bin/\($0)", "/usr/local/bin/\($0)"]) },
+ brew: Toolchain.firstExisting(["/opt/homebrew/bin/brew", "/usr/local/bin/brew"]))
- let (dn, dnOK) = findDotnet()
+ let (dn, dnOK) = Toolchain.findDotnet()
out.append(Dep(id: "dotnet", name: "dep.dotnet", hint: "dep.dotnet.hint",
present: dnOK, detail: dnOK ? dn : "dep.dotnet.missing",
installCmd: ["/bin/bash", "-c",
"curl -sSL https://dot.net/v1/dotnet-install.sh -o /tmp/di.sh && chmod +x /tmp/di.sh && /tmp/di.sh --channel 10.0 --install-dir $HOME/.dotnet"]))
- let (py, pyOK) = findPython()
+ let (py, pyOK) = Toolchain.findPython()
// A too-old interpreter is a different problem from a missing package: say which one it is,
// because the fix differs (install a newer Python vs pip install into this one).
// A version we cannot read means no interpreter ran at all (py is then the venv
// that does not exist yet), which is not the same as one that is too old.
- let pyDetail = pythonDetail(py: py, ok: pyOK)
+ let pyDetail = Toolchain.pythonDetail(py: py, ok: pyOK)
out.append(Dep(id: "python", name: "dep.python", hint: "dep.python.hint",
present: pyOK, detail: pyDetail,
installCmd: [py, "-m", "pip", "install", "--user", "lz4", "capstone", "fonttools", "zbic", "backports.zstd"]))
return out
}
- nonisolated static func pythonDetail(py: String, ok: Bool) -> String {
- let pyVer = pythonVersion(py).map { "\($0.0).\($0.1)" } ?? "?"
- let minVer = "\(minPython.0).\(minPython.1)"
- return ok ? (py == BundledTools.python() ? "dep.bundled" : py)
- : pythonVersion(py).map { $0 >= minPython
- ? "dep.python.missing:\(py) (\(pyVer))"
- : "dep.python.old:\(pyVer):\(minVer)" }
- ?? "dep.python.notFound:\(minVer):\(minVer)"
- }
-
func checkDeps() {
depsChecked = false
DispatchQueue.global(qos: .userInitiated).async {
let d = Self.detectDepsSync(repo: self.repoPath)
Self.writeDepsReport(d)
- let (py, _) = Self.findPython()
- let (dn, _) = Self.findDotnet()
+ let (py, _) = Toolchain.findPython()
+ let (dn, _) = Toolchain.findDotnet()
DispatchQueue.main.async {
self.deps = d
self.pythonPath = py // the interpreter the build runs under
@@ -2894,18 +2135,18 @@ final class BuildModel: ObservableObject {
/// gives the app (its PATH is /usr/bin:/bin:/usr/sbin:/sbin, unlike the terminal's), are both
/// invisible in a bug report. This file has them — paths and versions only, never key material.
nonisolated static func writeDepsReport(_ deps: [Dep]) {
- let dir = (venvDir as NSString).deletingLastPathComponent
+ let dir = (Toolchain.venvDir as NSString).deletingLastPathComponent
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
var out = "NX2Apple \(appVersion) dependency check\n"
out += "date: \(ISO8601DateFormatter().string(from: Date()))\n"
out += "HOME: \(NSHomeDirectory())\n"
out += "PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "(unset)")\n"
- let chosen = findPython()
+ let chosen = Toolchain.findPython()
let bundled = BundledTools.python()
out += "python chosen: \(chosen.path) (\(chosen.ok ? "ok" : "not usable")\(chosen.path == bundled ? ", bundled with the app" : ""))\n"
out += "bundled python: \(bundled ?? "(none: not the release app)")\n"
out += "python candidates (after the bundled one, in search order):\n"
- for c in pythonCandidates() { out += " \(c)\n" }
+ for c in Toolchain.pythonCandidates() { out += " \(c)\n" }
out += "rows:\n"
for d in deps { out += " \(d.id): \(d.present ? "ok" : "MISSING") \(d.detail)\n" }
try? out.write(toFile: dir + "/deps-check.txt", atomically: true, encoding: .utf8)
@@ -2924,7 +2165,7 @@ final class BuildModel: ObservableObject {
if dep.id == "python" {
// A venv of our own rather than pip --user: Homebrew's Python is externally
// managed (PEP 668) and refuses --user, which used to fail silently.
- let r = Self.makeVenv(base: self.pythonPath)
+ let r = Toolchain.makeVenv(base: self.pythonPath)
DispatchQueue.main.async { self.append("\n--- 安装输出 ---\n" + r.log) }
ok = r.ok
} else {
@@ -2937,7 +2178,7 @@ final class BuildModel: ObservableObject {
collected.append(line)
DispatchQueue.main.async { self.append(line + "\n") }
}
- let (error, fix) = Self.failureInfo(collected.lines)
+ let (error, fix) = BuildProgress.failureInfo(collected.lines)
DispatchQueue.main.async {
if let j = self.deps.firstIndex(where: { $0.id == dep.id }) {
self.deps[j].lastError = ok ? "" : error
@@ -2954,34 +2195,6 @@ final class BuildModel: ObservableObject {
}
}
- /// The line a failed install should show, and the fix to offer beside it.
- ///
- /// A GUI user sees a spinner turn back into a button; the reason (brew refusing a directory it
- /// does not own is the common one) lived only in the log. Prefer the tool's own `Error:` line,
- /// and map the few causes we can name to the exact command.
- nonisolated static func failureInfo(_ lines: [String]) -> (error: String, fix: String) {
- let meaningful = lines.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
- let error = meaningful.first { $0.hasPrefix("Error:") }
- ?? meaningful.first { $0.lowercased().contains("error") }
- ?? meaningful.last ?? ""
- let lower = lines.joined(separator: "\n").lowercased()
- let fix: String
- if lower.contains("/opt/homebrew is not writable") || lower.contains("permission denied @ dir_initialize")
- || lower.contains("/usr/local is not writable") {
- fix = "dep.fix.brewOwner"
- } else if lower.contains("command not found") || lower.contains("brew: not found") {
- fix = "dep.fix.brewMissing"
- } else if lower.contains("agreeing to the xcode license") || lower.contains("xcode license") {
- fix = "dep.fix.xcodeLicense"
- } else if lower.contains("could not resolve host") || lower.contains("failed to download")
- || lower.contains("operation timed out") {
- fix = "dep.fix.network"
- } else {
- fix = "dep.fix.log"
- }
- return (error, fix)
- }
-
/// The output lines seen so far, from the pipe's threads and read on the main queue.
final class LineBox: @unchecked Sendable {
private let lock = NSLock()
diff --git a/frontend/Sources/NX2Apple/Diagnostics.swift b/frontend/Sources/NX2Apple/Diagnostics.swift
index d1e0d0da..9e2eff1a 100644
--- a/frontend/Sources/NX2Apple/Diagnostics.swift
+++ b/frontend/Sources/NX2Apple/Diagnostics.swift
@@ -26,7 +26,7 @@ struct Diagnostics {
var engine: String? // the release app's engine: "<channel> <version> (<engine_id>)"
var python: String
var pythonVersion: String?
- var pythonIsVenv = false // the launcher's own venv (BuildModel.venvDir)
+ var pythonIsVenv = false // the launcher's own venv (Toolchain.venvDir)
var dotnet: String
var dotnetVersion: String?
var depsChecked = true
@@ -191,7 +191,7 @@ struct Diagnostics {
}
/// A dependency row in English: its name and what the check said (a path, or a message with its argument).
- static func dependency(_ d: BuildModel.Dep) -> Dependency {
+ static func dependency(_ d: Dep) -> Dependency {
let en = { (key: String) in L10n.string(key, .en) }
var detail = d.detail
if let colon = detail.firstIndex(of: ":"), !detail.hasPrefix("/"), L10n.table[String(detail[..<colon])] != nil {
@@ -296,7 +296,7 @@ struct Diagnostics {
extension BuildModel {
/// The report, read in the background and handed back on the main thread.
func diagnostics(game: LibraryGame? = nil, _ done: @escaping (String) -> Void) {
- let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Self.findPython().path : pythonPath, dotnet = dotnetPath
+ let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath, dotnet = dotnetPath
let rows = depsChecked ? deps.map(Diagnostics.dependency) : [], checked = depsChecked
let command = lastBuildCommand, log = logTail, xcrun = xcrunPath
let sel = engineSelection
@@ -317,7 +317,7 @@ extension BuildModel {
engine: engine,
python: python,
pythonVersion: Diagnostics.version(python, ["-c", "import sys; print(sys.version.split()[0])"], env: env),
- pythonIsVenv: python == Self.venvPython(),
+ pythonIsVenv: python == Toolchain.venvPython(),
dotnet: dotnet,
dotnetVersion: dotnet.isEmpty ? nil : Diagnostics.version(dotnet, ["--version"], env: dotnetEnv),
depsChecked: checked, deps: rows,
diff --git a/frontend/Sources/NX2Apple/DropFiles.swift b/frontend/Sources/NX2Apple/DropFiles.swift
index 854afdf9..89d53be3 100644
--- a/frontend/Sources/NX2Apple/DropFiles.swift
+++ b/frontend/Sources/NX2Apple/DropFiles.swift
@@ -5,7 +5,7 @@ import NXLauncher
// Game files dropped on the Builds page (issue #68): NSP, NSZ and XCI files, a folder, prod.keys, in any
// mix. They are sorted into the slots by the same classification as Choose game folder
-// (BuildModel.classify), so a drop and a picked folder never disagree about what is the update.
+// (GameInputs.classify), so a drop and a picked folder never disagree about what is the update.
extension BuildModel {
/// One dropped folder is the same as choosing it; anything else (files, several folders, a mix) is added to
@@ -16,13 +16,13 @@ extension BuildModel {
return FileManager.default.fileExists(atPath: p, isDirectory: &d) && d.boolValue
}
if paths.count == 1, isFolder(paths[0]) { scan(folder: paths[0]); return }
- var found = Self.classify(paths.flatMap { isFolder($0) ? Self.inputFiles(in: $0) : [$0] })
+ var found = GameInputs.classify(paths.flatMap { isFolder($0) ? GameInputs.inputFiles(in: $0) : [$0] })
// update and add-on files of another game than the base (the dropped one, else the one already chosen)
let baseName = (found.base ?? (basePath.isEmpty ? nil : basePath)).map { ($0 as NSString).lastPathComponent }
var rejected: [InputKind: String] = [:]
func fits(_ path: String, _ kind: InputKind) -> Bool {
let name = (path as NSString).lastPathComponent
- guard let why = Self.rowMismatch(kind, name: name, base: baseName) else { return true }
+ guard let why = GameInputs.rowMismatch(kind, name: name, base: baseName) else { return true }
if rejected[kind] == nil { rejected[kind] = rowProblemText(why, name: name) }
return false
}
@@ -35,7 +35,7 @@ extension BuildModel {
}
/// The slots after a drop of `found`. Nothing usable in it leaves the slots as they were, but says so on an empty base row.
- nonisolated static func merged(_ slots: [Slot], with found: FoundInputs) -> [Slot] {
+ nonisolated static func merged(_ slots: [Slot], with found: GameInputs.Found) -> [Slot] {
slots.map { s in
var s = s
switch s.id {
diff --git a/frontend/Sources/NX2Apple/Library.swift b/frontend/Sources/NX2Apple/Library.swift
index e25ea02f..e408a55c 100644
--- a/frontend/Sources/NX2Apple/Library.swift
+++ b/frontend/Sources/NX2Apple/Library.swift
@@ -387,7 +387,7 @@ final class GameLibrary: ObservableObject {
continue
}
guard packages.contains(url.pathExtension.lowercased()),
- let id = BuildModel.titleID(url.lastPathComponent), id & 0xfff == 0 else { continue }
+ let id = TitleID.parse(url.lastPathComponent), id & 0xfff == 0 else { continue }
let tid = String(format: "%016llX", id)
guard result[tid] == nil else { continue }
var game = LibraryGame(titleID: tid, name: title(for: url.path, repo: repo, titleID: tid))
@@ -397,7 +397,7 @@ final class GameLibrary: ObservableObject {
// root or at a folder that holds no more of them (issue: an auto-scanned game found no update or DLC).
let family = { (name: String) -> Bool in
guard packages.contains((name as NSString).pathExtension.lowercased()),
- let other = BuildModel.titleID(name) else { return false }
+ let other = TitleID.parse(name) else { return false }
return other == id || (other >= id + 0x800 && other < id + 0x1000) || (other >= id + 0x1000 && other < id + 0x2000)
}
var gameRoot = url.deletingLastPathComponent()
@@ -424,15 +424,15 @@ final class GameLibrary: ObservableObject {
}
}
let familyOf = { (u: URL, lo: UInt64, hi: UInt64) -> Bool in
- guard let other = BuildModel.titleID(u.lastPathComponent) else { return false }
+ guard let other = TitleID.parse(u.lastPathComponent) else { return false }
return other >= lo && other < hi
}
- let isBase = { (u: URL) -> Bool in BuildModel.titleID(u.lastPathComponent) == id }
+ let isBase = { (u: URL) -> Bool in TitleID.parse(u.lastPathComponent) == id }
game.inputs["base"] = ([url] + found.filter(isBase))
- .sorted { BuildModel.updateVersion($0.lastPathComponent) > BuildModel.updateVersion($1.lastPathComponent) }
+ .sorted { TitleID.updateVersion($0.lastPathComponent) > TitleID.updateVersion($1.lastPathComponent) }
.prefix(1).map(\.path)
game.inputs["update"] = found.filter { familyOf($0, id + 0x800, id + 0x1000) }
- .sorted { BuildModel.updateVersion($0.lastPathComponent) > BuildModel.updateVersion($1.lastPathComponent) }.prefix(1).map(\.path)
+ .sorted { TitleID.updateVersion($0.lastPathComponent) > TitleID.updateVersion($1.lastPathComponent) }.prefix(1).map(\.path)
game.inputs["dlc"] = found.filter { familyOf($0, id + 0x1000, id + 0x2000) }.map(\.path).sorted()
game.inputs["keys"] = [gameRoot.appendingPathComponent("prod.keys"), root.appendingPathComponent("keys/prod.keys"), root.appendingPathComponent("prod.keys"), gameRoot.appendingPathComponent("keys/prod.keys")]
.filter { FileManager.default.fileExists(atPath: $0.path) }.prefix(1).map(\.path)
@@ -492,7 +492,7 @@ final class GameLibrary: ObservableObject {
@discardableResult func rememberInputs(_ model: BuildModel) -> UUID? {
guard !model.basePath.isEmpty else { return nil }
- let titleID = BuildModel.titleID(model.basePath).map { String(format: "%016llX", $0) }
+ let titleID = TitleID.parse(model.basePath).map { String(format: "%016llX", $0) }
?? URL(fileURLWithPath: model.basePath).standardizedFileURL.path
var game = games.first { $0.titleID == titleID } ?? LibraryGame(titleID: titleID, name: Self.title(for: model.basePath, repo: model.repoPath, titleID: titleID))
game.inputs = Dictionary(uniqueKeysWithValues: model.slots.map { ($0.id, $0.paths) })
diff --git a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift
index c85afaae..77bd2c02 100644
--- a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift
+++ b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift
@@ -46,7 +46,7 @@ struct OnboardingEnvironment {
/// Detection again, finished when it has published (`BuildModel.checkDeps`).
var detectDeps: (BuildModel) async -> Void = { await $0.refreshDepsAndWait() }
/// One install through the launcher's own mechanics (`BuildModel.installDep`); its end shows as a new detection.
- var installDep: (BuildModel, BuildModel.Dep) -> Void = { $0.installDep($1) }
+ var installDep: (BuildModel, Dep) -> Void = { $0.installDep($1) }
var openURL: (URL) -> Void = { NSWorkspace.shared.open($0) }
var keyCheck: (_ keys: String, _ base: String) async -> KeyCheck.Outcome = { keys, base in
await Task.detached { KeyCheck.run(KeyCheck.Inputs(keys: keys, files: base.isEmpty ? [] : [base])) }.value
@@ -79,7 +79,7 @@ struct OnboardingEnvironment {
/// Xcode*.app that really work: the App Store creates the folder while Xcode is still downloading, so only an
/// `xcodebuild -version` that exits 0 counts.
static func xcodeApps(in directory: String = "/Applications") -> [String] {
- xcodeFolders(in: directory).filter { BuildModel.runOK($0 + "/Contents/Developer/usr/bin/xcodebuild", ["-version"]) }
+ xcodeFolders(in: directory).filter { Toolchain.runOK($0 + "/Contents/Developer/usr/bin/xcodebuild", ["-version"]) }
}
static func liveProbe() async -> XcodeProbe {
@@ -108,8 +108,8 @@ struct OnboardingEnvironment {
}
}
if probe.selectedIsXcode {
- probe.licenseAccepted = BuildModel.runOK("/usr/bin/xcodebuild", ["-license", "check"])
- probe.firstLaunchDone = BuildModel.runOK("/usr/bin/xcodebuild", ["-checkFirstLaunchStatus"])
+ probe.licenseAccepted = Toolchain.runOK("/usr/bin/xcodebuild", ["-license", "check"])
+ probe.firstLaunchDone = Toolchain.runOK("/usr/bin/xcodebuild", ["-checkFirstLaunchStatus"])
}
return probe
}.value
@@ -466,7 +466,7 @@ enum OnboardingLaunch {
// MARK: Xcode
- private func dep(_ id: String) -> BuildModel.Dep? { model.deps.first { $0.id == id } }
+ private func dep(_ id: String) -> Dep? { model.deps.first { $0.id == id } }
/// Every detection that finished: Xcode's state, the background tasks, and the next install.
func modelDidRefresh() async {
@@ -536,12 +536,12 @@ enum OnboardingLaunch {
}
let metalMissing = !(dep("metal")?.present ?? false)
if metalMissing {
- let r = await download(.metal, BuildModel.metalToolchainCmd)
+ let r = await download(.metal, Toolchain.metalToolchainCmd)
if !r.ok { return fail("onboarding.error.metal", r.output) }
}
let iosMissing = includesIOS && !(dep("xcode")?.present ?? false)
if iosMissing {
- let r = await download(.ios, BuildModel.iosPlatformCmd)
+ let r = await download(.ios, Toolchain.iosPlatformCmd)
if !r.ok { return fail("onboarding.error.ios", r.output) }
}
await env.detectDeps(model)
@@ -582,7 +582,7 @@ enum OnboardingLaunch {
/// The "tools" card is Homebrew and the brew formulas the build uses: every row that is none of Xcode, Python or .NET.
private static let handled: Set<String> = ["xcode", "metal", "python", "dotnet"]
- private func deps(for task: OnboardingBackgroundTask) -> [BuildModel.Dep] {
+ private func deps(for task: OnboardingBackgroundTask) -> [Dep] {
switch task {
case .python: return model.deps.filter { $0.id == "python" }
case .dotnet: return model.deps.filter { $0.id == "dotnet" }
diff --git a/frontend/Sources/NX2Apple/ShellInstall.swift b/frontend/Sources/NX2Apple/ShellInstall.swift
index 43eaf8b3..3e513ca9 100644
--- a/frontend/Sources/NX2Apple/ShellInstall.swift
+++ b/frontend/Sources/NX2Apple/ShellInstall.swift
@@ -480,7 +480,7 @@ struct ShellInstaller {
func sign(_ bundleID: String) -> ToolResult {
begin(Self.signStageID, signName)
return run(ShellInstall.buildCommand(xcrun: xcrun, root: root, device: device, team: team, bundleID: bundleID),
- env: nil, label: signName, step: BuildModel.xcodeStep)
+ env: nil, label: signName, step: BuildProgress.xcodeStep)
}
var bundleID = library.bundleID
var built = sign(bundleID)
@@ -519,7 +519,7 @@ struct ShellInstaller {
}
let installName = fmt("dev.installStage", deviceName)
begin(Self.installStageID, installName)
- let installed = run(ShellInstall.installCommand(xcrun: xcrun, device: device, app: app), env: nil, label: installName, step: BuildModel.installStep)
+ let installed = run(ShellInstall.installCommand(xcrun: xcrun, device: device, app: app), env: nil, label: installName, step: BuildProgress.installStep)
if installed.status != 0 {
let why = installed.lastError ?? fmt("msg.exitCode", installed.status)
end(Self.installStageID, installName, ok: false, detail: why)
@@ -609,7 +609,7 @@ struct ShellInstaller {
percent: Double(i) / Double(missing.count) * 100))
let r = run(ShellInstall.copyCommand(xcrun: xcrun, device: device, bundleID: bundleID, titleID: titleID,
source: archive + "/" + path, relativePath: path),
- env: nil, label: copyName, step: BuildModel.installStep)
+ env: nil, label: copyName, step: BuildProgress.installStep)
if r.status != 0 {
let why = r.lastError ?? fmt("msg.exitCode", r.status)
end(Self.copyStageID, copyName, ok: false, detail: why)
@@ -711,7 +711,7 @@ enum ShellCLI {
let archive = o["archive"]!
let root = o["shell-root"] ?? ShellLibrary.resolveRoot(
defaults: defaults, parent: ((archive as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent)
- let python = o["python"] ?? BuildModel.findPython().path
+ let python = o["python"] ?? Toolchain.findPython().path
var installer = ShellInstaller(xcrun: o["xcrun"] ?? "/usr/bin/xcrun", repo: o["repo"]!, python: python, root: root,
device: o["device"]!, team: o["team"]!)
installer.deviceName = o["device"]!
diff --git a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift
index 0e9148f9..f3953761 100644
--- a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift
+++ b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift
@@ -13,7 +13,7 @@ extension BuildModel {
guard let chain = StaleFrameworks.currentChain(engineRoot: EngineLayout.root(repoPath)) else { return [] }
let root = shellRoot
let known = ShellLibrary.load(root: root).games.map { (titleID: $0.titleID, name: $0.name, framework: $0.framework) }
- return StaleFrameworks.find(root: root, chain: chain, known: known, except: Self.buildKey(basePath))
+ return StaleFrameworks.find(root: root, chain: chain, known: known, except: TitleID.buildKey(basePath))
}
/// True when the build must wait for the player's answer: the prompt is showing (`staleFrameworks` is set).
diff --git a/frontend/Sources/NXCore/BuildProgress.swift b/frontend/Sources/NXCore/BuildProgress.swift
new file mode 100644
index 00000000..b1a1a462
--- /dev/null
+++ b/frontend/Sources/NXCore/BuildProgress.swift
@@ -0,0 +1,176 @@
+import Foundation
+
+package struct Stage: Identifiable {
+ package let id: Int // k, the stage number in the script's own plan
+ package var name: String
+ package var state: StepState = .running
+ package var detail: String = ""
+ package var percent: Double? = nil
+ package var started: Date? = nil // when the stage began here: its clock runs while the count may stand still
+ package var eta: Double? = nil // the script's estimate of the seconds left, as of etaAt
+ package var etaAt: Date? = nil
+
+ package init(id: Int, name: String, state: StepState = .running, detail: String = "", percent: Double? = nil,
+ started: Date? = nil, eta: Double? = nil, etaAt: Date? = nil) {
+ self.id = id; self.name = name; self.state = state; self.detail = detail; self.percent = percent
+ self.started = started; self.eta = eta; self.etaAt = etaAt
+ }
+
+ /// A stage's name in the launcher's language. The script names its stages in English (PROG.stage in
+ /// build_ipa_from_nsp.py): stage.<name> in the table, "extract <name>" and "<API> shader capture" with their
+ /// part kept; a name the table does not know (a newer script's) is shown as the script wrote it.
+ package static func localizedName(_ name: String, _ t: (String) -> String) -> String {
+ func known(_ key: String) -> String? { let s = t(key); return s == key ? nil : s }
+ let key = "stage." + name.lowercased().replacingOccurrences(of: "[^a-z0-9]+", with: "_", options: .regularExpression)
+ .trimmingCharacters(in: CharacterSet(charactersIn: "_"))
+ if let s = known(key) { return s }
+ if name.hasPrefix("extract "), let f = known("stage.extract") { return String(format: f, String(name.dropFirst("extract ".count))) }
+ if name.hasSuffix(" shader capture"), let f = known("stage.capture") { return String(format: f, String(name.dropLast(" shader capture".count))) }
+ return name
+ }
+
+ /// "3:42" since the stage began, then "1 min left" while the script's estimate, counted down from when it came,
+ /// lasts: the estimate only arrives with a new count, so one taken as it was would stand still with the count.
+ package func clock(at now: Date, left: String) -> String {
+ var parts: [String] = []
+ if let started {
+ let t = max(0, Int(now.timeIntervalSince(started)))
+ parts.append(t >= 3600 ? String(format: "%d:%02d:%02d", t / 3600, t / 60 % 60, t % 60) : String(format: "%d:%02d", t / 60, t % 60))
+ }
+ if let eta, let etaAt {
+ let remaining = eta - now.timeIntervalSince(etaAt)
+ if remaining >= 1 { parts.append(String(format: left, BuildProgress.duration(remaining))) }
+ }
+ return parts.joined(separator: " · ")
+ }
+}
+
+/// The state of one stage of a build. Its colour is in the app (`StepState.color`).
+package enum StepState: Equatable {
+ case pending, running, done, failed
+ package var icon: String {
+ switch self {
+ case .pending: return "circle"
+ case .running: return "spinner"
+ case .done: return "checkmark.circle.fill"
+ case .failed: return "xmark.octagon.fill"
+ }
+ }
+}
+
+/// Reading what a build prints: the script's stage lines and JSON events, durations, the steps of Xcode and the install, and what
+/// a failed install says. Pure functions of the text.
+package enum BuildProgress {
+ /// The last line of the log that says something: not blank, not a progress event. Used for the
+ /// failure note, where the exit code on its own is not actionable (issue #52).
+ package static func lastMeaningfulLine(_ log: String) -> String? {
+ for line in log.split(separator: "\n", omittingEmptySubsequences: true).reversed() {
+ let s = line.trimmingCharacters(in: .whitespaces)
+ if s.isEmpty || s.hasPrefix("{") { continue } // a --progress json event
+ return String(s.prefix(200))
+ }
+ return nil
+ }
+
+ /// "splitting · 1.2 / 3.4 GB", "1,203 / 19,592 shaders", "2,301 files": the step and the count (the time left is the Stage's clock).
+ package static func progressDetail(_ e: [String: Any]) -> String {
+ let step = e["step"] as? String ?? "", unit = e["unit"] as? String ?? "", note = e["note"] as? String ?? ""
+ let done = (e["done"] as? NSNumber)?.doubleValue, total = (e["total"] as? NSNumber)?.doubleValue
+ let estimate = (e["est"] as? Bool ?? false) ? "~" : ""
+ var count = ""
+ if let done {
+ if unit == "B" {
+ let bytes = { (v: Double) in ByteCountFormatter.string(fromByteCount: Int64(v), countStyle: .file) }
+ count = total.map { "\(bytes(done)) / \(estimate)\(bytes($0))" } ?? bytes(done)
+ } else {
+ let number = { (v: Double) in NumberFormatter.localizedString(from: NSNumber(value: Int(v)), number: .decimal) }
+ count = (total.map { "\(number(done)) / \(estimate)\(number($0))" } ?? number(done)) + (unit.isEmpty ? "" : " \(unit)")
+ }
+ }
+ return [step, count, note].filter { !$0.isEmpty }.joined(separator: " · ")
+ }
+
+ package static func duration(_ seconds: Double) -> String {
+ // Formatted by hand, not DateComponentsFormatter: the formatter follows the system
+ // locale, so a Chinese macOS wrote "4秒" into a log whose every other line was English
+ // (and the test that pinned "4s" failed on any non-English machine). The abbreviations
+ // are the interface language's, via the same string table as everything else.
+ let s = max(Int(seconds.rounded(.up)), 1)
+ if s >= 3600 {
+ let h = s / 3600, m = (s % 3600) / 60
+ return h > 0 && m > 0 ? "\(h)h \(m)m" : "\(h)h"
+ }
+ if s >= 60 {
+ let m = s / 60, sec = s % 60
+ return sec > 0 ? "\(m)m \(sec)s" : "\(m)m"
+ }
+ return "\(s)s"
+ }
+
+ package static func parseStage(_ line: String) -> (k: Int, name: String, state: StepState, detail: String, percent: Double?)? {
+ guard let re = try? NSRegularExpression(pattern: #"\[(\d+)/(\d+)\] (.+)$"#) else { return nil }
+ let ns = line as NSString
+ guard let m = re.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { return nil }
+ guard let k = Int(ns.substring(with: m.range(at: 1))) else { return nil }
+ var rest = ns.substring(with: m.range(at: 3))
+
+ if let pct = rest.range(of: #"(\d+)%"#, options: .regularExpression) {
+ let v = Double(rest[pct].dropLast()) ?? 0
+ var name = String(rest[..<pct.lowerBound]).trimmingCharacters(in: CharacterSet(charactersIn: " :·"))
+ if let dot = name.range(of: " · ", options: .backwards) { name = String(name[..<dot.lowerBound]) }
+ let after = String(rest[pct.upperBound...]).trimmingCharacters(in: CharacterSet(charactersIn: ", :"))
+ return (k, name, .running, after, v)
+ }
+ let ok = line.contains("✓"), bad = line.contains("✗")
+ if ok || bad {
+ var detail = ""
+ if let r = rest.range(of: "): ") { detail = String(rest[r.upperBound...]); rest = String(rest[..<r.lowerBound]) + ")" }
+ if let r = rest.range(of: " (", options: .backwards) { rest = String(rest[..<r.lowerBound]) }
+ return (k, rest, bad ? .failed : .done, detail, 100)
+ }
+ if rest.hasSuffix(" …") { rest = String(rest.dropLast(2)) }
+ if let dot = rest.range(of: " · ", options: .backwards), !rest.hasPrefix("survey") { rest = String(rest[..<dot.lowerBound]) }
+ return (k, rest, .running, "", nil)
+ }
+
+ /// What xcodebuild is doing, from the actions it prints.
+ package static func xcodeStep(_ line: String) -> (detail: String, percent: Double?)? {
+ let actions = [("CompileC ", "compiling"), ("SwiftCompile ", "compiling"), ("Ld ", "linking"),
+ ("PhaseScriptExecution ", "copying resources"), ("CodeSign ", "signing"), ("ProcessProductPackaging ", "provisioning")]
+ return actions.first { line.hasPrefix($0.0) }.map { ($0.1, nil) }
+ }
+
+ /// devicectl's install progress ("… 45%").
+ package static func installStep(_ line: String) -> (detail: String, percent: Double?)? {
+ guard let range = line.range(of: #"(\d{1,3})%"#, options: .regularExpression), let n = Double(line[range].dropLast()) else { return nil }
+ return ("installing", min(n, 100))
+ }
+
+ /// The line a failed install should show, and the fix to offer beside it.
+ ///
+ /// A GUI user sees a spinner turn back into a button; the reason (brew refusing a directory it
+ /// does not own is the common one) lived only in the log. Prefer the tool's own `Error:` line,
+ /// and map the few causes we can name to the exact command.
+ package static func failureInfo(_ lines: [String]) -> (error: String, fix: String) {
+ let meaningful = lines.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ let error = meaningful.first { $0.hasPrefix("Error:") }
+ ?? meaningful.first { $0.lowercased().contains("error") }
+ ?? meaningful.last ?? ""
+ let lower = lines.joined(separator: "\n").lowercased()
+ let fix: String
+ if lower.contains("/opt/homebrew is not writable") || lower.contains("permission denied @ dir_initialize")
+ || lower.contains("/usr/local is not writable") {
+ fix = "dep.fix.brewOwner"
+ } else if lower.contains("command not found") || lower.contains("brew: not found") {
+ fix = "dep.fix.brewMissing"
+ } else if lower.contains("agreeing to the xcode license") || lower.contains("xcode license") {
+ fix = "dep.fix.xcodeLicense"
+ } else if lower.contains("could not resolve host") || lower.contains("failed to download")
+ || lower.contains("operation timed out") {
+ fix = "dep.fix.network"
+ } else {
+ fix = "dep.fix.log"
+ }
+ return (error, fix)
+ }
+}
diff --git a/frontend/Sources/NXCore/GameInputs.swift b/frontend/Sources/NXCore/GameInputs.swift
new file mode 100644
index 00000000..fc56171d
--- /dev/null
+++ b/frontend/Sources/NXCore/GameInputs.swift
@@ -0,0 +1,118 @@
+import Foundation
+
+/// One of the four things the user points at.
+package enum InputKind { case base, update, dlc, keys }
+
+/// Which files make a game: classifying a folder or a set of dropped files into the four slots, and whether a file fits the row
+/// it was put in. Functions of the file names, apart from `inputFiles` and the size check in `classify`, which read the disk.
+package enum GameInputs {
+ /// What a set of files holds for the four slots (`classify`).
+ package struct Found: Equatable {
+ package var base: String?
+ package var update: String?
+ package var dlc: [String] = []
+ package var keys: String?
+ /// How many updates the files held and the version of the one taken (the newest), for the update row's note.
+ package var updateCount = 0
+ package var updateVersion = 0
+ package init(base: String? = nil, update: String? = nil, dlc: [String] = [], keys: String? = nil,
+ updateCount: Int = 0, updateVersion: Int = 0) {
+ self.base = base; self.update = update; self.dlc = dlc; self.keys = keys
+ self.updateCount = updateCount; self.updateVersion = updateVersion
+ }
+ package var anyGame: Bool { base != nil || update != nil || !dlc.isEmpty }
+ package static func == (a: Self, b: Self) -> Bool {
+ a.base == b.base && a.update == b.update && a.dlc == b.dlc && a.keys == b.keys
+ }
+ }
+
+ /// The files under a folder, pruning the build folders this pipeline itself writes so a rescan is not slow.
+ package static func inputFiles(in folder: String) -> [String] {
+ let fm = FileManager.default
+ var files: [String] = []
+ var seen = 0
+ let enumerator = fm.enumerator(atPath: folder)
+ while let rel = enumerator?.nextObject() as? String {
+ if seen > 8000 { break } // a pathological tree should not hang the picker
+ seen += 1
+ let name = (rel as NSString).lastPathComponent
+ if name.hasPrefix(".") { continue }
+ let path = folder + "/" + rel
+ var isDir: ObjCBool = false
+ guard fm.fileExists(atPath: path, isDirectory: &isDir) else { continue }
+ let low = name.lowercased()
+ if isDir.boolValue {
+ // the pipeline's own output, and anything hidden: never walk back into those
+ if low == "archive" || low == "xcode" || low.hasSuffix("_build") || low.hasSuffix("_survey") { enumerator?.skipDescendants() }
+ continue
+ }
+ files.append(path)
+ }
+ return files
+ }
+
+ /// NSP/XCI (and their compressed NSZ/XCZ) sorted by the title ID in the file name, plus the first prod.keys.
+ /// Shared by Choose game folder and files dropped on the Builds page.
+ package static func classify(_ files: [String]) -> Found {
+ var base: [(String, Int)] = [], update: [(String, Int, Int)] = [], dlc: [String] = []
+ var found = Found()
+ for path in files {
+ let name = (path as NSString).lastPathComponent
+ let low = name.lowercased()
+ if name.hasPrefix("._") { continue } // an AppleDouble file macOS writes beside every real file on exFAT/FAT drives: its name carries the same [title ID], so counting it made one update read as two
+ if found.keys == nil && (low == "prod.keys" || low.hasSuffix(".keys")) { found.keys = path; continue }
+ guard ["nsp", "xci", "nsz", "xcz"].contains((low as NSString).pathExtension) else { continue }
+ let size = (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? Int ?? 0
+ guard size > 0 else { continue } // an incomplete download leaves 0-byte files behind
+ guard let tid = TitleID.parse(name) else { continue } // a name without a title ID cannot be classified
+ switch tid & 0xFFF {
+ case 0: base.append((path, size))
+ case 0x800: update.append((path, size, TitleID.updateVersion(name)))
+ default: dlc.append(path)
+ }
+ }
+ // several bases happen when a folder holds a repack beside the original: the largest wins
+ found.base = base.sorted { $0.1 > $1.1 }.first?.0
+ // a folder that holds other games too: only the update and add-on content of the chosen base game count
+ if let app = found.base.flatMap({ TitleID.parse(($0 as NSString).lastPathComponent) }).map({ $0 & ~0xFFF }) {
+ update = update.filter { TitleID.parse(($0.0 as NSString).lastPathComponent).map(TitleID.owner) == app }
+ dlc = dlc.filter { TitleID.parse(($0 as NSString).lastPathComponent).map(TitleID.owner) == app }
+ }
+ // several updates: the newest version is the one a profile would pack (an update contains the earlier ones)
+ let newest = update.sorted { $0.2 > $1.2 }.first
+ found.update = newest?.0
+ found.updateCount = update.count
+ found.updateVersion = newest?.2 ?? 0
+ found.dlc = dlc.sorted()
+ return found
+ }
+
+ /// Why a file does not fit the row it was put in, judged by the title ID in its name.
+ package enum RowMismatch: Equatable { case notBase(UInt64), notUpdate(UInt64), notDLC(UInt64), otherGame }
+
+ /// A file whose name carries no title ID fits every row (the build script reads the ID from the package).
+ /// `base` is the selected base game's file name, when it carries one.
+ package static func rowMismatch(_ kind: InputKind, name: String, base: String?) -> RowMismatch? {
+ guard kind != .keys, let tid = TitleID.parse(name) else { return nil }
+ let low = tid & 0xFFF
+ switch kind {
+ case .base: if low != 0 { return .notBase(tid) }
+ case .update: if low != 0x800 { return .notUpdate(tid) }
+ case .dlc: if low == 0 || low == 0x800 { return .notDLC(tid) }
+ case .keys: break
+ }
+ if kind != .base, let b = base.flatMap(TitleID.parse), TitleID.owner(tid) != b & ~0xFFF { return .otherGame }
+ return nil
+ }
+
+
+ /// What the Choose… dialog of a row offers. The compressed NSZ / XCZ are accepted by the build
+ /// script like their plain forms. DLC ships as NSP (or NSZ), never as a cartridge image.
+ package static func allowedFileTypes(for kind: InputKind) -> [String] {
+ switch kind {
+ case .base, .update: return ["nsp", "xci", "nsz", "xcz"]
+ case .dlc: return ["nsp", "nsz"]
+ case .keys: return ["keys"]
+ }
+ }
+}
diff --git a/frontend/Sources/NXCore/TitleID.swift b/frontend/Sources/NXCore/TitleID.swift
new file mode 100644
index 00000000..79b29023
--- /dev/null
+++ b/frontend/Sources/NXCore/TitleID.swift
@@ -0,0 +1,54 @@
+import Foundation
+
+/// The title ID in a Switch file name and what follows from it: the owning base game, the update version and the key of a
+/// game's work folder. Pure functions of the name.
+package enum TitleID {
+ /// The title ID in a file name: `[0100F2C0115B6000]` first, else a bare 16-digit ID that starts with 01 as a token
+ /// (start of the name or after `_`, space, `-`, `.`, `(`, `[`). Only the file name counts, so a full path works and a folder named with an ID never
+ /// stands in for the file (#382). Like `01007EF00011E000_v0_420d1c5034ab.nsp`.
+ package static func parse(_ path: String) -> UInt64? {
+ let name = (path as NSString).lastPathComponent
+ let found = firstGroup(#"\[([0-9A-Fa-f]{16})\]"#, in: name)
+ ?? firstGroup(#"(?:^|[_ \-.(\[])(01[0-9A-Fa-f]{14})(?![0-9A-Fa-f])"#, in: name)
+ return found.flatMap { UInt64($0, radix: 16) }
+ }
+
+ /// The name of a game's work folder and output (`<key>_build`, `<key>.app`). The title ID in the file name when there
+ /// is one, so `<ID>_build` stays what the library looks for. Else the file name without its extension, cut to letters,
+ /// digits, `-` and `_`, plus a short hash of the full name: two games never share a folder (and so a shader cache),
+ /// the same file name always gets the same one (a rebuild reuses its cache). Never a constant.
+ package static func buildKey(_ path: String) -> String {
+ let name = (path as NSString).lastPathComponent
+ if let id = parse(name) { return String(format: "%016llX", id) }
+ let stem = (name as NSString).deletingPathExtension
+ var hash: UInt32 = 2166136261 // FNV-1a, stable across runs (Hashable is seeded per launch)
+ for byte in stem.utf8 { hash = (hash ^ UInt32(byte)) &* 16777619 }
+ let clean = String(stem.unicodeScalars.map { c in
+ c.isASCII && (CharacterSet.alphanumerics.contains(c) || c == "-" || c == "_") ? Character(c) : "_"
+ }).prefix(40)
+ return (clean.isEmpty ? "game" : String(clean)) + "-" + String(format: "%08x", hash)
+ }
+
+ /// The base game's title ID (low 12 bits clear) a title ID belongs to, as build_ipa_from_nsp.py reads it:
+ /// 0x000 is a base game, 0x800 its update, anything else add-on content in the block above the base.
+ package static func owner(_ tid: UInt64) -> UInt64 {
+ let low = tid & 0xFFF
+ return low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)
+ }
+
+ /// The version in a file name, 0 when absent: `[v65536]` first, then the `_v65536` / ` v65536` token the
+ /// eShop-style names use (`01007EF00011E800_v1114112_038ff9df0888.nsp`). Picks the newest of several updates.
+ package static func updateVersion(_ name: String) -> Int {
+ for pattern in [#"\[v(\d+)\]"#, #"(?:^|[_ ])v(\d+)(?=$|[_ .\-)\]])"#] {
+ if let v = firstGroup(pattern, in: name), let n = Int(v) { return n }
+ }
+ return 0
+ }
+
+ private static func firstGroup(_ pattern: String, in name: String) -> String? {
+ guard let re = try? NSRegularExpression(pattern: pattern) else { return nil }
+ let ns = name as NSString
+ guard let m = re.firstMatch(in: name, range: NSRange(location: 0, length: ns.length)) else { return nil }
+ return ns.substring(with: m.range(at: 1))
+ }
+}
diff --git a/frontend/Sources/NXCore/Toolchain.swift b/frontend/Sources/NXCore/Toolchain.swift
new file mode 100644
index 00000000..57eb6fd6
--- /dev/null
+++ b/frontend/Sources/NXCore/Toolchain.swift
@@ -0,0 +1,485 @@
+import Foundation
+
+/// One row of the dependency panel.
+package struct Dep: Identifiable {
+ package let id: String
+ package let name: String // an L10n key
+ package let hint: String // an L10n key
+ package var present: Bool
+ package var installing = false
+ package var detail = ""
+ package var lastError = "" // the tool's own first error line after a failed install (brew's, pip's)
+ package var fixHint = "" // an L10n key: what to type or click, chosen from that line
+ package var actionLabel = "" // an L10n key for the button when the action is not a plain install ("Fix")
+ package var warning = false // present, but with a caveat the row's error and hint lines explain (the Metal compiler is not the tested one)
+ package let installCmd: [String] // run via bash; empty = manual (Xcode from the App Store)
+
+ package init(id: String, name: String, hint: String, present: Bool, installing: Bool = false, detail: String = "",
+ lastError: String = "", fixHint: String = "", actionLabel: String = "", warning: Bool = false,
+ installCmd: [String]) {
+ self.id = id; self.name = name; self.hint = hint; self.present = present; self.installing = installing
+ self.detail = detail; self.lastError = lastError; self.fixHint = fixHint; self.actionLabel = actionLabel
+ self.warning = warning; self.installCmd = installCmd
+ }
+}
+
+/// Probing this Mac for what a build needs: Python and its venv, dotnet, Xcode and the Homebrew tools. A GUI app does not inherit the
+/// shell's PATH, so these look in the places the tools live. The rows they make are `Dep`. Pure over their inputs where they can be
+/// (`xcodeState`, `parseDotnetRoot`, `toolDeps`, `pythonDetail`), the rest runs the tools and reads the disk.
+package enum Toolchain {
+ /// A GUI app does not inherit the shell's PATH, so look where the tools actually
+ /// live instead of trusting `which` — that is why .NET (in ~/.dotnet) and the
+ /// Python packages (in /usr/local/bin/python3, not /usr/bin/python3) used to show
+ /// as missing while a terminal could see them.
+ package static func runOK(_ tool: String, _ args: [String], env: [String: String]? = nil) -> Bool {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: tool)
+ p.arguments = args
+ if let env { p.environment = env }
+ p.standardOutput = Pipe(); p.standardError = Pipe()
+ p.standardInput = FileHandle.nullDevice
+ do { try p.run() } catch { return false }
+ p.waitUntilExit()
+ return p.terminationStatus == 0
+ }
+
+ package static func firstExisting(_ paths: [String]) -> String? {
+ paths.first { FileManager.default.isExecutableFile(atPath: $0) }
+ }
+
+ /// The Python that actually has lz4/capstone/fontTools/zbic/backports.zstd — the one
+ /// the build must run under, not whatever /usr/bin/python3 happens to be.
+ /// The minimum the build scripts need. /usr/bin/python3 is 3.9 on a stock Mac and has none of
+ /// the packages; picking it made a build fail with a syntax error deep inside the script
+ /// (an f-string only 3.12 can parse) instead of a clear message here.
+ ///
+ /// 3.12 is the script's own floor, not a guess: build_ipa_from_nsp.py:1911 raises "Direct
+ /// RomFS image builds require Python 3.12 or newer". This said 3.9 — the comment above even
+ /// said 3.12 — so findPython() was happy to return Apple's 3.9 and the build then died inside
+ /// the script with a message the user could not act on (issue #53).
+ package static let minPython = (3, 12)
+
+ /// The Homebrew formulae the dependency check offers, with the localization key of each row. The repo-root
+ /// Brewfile lists the same formulae (BrewfileTests keeps the two equal).
+ /// `binary` is the file the formula puts in the Homebrew bin folder (glslang installs glslangValidator, which the
+ /// NSP script's environment check requires).
+ package static let brewDeps: [(formula: String, binary: String, key: String)] = [
+ ("xcodegen", "xcodegen", "dep.xcodegen"),
+ ("zstd", "zstd", "dep.zstd"),
+ ("spirv-cross", "spirv-cross", "dep.spirv"),
+ ("glslang", "glslangValidator", "dep.glslang"),
+ ]
+
+ /// The interpreter probe: lz4 / capstone / fontTools / zbic always, and zstd from either source —
+ /// `compression.zstd` is built in from Python 3.14 and `backports.zstd` (which declares
+ /// Python < 3.14) is the only option before that. Requiring the backport unconditionally
+ /// rejected an otherwise working Homebrew Python 3.15 (issue #1).
+ /// zbic is required although only a game with system 22.0.0+ modules (ZBIC segments, Nintendo's zstd variant) needs it:
+ /// the launcher cannot know that before the extraction, and the build stops late without it (issue #251).
+ /// nsz is deliberately not required here: it is only needed for NSZ / XCZ dumps, and the
+ /// pipeline says so by name when one shows up. The venv installs it anyway so that a player
+ /// who downloads a compressed dump never meets that error.
+ package static let importProbe = """
+ import lz4, capstone, fontTools, zbic
+ try:
+ from compression import zstd
+ except ImportError:
+ from backports import zstd
+ """
+
+ /// The interpreter the packages are installed into when no system Python has them. A venv
+ /// rather than `pip install --user`: Homebrew's Python is externally managed (PEP 668) and
+ /// refuses --user, and this leaves the user's environment untouched. Injectable so tests can
+ /// use a scratch directory.
+ package static var venvDir = NSHomeDirectory() + "/Library/Application Support/NS Port Builder/venv"
+
+ package static func venvPython() -> String { venvDir + "/bin/python3" }
+
+ /// Where uv keeps the Pythons it installs (`uv python install`): the shims in `~/.local/bin`
+ /// and the store the real binaries live in, which `UV_PYTHON_INSTALL_DIR` moves. A uv user
+ /// often has neither python.org's framework nor Homebrew, and a GUI launch's PATH is
+ /// /usr/bin:/bin:/usr/sbin:/sbin, so neither `which` nor the locations below see them: a
+ /// working uv Python 3.12 was reported as "No Python 3.12 or newer found". Injectable so a
+ /// test can point them at a scratch tree.
+ package static var uvShimDir = NSHomeDirectory() + "/.local/bin"
+ package static var uvPythonRoot: String = {
+ let dir = ProcessInfo.processInfo.environment["UV_PYTHON_INSTALL_DIR"] ?? ""
+ return dir.isEmpty ? NSHomeDirectory() + "/.local/share/uv/python" : dir
+ }()
+
+ /// Where mise and asdf keep the Pythons they install, and mise's shims. `MISE_DATA_DIR` and
+ /// `ASDF_DATA_DIR` move them. A GUI launch's PATH does not include the shims directory, so a
+ /// Python managed by either was not found at all (issue #113). Injectable for tests.
+ package static var miseDataDir: String = {
+ let dir = ProcessInfo.processInfo.environment["MISE_DATA_DIR"] ?? ""
+ return dir.isEmpty ? NSHomeDirectory() + "/.local/share/mise" : dir
+ }()
+ package static var asdfDataDir: String = {
+ let dir = ProcessInfo.processInfo.environment["ASDF_DATA_DIR"] ?? ""
+ return dir.isEmpty ? NSHomeDirectory() + "/.asdf" : dir
+ }()
+
+ package static func importsOK(_ py: String) -> Bool {
+ runOK(py, ["-c", importProbe], env: ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: py)) { $1 })
+ }
+
+ /// backports.zstd declares Python < 3.14, so it is only installed where it is needed.
+ /// nsz is always installed: NSZ / XCZ dumps are accepted by the pipeline now, and a player who
+ /// downloads one should not have to run pip by hand (it is a few hundred KB).
+ package static func pipPackages(_ version: (Int, Int)) -> [String] {
+ version < (3, 14) ? ["lz4", "capstone", "fonttools", "zbic", "backports.zstd", "nsz"]
+ : ["lz4", "capstone", "fonttools", "zbic", "nsz"]
+ }
+
+ /// Create the venv (reusing an existing one) and install the packages into it. Returns the
+ /// combined output so a failure can be shown instead of swallowed — the pip output used to go
+ /// to a pipe nobody read, and `externally-managed-environment` never reached the user.
+ package static func makeVenv(base: String) -> (ok: Bool, log: String) {
+ var log = ""
+ func run(_ exe: String, _ args: [String]) -> Bool {
+ let p = Process(); p.executableURL = URL(fileURLWithPath: exe); p.arguments = args
+ let out = Pipe(), err = Pipe()
+ p.standardOutput = out; p.standardError = err; p.standardInput = FileHandle.nullDevice
+ p.environment = ["PATH": BundledTools.path("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", python: base), "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: base)) { $1 }
+ do { try p.run() } catch { log += "could not start \(exe): \(error.localizedDescription)\n"; return false }
+ // both pipes are drained on this thread (before waitUntilExit, so the child cannot
+ // block on a full pipe), and the log string keeps a single owner
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ let errData = err.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ log += String(data: outData, encoding: .utf8) ?? ""
+ log += String(data: errData, encoding: .utf8) ?? ""
+ return p.terminationStatus == 0
+ }
+ let vpy = venvPython()
+ // An existing venv below minPython (built from Apple's 3.9 by an older app, issue #75) is
+ // moved aside and rebuilt: pip into it would "succeed" and the build would still fail.
+ // Moved, never deleted, because the folder is the user's. Only when a usable base exists,
+ // so a Mac with no new Python keeps its old venv instead of losing it for nothing.
+ if FileManager.default.isExecutableFile(atPath: vpy), pythonVersion(vpy).map({ $0 < minPython }) ?? true {
+ guard let interp = venvBase(preferred: base), interp != vpy else {
+ return (false, log + "\(venvDir) is older than Python \(minPython.0).\(minPython.1) and no newer Python was found to rebuild it from\n")
+ }
+ let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-")
+ let aside = venvDir + ".old-" + stamp
+ do { try FileManager.default.moveItem(atPath: venvDir, toPath: aside) } catch {
+ return (false, log + "could not move \(venvDir) aside: \(error.localizedDescription)\n")
+ }
+ log += "moved the old venv (Python below \(minPython.0).\(minPython.1)) to \(aside)\n"
+ }
+ if !FileManager.default.isExecutableFile(atPath: vpy) {
+ // findPython() returns the venv path it hopes to create when no interpreter was
+ // found, and the panel hands that to this function. It cannot be a base: `-m venv`
+ // failed with "could not start …" and the Python row never recovered.
+ guard let interp = venvBase(preferred: base) else {
+ return (false, log + "no Python \(minPython.0).\(minPython.1) or newer to create \(venvDir) from\n")
+ }
+ if interp != base { log += "\(base) is not a usable interpreter; using \(interp)\n" }
+ log += "$ \(interp) -m venv \(venvDir)\n"
+ try? FileManager.default.createDirectory(atPath: (venvDir as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
+ guard run(interp, ["-m", "venv", venvDir]) else { return (false, log + "venv creation failed\n") }
+ }
+ let pkgs = pipPackages(pythonVersion(vpy) ?? minPython).joined(separator: " ")
+ log += "$ \(vpy) -m pip install \(pkgs)\n"
+ let ok = run(vpy, ["-m", "pip", "install"] + pipPackages(pythonVersion(vpy) ?? minPython))
+ return (ok && importsOK(vpy), log)
+ }
+
+ /// "3.12.4" → (3, 12). nil when the interpreter cannot be run.
+ package static func pythonVersion(_ path: String) -> (Int, Int)? {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: path)
+ p.arguments = ["-c", "import sys; print('%d.%d' % sys.version_info[:2])"]
+ p.environment = ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: path)) { $1 }
+ let pipe = Pipe()
+ p.standardOutput = pipe; p.standardError = Pipe()
+ p.standardInput = FileHandle.nullDevice
+ guard (try? p.run()) != nil else { return nil }
+ p.waitUntilExit()
+ guard p.terminationStatus == 0 else { return nil }
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ let parts = out.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ".")
+ guard parts.count == 2, let a = Int(parts[0]), let b = Int(parts[1]) else { return nil }
+ return (a, b)
+ }
+
+ /// The interpreter to create the venv from. `preferred` is what the panel picked; when
+ /// findPython() found nothing that is the venv path it hopes to create, which cannot be a
+ /// base (see makeVenv). So a base that does not run at the required version falls back to
+ /// the newest candidate that does. nil when this Mac has no such interpreter at all.
+ package static func venvBase(preferred: String) -> String? {
+ if FileManager.default.isExecutableFile(atPath: preferred),
+ let v = pythonVersion(preferred), v >= minPython {
+ return preferred
+ }
+ return pythonCandidates().first {
+ FileManager.default.isExecutableFile(atPath: $0)
+ && (pythonVersion($0).map { $0 >= minPython } ?? false)
+ }
+ }
+
+ /// The `python3` / `python3.x` names in a directory, newest version first.
+ package static func pythonNames(in dir: String, matching pattern: String) -> [String] {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? []
+ return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }
+ .sorted { $0.compare($1, options: .numeric) == .orderedDescending }
+ }
+
+ /// uv's managed Pythons: the shims in `uvShimDir` and every install under `uvPythonRoot`
+ /// (`cpython-3.12.13-macos-aarch64-none/bin/python3.12`). A uv user often has neither
+ /// python.org's framework nor Homebrew, and a GUI launch's PATH does not contain
+ /// `~/.local/bin`, so nothing else on this Mac finds them.
+ package static func uvPythonCandidates() -> [String] {
+ var out = pythonNames(in: uvShimDir, matching: #"^python3(\.\d+)?$"#).map { uvShimDir + "/" + $0 }
+ let installs = (try? FileManager.default.contentsOfDirectory(atPath: uvPythonRoot)) ?? []
+ for d in installs.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
+ let bin = uvPythonRoot + "/" + d + "/bin"
+ out += pythonNames(in: bin, matching: #"^python3(\.\d+)?$"#).map { bin + "/" + $0 }
+ }
+ return out
+ }
+
+ /// Pythons managed by mise (installs, then its shims) and asdf (installs only: an asdf shim is
+ /// a script that needs `asdf` on the PATH, which a GUI launch lacks). Only the interpreter
+ /// names are taken, never `python3-config` and the other files that share the folder.
+ package static func versionManagerPythonCandidates() -> [String] {
+ var out: [String] = []
+ let strict = #"^python3(\.\d+)?$"#
+ for root in [miseDataDir + "/installs/python", asdfDataDir + "/installs/python"] {
+ let installs = (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? []
+ for d in installs.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
+ let bin = root + "/" + d + "/bin"
+ out += pythonNames(in: bin, matching: strict).map { bin + "/" + $0 }
+ }
+ }
+ let shims = miseDataDir + "/shims"
+ out += pythonNames(in: shims, matching: strict).map { shims + "/" + $0 }
+ return out
+ }
+
+ /// Every interpreter a build could run under, best first: python.org's framework, Homebrew,
+ /// /usr/local, uv's store, mise and asdf, then whatever `which` can see. Probed by hand because a GUI app
+ /// does not inherit the shell's PATH — the same reason .NET (in ~/.dotnet) used to show as
+ /// missing while a terminal saw it.
+ package static func pythonCandidates() -> [String] {
+ var cands: [String] = []
+ let fw = "/Library/Frameworks/Python.framework/Versions"
+ if let vers = try? FileManager.default.contentsOfDirectory(atPath: fw) {
+ for v in vers.sorted(by: { $0.compare($1, options: .numeric) == .orderedDescending }) {
+ cands.append(fw + "/" + v + "/bin/python3")
+ }
+ }
+ cands += ["/opt/homebrew/bin/python3", "/usr/local/bin/python3", "/usr/bin/python3"]
+ // Homebrew's [email protected] is always python3.x, but the bare python3 link exists only for
+ // the formula that is linked: a 3.12 beside an unlinked default would go unseen.
+ for dir in ["/opt/homebrew/bin", "/usr/local/bin"] {
+ cands += pythonNames(in: dir, matching: #"^python3\.\d+$"#).map { dir + "/" + $0 }
+ }
+ cands += uvPythonCandidates()
+ cands += versionManagerPythonCandidates()
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/which")
+ p.arguments = ["-a", "python3"]
+ let pipe = Pipe()
+ p.standardOutput = pipe; p.standardError = Pipe()
+ p.standardInput = FileHandle.nullDevice
+ if (try? p.run()) != nil {
+ p.waitUntilExit()
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ cands += out.split(separator: "\n").map(String.init)
+ }
+ return cands
+ }
+
+ /// Every python3 on this Mac, newest-looking first, each tried for a usable version and the
+ /// packages. Returns the one to build with, plus why the others were rejected for the message.
+ package static func findPython(resources: URL? = BundledTools.resources) -> (path: String, ok: Bool) {
+ // The release app's own Python (BundledTools.swift) has every package and is the one the build is tested with: it wins over
+ // any Python on this Mac and needs no venv. One that does not run (a damaged copy) falls through to the search below
+ // (uv's Pythons, the other candidates, then the venv).
+ if let bundled = BundledTools.python(in: resources), pythonVersion(bundled).map({ $0 >= minPython }) == true, importsOK(bundled) {
+ return (bundled, true)
+ }
+ var seen = Set<String>()
+ var fallback: (String, (Int, Int))? = nil // newest with an acceptable version but no packages
+ for c in pythonCandidates() where !c.isEmpty && seen.insert(c).inserted {
+ guard FileManager.default.isExecutableFile(atPath: c), let v = pythonVersion(c) else { continue }
+ guard v >= minPython else { continue }
+ if importsOK(c) { return (c, true) }
+ if fallback == nil || v > fallback!.1 { fallback = (c, v) }
+ }
+ // No system interpreter has the packages: the venv (existing, or created by 安装) is next.
+ let vpy = venvPython()
+ // A venv below minPython is not ready however complete its packages are: an older app
+ // version made it from Apple's 3.9, and the build script refuses that (issue #75). It
+ // falls through to the candidates above, or to the row saying the Python is too old.
+ if FileManager.default.isExecutableFile(atPath: vpy), let v = pythonVersion(vpy), v >= minPython {
+ if importsOK(vpy) { return (vpy, true) }
+ return (vpy, false) // exists but incomplete: 安装 finishes it
+ }
+ return (fallback?.0 ?? vpy, false)
+ }
+
+ /// The runtime root of a dotnet installation, parsed from `dotnet --list-runtimes`. It cannot
+ /// be assumed to be the binary's directory: Homebrew's /opt/homebrew/bin/dotnet is a symlink
+ /// into Cellar, and the runtime lives in …/libexec, so a hardcoded ~/.dotnet left the apphost
+ /// without a runtime and nx_extract died with exit code 131 (issue #2).
+ package static func parseDotnetRoot(_ listRuntimes: String) -> String? {
+ for ln in listRuntimes.split(separator: "\n") {
+ guard ln.hasPrefix("Microsoft.NETCore.App"), let a = ln.firstIndex(of: "["), let b = ln.lastIndex(of: "]") else { continue }
+ let p = String(ln[ln.index(after: a)..<b])
+ for suffix in ["/shared/Microsoft.NETCore.App", "\\shared\\Microsoft.NETCore.App"] where p.hasSuffix(suffix) {
+ return String(p.dropLast(suffix.count))
+ }
+ return p
+ }
+ return nil
+ }
+
+ package static func dotnetRoot(for dotnet: String) -> String? {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: dotnet)
+ p.arguments = ["--list-runtimes"]
+ let pipe = Pipe()
+ p.standardOutput = pipe; p.standardError = Pipe(); p.standardInput = FileHandle.nullDevice
+ p.environment = ["HOME": NSHomeDirectory(), "PATH": "/usr/bin:/bin", "TMPDIR": NSTemporaryDirectory()]
+ guard (try? p.run()) != nil else { return nil }
+ p.waitUntilExit()
+ guard p.terminationStatus == 0 else { return nil }
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ // No directory fallback: for Homebrew's symlink layout the binary's directory is not the root,
+ // and a wrong DOTNET_ROOT is worse than none (the apphost stops searching once it is set).
+ // When this returns nil the pipeline derives and verifies a root itself.
+ return parseDotnetRoot(out)
+ }
+
+ package static func findDotnet() -> (path: String, ok: Bool) {
+ let cands = [NSHomeDirectory() + "/.dotnet/dotnet",
+ "/usr/local/share/dotnet/dotnet",
+ "/opt/homebrew/bin/dotnet",
+ "/usr/local/bin/dotnet"]
+ if let d = firstExisting(cands) {
+ // the extractor targets net10.0, so an SDK (not just a runtime) is needed
+ let ok = runOK(d, ["--list-sdks"], env: ["DOTNET_ROOT": (d as NSString).deletingLastPathComponent,
+ "PATH": "/usr/bin:/bin", "HOME": NSHomeDirectory(),
+ "TMPDIR": NSTemporaryDirectory()])
+ return (d, ok)
+ }
+ return ("dotnet", false)
+ }
+
+ /// Whether the selected developer directory exists (`xcode-select -p`), which is the same
+ /// source of truth xcodebuild and xcrun use — so an Xcode beta, a custom location, or a
+ /// Command Line Tools-only setup is reported for what it is instead of "no Xcode".
+ package static func developerDir() -> String? {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")
+ p.arguments = ["-p"]
+ let pipe = Pipe()
+ p.standardOutput = pipe
+ p.standardError = FileHandle.nullDevice
+ do { try p.run() } catch { return nil }
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ guard p.terminationStatus == 0,
+ let dir = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !dir.isEmpty else { return nil }
+ var isDir: ObjCBool = false
+ return FileManager.default.fileExists(atPath: dir, isDirectory: &isDir) && isDir.boolValue ? dir : nil
+ }
+
+ package static func developerDirExists() -> Bool { developerDir() != nil }
+
+ /// An Xcode.app that is installed but not selected: an App Store download arrives as
+ /// /Applications/Xcode.app and stays unused until someone opens it or points xcode-select at
+ /// it, so `xcode-select -p` keeps saying CommandLineTools and xcodebuild fails later.
+ package static func installedXcode() -> String? {
+ for app in ["/Applications/Xcode.app", "/Applications/Xcode-beta.app"]
+ where FileManager.default.isExecutableFile(atPath: app + "/Contents/Developer/usr/bin/xcodebuild") {
+ return app
+ }
+ let apps = (try? FileManager.default.contentsOfDirectory(atPath: "/Applications")) ?? []
+ for name in apps.sorted() where name.hasPrefix("Xcode") && name.hasSuffix(".app") {
+ let app = "/Applications/" + name
+ if FileManager.default.isExecutableFile(atPath: app + "/Contents/Developer/usr/bin/xcodebuild") { return app }
+ }
+ return nil
+ }
+
+ /// What the Xcode row is looking at: the selected developer directory, the Xcode that is only
+ /// installed, and whether the iOS SDK answers. Pure, so the four cases are tested.
+ package enum XcodeState: Equatable {
+ case ready
+ case noIOSSDK(selected: String) // Xcode selected, its iOS platform not downloaded
+ case commandLineToolsOnly(xcode: String) // Xcode.app installed, xcode-select still on the CLT
+ case notInstalled
+ }
+
+ package static func xcodeState(selected: String?, xcodeApp: String?, iosSDK: Bool) -> XcodeState {
+ if let selected, selected.contains(".app/Contents/Developer") {
+ return iosSDK ? .ready : .noIOSSDK(selected: selected)
+ }
+ if let xcodeApp { return .commandLineToolsOnly(xcode: xcodeApp) }
+ return iosSDK ? .ready : .notInstalled // a CLT whose xcrun does answer the SDK is usable
+ }
+
+ /// The commands that fetch Xcode's two downloadable parts; the setup panel and the guided setup run the same ones.
+ package static let metalToolchainCmd = ["/usr/bin/xcodebuild", "-downloadComponent", "MetalToolchain"]
+ package static let iosPlatformCmd = ["/usr/bin/xcodebuild", "-downloadPlatform", "iOS"]
+
+ /// One admin prompt runs both steps: switch the toolchain to this Xcode, then let it finish its first launch (license and
+ /// components) - a fresh App Store download has neither. The Xcode row and the failure card run the same command.
+ package static func selectXcodeCmd(_ xcode: String) -> [String] {
+ let script = "xcode-select -s '" + xcode + "/Contents/Developer' && xcodebuild -runFirstLaunch"
+ let apple = "do shell script \"" + script.replacingOccurrences(of: "\"", with: "\\\"") + "\" with administrator privileges"
+ return ["/usr/bin/osascript", "-e", apple]
+ }
+
+ /// The rows for the build tools (xcodegen, zstd, spirv-cross, glslangValidator) and the Homebrew row they may need.
+ /// A tool the app carries counts as present and says "bundled"; otherwise Homebrew's copy counts (`installed` answers
+ /// a binary name with its path in a Homebrew folder, or nil). The Homebrew row appears only when some tool is neither
+ /// bundled nor installed (with a bundle; with none the row stays, as before): it is the way to get that one.
+ package static func toolDeps(resources: URL?, installed: (String) -> String?, brew: String?) -> [Dep] {
+ var rows: [Dep] = []
+ var needsBrew = false, anyBundled = false
+ for (pkg, binary, key) in brewDeps {
+ let bundled = BundledTools.tool(binary, in: resources) != nil
+ let path = bundled ? nil : installed(binary)
+ if !bundled && path == nil { needsBrew = true }
+ if bundled { anyBundled = true }
+ // A bundled tool is named by the tool; "brew: …" says where a Homebrew copy comes from, so it stays for the rows that
+ // refer to one (installed there, or missing with the install button)
+ rows.append(Dep(id: "brew:" + pkg, name: bundled ? "dep.tool." + binary : key, hint: key + ".hint", present: bundled || path != nil,
+ detail: bundled ? "dep.bundled" : (path ?? ""),
+ installCmd: [(brew ?? "/opt/homebrew/bin/brew"), "install", pkg]))
+ }
+ guard needsBrew || !anyBundled else { return rows } // without a bundle the row is always there, as it was
+ return [Dep(id: "brew", name: "dep.brew", hint: "dep.brew.hint", present: brew != nil,
+ installCmd: ["/bin/bash", "-c",
+ "NONINTERACTIVE=1 /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""])] + rows
+ }
+
+ /// First line of a tool's output (the Metal compiler's version line), nil when it does not run or says nothing.
+ package static func firstOutputLine(_ tool: String, _ args: [String]) -> String? {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: tool)
+ p.arguments = args
+ let out = Pipe()
+ p.standardOutput = out; p.standardError = Pipe(); p.standardInput = FileHandle.nullDevice
+ do { try p.run() } catch { return nil }
+ let data = out.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ guard p.terminationStatus == 0 else { return nil }
+ return String(decoding: data, as: UTF8.self).split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
+ }
+
+ package static func pythonDetail(py: String, ok: Bool) -> String {
+ let pyVer = pythonVersion(py).map { "\($0.0).\($0.1)" } ?? "?"
+ let minVer = "\(minPython.0).\(minPython.1)"
+ return ok ? (py == BundledTools.python() ? "dep.bundled" : py)
+ : pythonVersion(py).map { $0 >= minPython
+ ? "dep.python.missing:\(py) (\(pyVer))"
+ : "dep.python.old:\(pyVer):\(minVer)" }
+ ?? "dep.python.notFound:\(minVer):\(minVer)"
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
index 41c552fd..ccbcaa7d 100644
--- a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
@@ -217,6 +217,6 @@ final class BuildFailureRowsTests: XCTestCase {
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) }
+ if let xcode = Toolchain.installedXcode() { XCTAssertEqual(opened, [URL(fileURLWithPath: xcode)]) } else { XCTAssertTrue(opened.isEmpty) }
}
}
diff --git a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
index 68b2e48c..2e14fc27 100644
--- a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
@@ -244,7 +244,7 @@ final class BuildFailureTests: XCTestCase {
let dep = BuildModel.metalDep(runs: false, lock: Self.lock, now: ["macosx": nil, "iphoneos": nil], needsIOS: true)
XCTAssertFalse(dep.present)
XCTAssertFalse(dep.warning)
- XCTAssertEqual(dep.installCmd, BuildModel.metalToolchainCmd)
+ XCTAssertEqual(dep.installCmd, Toolchain.metalToolchainCmd)
}
func testWithoutALockThereIsNothingToCompare() {
@@ -295,7 +295,7 @@ final class BuildFailureTests: XCTestCase {
let m = BuildModel()
m.lang = .en
m.depsChecked = true
- m.deps = [BuildModel.Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),
+ m.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),
BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": Self.other], needsIOS: true)]
try capture("deps-metal-warning", width: 760, height: 260, ZStack(alignment: .top) {
LauncherPalette.background
diff --git a/frontend/Tests/NX2AppleTests/BuildKeyTests.swift b/frontend/Tests/NX2AppleTests/BuildKeyTests.swift
deleted file mode 100644
index d24a682a..00000000
--- a/frontend/Tests/NX2AppleTests/BuildKeyTests.swift
+++ /dev/null
@@ -1,52 +0,0 @@
-import XCTest
-@testable import NX2Apple
-@testable import NXCore
-@testable import NXLauncher
-
-/// #382: a file name without a title ID used to give the work folder `game_build` and the app `game.app` for every game,
-/// so a second game hit the first one's shader cache. One key per game now.
-final class BuildKeyTests: XCTestCase {
- func testNameWithTitleIDKeepsItsFolder() {
- XCTAssertEqual(BuildModel.buildKey("/x/Game [01007EF00011E000][v0].nsp"), "01007EF00011E000")
- XCTAssertEqual(BuildModel.buildKey("/x/01007ef00011e000_v0_420d1c5034ab.nsp"), "01007EF00011E000")
- }
-
- func testDifferentNamesWithoutIDGetDifferentKeys() {
- let a = BuildModel.buildKey("/x/Zelda.nsp"), b = BuildModel.buildKey("/x/Mario.nsp")
- XCTAssertNotEqual(a, b)
- XCTAssertNotEqual(a, "game")
- }
-
- func testSameNameGivesTheSameKeyEveryTime() {
- XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), BuildModel.buildKey("/other/Zelda.nsp"))
- XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), BuildModel.buildKey("/x/Zelda.nsp"))
- XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), "Zelda-74c1008b") // the Qt front end gives the same key
- }
-
- func testOddCharactersAreSanitized() {
- let k = BuildModel.buildKey("/x/Pokémon: Sword/Shield ../.. §.nsp")
- XCTAssertNil(k.range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
- XCTAssertFalse(k.contains("/"))
- XCTAssertNotEqual(BuildModel.buildKey("/x/a b.nsp"), BuildModel.buildKey("/x/a_b.nsp")) // same clean stem, different hash
- XCTAssertNil(BuildModel.buildKey("/x/日本語.nsp").range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
- }
-
- func testBuildFolderStillEndsInBuild() {
- XCTAssertTrue((BuildModel.buildKey("/x/Zelda.nsp") + "_build").hasSuffix("_build"))
- XCTAssertEqual(BuildModel.buildKey("/x/[0100F2C0115B6000].nsp") + "_build", "0100F2C0115B6000_build")
- }
-
- /// The reporter's layout: <ID>/<ID>_v0_<hash>.nsp, the ID bare (no brackets), the full path passed in.
- func testBareIDInAFullPathIsFound() {
- let dir = "/Users/me/Games/01007EF00011E000/"
- XCTAssertEqual(BuildModel.titleID(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"), 0x01007EF00011E000)
- XCTAssertEqual(BuildModel.buildKey(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"), "01007EF00011E000")
- // the update and the DLC beside it keep their own IDs and never stand in for the base
- XCTAssertEqual(BuildModel.titleID(dir + "01007EF00011E800_v1048576_aaaa.nsp"), 0x01007EF00011E800)
- XCTAssertEqual(BuildModel.titleID(dir + "01007EF00011F001_bbbb.nsp"), 0x01007EF00011F001)
- XCTAssertEqual(BuildModel.buildKey(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"),
- BuildModel.buildKey("01007EF00011E000_v0_420d1c5034ab.nsp"))
- // the folder's ID does not leak into a file name that has none
- XCTAssertNotEqual(BuildModel.buildKey(dir + "Zelda.nsp"), "01007EF00011E000")
- }
-}
diff --git a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
index a28f20af..e210f60b 100644
--- a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
@@ -60,7 +60,7 @@ final class BuildNotificationsTests: XCTestCase {
let model = BuildModel()
model.lang = CaptureLanguage.current(.en)
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .settings, performStartupChecks: false))
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1500), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
diff --git a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift b/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
index eaab75ed..69d70da5 100644
--- a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
@@ -24,9 +24,9 @@ final class BundledToolsTests: XCTestCase {
return url.path
}
private func installAllTools() throws {
- for (_, binary, _) in BuildModel.brewDeps { try install("tools/bin/" + binary) }
+ for (_, binary, _) in Toolchain.brewDeps { try install("tools/bin/" + binary) }
}
- private func row(_ rows: [BuildModel.Dep], _ pkg: String) -> BuildModel.Dep? { rows.first { $0.id == "brew:" + pkg } }
+ private func row(_ rows: [Dep], _ pkg: String) -> Dep? { rows.first { $0.id == "brew:" + pkg } }
// ---- what the bundle holds ----
@@ -105,34 +105,34 @@ final class BundledToolsTests: XCTestCase {
// ---- the dependency rows ----
func testWithoutABundleTheRowsAreHomebrews() {
- let rows = BuildModel.toolDeps(resources: nil, installed: { "/opt/homebrew/bin/" + $0 }, brew: "/opt/homebrew/bin/brew")
- XCTAssertEqual(rows.map { $0.id }, ["brew"] + BuildModel.brewDeps.map { "brew:" + $0.formula })
+ let rows = Toolchain.toolDeps(resources: nil, installed: { "/opt/homebrew/bin/" + $0 }, brew: "/opt/homebrew/bin/brew")
+ XCTAssertEqual(rows.map { $0.id }, ["brew"] + Toolchain.brewDeps.map { "brew:" + $0.formula })
XCTAssertTrue(rows.allSatisfy { $0.present })
XCTAssertEqual(row(rows, "zstd")?.detail, "/opt/homebrew/bin/zstd")
XCTAssertEqual(row(rows, "glslang")?.detail, "/opt/homebrew/bin/glslangValidator")
}
func testWithoutABundleOrHomebrewTheRowsAreMissing() {
- let rows = BuildModel.toolDeps(resources: nil, installed: { _ in nil }, brew: nil)
+ let rows = Toolchain.toolDeps(resources: nil, installed: { _ in nil }, brew: nil)
XCTAssertFalse(rows.first { $0.id == "brew" }!.present)
- XCTAssertTrue(BuildModel.brewDeps.allSatisfy { row(rows, $0.formula)?.present == false })
+ XCTAssertTrue(Toolchain.brewDeps.allSatisfy { row(rows, $0.formula)?.present == false })
}
func testBundledToolsArePresentAndNeedNoHomebrew() throws {
try installAllTools()
- let rows = BuildModel.toolDeps(resources: root, installed: { _ in nil }, brew: nil)
+ let rows = Toolchain.toolDeps(resources: root, installed: { _ in nil }, brew: nil)
XCTAssertNil(rows.first { $0.id == "brew" }, "nothing needs Homebrew")
- XCTAssertEqual(rows.count, BuildModel.brewDeps.count)
+ XCTAssertEqual(rows.count, Toolchain.brewDeps.count)
XCTAssertTrue(rows.allSatisfy { $0.present && $0.detail == "dep.bundled" })
- XCTAssertEqual(rows.map { $0.name }, BuildModel.brewDeps.map { "dep.tool." + $0.binary }, "named by the tool, not \"brew: …\"")
- for (_, binary, _) in BuildModel.brewDeps {
+ XCTAssertEqual(rows.map { $0.name }, Toolchain.brewDeps.map { "dep.tool." + $0.binary }, "named by the tool, not \"brew: …\"")
+ for (_, binary, _) in Toolchain.brewDeps {
for lang in [Lang.en, .zh] { XCTAssertEqual(L10n.string("dep.tool." + binary, lang), binary) }
}
}
func testBundledWinsOverHomebrews() throws {
try installAllTools()
- let rows = BuildModel.toolDeps(resources: root, installed: { "/opt/homebrew/bin/" + $0 }, brew: "/opt/homebrew/bin/brew")
+ let rows = Toolchain.toolDeps(resources: root, installed: { "/opt/homebrew/bin/" + $0 }, brew: "/opt/homebrew/bin/brew")
XCTAssertTrue(rows.allSatisfy { $0.detail == "dep.bundled" })
XCTAssertNil(rows.first { $0.id == "brew" })
}
@@ -140,7 +140,7 @@ final class BundledToolsTests: XCTestCase {
func testOneMissingToolBringsBackTheHomebrewRowForThatTool() throws {
try installAllTools()
try FileManager.default.removeItem(at: root.appendingPathComponent("tools/bin/spirv-cross"))
- let rows = BuildModel.toolDeps(resources: root, installed: { _ in nil }, brew: nil)
+ let rows = Toolchain.toolDeps(resources: root, installed: { _ in nil }, brew: nil)
XCTAssertEqual(rows.first?.id, "brew")
XCTAssertFalse(rows.first!.present)
XCTAssertEqual(row(rows, "spirv-cross")?.present, false)
@@ -152,7 +152,7 @@ final class BundledToolsTests: XCTestCase {
func testAMissingBundledToolFallsBackToHomebrewsCopy() throws {
try installAllTools()
try FileManager.default.removeItem(at: root.appendingPathComponent("tools/bin/xcodegen"))
- let rows = BuildModel.toolDeps(resources: root, installed: { $0 == "xcodegen" ? "/opt/homebrew/bin/xcodegen" : nil },
+ let rows = Toolchain.toolDeps(resources: root, installed: { $0 == "xcodegen" ? "/opt/homebrew/bin/xcodegen" : nil },
brew: "/opt/homebrew/bin/brew")
XCTAssertEqual(row(rows, "xcodegen")?.detail, "/opt/homebrew/bin/xcodegen")
XCTAssertEqual(row(rows, "xcodegen")?.present, true)
@@ -175,47 +175,47 @@ final class BundledToolsTests: XCTestCase {
exit 0
""")
- let found = BuildModel.findPython(resources: root)
+ let found = Toolchain.findPython(resources: root)
XCTAssertEqual(found.path, py)
XCTAssertTrue(found.ok)
}
func testFindPythonSkipsABundledOneThatDoesNotRun() throws {
let py = try install("python/bin/python3", script: "#!/bin/sh\nexit 1\n")
- XCTAssertNotEqual(BuildModel.findPython(resources: root).path, py)
+ XCTAssertNotEqual(Toolchain.findPython(resources: root).path, py)
}
func testFindPythonSkipsABundledOneThatIsTooOld() throws {
let py = try install("python/bin/python3", script: "#!/bin/sh\ncase \"$2\" in *sys.version_info*) echo 3.9;; esac\nexit 0\n")
- XCTAssertNotEqual(BuildModel.findPython(resources: root).path, py)
+ XCTAssertNotEqual(Toolchain.findPython(resources: root).path, py)
}
/// The order of #107 and #154: the bundled Python (when it runs, is new enough and imports the
/// packages) beats a working uv interpreter; a damaged bundled one falls through to uv's.
func testBundledPythonBeatsUvAndAUvOneIsNextWhenItFails() throws {
- let oldShim = BuildModel.uvShimDir, oldRoot = BuildModel.uvPythonRoot
- defer { BuildModel.uvShimDir = oldShim; BuildModel.uvPythonRoot = oldRoot }
+ let oldShim = Toolchain.uvShimDir, oldRoot = Toolchain.uvPythonRoot
+ defer { Toolchain.uvShimDir = oldShim; Toolchain.uvPythonRoot = oldRoot }
let good = "#!/bin/sh\ncase \"$2\" in *sys.version_info*) echo 3.13;; esac\nexit 0\n"
let shim = root.appendingPathComponent("uvhome/.local/bin")
try FileManager.default.createDirectory(at: shim, withIntermediateDirectories: true)
let uvPy = shim.appendingPathComponent("python3")
try Data(good.utf8).write(to: uvPy)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: uvPy.path)
- BuildModel.uvShimDir = shim.path
- BuildModel.uvPythonRoot = root.appendingPathComponent("uvhome/none").path
+ Toolchain.uvShimDir = shim.path
+ Toolchain.uvPythonRoot = root.appendingPathComponent("uvhome/none").path
let bundled = try install("python/bin/python3", script: good)
- XCTAssertEqual(BuildModel.findPython(resources: root).path, bundled)
+ XCTAssertEqual(Toolchain.findPython(resources: root).path, bundled)
try Data("#!/bin/sh\nexit 1\n".utf8).write(to: URL(fileURLWithPath: bundled))
- XCTAssertTrue(BuildModel.pythonCandidates().contains(uvPy.path))
- let next = BuildModel.findPython(resources: root)
+ XCTAssertTrue(Toolchain.pythonCandidates().contains(uvPy.path))
+ let next = Toolchain.findPython(resources: root)
XCTAssertNotEqual(next.path, bundled)
}
// ---- the interpreter probe ----
func testTheProbeRequiresZbicAndThePipPackagesInstallIt() {
- XCTAssertTrue(BuildModel.importProbe.contains("zbic"))
- for v in [(3, 12), (3, 13), (3, 14), (3, 15)] { XCTAssertTrue(BuildModel.pipPackages(v).contains("zbic"), "\(v)") }
+ XCTAssertTrue(Toolchain.importProbe.contains("zbic"))
+ for v in [(3, 12), (3, 13), (3, 14), (3, 15)] { XCTAssertTrue(Toolchain.pipPackages(v).contains("zbic"), "\(v)") }
}
func testAPythonWithoutZbicFailsTheProbe() throws {
@@ -232,9 +232,9 @@ final class BundledToolsTests: XCTestCase {
let old = ProcessInfo.processInfo.environment["PYTHONPATH"]
setenv("PYTHONPATH", dir.path, 1)
defer { if let old { setenv("PYTHONPATH", old, 1) } else { unsetenv("PYTHONPATH") } }
- XCTAssertFalse(BuildModel.importsOK(py), "zbic is missing")
+ XCTAssertFalse(Toolchain.importsOK(py), "zbic is missing")
try Data().write(to: dir.appendingPathComponent("zbic.py"))
- XCTAssertTrue(BuildModel.importsOK(py), "everything the probe names is there")
+ XCTAssertTrue(Toolchain.importsOK(py), "everything the probe names is there")
}
// ---- the pinned packages ----
@@ -247,7 +247,7 @@ final class BundledToolsTests: XCTestCase {
// a requirement starts at column 0, its --hash lines are indented continuations
let pins = text.split(separator: "\n").filter { !$0.hasPrefix("#") && !$0.hasPrefix(" ") && !$0.isEmpty }
let names = Set(pins.map { String($0.split(separator: "=", maxSplits: 1)[0]).lowercased() })
- for pkg in BuildModel.pipPackages((3, 13)) {
+ for pkg in Toolchain.pipPackages((3, 13)) {
XCTAssertTrue(names.contains(pkg.lowercased()), "\(pkg) is installed by the launcher's venv but not pinned for the bundle")
}
XCTAssertTrue(pins.allSatisfy { $0.contains("==") }, "every bundled package has an exact version")
diff --git a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
index 351158ba..31728828 100644
--- a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
@@ -376,7 +376,7 @@ final class CheatFilesTests: XCTestCase {
let model = BuildModel()
model.lang = .en
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
let id = try library.addApp(app)
library.recordCompletedIOS(archive: "", app: ios.path, device: "00008150-AAAA", for: id)
diff --git a/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift b/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
index c108bfa1..96f79b48 100644
--- a/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
+++ b/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
@@ -97,7 +97,7 @@ final class DiagnosticsTests: XCTestCase {
}
func testADependencyIsDescribedInEnglish() {
- let python = BuildModel.Dep(id: "python", name: "dep.python", hint: "dep.python.hint", present: false,
+ let python = Dep(id: "python", name: "dep.python", hint: "dep.python.hint", present: false,
detail: "dep.python.old:3.9:3.12", installCmd: [])
let row = Diagnostics.dependency(python)
XCTAssertEqual(row.name, L10n.string("dep.python", .en))
@@ -105,7 +105,7 @@ final class DiagnosticsTests: XCTestCase {
// passing the remainder whole printed "3.9:3.12" for the first %@ and "(null)" for the second.
XCTAssertEqual(row.detail, String(format: L10n.string("dep.python.old", .en), "3.9", "3.12"))
XCTAssertFalse(row.detail.contains("(null)"))
- let zstd = BuildModel.Dep(id: "brew:zstd", name: "dep.zstd", hint: "dep.zstd.hint", present: true, detail: "/opt/homebrew/bin/zstd", installCmd: [])
+ let zstd = Dep(id: "brew:zstd", name: "dep.zstd", hint: "dep.zstd.hint", present: true, detail: "/opt/homebrew/bin/zstd", installCmd: [])
XCTAssertEqual(Diagnostics.dependency(zstd).detail, "/opt/homebrew/bin/zstd")
}
diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
index 7497131d..fffb7a7a 100644
--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
@@ -24,84 +24,6 @@ final class DropFilesTests: XCTestCase {
return path
}
- /// The per-row Choose… dialog must not grey out compressed dumps (issue #236).
- func testChooseDialogOffersCompressedDumps() {
- XCTAssertEqual(Set(BuildModel.allowedFileTypes(for: .base)), ["nsp", "xci", "nsz", "xcz"])
- XCTAssertEqual(BuildModel.allowedFileTypes(for: .update), BuildModel.allowedFileTypes(for: .base))
- XCTAssertEqual(Set(BuildModel.allowedFileTypes(for: .dlc)), ["nsp", "nsz"])
- XCTAssertEqual(BuildModel.allowedFileTypes(for: .keys), ["keys"])
- }
-
- func testADroppedMixedSetIsSortedByTitleID() throws {
- let base = try file("Game [0100000000010000][v0].nsp", size: 64)
- let repack = try file("Game [0100000000010000].nsz", size: 32)
- let old = try file("Game [0100000000010800][v65536].nsp")
- let new = try file("Game [0100000000010800][v131072].nsz")
- let dlc1 = try file("Game DLC [0100000000011001].nsp"), dlc2 = try file("Game DLC [0100000000011002].xci")
- let keys = try file("prod.keys")
- let unfinished = try file("Game [0100000000010000].xci", size: 0)
- let unnamed = try file("game.nsp"), text = try file("readme.txt")
- let found = BuildModel.classify([dlc2, text, old, repack, unfinished, base, keys, new, unnamed, dlc1])
- XCTAssertEqual(found, BuildModel.FoundInputs(base: base, update: new, dlc: [dlc1, dlc2], keys: keys),
- "the largest base, the newest update, every add-on sorted, the keys")
- XCTAssertEqual(BuildModel.classify([text, unnamed]), BuildModel.FoundInputs())
- XCTAssertFalse(BuildModel.FoundInputs(keys: keys).anyGame)
- }
-
- /// The names from issue #237: the title ID bare at the start of the name, the version as a `_vN` token.
- func testBareTitleIDNamesAreClassified() throws {
- let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp", size: 64)
- let old = try file("01007EF00011E800_v1048576_48d51e6d7ff4.nsp")
- let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")
- let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")
- let dlc2 = try file("01007EF00011F002_v196608_193e5731baf2.nsp")
- let found = BuildModel.classify([dlc2, old, base, dlc1, new])
- XCTAssertEqual(found, BuildModel.FoundInputs(base: base, update: new, dlc: [dlc1, dlc2]))
- XCTAssertEqual(found.updateCount, 2)
- XCTAssertEqual(found.updateVersion, 1114112)
- // bracket names keep working, and win when a name has both
- XCTAssertEqual(BuildModel.titleID("Game [0100F2C0115B6000][v0].nsp"), 0x0100F2C0115B6000)
- XCTAssertEqual(BuildModel.titleID("Game 0100AAAA00000000 [0100F2C0115B6000].nsp"), 0x0100F2C0115B6000)
- XCTAssertEqual(BuildModel.updateVersion("Game [v65536] _v1.nsp"), 65536)
- XCTAssertEqual(BuildModel.updateVersion("Game v131072.nsp"), 131072)
- XCTAssertEqual(BuildModel.updateVersion("01007EF00011E800_v1114112_038ff9df0888.nsp"), 1114112)
- XCTAssertEqual(BuildModel.updateVersion("game.nsp"), 0)
- // token separators, and only IDs that look like Switch title IDs
- XCTAssertEqual(BuildModel.titleID("Game (01007EF00011E000).nsp"), 0x01007EF00011E000)
- XCTAssertEqual(BuildModel.titleID("Game-01007EF00011E000.nsp"), 0x01007EF00011E000)
- XCTAssertNil(BuildModel.titleID("0200000000000000_v0.nsp"))
- XCTAssertNil(BuildModel.titleID("x01007EF00011E000.nsp"), "not a token")
- XCTAssertNil(BuildModel.titleID("01007EF00011E0001.nsp"), "17 digits")
- // another game's update and DLC in the same folder are not taken for this base
- let other = try file("0100AAAA00000800_v65536_aaaaaaaaaaaa.nsp")
- let otherDLC = try file("0100AAAA00001001_v0_bbbbbbbbbbbb.nsp")
- XCTAssertEqual(BuildModel.classify([base, new, dlc1, other, otherDLC]).update, new)
- XCTAssertEqual(BuildModel.classify([base, new, dlc1, other, otherDLC]).dlc, [dlc1])
- }
-
- func testRowChecks() throws {
- let base = "01007EF00011E000_v0_420d1c5034ab.nsp"
- let update = "01007EF00011E800_v1114112_038ff9df0888.nsp"
- let dlc = "01007EF00011F001_v196608_8a46aae731b8.nsp"
- func check(_ kind: InputKind, _ name: String, _ b: String? = base) -> BuildModel.RowMismatch? {
- BuildModel.rowMismatch(kind, name: name, base: b)
- }
- XCTAssertNil(check(.update, update))
- XCTAssertNil(check(.dlc, dlc))
- XCTAssertNil(check(.base, base, nil))
- XCTAssertEqual(check(.dlc, update), .notDLC(0x01007EF00011E800), "the reporter's update in the DLC row")
- XCTAssertEqual(check(.update, dlc), .notUpdate(0x01007EF00011F001))
- XCTAssertEqual(check(.dlc, base), .notDLC(0x01007EF00011E000))
- XCTAssertEqual(check(.update, base), .notUpdate(0x01007EF00011E000))
- XCTAssertEqual(check(.base, update, nil), .notBase(0x01007EF00011E800))
- XCTAssertEqual(check(.base, dlc, nil), .notBase(0x01007EF00011F001))
- XCTAssertEqual(check(.update, "0100AAAA00000800_v1.nsp"), .otherGame)
- XCTAssertEqual(check(.dlc, "0100AAAA00001001_v1.nsp"), .otherGame)
- XCTAssertNil(check(.update, "0100AAAA00000800_v1.nsp", nil), "no base chosen yet")
- XCTAssertNil(check(.dlc, "game.nsp"), "no title ID in the name: the build script reads it from the package")
- XCTAssertNil(check(.keys, "prod.keys"))
- }
-
func testPickedFilesThatDoNotFitTheRowAreNotTaken() throws {
let m = BuildModel()
let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp")
@@ -213,7 +135,7 @@ final class DropFilesTests: XCTestCase {
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
// the page as a drag shows it: the highlight drawn over the Builds page
let page = BuilderView(m: model, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)
diff --git a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
index 366291a2..6dc4cd43 100644
--- a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
+++ b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
@@ -174,7 +174,7 @@ final class KeyCheckTests: XCTestCase {
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
let base = try pfs0([("a.nca", ncaHeader(generation: 0x0C))], name: "Metroid Dread [010093801237C000].nsp")
let update = try pfs0([("b.nca", ncaHeader(generation: 0x13))], name: "Metroid Dread [010093801237C800][v327680].nsp")
diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
index a5cef2ce..19ebb273 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -73,8 +73,8 @@ final class LauncherControlWidthTests: XCTestCase {
// The names of devices and teams are the user's own, so the scenarios use short ones: only the launcher's words are measured.
let team = SigningTeam(id: "E75GJAP35S", identity: "Apple Development: Mia (ABCDE12345)")
let release = AppUpdate.Release(tag: "v9.9.9", url: "https://example.org/app.zip", digest: nil)
- func missing(_ id: String, action: String = "", command: [String] = []) -> BuildModel.Dep {
- BuildModel.Dep(id: id, name: "dep.xcode", hint: "dep.xcode.hint", present: false, actionLabel: action, installCmd: command)
+ func missing(_ id: String, action: String = "", command: [String] = []) -> Dep {
+ Dep(id: id, name: "dep.xcode", hint: "dep.xcode.hint", present: false, actionLabel: action, installCmd: command)
}
return [
Scenario(name: "settings without a repository", page: .settings, atLeast: 4) { m, _, _ in
@@ -85,7 +85,7 @@ final class LauncherControlWidthTests: XCTestCase {
m.repoPath = try self.makeRepo(directory, git: false)
m.appInstallability = .ok
m.depsChecked = true
- m.deps = [BuildModel.Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])]
+ m.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])]
library.setFolder(directory)
},
Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in
diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swift
index 562beede..fa84e2f0 100644
--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift
+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift
@@ -283,24 +283,6 @@ final class LibraryTests: XCTestCase {
XCTAssertLessThan(Date().timeIntervalSince(stopped), 3)
}
- func testProgressDetailReadsTheScriptsCounts() {
- XCTAssertEqual(BuildModel.progressDetail(["step": "splitting", "done": 1203, "total": 19592, "unit": "shaders", "eta": 130]),
- "splitting · " + NumberFormatter.localizedString(from: 1203, number: .decimal) + " / "
- + NumberFormatter.localizedString(from: 19592, number: .decimal) + " shaders")
- XCTAssertEqual(BuildModel.progressDetail(["done": 2301, "unit": "files"]), NumberFormatter.localizedString(from: 2301, number: .decimal) + " files")
- XCTAssertTrue(BuildModel.progressDetail(["done": 1_000_000_000, "total": 3_000_000_000, "unit": "B", "est": true]).contains(" / ~"))
- XCTAssertEqual(BuildModel.progressDetail(["step": "booting the game"]), "booting the game")
- }
-
- /// The stage's clock runs on while the count stands still, and the script's estimate counts down from when it came, then goes.
- func testStageClockCountsOnAndTheEstimateRunsOut() {
- let t0 = Date()
- let stage = Stage(id: 1, name: "shader split", started: t0, eta: 71, etaAt: t0.addingTimeInterval(10))
- XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(42), left: "%@ left"), "0:42 · " + BuildModel.duration(39) + " left")
- XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(125), left: "%@ left"), "2:05") // the estimate ran out: no stale "1 min 11 s left"
- XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(3725), left: "%@ left"), "1:02:05")
- }
-
/// Stop ends the build and leaves no stage behind (a spinner and a percentage of a build that no longer runs).
@MainActor func testStoppedBuildResetsItsProgress() throws {
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
@@ -313,7 +295,7 @@ final class LibraryTests: XCTestCase {
model.pythonPath = "/usr/bin/python3"
model.dotnetPath = "/usr/bin/true"
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")
try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data().write(to: marker)
@@ -596,7 +578,7 @@ final class LibraryTests: XCTestCase {
model.pythonPath = "/usr/bin/python3"
model.dotnetPath = "/usr/bin/true"
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")
try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data().write(to: marker)
@@ -683,7 +665,7 @@ final class LibraryTests: XCTestCase {
model.repoPath = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path
model.lang = .en
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
for game in real_.games.sorted(by: { $0.name < $1.name }) {
let name = game.name.replacingOccurrences(of: #"\s*\([0-9.]+ GB\)"#, with: "", options: .regularExpression)
if game.titleID == botw { _ = try library.addApp(makeApp(botw, name: name)) }
@@ -790,7 +772,7 @@ final class LibraryTests: XCTestCase {
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
let examples = [(titleID, "Hades"), ("01007EF00011E000", "The Legend of Zelda: Breath of the Wild"),
("0100000000010000", "Super Mario Odyssey"), ("010093801237C000", "Metroid Dread")]
@@ -1101,52 +1083,16 @@ final class LibraryTests: XCTestCase {
}
}
- /// Issue #52: the failure note names the last real line, not just the exit code.
- func testLastMeaningfulLineSkipsProgressEventsAndBlankLines() {
- let log = """
- [1/7] extract
- {"event":"progress","frac":0.4}
-
- RuntimeError: no prod.keys in the game folder
-
- """
- XCTAssertEqual(BuildModel.lastMeaningfulLine(log), "RuntimeError: no prod.keys in the game folder")
- XCTAssertNil(BuildModel.lastMeaningfulLine("\n\n"))
- XCTAssertNil(BuildModel.lastMeaningfulLine("{\"event\":\"stage_end\"}\n"))
- }
-
- /// Issue #58: a folder holding several games is staged down to the picked one, and its update
- /// and add-on content come along — classified exactly as build_ipa_from_nsp.py:445 does.
- func testSiblingsOfThePickedGameAreClassifiedAsTheScriptDoes() {
- let base = UInt64(0x010015100B514000)
- let app = base & ~UInt64(0xFFF)
- func owner(_ tid: UInt64) -> UInt64 {
- let low = tid & 0xFFF
- return low == 0 ? tid : (low == 0x800 ? tid & ~UInt64(0xFFF) : (tid & ~UInt64(0xFFF)) - 0x1000)
- }
- XCTAssertEqual(owner(base), app, "the base game")
- XCTAssertEqual(owner(base + 0x800), app, "its update")
- XCTAssertEqual(owner(base + 0x1001), app, "add-on content 1")
- XCTAssertNotEqual(owner(UInt64(0x01007EF00011E000)), app, "another game")
- XCTAssertNotEqual(owner(UInt64(0x01007EF00011E800)), app, "another game's update")
- }
-
- func testTitleIDReadsTheBracketedFormTheFilesUse() {
- XCTAssertEqual(BuildModel.titleID("Mario Wonder [010015100B514000][v0].nsp"), 0x010015100B514000)
- XCTAssertEqual(BuildModel.titleID("/ROMs/TotK [01007EF00011E000].xci"), 0x01007EF00011E000)
- XCTAssertNil(BuildModel.titleID("no title id here.nsp"))
- }
-
/// Issue #53: the interpreter floor is the script's own, so Apple's 3.9 is never picked.
func testThePythonFloorIsTheScriptsOwnThreeTwelve() {
- XCTAssertEqual(BuildModel.minPython.0, 3)
- XCTAssertEqual(BuildModel.minPython.1, 12,
+ XCTAssertEqual(Toolchain.minPython.0, 3)
+ XCTAssertEqual(Toolchain.minPython.1, 12,
"build_ipa_from_nsp.py:1911 refuses anything below 3.12; a lower floor let the "
+ "app pick /usr/bin/python3 and the build died in the script")
- let (path, _) = BuildModel.findPython()
+ let (path, _) = Toolchain.findPython()
XCTAssertFalse(path.isEmpty, "a Mac with any usable interpreter must yield one")
- if let v = BuildModel.pythonVersion(path) {
- let floor = BuildModel.minPython
+ if let v = Toolchain.pythonVersion(path) {
+ let floor = Toolchain.minPython
XCTAssertTrue(v.0 > floor.0 || (v.0 == floor.0 && v.1 >= floor.1),
"picked \(path) at \(v.0).\(v.1), below the \(floor.0).\(floor.1) floor")
}
@@ -1156,8 +1102,8 @@ final class LibraryTests: XCTestCase {
/// hides ~/.local/bin: uv had a working 3.12 with the packages and the panel still said
/// "No Python 3.12 or newer found".
func testUvManagedPythonsAreCandidates() throws {
- let oldShim = BuildModel.uvShimDir, oldRoot = BuildModel.uvPythonRoot
- defer { BuildModel.uvShimDir = oldShim; BuildModel.uvPythonRoot = oldRoot }
+ let oldShim = Toolchain.uvShimDir, oldRoot = Toolchain.uvPythonRoot
+ defer { Toolchain.uvShimDir = oldShim; Toolchain.uvPythonRoot = oldRoot }
let shim = temporary.appendingPathComponent("local/bin")
let root = temporary.appendingPathComponent("uv/python")
let store = root.appendingPathComponent("cpython-3.12.13-macos-aarch64-none/bin")
@@ -1170,9 +1116,9 @@ final class LibraryTests: XCTestCase {
try Data("#!/bin/sh\n".utf8).write(to: dir.appendingPathComponent(name))
}
}
- BuildModel.uvShimDir = shim.path
- BuildModel.uvPythonRoot = root.path
- let cands = BuildModel.pythonCandidates()
+ Toolchain.uvShimDir = shim.path
+ Toolchain.uvPythonRoot = root.path
+ let cands = Toolchain.pythonCandidates()
XCTAssertTrue(cands.contains(shim.appendingPathComponent("python3").path),
"the uv shim must be probed: a GUI launch's PATH does not contain ~/.local/bin")
XCTAssertTrue(cands.contains(shim.appendingPathComponent("python3.12").path))
@@ -1184,11 +1130,11 @@ final class LibraryTests: XCTestCase {
/// interpreter. That cannot be a base: `-m venv` on it could not even start, so the Python
/// row stayed red however often 安装 was pressed.
func testVenvBaseIsNeverTheVenvItHasToCreate() throws {
- let oldShim = BuildModel.uvShimDir, oldRoot = BuildModel.uvPythonRoot, oldVenv = BuildModel.venvDir
+ let oldShim = Toolchain.uvShimDir, oldRoot = Toolchain.uvPythonRoot, oldVenv = Toolchain.venvDir
defer {
- BuildModel.uvShimDir = oldShim
- BuildModel.uvPythonRoot = oldRoot
- BuildModel.venvDir = oldVenv
+ Toolchain.uvShimDir = oldShim
+ Toolchain.uvPythonRoot = oldRoot
+ Toolchain.venvDir = oldVenv
}
let shim = temporary.appendingPathComponent("bin")
try FileManager.default.createDirectory(at: shim, withIntermediateDirectories: true)
@@ -1196,16 +1142,16 @@ final class LibraryTests: XCTestCase {
let interp = shim.appendingPathComponent("python3.12")
try Data("#!/bin/sh\n[ \"$1\" = -c ] && echo 3.12\nexit 0\n".utf8).write(to: interp)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: interp.path)
- BuildModel.uvShimDir = shim.path
- BuildModel.uvPythonRoot = temporary.appendingPathComponent("no-uv").path
- BuildModel.venvDir = temporary.appendingPathComponent("no-venv").path
+ Toolchain.uvShimDir = shim.path
+ Toolchain.uvPythonRoot = temporary.appendingPathComponent("no-uv").path
+ Toolchain.venvDir = temporary.appendingPathComponent("no-venv").path
- let wanted = BuildModel.venvPython() // findPython()'s last resort, and what the panel passes
- let base = try XCTUnwrap(BuildModel.venvBase(preferred: wanted), "a usable interpreter must be found")
+ let wanted = Toolchain.venvPython() // findPython()'s last resort, and what the panel passes
+ let base = try XCTUnwrap(Toolchain.venvBase(preferred: wanted), "a usable interpreter must be found")
XCTAssertNotEqual(base, wanted, "the venv cannot be the base it is created from")
- let v = try XCTUnwrap(BuildModel.pythonVersion(base))
- XCTAssertTrue(v.0 > BuildModel.minPython.0 || (v.0 == BuildModel.minPython.0 && v.1 >= BuildModel.minPython.1))
- XCTAssertEqual(BuildModel.venvBase(preferred: interp.path), interp.path,
+ let v = try XCTUnwrap(Toolchain.pythonVersion(base))
+ XCTAssertTrue(v.0 > Toolchain.minPython.0 || (v.0 == Toolchain.minPython.0 && v.1 >= Toolchain.minPython.1))
+ XCTAssertEqual(Toolchain.venvBase(preferred: interp.path), interp.path,
"an interpreter that does run at the required version is kept as given")
}
diff --git a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
index 06905d3f..e9918f5c 100644
--- a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
+++ b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
@@ -20,8 +20,8 @@ import XCTest
var os = OperatingSystemVersion(majorVersion: 26, minorVersion: 6, patchVersion: 0)
}
- func dep(_ id: String, present: Bool) -> BuildModel.Dep {
- BuildModel.Dep(id: id, name: "dep." + (id.hasPrefix("brew:") ? String(id.dropFirst(5)) : id), hint: "", present: present, installCmd: ["/usr/bin/true"])
+ func dep(_ id: String, present: Bool) -> Dep {
+ Dep(id: id, name: "dep." + (id.hasPrefix("brew:") ? String(id.dropFirst(5)) : id), hint: "", present: present, installCmd: ["/usr/bin/true"])
}
var defaults: UserDefaults!
@@ -39,7 +39,7 @@ import XCTest
addTeardownBlock { [home] in try? FileManager.default.removeItem(at: home!) }
}
- func make(_ fake: Fake, deps: [BuildModel.Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildModel) {
+ func make(_ fake: Fake, deps: [Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildModel) {
if let platform { defaults.set(platform.rawValue, forKey: OnboardingDefaults.platform) }
if let step { defaults.set(step.rawValue, forKey: OnboardingDefaults.step); defaults.set(true, forKey: OnboardingDefaults.inProgress) }
let model = BuildModel()
@@ -204,7 +204,7 @@ import XCTest
driver.finishXcodeSetup()
await driver.settle()
XCTAssertEqual(fake.adminCalls.count, 1)
- XCTAssertEqual(fake.commands, [BuildModel.metalToolchainCmd, BuildModel.iosPlatformCmd])
+ XCTAssertEqual(fake.commands, [Toolchain.metalToolchainCmd, Toolchain.iosPlatformCmd])
XCTAssertEqual(driver.state.xcode, .ready)
XCTAssertEqual(driver.state.setup[.ios], .done)
_ = model
@@ -220,7 +220,7 @@ import XCTest
await driver.refreshXcode()
driver.finishXcodeSetup()
await driver.settle()
- XCTAssertEqual(fake.commands, [BuildModel.metalToolchainCmd])
+ XCTAssertEqual(fake.commands, [Toolchain.metalToolchainCmd])
XCTAssertEqual(driver.state.xcode, .ready)
}
diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
index a2c1ed95..e6f984cc 100644
--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
@@ -778,7 +778,7 @@ final class ShellInstallTests: XCTestCase {
model.pythonPath = "/usr/bin/python3"
model.dotnetPath = "/usr/bin/true"
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
model.installDevice = device
model.signingTeam = team
model.xcrunPath = f.xcrun
@@ -842,7 +842,7 @@ final class ShellInstallTests: XCTestCase {
model.pythonPath = "/usr/bin/python3"
model.dotnetPath = "/usr/bin/true"
model.depsChecked = true
- model.deps = [BuildModel.Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
+ model.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
model.installDevice = device
model.signingTeam = team
model.xcrunPath = f.xcrun
diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
index e384f448..e9f35674 100644
--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
@@ -7,7 +7,7 @@ final class SourceSizeTests: XCTestCase {
/// Path under frontend/Sources → its line count when the limit came in. Lower the number when the file shrinks.
private static let aboveTheLimit: [String: Int] = [
- "NX2Apple/ContentView.swift": 3730,
+ "NX2Apple/ContentView.swift": 2943,
"NX2Apple/LauncherView.swift": 973,
"NXCore/Localization.swift": 4237,
]
diff --git a/frontend/Tests/NX2AppleTests/BrewfileTests.swift b/frontend/Tests/NXCoreTests/BrewfileTests.swift
similarity index 93%
rename from frontend/Tests/NX2AppleTests/BrewfileTests.swift
rename to frontend/Tests/NXCoreTests/BrewfileTests.swift
index ec47a0e8..5295d547 100644
--- a/frontend/Tests/NX2AppleTests/BrewfileTests.swift
+++ b/frontend/Tests/NXCoreTests/BrewfileTests.swift
@@ -1,7 +1,5 @@
import XCTest
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// #111: the repo-root Brewfile is the one list of Homebrew tools, and the launcher's dependency check offers the same.
final class BrewfileTests: XCTestCase {
@@ -25,7 +23,7 @@ final class BrewfileTests: XCTestCase {
}
func testBrewfileFormulaeAreTheLaunchersDependencies() throws {
- let launcher = Set(BuildModel.brewDeps.map { $0.formula })
+ let launcher = Set(Toolchain.brewDeps.map { $0.formula })
XCTAssertEqual(Set(try entries("brew")), launcher)
XCTAssertEqual(try entries("brew").count, launcher.count, "a formula is listed twice")
}
diff --git a/frontend/Tests/NXCoreTests/BuildProgressTests.swift b/frontend/Tests/NXCoreTests/BuildProgressTests.swift
new file mode 100644
index 00000000..1b639aac
--- /dev/null
+++ b/frontend/Tests/NXCoreTests/BuildProgressTests.swift
@@ -0,0 +1,77 @@
+import XCTest
+@testable import NXCore
+
+/// Reading what a build prints: stage lines, progress counts, durations and the steps of Xcode and the install.
+/// Runs on NXCore alone, without SwiftUI.
+final class BuildProgressTests: XCTestCase {
+ func testProgressDetailReadsTheScriptsCounts() {
+ XCTAssertEqual(BuildProgress.progressDetail(["step": "splitting", "done": 1203, "total": 19592, "unit": "shaders", "eta": 130]),
+ "splitting · " + NumberFormatter.localizedString(from: 1203, number: .decimal) + " / "
+ + NumberFormatter.localizedString(from: 19592, number: .decimal) + " shaders")
+ XCTAssertEqual(BuildProgress.progressDetail(["done": 2301, "unit": "files"]), NumberFormatter.localizedString(from: 2301, number: .decimal) + " files")
+ XCTAssertTrue(BuildProgress.progressDetail(["done": 1_000_000_000, "total": 3_000_000_000, "unit": "B", "est": true]).contains(" / ~"))
+ XCTAssertEqual(BuildProgress.progressDetail(["step": "booting the game"]), "booting the game")
+ }
+
+ /// The stage's clock runs on while the count stands still, and the script's estimate counts down from when it came, then goes.
+ func testStageClockCountsOnAndTheEstimateRunsOut() {
+ let t0 = Date()
+ let stage = Stage(id: 1, name: "shader split", started: t0, eta: 71, etaAt: t0.addingTimeInterval(10))
+ XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(42), left: "%@ left"), "0:42 · " + BuildProgress.duration(39) + " left")
+ XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(125), left: "%@ left"), "2:05") // the estimate ran out: no stale "1 min 11 s left"
+ XCTAssertEqual(stage.clock(at: t0.addingTimeInterval(3725), left: "%@ left"), "1:02:05")
+ }
+
+ /// Issue #52: the failure note names the last real line, not just the exit code.
+ func testLastMeaningfulLineSkipsProgressEventsAndBlankLines() {
+ let log = """
+ [1/7] extract
+ {"event":"progress","frac":0.4}
+
+ RuntimeError: no prod.keys in the game folder
+
+ """
+ XCTAssertEqual(BuildProgress.lastMeaningfulLine(log), "RuntimeError: no prod.keys in the game folder")
+ XCTAssertNil(BuildProgress.lastMeaningfulLine("\n\n"))
+ XCTAssertNil(BuildProgress.lastMeaningfulLine("{\"event\":\"stage_end\"}\n"))
+ }
+
+ func testDurationIsWrittenByHandInEnglish() {
+ XCTAssertEqual(BuildProgress.duration(0), "1s", "never below one second")
+ XCTAssertEqual(BuildProgress.duration(3.2), "4s", "rounded up")
+ XCTAssertEqual(BuildProgress.duration(60), "1m")
+ XCTAssertEqual(BuildProgress.duration(125), "2m 5s")
+ XCTAssertEqual(BuildProgress.duration(3600), "1h")
+ XCTAssertEqual(BuildProgress.duration(3600 + 120), "1h 2m")
+ }
+
+ func testParseStageReadsTheScriptsLineForm() throws {
+ let start = try XCTUnwrap(BuildProgress.parseStage("[12:00:01] [2/7] extract v720896 …"))
+ XCTAssertEqual(start.k, 2)
+ XCTAssertEqual(start.name, "extract v720896")
+ XCTAssertEqual(start.state, .running)
+ XCTAssertNil(start.percent)
+ let done = try XCTUnwrap(BuildProgress.parseStage("[12:00:20] ✓ [2/7] extract v720896 (0:19): 30,000 files, 3.4 GB"))
+ XCTAssertEqual(done.name, "extract v720896")
+ XCTAssertEqual(done.state, .done)
+ XCTAssertEqual(done.detail, "30,000 files, 3.4 GB")
+ XCTAssertEqual(done.percent, 100)
+ let failed = try XCTUnwrap(BuildProgress.parseStage("✗ [3/7] rewrite (0:02)"))
+ XCTAssertEqual(failed.state, .failed)
+ let counting = try XCTUnwrap(BuildProgress.parseStage("[4/7] shader split · 26%, 10,577 / 41,062 files"))
+ XCTAssertEqual(counting.name, "shader split")
+ XCTAssertEqual(counting.percent, 26)
+ XCTAssertNil(BuildProgress.parseStage("no stage in this line"))
+ }
+
+ func testXcodeAndInstallStepsNameWhatIsHappening() {
+ XCTAssertEqual(BuildProgress.xcodeStep("CompileC build/x.o")?.detail, "compiling")
+ XCTAssertEqual(BuildProgress.xcodeStep("Ld build/x")?.detail, "linking")
+ XCTAssertEqual(BuildProgress.xcodeStep("CodeSign build/x.app")?.detail, "signing")
+ XCTAssertNil(BuildProgress.xcodeStep("note: something else"))
+ XCTAssertEqual(BuildProgress.installStep("Installing … 45%")?.percent, 45)
+ XCTAssertEqual(BuildProgress.installStep("Installing … 45%")?.detail, "installing")
+ XCTAssertEqual(BuildProgress.installStep("done 250%")?.percent, 100, "capped")
+ XCTAssertNil(BuildProgress.installStep("no number here"))
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/DependencyFailureTests.swift b/frontend/Tests/NXCoreTests/DependencyFailureTests.swift
similarity index 72%
rename from frontend/Tests/NX2AppleTests/DependencyFailureTests.swift
rename to frontend/Tests/NXCoreTests/DependencyFailureTests.swift
index 1f773ae6..75f2df76 100644
--- a/frontend/Tests/NX2AppleTests/DependencyFailureTests.swift
+++ b/frontend/Tests/NXCoreTests/DependencyFailureTests.swift
@@ -1,13 +1,11 @@
import XCTest
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// A failed dependency install must say why and what to type — the report that motivated this
/// showed a spinner turning back into a button with the reason buried in the log.
final class DependencyFailureTests: XCTestCase {
func testABrewPermissionProblemNamesTheChownCommand() {
- let (error, fix) = BuildModel.failureInfo([
+ let (error, fix) = BuildProgress.failureInfo([
"Error: ", "/opt/homebrew is not writable. You should change the",
"ownership and permissions of /opt/homebrew back to your",
"user account:", " sudo chown -R junli /opt/homebrew",
@@ -17,19 +15,19 @@ final class DependencyFailureTests: XCTestCase {
}
func testAMissingBrewSaysWhereToInstallIt() {
- XCTAssertEqual(BuildModel.failureInfo(["/bin/bash: line 1: brew: command not found"]).fix, "dep.fix.brewMissing")
+ XCTAssertEqual(BuildProgress.failureInfo(["/bin/bash: line 1: brew: command not found"]).fix, "dep.fix.brewMissing")
}
func testTheXcodeLicenseIsNamed() {
- XCTAssertEqual(BuildModel.failureInfo(["Error: You have not agreed to the Xcode license."]).fix, "dep.fix.xcodeLicense")
+ XCTAssertEqual(BuildProgress.failureInfo(["Error: You have not agreed to the Xcode license."]).fix, "dep.fix.xcodeLicense")
}
func testANetworkFailureIsNamed() {
- XCTAssertEqual(BuildModel.failureInfo(["curl: (6) Could not resolve host: github.com"]).fix, "dep.fix.network")
+ XCTAssertEqual(BuildProgress.failureInfo(["curl: (6) Could not resolve host: github.com"]).fix, "dep.fix.network")
}
func testAnUnknownFailurePointsAtTheLog() {
- let (error, fix) = BuildModel.failureInfo(["something odd happened", "still odd"])
+ let (error, fix) = BuildProgress.failureInfo(["something odd happened", "still odd"])
XCTAssertEqual(fix, "dep.fix.log")
XCTAssertFalse(error.isEmpty)
}
diff --git a/frontend/Tests/NXCoreTests/GameInputsTests.swift b/frontend/Tests/NXCoreTests/GameInputsTests.swift
new file mode 100644
index 00000000..15c785cb
--- /dev/null
+++ b/frontend/Tests/NXCoreTests/GameInputsTests.swift
@@ -0,0 +1,102 @@
+import XCTest
+@testable import NXCore
+
+/// Which files make a game: classifying dropped files and a chosen folder into the four rows, and what a row accepts.
+/// Runs on NXCore alone, without SwiftUI.
+final class GameInputsTests: XCTestCase {
+ private var temporary: URL!
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-inputs-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }
+
+ /// A stand-in file of `size` bytes (the classification skips empty ones, as an unfinished download leaves).
+ @discardableResult private func file(_ name: String, size: Int = 16, in folder: String = "") throws -> String {
+ let dir = folder.isEmpty ? temporary! : temporary.appendingPathComponent(folder)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let path = dir.appendingPathComponent(name).path
+ FileManager.default.createFile(atPath: path, contents: Data(repeating: 0, count: size))
+ return path
+ }
+
+ /// The per-row Choose… dialog must not grey out compressed dumps (issue #236).
+ func testChooseDialogOffersCompressedDumps() {
+ XCTAssertEqual(Set(GameInputs.allowedFileTypes(for: .base)), ["nsp", "xci", "nsz", "xcz"])
+ XCTAssertEqual(GameInputs.allowedFileTypes(for: .update), GameInputs.allowedFileTypes(for: .base))
+ XCTAssertEqual(Set(GameInputs.allowedFileTypes(for: .dlc)), ["nsp", "nsz"])
+ XCTAssertEqual(GameInputs.allowedFileTypes(for: .keys), ["keys"])
+ }
+
+ func testADroppedMixedSetIsSortedByTitleID() throws {
+ let base = try file("Game [0100000000010000][v0].nsp", size: 64)
+ let repack = try file("Game [0100000000010000].nsz", size: 32)
+ let old = try file("Game [0100000000010800][v65536].nsp")
+ let new = try file("Game [0100000000010800][v131072].nsz")
+ let dlc1 = try file("Game DLC [0100000000011001].nsp"), dlc2 = try file("Game DLC [0100000000011002].xci")
+ let keys = try file("prod.keys")
+ let unfinished = try file("Game [0100000000010000].xci", size: 0)
+ let unnamed = try file("game.nsp"), text = try file("readme.txt")
+ let found = GameInputs.classify([dlc2, text, old, repack, unfinished, base, keys, new, unnamed, dlc1])
+ XCTAssertEqual(found, GameInputs.Found(base: base, update: new, dlc: [dlc1, dlc2], keys: keys),
+ "the largest base, the newest update, every add-on sorted, the keys")
+ XCTAssertEqual(GameInputs.classify([text, unnamed]), GameInputs.Found())
+ XCTAssertFalse(GameInputs.Found(keys: keys).anyGame)
+ }
+
+ /// The names from issue #237: the title ID bare at the start of the name, the version as a `_vN` token.
+ func testBareTitleIDNamesAreClassified() throws {
+ let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp", size: 64)
+ let old = try file("01007EF00011E800_v1048576_48d51e6d7ff4.nsp")
+ let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")
+ let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")
+ let dlc2 = try file("01007EF00011F002_v196608_193e5731baf2.nsp")
+ let found = GameInputs.classify([dlc2, old, base, dlc1, new])
+ XCTAssertEqual(found, GameInputs.Found(base: base, update: new, dlc: [dlc1, dlc2]))
+ XCTAssertEqual(found.updateCount, 2)
+ XCTAssertEqual(found.updateVersion, 1114112)
+ // bracket names keep working, and win when a name has both
+ XCTAssertEqual(TitleID.parse("Game [0100F2C0115B6000][v0].nsp"), 0x0100F2C0115B6000)
+ XCTAssertEqual(TitleID.parse("Game 0100AAAA00000000 [0100F2C0115B6000].nsp"), 0x0100F2C0115B6000)
+ XCTAssertEqual(TitleID.updateVersion("Game [v65536] _v1.nsp"), 65536)
+ XCTAssertEqual(TitleID.updateVersion("Game v131072.nsp"), 131072)
+ XCTAssertEqual(TitleID.updateVersion("01007EF00011E800_v1114112_038ff9df0888.nsp"), 1114112)
+ XCTAssertEqual(TitleID.updateVersion("game.nsp"), 0)
+ // token separators, and only IDs that look like Switch title IDs
+ XCTAssertEqual(TitleID.parse("Game (01007EF00011E000).nsp"), 0x01007EF00011E000)
+ XCTAssertEqual(TitleID.parse("Game-01007EF00011E000.nsp"), 0x01007EF00011E000)
+ XCTAssertNil(TitleID.parse("0200000000000000_v0.nsp"))
+ XCTAssertNil(TitleID.parse("x01007EF00011E000.nsp"), "not a token")
+ XCTAssertNil(TitleID.parse("01007EF00011E0001.nsp"), "17 digits")
+ // another game's update and DLC in the same folder are not taken for this base
+ let other = try file("0100AAAA00000800_v65536_aaaaaaaaaaaa.nsp")
+ let otherDLC = try file("0100AAAA00001001_v0_bbbbbbbbbbbb.nsp")
+ XCTAssertEqual(GameInputs.classify([base, new, dlc1, other, otherDLC]).update, new)
+ XCTAssertEqual(GameInputs.classify([base, new, dlc1, other, otherDLC]).dlc, [dlc1])
+ }
+
+ func testRowChecks() throws {
+ let base = "01007EF00011E000_v0_420d1c5034ab.nsp"
+ let update = "01007EF00011E800_v1114112_038ff9df0888.nsp"
+ let dlc = "01007EF00011F001_v196608_8a46aae731b8.nsp"
+ func check(_ kind: InputKind, _ name: String, _ b: String? = base) -> GameInputs.RowMismatch? {
+ GameInputs.rowMismatch(kind, name: name, base: b)
+ }
+ XCTAssertNil(check(.update, update))
+ XCTAssertNil(check(.dlc, dlc))
+ XCTAssertNil(check(.base, base, nil))
+ XCTAssertEqual(check(.dlc, update), .notDLC(0x01007EF00011E800), "the reporter's update in the DLC row")
+ XCTAssertEqual(check(.update, dlc), .notUpdate(0x01007EF00011F001))
+ XCTAssertEqual(check(.dlc, base), .notDLC(0x01007EF00011E000))
+ XCTAssertEqual(check(.update, base), .notUpdate(0x01007EF00011E000))
+ XCTAssertEqual(check(.base, update, nil), .notBase(0x01007EF00011E800))
+ XCTAssertEqual(check(.base, dlc, nil), .notBase(0x01007EF00011F001))
+ XCTAssertEqual(check(.update, "0100AAAA00000800_v1.nsp"), .otherGame)
+ XCTAssertEqual(check(.dlc, "0100AAAA00001001_v1.nsp"), .otherGame)
+ XCTAssertNil(check(.update, "0100AAAA00000800_v1.nsp", nil), "no base chosen yet")
+ XCTAssertNil(check(.dlc, "game.nsp"), "no title ID in the name: the build script reads it from the package")
+ XCTAssertNil(check(.keys, "prod.keys"))
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/PythonVenvTests.swift b/frontend/Tests/NXCoreTests/PythonVenvTests.swift
similarity index 77%
rename from frontend/Tests/NX2AppleTests/PythonVenvTests.swift
rename to frontend/Tests/NXCoreTests/PythonVenvTests.swift
index 4a702d05..afe7e5ba 100644
--- a/frontend/Tests/NX2AppleTests/PythonVenvTests.swift
+++ b/frontend/Tests/NXCoreTests/PythonVenvTests.swift
@@ -1,7 +1,5 @@
import XCTest
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// A stale venv below minPython (issue #75) and Pythons managed by mise or asdf (issue #113).
final class PythonVenvTests: XCTestCase {
@@ -11,11 +9,11 @@ final class PythonVenvTests: XCTestCase {
override func setUpWithError() throws {
tmp = FileManager.default.temporaryDirectory.appendingPathComponent("pyvenv-" + UUID().uuidString)
try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
- oldVenv = BuildModel.venvDir; oldMise = BuildModel.miseDataDir; oldAsdf = BuildModel.asdfDataDir
+ oldVenv = Toolchain.venvDir; oldMise = Toolchain.miseDataDir; oldAsdf = Toolchain.asdfDataDir
}
override func tearDownWithError() throws {
- BuildModel.venvDir = oldVenv; BuildModel.miseDataDir = oldMise; BuildModel.asdfDataDir = oldAsdf
+ Toolchain.venvDir = oldVenv; Toolchain.miseDataDir = oldMise; Toolchain.asdfDataDir = oldAsdf
try? FileManager.default.removeItem(at: tmp)
}
@@ -30,29 +28,29 @@ final class PythonVenvTests: XCTestCase {
}
func testAVenvBelowTheFloorIsNotReturnedAsReady() throws {
- BuildModel.venvDir = tmp.appendingPathComponent("venv").path
+ Toolchain.venvDir = tmp.appendingPathComponent("venv").path
let vpy = try stub("venv/bin/python3", version: "3.9")
- let found = BuildModel.findPython(resources: tmp)
+ let found = Toolchain.findPython(resources: tmp)
XCTAssertFalse(found.path == vpy && found.ok, "a 3.9 venv with every package is still too old")
// With nothing else on the Mac the row reports the old state, not ready.
- let detail = BuildModel.pythonDetail(py: vpy, ok: false)
+ let detail = Toolchain.pythonDetail(py: vpy, ok: false)
XCTAssertTrue(detail.hasPrefix("dep.python.old:3.9:"), detail)
}
func testAVenvAtTheFloorIsStillReady() throws {
- BuildModel.venvDir = tmp.appendingPathComponent("venv").path
+ Toolchain.venvDir = tmp.appendingPathComponent("venv").path
let vpy = try stub("venv/bin/python3", version: "3.12")
- let found = BuildModel.findPython(resources: tmp)
+ let found = Toolchain.findPython(resources: tmp)
// A system Python with the packages may win on a developer Mac, the venv must not be rejected.
XCTAssertTrue(found.ok)
XCTAssertTrue(found.path == vpy || FileManager.default.isExecutableFile(atPath: found.path))
}
func testMakeVenvMovesATooOldVenvAside() throws {
- BuildModel.venvDir = tmp.appendingPathComponent("venv").path
+ Toolchain.venvDir = tmp.appendingPathComponent("venv").path
try stub("venv/bin/python3", version: "3.9")
let base = try stub("base/python3", version: "3.12")
- _ = BuildModel.makeVenv(base: base)
+ _ = Toolchain.makeVenv(base: base)
let names = try FileManager.default.contentsOfDirectory(atPath: tmp.path)
let aside = names.filter { $0.hasPrefix("venv.old-") }
XCTAssertEqual(aside.count, 1, "the old venv is renamed, not deleted: \(names)")
@@ -61,22 +59,22 @@ final class PythonVenvTests: XCTestCase {
}
func testMakeVenvLeavesAVenvAtTheFloorInPlace() throws {
- BuildModel.venvDir = tmp.appendingPathComponent("venv").path
+ Toolchain.venvDir = tmp.appendingPathComponent("venv").path
let vpy = try stub("venv/bin/python3", version: "3.12")
- _ = BuildModel.makeVenv(base: vpy)
+ _ = Toolchain.makeVenv(base: vpy)
XCTAssertTrue(FileManager.default.isExecutableFile(atPath: vpy))
XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: tmp.path).contains { $0.hasPrefix("venv.old-") })
}
func testMiseAndAsdfPythonsAreCandidates() throws {
- BuildModel.miseDataDir = tmp.appendingPathComponent("mise").path
- BuildModel.asdfDataDir = tmp.appendingPathComponent("asdf").path
+ Toolchain.miseDataDir = tmp.appendingPathComponent("mise").path
+ Toolchain.asdfDataDir = tmp.appendingPathComponent("asdf").path
let install = try stub("mise/installs/python/3.12.8/bin/python3", version: "3.12")
let minor = try stub("mise/installs/python/3.12.8/bin/python3.12", version: "3.12")
let config = try stub("mise/installs/python/3.12.8/bin/python3-config", version: "3.12")
let shim = try stub("mise/shims/python3", version: "3.12")
let asdf = try stub("asdf/installs/python/3.13.1/bin/python3", version: "3.13")
- let cands = BuildModel.pythonCandidates()
+ let cands = Toolchain.pythonCandidates()
for p in [install, minor, shim, asdf] { XCTAssertTrue(cands.contains(p), p) }
XCTAssertFalse(cands.contains(config), "python3-config is not an interpreter")
}
diff --git a/frontend/Tests/NXCoreTests/TitleIDTests.swift b/frontend/Tests/NXCoreTests/TitleIDTests.swift
new file mode 100644
index 00000000..a8de577e
--- /dev/null
+++ b/frontend/Tests/NXCoreTests/TitleIDTests.swift
@@ -0,0 +1,69 @@
+import XCTest
+@testable import NXCore
+
+/// #382: a file name without a title ID used to give the work folder `game_build` and the app `game.app` for every game,
+/// so a second game hit the first one's shader cache. One key per game now.
+final class TitleIDTests: XCTestCase {
+ func testNameWithTitleIDKeepsItsFolder() {
+ XCTAssertEqual(TitleID.buildKey("/x/Game [01007EF00011E000][v0].nsp"), "01007EF00011E000")
+ XCTAssertEqual(TitleID.buildKey("/x/01007ef00011e000_v0_420d1c5034ab.nsp"), "01007EF00011E000")
+ }
+
+ func testDifferentNamesWithoutIDGetDifferentKeys() {
+ let a = TitleID.buildKey("/x/Zelda.nsp"), b = TitleID.buildKey("/x/Mario.nsp")
+ XCTAssertNotEqual(a, b)
+ XCTAssertNotEqual(a, "game")
+ }
+
+ func testSameNameGivesTheSameKeyEveryTime() {
+ XCTAssertEqual(TitleID.buildKey("/x/Zelda.nsp"), TitleID.buildKey("/other/Zelda.nsp"))
+ XCTAssertEqual(TitleID.buildKey("/x/Zelda.nsp"), TitleID.buildKey("/x/Zelda.nsp"))
+ XCTAssertEqual(TitleID.buildKey("/x/Zelda.nsp"), "Zelda-74c1008b") // the Qt front end gives the same key
+ }
+
+ func testOddCharactersAreSanitized() {
+ let k = TitleID.buildKey("/x/Pokémon: Sword/Shield ../.. §.nsp")
+ XCTAssertNil(k.range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
+ XCTAssertFalse(k.contains("/"))
+ XCTAssertNotEqual(TitleID.buildKey("/x/a b.nsp"), TitleID.buildKey("/x/a_b.nsp")) // same clean stem, different hash
+ XCTAssertNil(TitleID.buildKey("/x/日本語.nsp").range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
+ }
+
+ func testBuildFolderStillEndsInBuild() {
+ XCTAssertTrue((TitleID.buildKey("/x/Zelda.nsp") + "_build").hasSuffix("_build"))
+ XCTAssertEqual(TitleID.buildKey("/x/[0100F2C0115B6000].nsp") + "_build", "0100F2C0115B6000_build")
+ }
+
+ /// The reporter's layout: <ID>/<ID>_v0_<hash>.nsp, the ID bare (no brackets), the full path passed in.
+ func testBareIDInAFullPathIsFound() {
+ let dir = "/Users/me/Games/01007EF00011E000/"
+ XCTAssertEqual(TitleID.parse(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"), 0x01007EF00011E000)
+ XCTAssertEqual(TitleID.buildKey(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"), "01007EF00011E000")
+ // the update and the DLC beside it keep their own IDs and never stand in for the base
+ XCTAssertEqual(TitleID.parse(dir + "01007EF00011E800_v1048576_aaaa.nsp"), 0x01007EF00011E800)
+ XCTAssertEqual(TitleID.parse(dir + "01007EF00011F001_bbbb.nsp"), 0x01007EF00011F001)
+ XCTAssertEqual(TitleID.buildKey(dir + "01007EF00011E000_v0_420d1c5034ab.nsp"),
+ TitleID.buildKey("01007EF00011E000_v0_420d1c5034ab.nsp"))
+ // the folder's ID does not leak into a file name that has none
+ XCTAssertNotEqual(TitleID.buildKey(dir + "Zelda.nsp"), "01007EF00011E000")
+ }
+
+ func testTitleIDReadsTheBracketedFormTheFilesUse() {
+ XCTAssertEqual(TitleID.parse("Mario Wonder [010015100B514000][v0].nsp"), 0x010015100B514000)
+ XCTAssertEqual(TitleID.parse("/ROMs/TotK [01007EF00011E000].xci"), 0x01007EF00011E000)
+ XCTAssertNil(TitleID.parse("no title id here.nsp"))
+ }
+
+ /// Issue #58: a folder holding several games is staged down to the picked one, and its update
+ /// and add-on content come along, classified exactly as build_ipa_from_nsp.py:445 does.
+ func testSiblingsOfThePickedGameAreClassifiedAsTheScriptDoes() {
+ let base = UInt64(0x010015100B514000)
+ let app = base & ~UInt64(0xFFF)
+ let owner = TitleID.owner
+ XCTAssertEqual(owner(base), app, "the base game")
+ XCTAssertEqual(owner(base + 0x800), app, "its update")
+ XCTAssertEqual(owner(base + 0x1001), app, "add-on content 1")
+ XCTAssertNotEqual(owner(UInt64(0x01007EF00011E000)), app, "another game")
+ XCTAssertNotEqual(owner(UInt64(0x01007EF00011E800)), app, "another game's update")
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/XcodeStateTests.swift b/frontend/Tests/NXCoreTests/XcodeStateTests.swift
similarity index 73%
rename from frontend/Tests/NX2AppleTests/XcodeStateTests.swift
rename to frontend/Tests/NXCoreTests/XcodeStateTests.swift
index f78f6452..61d4bf8b 100644
--- a/frontend/Tests/NX2AppleTests/XcodeStateTests.swift
+++ b/frontend/Tests/NXCoreTests/XcodeStateTests.swift
@@ -1,34 +1,32 @@
import XCTest
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// An App Store download that was never opened leaves `xcode-select -p` on CommandLineTools.
/// The Xcode row has to say that, and offer the one-click switch, instead of "no iOS SDK".
final class XcodeStateTests: XCTestCase {
func testXcodeSelectedWithTheSDKIsReady() {
- XCTAssertEqual(BuildModel.xcodeState(selected: "/Applications/Xcode.app/Contents/Developer",
+ XCTAssertEqual(Toolchain.xcodeState(selected: "/Applications/Xcode.app/Contents/Developer",
xcodeApp: "/Applications/Xcode.app", iosSDK: true), .ready)
}
func testXcodeSelectedWithoutTheIOSPlatformAsksForTheDownload() {
- XCTAssertEqual(BuildModel.xcodeState(selected: "/Applications/Xcode.app/Contents/Developer",
+ XCTAssertEqual(Toolchain.xcodeState(selected: "/Applications/Xcode.app/Contents/Developer",
xcodeApp: "/Applications/Xcode.app", iosSDK: false),
.noIOSSDK(selected: "/Applications/Xcode.app/Contents/Developer"))
}
func testCommandLineToolsSelectedWhileXcodeIsInstalledIsItsOwnState() {
- XCTAssertEqual(BuildModel.xcodeState(selected: "/Library/Developer/CommandLineTools",
+ XCTAssertEqual(Toolchain.xcodeState(selected: "/Library/Developer/CommandLineTools",
xcodeApp: "/Applications/Xcode.app", iosSDK: false),
.commandLineToolsOnly(xcode: "/Applications/Xcode.app"))
}
func testNothingInstalled() {
- XCTAssertEqual(BuildModel.xcodeState(selected: nil, xcodeApp: nil, iosSDK: false), .notInstalled)
+ XCTAssertEqual(Toolchain.xcodeState(selected: nil, xcodeApp: nil, iosSDK: false), .notInstalled)
}
func testACommandLineToolsThatAnswersTheSDKIsUsable() {
- XCTAssertEqual(BuildModel.xcodeState(selected: "/Library/Developer/CommandLineTools",
+ XCTAssertEqual(Toolchain.xcodeState(selected: "/Library/Developer/CommandLineTools",
xcodeApp: nil, iosSDK: true), .ready)
}