Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Stage multi-folder game files in a stable folder per game
v0lumehie754867d97f5
diff --git a/frontend-qt/nspb_qt/input_staging.py b/frontend-qt/nspb_qt/input_staging.pynew file mode 100644index 00000000..6f42793a--- /dev/null+++ b/frontend-qt/nspb_qt/input_staging.py@@ -0,0 +1,62 @@+"""The folder the build script reads when the picked game files live in more than one folder (#132).++The script keys a provisional profile's shader split and shader build on the files' size and+modification time and on the profile's path (<input folder>/<title ID>_build/profile), so the folder+must be the same one on every build of a game: it sits in the game's build folder, is never deleted+after a build, and holds exactly the current selection. The build's own folders beside the files+(<title ID>_build, <title ID>_survey) are left alone.+"""+from __future__ import annotations++import os+import shutil+from pathlib import Path++FOLDER_NAME = 'staging'+GAME_SUFFIXES = {'.nsp', '.xci', '.nsz', '.xcz'}+++def folder(work_dir: str) -> str:+ return str(Path(work_dir, FOLDER_NAME))+++def _same(src: str, dst: Path) -> bool:+ """dst is already src: the same file, or a copy with its size and date."""+ try:+ if os.path.samefile(src, dst):+ return True+ a, b = os.stat(src), os.stat(dst)+ return a.st_size == b.st_size and a.st_mtime_ns == b.st_mtime_ns+ except OSError:+ return False+++def sync(files: list[str], into: str, *, hard_links: bool = True) -> int:+ """Make `into` hold exactly `files` (by file name), with their dates. Returns how many were linked."""+ root = Path(into)+ root.mkdir(parents=True, exist_ok=True)+ wanted = {Path(f).name: f for f in files if f}+ for entry in root.iterdir(): # a stale entry from an earlier selection goes: only game files and links+ if entry.is_symlink() or (entry.is_file() and entry.suffix.lower() in GAME_SUFFIXES):+ src = wanted.get(entry.name)+ if src and entry.exists() and _same(src, entry):+ continue+ entry.unlink(missing_ok=True)+ linked = 0+ for name, src in wanted.items():+ dst = root / name+ if dst.exists() and _same(src, dst):+ linked += 1+ continue+ try:+ if hard_links:+ os.link(src, dst)+ else:+ raise OSError+ except OSError:+ try:+ shutil.copy2(src, dst) # copy2 keeps the modification date+ except OSError:+ continue+ linked += 1+ return linkeddiff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex fdd710b8..177c75ae 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -6,7 +6,6 @@ import reimport shutilimport subprocessimport sys-import tempfileimport threadingimport timefrom collections.abc import Callable@@ -17,6 +16,7 @@ from pathlib import Pathfrom PySide6.QtCore import QSettings, Q_ARG, QMetaObject, QObject, Qt, QThread, Signal, Slotfrom . import build_failure as bf+from . import input_stagingfrom . import platform_util as pufrom .i18n import Langfrom .localization import t@@ -995,34 +995,20 @@ class Model(QObject):all_files = [self.base_path, self.update_path] + self.dlc_pathsdirs = {str(Path(f).parent) for f in all_files if f}- staging: str | None = None+ tid = self._title_id(self.base_path)+ tid_hex = f'{tid:016X}' if tid else 'game'+ work_dir = str(Path(self.out_dir or base_dir, f'{tid_hex}_build'))+input_dir = base_dirif len(dirs) > 1:- # files from different folders: a staging folder of links so the script sees one folder- staging = tempfile.mkdtemp(prefix='nspb-stage-')- linked = 0- for f in all_files:- if not f:- continue- dst = Path(staging, Path(f).name)- try:- os.link(f, dst) if not pu.IS_WIN else shutil.copy2(f, dst)- linked += 1- except OSError:- try:- shutil.copy2(f, dst)- linked += 1- except OSError:- pass- if linked == 0:+ # files from different folders: a stable folder of links per game, so the script sees one+ # folder and its fingerprints match on the next build (#132)+ staging = input_staging.folder(work_dir)+ if input_staging.sync(all_files, staging, hard_links=not pu.IS_WIN) == 0:self.finished.emit(False, self.t('msg.stagingFailed'))returninput_dir = staging- tid = self._title_id(self.base_path)- tid_hex = f'{tid:016X}' if tid else 'game'- work_dir = str(Path(self.out_dir or base_dir, f'{tid_hex}_build'))-compressed = any(Path(f).suffix.lower() in ('.nsz', '.xcz')for f in all_files if f)if compressed and not pu._runs(py, ['-c', 'import nsz']):@@ -1131,8 +1117,6 @@ class Model(QObject):self.failure = knownnote = self.failure_what(known)self.finished.emit(False, note)- if staging:- shutil.rmtree(staging, ignore_errors=True)self._thread = threading.Thread(target=work, daemon=True)self._thread.start()diff --git a/frontend-qt/tests/test_input_staging.py b/frontend-qt/tests/test_input_staging.pynew file mode 100644index 00000000..19781833--- /dev/null+++ b/frontend-qt/tests/test_input_staging.py@@ -0,0 +1,58 @@+"""The staging folder for files picked from several folders (#132): the same selection stages to the+same paths with the same sizes and dates, and the folder holds exactly the current selection."""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'frontend-qt'))++from nspb_qt import input_staging # noqa: E402+++def make(path: Path, age: int) -> str:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b'x' * 4096)+ t = path.stat().st_mtime_ns - age * 10**9+ os.utime(path, ns=(t, t))+ return str(path)+++def seen(d: str) -> list[tuple]:+ return [(p.name, p.stat().st_size, p.stat().st_mtime_ns) for p in sorted(Path(d).iterdir())]+++class InputStagingTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.addCleanup(self.tmp.cleanup)+ self.work = str(self.root / '0100000000000000_build')++ def test_two_stagings_are_identical(self):+ for hard in (True, False):+ files = [make(self.root / 'a' / 'base.nsp', 5000), make(self.root / 'b' / 'update.nsp', 9000)]+ d = input_staging.folder(self.work + str(hard))+ self.assertEqual(input_staging.sync(files, d, hard_links=hard), 2)+ first = seen(d)+ self.assertEqual(input_staging.sync(files, d, hard_links=hard), 2)+ self.assertEqual(seen(d), first)+ self.assertEqual([p.stat().st_mtime_ns for p in sorted(Path(d).iterdir())],+ [os.stat(f).st_mtime_ns for f in sorted(files, key=os.path.basename)])++ def test_stale_entry_removed_build_folders_kept(self):+ base = make(self.root / 'a' / 'base.nsp', 100)+ upd = make(self.root / 'b' / 'update.nsp', 200)+ d = input_staging.folder(self.work)+ input_staging.sync([base, upd], d)+ (Path(d) / '0100000000000000_build' / 'profile').mkdir(parents=True)+ self.assertEqual(input_staging.sync([base], d), 1)+ self.assertEqual({p.name for p in Path(d).iterdir()}, {'base.nsp', '0100000000000000_build'})+++if __name__ == '__main__':+ unittest.main()diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 0ac1cc25..a06f10bd 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1078,15 +1078,13 @@ final class BuildModel: ObservableObject {staged.append(baseDir + "/" + f)}}+ let tidHex = Self.titleID(basePath).map { String(format: "%016llX", $0) } ?? "game"+ let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"var inputDir = baseDirif dirs.count > 1 || !unpicked.isEmpty {- let tmp = NSTemporaryDirectory() + "nsport-\(UUID().uuidString.prefix(8))"- try? FileManager.default.createDirectory(atPath: tmp, withIntermediateDirectories: true)- var linked = 0- for f in staged where !f.isEmpty {- let dst = tmp + "/" + (f as NSString).lastPathComponent- if (try? FileManager.default.createSymbolicLink(atPath: dst, withDestinationPath: f)) != nil { linked += 1 }- }+ // A stable folder per game (#132): the script's fingerprints name its files and its profile path.+ let tmp = InputStaging.folder(workDir: workDir)+ let linked = InputStaging.sync(files: staged, into: tmp)if linked == 0 { fail(t("msg.stagingFailed")); return }staging = tmp; inputDir = tmpif !unpicked.isEmpty {@@ -1094,8 +1092,6 @@ final class BuildModel: ObservableObject {}} else { staging = nil }- let tidHex = Self.titleID(basePath).map { String(format: "%016llX", $0) } ?? "game"- let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"// This fork's --work-dir keeps the build folder (extracted files, shader cache, the romfs// archive) outside the NSPs' folder. An upstream checkout or an older ZIP does not have the// option and would stop with "unrecognized arguments" (issue #5), so ask the script; without@@ -1368,7 +1364,7 @@ final class BuildModel: ObservableObject {}private func cleanupStaging() {- if let s = staging { try? FileManager.default.removeItem(atPath: s); staging = nil }+ staging = nil // the folder stays for the next build of this game (#132, InputStaging)}/// A stopped build leaves no half-finished stages behind: the progress starts empty again.diff --git a/frontend/Sources/NSPortBuilder/InputStaging.swift b/frontend/Sources/NSPortBuilder/InputStaging.swiftnew file mode 100644index 00000000..293031d2--- /dev/null+++ b/frontend/Sources/NSPortBuilder/InputStaging.swift@@ -0,0 +1,46 @@+import Foundation++/// The folder the build script reads when the picked game files live in more than one folder (#132).+/// The script keys a provisional profile's shader split and shader build on the files' size and+/// modification time and on the profile's path (`<input folder>/<title ID>_build/profile`), so the+/// folder must be the same one on every build of a game. It sits in the game's build folder, is+/// never deleted after a build, and holds exactly the current selection: one symlink per file+/// (the script follows links, so it sees the original's size and date). The build's own+/// folders next to the links (`<title ID>_build`, `<title ID>_survey`) are left alone.+enum InputStaging {+ static let folderName = "staging"+ private static let gameExtensions: Set<String> = ["nsp", "xci", "nsz", "xcz"]++ static func folder(workDir: String) -> String { workDir + "/" + folderName }++ /// Makes `dir` hold exactly `files`, by file name. Returns how many were linked.+ static func sync(files: [String], into dir: String) -> Int {+ let fm = FileManager.default+ try? fm.createDirectory(atPath: dir, withIntermediateDirectories: true)+ var wanted: [String: String] = [:]+ for f in files where !f.isEmpty { wanted[(f as NSString).lastPathComponent] = f }+ // A stale entry from an earlier selection goes. Only game files and links are touched.+ for name in (try? fm.contentsOfDirectory(atPath: dir)) ?? [] {+ let path = dir + "/" + name+ let isLink = (try? fm.destinationOfSymbolicLink(atPath: path)) != nil+ guard isLink || gameExtensions.contains((name as NSString).pathExtension.lowercased()) else { continue }+ if let src = wanted[name], isLink, (try? fm.destinationOfSymbolicLink(atPath: path)) == src { continue }+ try? fm.removeItem(atPath: path)+ }+ var linked = 0+ for (name, src) in wanted {+ let dst = dir + "/" + name+ if (try? fm.destinationOfSymbolicLink(atPath: dst)) == src { linked += 1; continue }+ if (try? fm.createSymbolicLink(atPath: dst, withDestinationPath: src)) != nil { linked += 1; continue }+ // No symlinks here (a volume without them): a hard link keeps the file's date, a copy gets it back.+ if (try? fm.linkItem(atPath: src, toPath: dst)) != nil { linked += 1; continue }+ if (try? fm.copyItem(atPath: src, toPath: dst)) != nil {+ if let date = (try? fm.attributesOfItem(atPath: src))?[.modificationDate] {+ try? fm.setAttributes([.modificationDate: date], ofItemAtPath: dst)+ }+ linked += 1+ }+ }+ return linked+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/InputStagingTests.swift b/frontend/Tests/NSPortBuilderTests/InputStagingTests.swiftnew file mode 100644index 00000000..4144d784--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/InputStagingTests.swift@@ -0,0 +1,65 @@+import XCTest+@testable import NSPortBuilder++/// The staging folder for files picked from several folders (#132): the same selection stages to the same+/// paths with the same dates, and the folder holds exactly the current selection.+final class InputStagingTests: XCTestCase {+ private var temporary: URL!+ private var a: URL { temporary.appendingPathComponent("one") }+ private var b: URL { temporary.appendingPathComponent("two") }+ private var work: String { temporary.appendingPathComponent("0100000000000000_build").path }++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-stage-" + UUID().uuidString)+ for d in [a, b] { try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }+ }++ override func tearDownWithError() throws { try? FileManager.default.removeItem(at: temporary) }++ private func game(_ name: String, in dir: URL, age: TimeInterval) throws -> String {+ let url = dir.appendingPathComponent(name)+ try Data(repeating: 1, count: 4096).write(to: url)+ try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -age)], ofItemAtPath: url.path)+ return url.path+ }++ /// What the script's fingerprint sees: name, size and modification time, following links.+ private func seen(_ dir: String) throws -> [String] {+ try FileManager.default.contentsOfDirectory(atPath: dir).sorted().map { name in+ var st = stat()+ XCTAssertEqual(stat(dir + "/" + name, &st), 0)+ return "\(dir)/\(name) \(st.st_size) \(st.st_mtimespec.tv_sec).\(st.st_mtimespec.tv_nsec)"+ }+ }++ func testTwoStagingsOfTheSameSelectionAreIdentical() throws {+ let files = [try game("base.nsp", in: a, age: 5000), try game("update.nsp", in: b, age: 9000)]+ let dir = InputStaging.folder(workDir: work)+ XCTAssertEqual(InputStaging.sync(files: files, into: dir), 2)+ let first = try seen(dir)+ Thread.sleep(forTimeInterval: 0.05)+ XCTAssertEqual(InputStaging.sync(files: files, into: dir), 2)+ XCTAssertEqual(try seen(dir), first)+ XCTAssertEqual(first.count, 2)+ }++ func testStaleEntryIsRemovedButBuildFoldersStay() throws {+ let base = try game("base.nsp", in: a, age: 100)+ let update = try game("update.nsp", in: b, age: 200)+ let dir = InputStaging.folder(workDir: work)+ _ = InputStaging.sync(files: [base, update], into: dir)+ try FileManager.default.createDirectory(atPath: dir + "/0100000000000000_build/profile", withIntermediateDirectories: true)+ XCTAssertEqual(InputStaging.sync(files: [base], into: dir), 1)+ let names = Set(try FileManager.default.contentsOfDirectory(atPath: dir))+ XCTAssertEqual(names, ["base.nsp", "0100000000000000_build"])+ }++ func testLinkToAnotherFileIsRelinked() throws {+ let one = try game("base.nsp", in: a, age: 100)+ let two = try game("base.nsp", in: b, age: 300)+ let dir = InputStaging.folder(workDir: work)+ _ = InputStaging.sync(files: [one], into: dir)+ _ = InputStaging.sync(files: [two], into: dir)+ XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: dir + "/base.nsp"), two)+ }+}