Skip to content

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

Launcher: Free space removes a built game's build files (#67)

v0lumehia0ad84d4a95c
diff --git a/frontend/Sources/NSPortBuilder/FreeSpace.swift b/frontend/Sources/NSPortBuilder/FreeSpace.swift
new file mode 100644
index 00000000..d4907955
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/FreeSpace.swift
@@ -0,0 +1,308 @@
+import AppKit
+import SwiftUI
+
+/// The parts of a game's build folder (<output folder>/<title ID>_build) that the next build makes again
+/// (LNPANDY/NX2Apple#67, after seedds/nxnative#264). The layout is scripts/build_ipa_from_nsp.py's: extract/ (the extracted
+/// game files), shader/ and pso/ (the shader package, caches and libraries), xcode/, xcode-derived-data/ and ipa/ (the app
+/// build), and the smaller caches beside them. What the script keeps for its own sake stays: logs/, profile/ (a provisional
+/// or derived profile, which someone may have edited), run/ (the Mac development build's save) and nsp/ (NSZ files
+/// converted to NSP, which are game files).
+enum BuildFolderPart: String, CaseIterable, Identifiable {
+ case extracted, shaders, xcode, caches
+ var id: String { rawValue }
+
+ /// The part a top-level entry of the build folder belongs to; nil for what is never offered. A stage's reuse key
+ /// (<name>.key) and an interrupted stage's output (<name>.partial) go with the folder they belong to.
+ static func of(_ name: String) -> BuildFolderPart? {
+ var base = name
+ for suffix in [".key", ".partial"] where base.hasSuffix(suffix) { base = String(base.dropLast(suffix.count)) }
+ switch base {
+ case "extract", "exefs": return .extracted
+ case "shader", "pso": return .shaders
+ case "xcode", "xcode-derived-data", "ipa": return .xcode
+ case "tools", "tmp", "aoc", "font": return .caches
+ default: // the rewritten modules and the NROs collected for them, one folder per packed version
+ return base.hasPrefix("patched_") || base.hasPrefix("nro_") ? .caches : nil
+ }
+ }
+}
+
+/// What a build folder holds, part by part, in bytes on disk.
+struct BuildFolderSurvey: Equatable {
+ var folder: String
+ var sizes: [BuildFolderPart: Int64] = [:]
+ /// Everything that stays: logs, the profile, converted NSPs, saves, and anything the game still needs that lies inside.
+ var kept: Int64 = 0
+ var parts: [BuildFolderPart] { BuildFolderPart.allCases.filter { (sizes[$0] ?? 0) > 0 } }
+}
+
+enum FreeSpaceError: LocalizedError, Equatable {
+ case buildRunning, notABuildFolder(String), failed(String)
+ var errorDescription: String? {
+ switch self {
+ case .buildRunning: return "A build is running."
+ case .notABuildFolder(let path): return "Not a build folder: \(path)"
+ case .failed(let why): return why
+ }
+ }
+}
+
+enum BuildFolder {
+ /// Where the game's build folder can be: in its output folder (--work-dir), else beside its NSPs (the script's default,
+ /// and where a checkout without --work-dir puts it).
+ nonisolated static func candidates(for game: LibraryGame) -> [String] {
+ let base = game.inputs["base", default: []].first.map { ($0 as NSString).deletingLastPathComponent } ?? ""
+ let dirs = [game.outputDirectory, base].filter { !$0.isEmpty }
+ var seen = Set<String>()
+ return dirs.map { $0 + "/" + game.titleID + "_build" }.filter { seen.insert($0).inserted }
+ }
+
+ nonisolated static func location(for game: LibraryGame) -> String? {
+ candidates(for: game).first { path in
+ var dir: ObjCBool = false
+ return FileManager.default.fileExists(atPath: path, isDirectory: &dir) && dir.boolValue
+ }
+ }
+
+ /// What this sheet never removes, wherever it lies: the finished Mac app, the IPA, the app installed on a device (its
+ /// build is in xcode-derived-data), the game data archive (games/<title ID>/ with romfs.img), and the NSPs and keys.
+ nonisolated static func protectedPaths(for game: LibraryGame) -> [String] {
+ let out = game.outputDirectory.isEmpty
+ ? game.inputs["base", default: []].first.map { ($0 as NSString).deletingLastPathComponent } ?? "" : game.outputDirectory
+ var paths = [game.appPath, game.ipaPath, game.iosAppPath, game.archivePath]
+ if !game.archivePath.isEmpty { paths.append(game.archivePath + "/romfs.img") }
+ if !out.isEmpty { paths.append(out + "/games/" + game.titleID) }
+ paths += game.inputs.values.flatMap { $0 }
+ return paths.filter { !$0.isEmpty }.map(resolved)
+ }
+
+ nonisolated static func resolved(_ path: String) -> String {
+ URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
+ }
+
+ /// The sizes of the parts and of what stays. Reads the whole folder (tens of GB for some games): off the main thread.
+ nonisolated static func survey(_ folder: String, protecting: [String]) -> BuildFolderSurvey {
+ let root = resolved(folder)
+ var result = BuildFolderSurvey(folder: root)
+ for name in (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? [] {
+ let path = root + "/" + name
+ guard let part = BuildFolderPart.of(name) else { result.kept += size(path); continue }
+ let kept = protectedSize(path, protecting: protecting)
+ result.sizes[part, default: 0] += size(path) - kept
+ result.kept += kept
+ }
+ return result
+ }
+
+ /// Delete the chosen parts. Refused while a build runs (it may be writing into this folder) and for a folder that is
+ /// not a build folder. A protected path inside a part stays, with the folders that lead to it. Deleted, not moved to the
+ /// Trash: the Trash keeps the bytes on the same drive. Returns the bytes freed.
+ @discardableResult
+ nonisolated static func remove(_ parts: Set<BuildFolderPart>, in folder: String, protecting: [String], buildRunning: Bool) throws -> Int64 {
+ guard !buildRunning else { throw FreeSpaceError.buildRunning }
+ let root = resolved(folder)
+ guard root.hasSuffix("_build"), root.split(separator: "/").count > 1 else { throw FreeSpaceError.notABuildFolder(folder) }
+ var freed: Int64 = 0
+ var failures: [String] = []
+ for name in (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? [] {
+ guard let part = BuildFolderPart.of(name), parts.contains(part) else { continue }
+ removeTree(root + "/" + name, protecting: protecting, freed: &freed, failures: &failures)
+ }
+ if let first = failures.first { throw FreeSpaceError.failed(first) }
+ return freed
+ }
+
+ private nonisolated static func removeTree(_ path: String, protecting: [String], freed: inout Int64, failures: inout [String]) {
+ if protecting.contains(where: { path == $0 || path.hasPrefix($0 + "/") }) { return }
+ if protecting.contains(where: { $0.hasPrefix(path + "/") }) { // something to keep lies inside: go in, around it
+ for name in (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? [] {
+ removeTree(path + "/" + name, protecting: protecting, freed: &freed, failures: &failures)
+ }
+ return
+ }
+ let bytes = size(path)
+ do { try FileManager.default.removeItem(atPath: path); freed += bytes }
+ catch { failures.append(error.localizedDescription) }
+ }
+
+ /// The bytes of the protected paths inside path, each counted once (the archive folder holds romfs.img).
+ private nonisolated static func protectedSize(_ path: String, protecting: [String]) -> Int64 {
+ let inside = Set(protecting.filter { $0 == path || $0.hasPrefix(path + "/") })
+ return inside.filter { p in !inside.contains { p.hasPrefix($0 + "/") } }.reduce(0) { $0 + size($1) }
+ }
+
+ /// Allocated bytes of a file or folder, symbolic links not followed.
+ nonisolated static func size(_ path: String) -> Int64 {
+ let url = URL(fileURLWithPath: path)
+ let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .isSymbolicLinkKey, .isDirectoryKey]
+ func bytes(_ u: URL) -> Int64 {
+ guard let v = try? u.resourceValues(forKeys: Set(keys)) else { return 0 }
+ return Int64(v.totalFileAllocatedSize ?? v.fileAllocatedSize ?? 0)
+ }
+ guard let top = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) else { return 0 }
+ if top.isSymbolicLink == true || top.isDirectory != true { return bytes(url) }
+ var total: Int64 = 0
+ let e = FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys, options: [], errorHandler: { _, _ in true })
+ while let u = e?.nextObject() as? URL { total += bytes(u) }
+ return total
+ }
+}
+
+/// The game's Free space sheet: the parts of its build folder with their sizes and what removing each costs; the player
+/// picks parts and confirms.
+struct FreeSpaceView: View {
+ @ObservedObject var m: BuildModel
+ let game: LibraryGame
+ @Environment(\.dismiss) private var dismiss
+ @EnvironmentObject private var focus: PadFocus
+ @State private var survey: BuildFolderSurvey?
+ @State private var chosen: Set<BuildFolderPart> = []
+ @State private var confirming = false
+ @State private var working = false
+ @State private var outcome: String?
+
+ init(m: BuildModel, game: LibraryGame, survey: BuildFolderSurvey? = nil, chosen: Set<BuildFolderPart> = []) {
+ self.m = m
+ self.game = game
+ _survey = State(initialValue: survey) // visual QA: a measured folder without one on disk
+ _chosen = State(initialValue: chosen)
+ }
+
+ private var chosenBytes: Int64 { chosen.reduce(0) { $0 + (survey?.sizes[$1] ?? 0) } }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(m.t("free.title")).font(.manrope(26, .heavy)).tracking(-0.6)
+ Text(game.name).font(.manrope(14)).foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 14)
+ Text(m.t("free.note")).font(.manrope(13)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 30).padding(.bottom, 18)
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ if let survey {
+ if survey.parts.isEmpty {
+ Text(m.t("free.empty")).font(.manrope(14)).foregroundStyle(.secondary)
+ } else {
+ card {
+ ForEach(survey.parts) { part in
+ row(part, bytes: survey.sizes[part] ?? 0)
+ Divider().opacity(0.25).padding(.leading, 18)
+ }
+ HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(m.t("free.kept")).font(.manrope(14, .medium)).foregroundStyle(.secondary)
+ Text(m.t("free.keptNote")).font(.manrope(12)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ sizeText(survey.kept).foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13)
+ }
+ }
+ if game.isReady { // pack_app.py clones the game files and shaders into the app on the same APFS volume
+ Text(m.t("free.clones")).font(.manrope(12)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true).padding(.horizontal, 2)
+ }
+ Text(survey.folder).font(.system(size: 11, design: .monospaced)).foregroundStyle(.tertiary)
+ .lineLimit(1).truncationMode(.middle).textSelection(.enabled).padding(.horizontal, 2)
+ } else {
+ HStack(spacing: 10) { ProgressView().controlSize(.small); Text(m.t("free.measuring")).foregroundStyle(.secondary) }
+ }
+ }
+ .padding(.horizontal, 30).padding(.bottom, 20)
+ }
+ Divider().opacity(0.3)
+ HStack(spacing: 14) {
+ Text(outcome ?? (m.running ? m.t("free.running") : String(format: m.t("free.selected"), Self.bytes(chosenBytes))))
+ .font(.manrope(12)).foregroundStyle(.secondary).lineLimit(2)
+ Spacer(minLength: 8)
+ Button(m.t("free.remove")) { confirming = true }
+ .buttonStyle(LauncherSecondaryButtonStyle(accent: LauncherPalette.building))
+ .disabled(chosen.isEmpty || m.running || working)
+ .padTarget("free.remove", scope: "free") { if !chosen.isEmpty && !m.running && !working { confirming = true } }
+ Button { dismiss() } label: {
+ Text(m.t("free.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)
+ .padding(.horizontal, 22).padding(.vertical, 9)
+ .background(LauncherPalette.cream, in: Capsule())
+ }
+ .buttonStyle(.plain).keyboardShortcut(.defaultAction)
+ .padTarget("free.done", scope: "free", radius: 20) { dismiss() }
+ }
+ .padding(.horizontal, 30).padding(.vertical, 16)
+ }
+ .padScope("free", focus)
+ .frame(width: 560, height: 690)
+ .background(LauncherPalette.background)
+ .font(.manrope(13))
+ .preferredColorScheme(.dark)
+ .tint(LauncherPalette.cream)
+ .onAppear { if survey == nil { measure() } }
+ .confirmationDialog(String(format: m.t("free.confirm"), Self.bytes(chosenBytes)), isPresented: $confirming, titleVisibility: .visible) {
+ Button(m.t("free.confirmButton"), role: .destructive) { removeChosen() }
+ } message: {
+ Text(([m.t("free.confirmNote")] + BuildFolderPart.allCases.filter(chosen.contains).map { m.t("free.cost." + $0.rawValue) }).joined(separator: "\n"))
+ }
+ }
+
+ private func row(_ part: BuildFolderPart, bytes: Int64) -> some View {
+ let on = Binding(get: { chosen.contains(part) }, set: { if $0 { chosen.insert(part) } else { chosen.remove(part) } })
+ return HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(m.t("free.part." + part.rawValue)).font(.manrope(14, .medium))
+ Text(m.t("free.cost." + part.rawValue)).font(.manrope(12)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ sizeText(bytes)
+ Toggle("", isOn: on).labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(working)
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13).frame(minHeight: 52)
+ .padTarget("free." + part.rawValue, scope: "free", radius: 10,
+ activate: { on.wrappedValue.toggle() }, adjust: { _ in on.wrappedValue.toggle() })
+ }
+
+ private func sizeText(_ bytes: Int64) -> some View {
+ Text(Self.bytes(bytes)).font(.manrope(13, .semibold)).monospacedDigit().frame(minWidth: 70, alignment: .trailing)
+ }
+
+ private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
+ VStack(spacing: 0, content: content)
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
+ }
+
+ nonisolated static func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) }
+
+ private func measure() {
+ let protected = BuildFolder.protectedPaths(for: game)
+ guard let folder = BuildFolder.location(for: game) else { survey = BuildFolderSurvey(folder: ""); return }
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = BuildFolder.survey(folder, protecting: protected)
+ DispatchQueue.main.async { survey = result; chosen = chosen.filter { (result.sizes[$0] ?? 0) > 0 } }
+ }
+ }
+
+ private func removeChosen() {
+ guard let folder = survey?.folder, !folder.isEmpty else { return }
+ let parts = chosen, protected = BuildFolder.protectedPaths(for: game), running = m.running
+ working = true
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = Result { try BuildFolder.remove(parts, in: folder, protecting: protected, buildRunning: running) }
+ let after = BuildFolder.survey(folder, protecting: protected)
+ DispatchQueue.main.async {
+ working = false
+ survey = after
+ chosen = []
+ switch result {
+ case .success(let freed): outcome = String(format: m.t("free.freed"), Self.bytes(freed))
+ case .failure(FreeSpaceError.buildRunning): outcome = m.t("free.running")
+ case .failure(let error): outcome = String(format: m.t("free.failed"), error.localizedDescription)
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index fbe16529..ebf06eb8 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -34,6 +34,7 @@ struct ContentView: View {
@State private var launchError: String?
@State private var removing: LibraryGame?
@State private var optionsFor: UUID?
+ @State private var freeSpaceFor: UUID? // the game whose Free space sheet is open
@State private var controlsOpen = false
@StateObject private var controls = ControlLayout()
@StateObject private var gamepad = LauncherGamepad()
@@ -127,6 +128,10 @@ struct ContentView: View {
if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id).environmentObject(padFocus) }
}
.sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls).environmentObject(padFocus) }
+ .sheet(isPresented: Binding(get: { freeSpaceFor != nil }, set: { if !$0 { freeSpaceFor = nil } })) {
+ if let game = library.games.first(where: { $0.id == freeSpaceFor }) { FreeSpaceView(m: m, game: game).environmentObject(padFocus) }
+ }
+ .onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : "main" }
.sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) }
.onChange(of: optionsFor) { id in padFocus.scope = id != nil ? "launch" : (controlsOpen ? "controls" : "main") }
.onChange(of: controlsOpen) { open in padFocus.scope = open ? "controls" : (optionsFor != nil ? "launch" : "main") }
@@ -315,6 +320,7 @@ struct ContentView: View {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.appPath)])
}
}
+ if BuildFolder.location(for: game) != nil { Button(m.t("free.menu")) { freeSpaceFor = game.id } }
Divider()
Button(m.t("library.remove"), role: .destructive) { removing = game }.disabled(game.id == activeBuildID)
} label: {
@@ -515,6 +521,8 @@ struct ContentView: View {
/// game's launch options, L and R switch the pages.
private func padAction(_ action: LauncherGamepad.Action) {
let sheetOpen = optionsFor != nil || controlsOpen
+ // The Free space sheet: B closes it, the D-pad and A work in it, X, L and R do nothing behind it
+ if freeSpaceFor != nil && [.b, .x, .l, .r].contains(action) { if action == .b { freeSpaceFor = nil }; return }
if action == .b {
if optionsFor != nil { optionsFor = nil } else if controlsOpen { controlsOpen = false }
else if searching { searching = false; search = "" } else if page != .library { page = .library }
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 4454dd15..7d88f1dd 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -93,6 +93,31 @@ enum L10n {
"build.saveDefault": ("\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{65c1}\u{8fb9}", "Next to the game files"),
"build.log": ("\u{6784}\u{5efa}\u{65e5}\u{5fd7}", "Build log"),
"section.log": ("\u{6784}\u{5efa}\u{65e5}\u{5fd7}", "Log"),
+ "free.menu": ("释放空间…", "Free space…"),
+ "free.title": ("释放空间", "Free space"),
+ "free.note": ("删除这个游戏的构建文件,下次构建时会重新生成。应用、IPA、游戏数据归档和 NSP 文件都会保留。", "Removes this game’s build files, which the next build makes again. The app, the IPA, the game data archive and the NSPs stay."),
+ "free.part.extracted": ("解包的游戏文件", "Extracted game files"),
+ "free.part.shaders": ("着色器输出", "Shader output"),
+ "free.part.xcode": ("Xcode 项目和应用构建文件", "Xcode project and app build"),
+ "free.part.caches": ("其他缓存", "Other caches"),
+ "free.cost.extracted": ("下次构建会重新解包游戏。", "The next build extracts the game again."),
+ "free.cost.shaders": ("下次构建会重新编译着色器,可能需要很长时间。", "The next build compiles the shaders again, which can take a long time."),
+ "free.cost.xcode": ("下次构建会重新准备并编译应用。", "The next build prepares and compiles the app again."),
+ "free.cost.caches": ("构建工具、改写后的游戏代码、DLC 镜像和临时文件:下次构建会重新生成。", "Build tools, rewritten game code, DLC images and temporary files: the next build makes them again."),
+ "free.kept": ("保留", "Kept"),
+ "free.keptNote": ("日志、游戏配置、转换后的 NSP 和存档", "Logs, the game’s profile, converted NSPs and saves"),
+ "free.empty": ("这个游戏的构建文件夹中没有可删除的内容。", "There is nothing to remove in this game’s build folder."),
+ "free.measuring": ("正在计算大小…", "Measuring…"),
+ "free.running": ("正在构建。构建完成后才能删除构建文件。", "A build is running. Build files can be removed when it has finished."),
+ "free.selected": ("已选 %@", "%@ selected"),
+ "free.remove": ("删除…", "Remove…"),
+ "free.confirm": ("删除 %@ 的构建文件?", "Remove %@ of build files?"),
+ "free.confirmButton": ("删除", "Remove"),
+ "free.confirmNote": ("文件会被直接删除,不会移到废纸篓。", "The files are deleted, not moved to the Trash."),
+ "free.freed": ("已释放 %@。", "Freed %@."),
+ "free.failed": ("有些文件无法删除:%@", "Some files could not be removed: %@"),
+ "free.clones": ("在同一个磁盘上构建的 Mac 应用与这里的游戏文件和着色器共享数据(APFS 克隆),因此实际释放的空间可能少于显示的大小。", "A Mac app built on the same drive shares its game files and shaders with this folder (APFS clones), so removing them can free less than shown."),
+ "free.done": ("完成", "Done"),
"library.folderUnset": ("\u{5c1a}\u{672a}\u{8bbe}\u{7f6e}", "Not set"),
"app.version": ("\u{7248}\u{672c} %@", "Version %@"),
"library.scrollBack": ("\u{5411}\u{524d}\u{6eda}\u{52a8}", "Scroll back"),
diff --git a/frontend/Tests/NSPortBuilderTests/FreeSpaceTests.swift b/frontend/Tests/NSPortBuilderTests/FreeSpaceTests.swift
new file mode 100644
index 00000000..df56b7a8
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/FreeSpaceTests.swift
@@ -0,0 +1,148 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// Free space (#67): a synthetic <title ID>_build folder in a temporary directory, laid out as build_ipa_from_nsp.py
+/// leaves it, with the finished app, the IPA and the game data archive beside it.
+final class FreeSpaceTests: XCTestCase {
+ private var temporary: URL!
+ private let titleID = "0100535012974000"
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-free-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws {
+ try? FileManager.default.removeItem(at: temporary)
+ }
+
+ private var out: URL { temporary.appendingPathComponent("games folder") }
+ private var build: URL { out.appendingPathComponent(titleID + "_build") }
+
+ private func file(_ path: String, in dir: URL? = nil, kb: Int = 64) throws {
+ let url = (dir ?? build).appendingPathComponent(path)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(repeating: 7, count: kb * 1024).write(to: url)
+ }
+
+ private func exists(_ path: String, in dir: URL? = nil) -> Bool {
+ FileManager.default.fileExists(atPath: (dir ?? build).appendingPathComponent(path).path)
+ }
+
+ /// The build folder of a game that was built for the Mac and installed on a device (its app in xcode-derived-data).
+ private func fixture() throws -> LibraryGame {
+ for path in ["extract/v0/RomFS/data.bin", "extract/v0/ExeFS/main", "extract.partial/x", "exefs.partial/x",
+ "shader/package.bin", "shader/cache/b-1/a_b.metallib", "pso/mac/a.bin",
+ "xcode/DmIOS.xcodeproj/project.pbxproj", "xcode-derived-data/Build/Intermediates.noindex/a.o", "ipa/Payload/x",
+ "tools/nx_extract/nx_extract", "tmp/x", "patched_v0/main.patched.bin", "nro_v0/nro.tsv", "aoc/1.img", "font/nintendo_ext.ttf",
+ "logs/split.log", "profile/\(titleID)/game.tsv", "run/save/save.bin", "nsp/game.nsp"] { try file(path) }
+ for path in ["patched_v0.key", "aoc.key"] { try file(path, kb: 1) }
+ try file("xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app/Info.plist")
+ try file(titleID + ".app/Contents/Info.plist", in: out)
+ try file(titleID + ".ipa", in: out)
+ try file("games/\(titleID)/romfs.img", in: out)
+ try file("Hades [\(titleID)].nsp", in: out)
+ var game = LibraryGame(titleID: titleID, name: "Hades")
+ game.outputDirectory = out.path
+ game.inputs = ["base": [out.appendingPathComponent("Hades [\(titleID)].nsp").path]]
+ game.appPath = out.appendingPathComponent(titleID + ".app").path
+ game.ipaPath = out.appendingPathComponent(titleID + ".ipa").path
+ game.archivePath = out.appendingPathComponent("games/" + titleID).path
+ game.iosAppPath = build.appendingPathComponent("xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app").path
+ game.installedDevice = "00008150-AAAA"
+ return game
+ }
+
+ func testTheFolderIsFoundInTheOutputFolderOrBesideTheNSPs() throws {
+ let game = try fixture()
+ XCTAssertEqual(BuildFolder.location(for: game), build.path)
+ var beside = game
+ beside.outputDirectory = temporary.appendingPathComponent("elsewhere").path // a checkout without --work-dir
+ XCTAssertEqual(BuildFolder.location(for: beside), build.path)
+ beside.inputs = [:]
+ XCTAssertNil(BuildFolder.location(for: beside))
+ }
+
+ func testThePartsAreSizedAndWhatStaysIsNotOffered() throws {
+ let game = try fixture()
+ let survey = BuildFolder.survey(build.path, protecting: BuildFolder.protectedPaths(for: game))
+ XCTAssertEqual(survey.parts, BuildFolderPart.allCases)
+ let kb: Int64 = 1024
+ XCTAssertGreaterThanOrEqual(survey.sizes[.extracted] ?? 0, 4 * 64 * kb)
+ XCTAssertGreaterThanOrEqual(survey.sizes[.shaders] ?? 0, 3 * 64 * kb)
+ // the installed app inside xcode-derived-data is kept, not counted with the Xcode files
+ XCTAssertGreaterThanOrEqual(survey.sizes[.xcode] ?? 0, 3 * 64 * kb)
+ XCTAssertLessThan(survey.sizes[.xcode] ?? 0, 4 * 64 * kb + 16 * kb)
+ XCTAssertGreaterThanOrEqual(survey.kept, 5 * 64 * kb, "logs, profile, saves, converted NSPs and the installed app")
+ }
+
+ func testRemovingOnePartLeavesTheRest() throws {
+ let game = try fixture()
+ let freed = try BuildFolder.remove([.extracted], in: build.path, protecting: BuildFolder.protectedPaths(for: game), buildRunning: false)
+ XCTAssertGreaterThanOrEqual(freed, 4 * 64 * 1024)
+ XCTAssertFalse(exists("extract")); XCTAssertFalse(exists("extract.partial")); XCTAssertFalse(exists("exefs.partial"))
+ for path in ["shader/package.bin", "pso", "xcode", "tools", "patched_v0", "logs"] { XCTAssertTrue(exists(path), path) }
+ }
+
+ func testTheFinishedAppTheArchiveAndTheNSPsAreNeverRemoved() throws {
+ let game = try fixture()
+ try BuildFolder.remove(Set(BuildFolderPart.allCases), in: build.path, protecting: BuildFolder.protectedPaths(for: game), buildRunning: false)
+ for path in ["extract", "shader", "pso", "xcode", "ipa", "tools", "tmp", "patched_v0", "patched_v0.key", "nro_v0", "aoc", "aoc.key", "font",
+ "xcode-derived-data/Build/Intermediates.noindex"] {
+ XCTAssertFalse(exists(path), path)
+ }
+ for path in ["logs/split.log", "profile/\(titleID)/game.tsv", "run/save/save.bin", "nsp/game.nsp",
+ "xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app/Info.plist"] {
+ XCTAssertTrue(exists(path), path)
+ }
+ for path in [titleID + ".app/Contents/Info.plist", titleID + ".ipa", "games/\(titleID)/romfs.img", "Hades [\(titleID)].nsp"] {
+ XCTAssertTrue(exists(path, in: out), path)
+ }
+ let after = BuildFolder.survey(build.path, protecting: BuildFolder.protectedPaths(for: game))
+ XCTAssertEqual(after.parts, [], "nothing left to offer")
+ }
+
+ /// Even where the app or the game data archive lies inside a part, it is neither offered nor removed.
+ func testAProtectedFileInsideAPartStays() throws {
+ var game = try fixture()
+ try file("tmp/Hades.app/Contents/Info.plist")
+ try file("tmp/games/\(titleID)/romfs.img", kb: 256)
+ game.appPath = build.appendingPathComponent("tmp/Hades.app").path
+ game.archivePath = build.appendingPathComponent("tmp/games/" + titleID).path
+ let protected = BuildFolder.protectedPaths(for: game)
+ let before = BuildFolder.survey(build.path, protecting: protected)
+ XCTAssertLessThan(before.sizes[.caches] ?? 0, 8 * 64 * 1024 + 64 * 1024, "the 256 KB archive is not counted as a cache")
+ try BuildFolder.remove([.caches], in: build.path, protecting: protected, buildRunning: false)
+ XCTAssertTrue(exists("tmp/Hades.app/Contents/Info.plist"))
+ XCTAssertTrue(exists("tmp/games/\(titleID)/romfs.img"))
+ XCTAssertFalse(exists("tmp/x"))
+ XCTAssertFalse(exists("tools"))
+ }
+
+ func testRefusedWhileABuildRuns() throws {
+ let game = try fixture()
+ XCTAssertThrowsError(try BuildFolder.remove(Set(BuildFolderPart.allCases), in: build.path, protecting: BuildFolder.protectedPaths(for: game), buildRunning: true)) {
+ XCTAssertEqual($0 as? FreeSpaceError, .buildRunning)
+ }
+ XCTAssertTrue(exists("extract/v0/RomFS/data.bin"))
+ XCTAssertTrue(exists("shader/package.bin"))
+ }
+
+ func testOnlyABuildFolderIsTouched() throws {
+ try file("extract/x", in: out)
+ XCTAssertThrowsError(try BuildFolder.remove([.extracted], in: out.path, protecting: [], buildRunning: false)) {
+ XCTAssertEqual($0 as? FreeSpaceError, .notABuildFolder(self.out.path))
+ }
+ XCTAssertTrue(exists("extract/x", in: out))
+ }
+
+ func testWhichPartAnEntryBelongsTo() {
+ XCTAssertEqual(BuildFolderPart.of("extract"), .extracted)
+ XCTAssertEqual(BuildFolderPart.of("exefs.partial"), .extracted)
+ XCTAssertEqual(BuildFolderPart.of("shader"), .shaders)
+ XCTAssertEqual(BuildFolderPart.of("xcode-derived-data"), .xcode)
+ XCTAssertEqual(BuildFolderPart.of("patched_v65536.key"), .caches)
+ XCTAssertEqual(BuildFolderPart.of("nro_v0"), .caches)
+ for kept in ["logs", "profile", "profile.derived.key", "run", "nsp", "survey.md", "unknown"] { XCTAssertNil(BuildFolderPart.of(kept), kept) }
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index 20b9fddf..7ab3fde2 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -671,6 +671,23 @@ final class LibraryTests: XCTestCase {
model.installDevice = "00008150-AAAA"; model.signingTeam = "TEAM123456"
try capture("build-install", height: 1300, page: .builds)
model.installDevice = previousDevice; model.signingTeam = previousTeam; model.target = previousTarget
+ // The Free space sheet with a measured build folder (example sizes), two parts picked, then while a build runs
+ let measured = BuildFolderSurvey(folder: "/Volumes/Games/Hades/\(titleID)_build",
+ sizes: [.extracted: 9_800_000_000, .shaders: 1_450_000_000, .xcode: 2_100_000_000, .caches: 610_000_000], kept: 48_000_000)
+ for (name, running) in [("free-space", false), ("free-space-running", true)] {
+ model.running = running
+ let sheet = NSHostingView(rootView: FreeSpaceView(m: model, game: library.games[0], survey: measured, chosen: [.extracted, .xcode])
+ .environmentObject(PadFocus()))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 690), styleMask: [.titled], backing: .buffered, defer: false)
+ window.contentView = sheet
+ window.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))
+ let rep = try XCTUnwrap(sheet.bitmapImageRepForCachingDisplay(in: sheet.bounds))
+ sheet.cacheDisplay(in: sheet.bounds, to: rep)
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))
+ window.orderOut(nil)
+ }
+ model.running = false
if let json = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_SETTINGS"] { // a launcher.json from dm/games/settings.py
let first = library.games[0]
let dm = URL(fileURLWithPath: first.appPath).appendingPathComponent("Contents/Resources/dm")