Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Epic saves: uninstall asks to keep or delete them, and a reinstall puts kept ones back
Gabe240d1fb9652a
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 4f7c632..25a5ca7 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -1104,6 +1104,7 @@ final class AppState {await MainActor.run { [weak self] inguard let self else { return }self.epicFetchInFlight = false+ defer { self.offerKeptEpicSaves() }let installs = EpicStore.installMap(installed)guard installs != self.epicInstalls else { return }self.epicInstalls = installs@@ -2256,7 +2257,7 @@ final class AppState {}}- /// Carries out the route the ask offered. `deleteSaves`: a GOG game's saves go with it.+ /// Carries out the route the ask offered. `deleteSaves`: a GOG or Epic game's saves go with it.func uninstallConfirmed(deleteSaves: Bool = false) {guard let (item, route) = pendingUninstall else { return }pendingUninstall = nil@@ -2284,14 +2285,7 @@ final class AppState {}}case let .epic(appName):- appendLog("\(item.title): asking the Epic tools to uninstall it")- let store = EpicStore(paths: paths)- runBusy(String(format: L("Removing %@"), item.title),- done: DoneState(title: String(format: L("%@ removed"), item.title), ctaTitle: nil, cta: nil),- stop: .cancelTask(label: L("Stop"))) { [self] in- _ = try store.uninstall(appName) { line in Task { @MainActor in self.appendLog(line) } }- await MainActor.run { self.refresh() }- }+ epicUninstall(appName, title: item.title, in: bottle, deleteSaves: deleteSaves)case let .gog(id):gogUninstall(id: id, title: item.title, in: bottle, deleteSaves: deleteSaves)case .windowsUninstaller:@@ -3305,6 +3299,7 @@ final class AppState {self?.epicLoading = falseself?.epicFetchInFlight = falseself?.rebuildLibrary() // Epic results arrive after refresh(); fold them in+ self?.offerKeptEpicSaves()}}}@@ -3332,6 +3327,9 @@ final class AppState {let refused = try await Task.detached {try store.move(appName, from: path, into: dest) { line in Task { @MainActor in self.appendLog(line) } }}.value+ if refused == nil, let from = bottles.first(where: { EpicStore.isInstalled(path: path, inDriveC: $0.driveC) }) {+ EpicSaves.moveHistory(app: appName, from: from.driveC, to: dest.driveC)+ }await MainActor.run { self.epicRefresh() }if let refused { throw HighballError.failed(String(format: L("%@ could not move. %@"), item.title, refused)) }}@@ -3358,17 +3356,28 @@ final class AppState {epicDownloadTotal = nillet refused = OSAllocatedUnfairLock(initialState: false)let failure = OSAllocatedUnfairLock<String?>(initialState: nil)+ // What changes in the game's folder while legendary installs or updates it is+ // legendary's, not saves (EpicSaves.historyFile).+ let start = Date()// Stop cancels this task, and the cancellation reaches legendary as a Ctrl-C, which// keeps the download's progress for the next Install.- let status = try await withTaskCancellationHandler {- try await Task.detached {- try store.install(game.app_name, into: bottle, control: control) { line in- if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }- if let why = EpicStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }- Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }- }- }.value- } onCancel: { control.stop() }+ let status: Int32+ do {+ status = try await withTaskCancellationHandler {+ try await Task.detached {+ try store.install(game.app_name, into: bottle, control: control) { line in+ if EpicStore.refusedForLock(line) { refused.withLock { $0 = true } }+ if let why = EpicStore.installFailure(line) { failure.withLock { if $0 == nil { $0 = why } } }+ Task { @MainActor in self.appendLog(line); self.reportEpicDownload(line) }+ }+ }.value+ } onCancel: { control.stop() }+ } catch {+ EpicSaves.recordInstall(app: game.app_name, driveC: bottle.driveC, start: start, end: Date(), finished: false)+ throw error+ }+ EpicSaves.recordInstall(app: game.app_name, driveC: bottle.driveC, start: start, end: Date(),+ finished: status == 0 && !refused.withLock({ $0 }) && !Task.isCancelled)try Task.checkCancellation()if refused.withLock({ $0 }) {throw HighballError.failed(L("Another Epic download is still running, and legendary installs one game at a time. If Highball shows none, one started before Highball last quit is still going, so quit legendary in Activity Monitor and press Install again."))@@ -3381,6 +3390,103 @@ final class AppState {}}+ /// Removes an Epic game through legendary, so its library stays right. Keep save data (the+ /// default) first copies, as kept backups, the game's Epic save folder and every file the game+ /// wrote in its install folder since Highball installed it, and stops if a copy fails; a later+ /// install is offered them back. `deleteSaves` copies nothing and also deletes the save folder+ /// when it lies inside the environment (EpicSaves.removeSaves).+ private func epicUninstall(_ app: String, title: String, in bottle: Bottle, deleteSaves: Bool) {+ let store = epicStore+ let install = epicInstalls[app].map { URL(fileURLWithPath: $0, isDirectory: true) }+ // Resolving the save folder runs legendary's sync-saves (moving nothing), which a player+ // who turned Sync saves with Epic off didn't ask for.+ let resolve = !epicCloudSavesOff.contains(app)+ runBusy(String(format: L("Removing %@"), title),+ done: DoneState(title: String(format: L("%@ removed"), title), ctaTitle: nil, cta: nil),+ stop: .cancelTask(label: L("Stop"))) { [self] in+ let saves = EpicSaves(store: store), prefix = bottle.url+ let log: @Sendable (String) -> Void = { line in Task { @MainActor in self.appendLog(line) } }+ var saveFolder: URL?+ var kept: [KeptSaves.Entry] = []+ if let install, EpicStore.isInstalled(path: install.path, inDriveC: bottle.driveC) {+ stage = L("Finding the game's saves")+ saveFolder = await Task.detached { saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: resolve, onLine: log) }.value+ if !deleteSaves {+ // These would go with the game, so they are copied before anything runs, and a+ // failed copy stops the removal. Never pruned.+ stage = L("Keeping a copy of the game's saves")+ kept = try await Task.detached { try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: saveFolder) }.value+ for entry in kept {+ let (files, bytes) = SaveBackups.contents(of: entry.backup)+ let what = entry.name == EpicSaves.gameFolderName ? "the game wrote in its folder" : "in its save folder"+ appendLog("\(title): \(files) file\(files == 1 ? "" : "s") \(what) (\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))) copied to \(entry.backup.path)")+ }+ }+ }+ appendLog("\(title): asking the Epic tools to uninstall it")+ _ = try await Task.detached { try store.uninstall(app, onLine: log) }.value+ if let install, !FileManager.default.fileExists(atPath: install.path) {+ EpicSaves.forgetHistory(app: app, driveC: bottle.driveC)+ if deleteSaves, let saveFolder, !EpicSaves.isInside(saveFolder, roots: [install]) {+ if saves.removeSaves(app, folder: saveFolder, install: install, prefix: prefix) {+ appendLog("\(title): saves at \(saveFolder.path) deleted, as asked")+ } else if FileManager.default.fileExists(atPath: saveFolder.path) {+ appendLog("\(title): saves at \(saveFolder.path) left in place: they are outside this environment, or hold other things Highball keeps")+ }+ }+ // Recorded once the folder is gone, so this install is never offered its own saves.+ saves.keep(kept, of: app)+ }+ await MainActor.run { self.refresh() }+ }+ }++ /// Saves an uninstall kept, offered to a new install of the game (EpicSaves.keep).+ struct EpicSavesToPutBack {+ let app: String+ let title: String+ let install: URL+ let bottle: Bottle+ let kept: KeptSaves+ }+ var epicSavesToPutBack: EpicSavesToPutBack?++ /// Offers, once per install, to put back saves an uninstall kept of the same game. Only for+ /// an install Highball made (EpicSaves.history), and while the game isn't running.+ private func offerKeptEpicSaves() {+ guard epicSavesToPutBack == nil else { return }+ let all = EpicSaves(store: epicStore).keptSaves() // one read, not one per installed game+ guard !all.isEmpty else { return }+ for (app, path) in epicInstalls.sorted(by: { $0.key < $1.key }) {+ let install = URL(fileURLWithPath: path, isDirectory: true)+ guard let bottle = bottles.first(where: { EpicStore.isInstalled(path: path, inDriveC: $0.driveC) }),+ let kept = KeptSavesFile.toOffer(all[app], install: install),+ EpicSaves.history(app: app, driveC: bottle.driveC).firstSetup != nil,+ !runningSessions.contains(where: { $0.libraryID == "epic:\(app)" }) else { continue }+ let title = epicOwned.first { $0.app_name == app }?.app_title ?? app+ epicSavesToPutBack = EpicSavesToPutBack(app: app, title: title, install: install, bottle: bottle, kept: kept)+ return+ }+ }++ /// The answer to the put-back question; either way that install isn't asked again.+ func epicPutBackSaves(_ putBack: Bool) {+ guard let pending = epicSavesToPutBack else { return }+ epicSavesToPutBack = nil+ let saves = EpicSaves(store: epicStore)+ saves.markAsked(pending.app, install: pending.install)+ guard putBack else { offerKeptEpicSaves(); return }+ Task {+ do {+ let count = try await Task.detached { try saves.putBack(pending.kept, app: pending.app, install: pending.install, prefix: pending.bottle.url) }.value+ appendLog("\(pending.title): \(count) saved file\(count == 1 ? "" : "s") put back from \(pending.kept.date.formatted()), what was there copied to save-backups first")+ } catch {+ fail(HighballError.failed(String(format: L("Highball could not put back all of %@'s saves: %@"), pending.title, error.localizedDescription)))+ }+ offerKeptEpicSaves()+ }+ }+/// Quitting the app stops an Epic download the way Stop does, so it never runs on alone,/// holding legendary's install lock with nothing on screen to stop it (highball#323).func stopEpicInstall() { epicInstallControl?.stop() }diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex b3555f8..ee76343 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -258,6 +258,7 @@ struct ContentView: View {.gogSaveConflictAsk(state).gogRemovalWithoutBackupAsk(state).gogPutBackSavesAsk(state)+ .epicPutBackSavesAsk(state).sheet(item: $state.engineTransition) { t in EngineTransitionSheet(transition: t) }#if DEBUG// Screenshot runs only: HB_SHOW_ENGINE_SWITCH="<environment>><engine id>" opens the switch@@ -532,12 +533,15 @@ private extension View {self.alert(state.pendingUninstall.map { String(format: L("Remove %@?"), $0.item.title) } ?? "",isPresented: .init(get: { state.pendingUninstall != nil }, set: { if !$0 { state.pendingUninstall = nil } }),presenting: state.pendingUninstall) { pending in- if case .gog = pending.route {+ switch pending.route {+ case .gog, .epic:// Keeping the saves is the answer Return gives.Button(L("Keep save data")) { state.uninstallConfirmed() }.keyboardShortcut(.defaultAction)Button(L("Delete save data too"), role: .destructive) { state.uninstallConfirmed(deleteSaves: true) }- } else if Uninstall.isActionable(pending.route) {- Button(L("Remove"), role: .destructive) { state.uninstallConfirmed() }+ default:+ if Uninstall.isActionable(pending.route) {+ Button(L("Remove"), role: .destructive) { state.uninstallConfirmed() }+ }}Button(L("Cancel"), role: .cancel) { state.pendingUninstall = nil }} message: { pending in@@ -575,6 +579,20 @@ private extension View {}}+ /// An uninstall kept this Epic game's saves, and it is installed again: offered once per install.+ @MainActor func epicPutBackSavesAsk(_ state: AppState) -> some View {+ self.alert(state.epicSavesToPutBack.map { String(format: L("Put back your saves from %@?"),+ $0.kept.date.formatted(date: .abbreviated, time: .omitted)) } ?? "",+ // As GOG's: the buttons answer, the dismissal never answers the next game's question.+ isPresented: .init(get: { state.epicSavesToPutBack != nil }, set: { _ in }),+ presenting: state.epicSavesToPutBack) { _ in+ Button(L("Put them back")) { state.epicPutBackSaves(true) }.keyboardShortcut(.defaultAction)+ Button(L("Not now"), role: .cancel) { state.epicPutBackSaves(false) }+ } message: { pending in+ Text(String(format: L("Highball kept %@'s saves when it was removed. Put them back copies them to where they were; anything already there is copied to save-backups first."), pending.title))+ }+ }+/// Some of a game's saves can't be backed up before it is removed (GOG unreachable, or saves/// kept directly in the game's folder). Nothing is removed unless the player agrees.@MainActor func gogRemovalWithoutBackupAsk(_ state: AppState) -> some View {diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex ec83117..52adcc8 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -258,6 +258,7 @@ enum L10n {"Put back your saves from %@?": "Remettre vos sauvegardes du %@ ?","Put them back": "Les remettre","Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie dans le dossier du jeu ; ce qui s’y trouve déjà est d’abord copié dans save-backups.",+ "Highball kept %@'s saves when it was removed. Put them back copies them to where they were; anything already there is copied to save-backups first.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie là où elles étaient ; ce qui s’y trouve déjà est d’abord copié dans save-backups.","Highball could not put back all of %@'s saves: %@": "Highball n’a pas pu remettre toutes les sauvegardes de %@ : %@","GOG says %@ keeps some of its saves directly in the game's folder, which Highball can't copy as one save folder. Files the game changed in its folder since you first played it are still copied to save-backups first, along with its other save folders, and saves already in GOG's cloud are not affected.":"Selon GOG, %@ garde une partie de ses sauvegardes directement dans le dossier du jeu, que Highball ne peut pas copier comme un dossier de sauvegardes. Les fichiers que le jeu a modifiés dans son dossier depuis votre première partie sont tout de même copiés dans save-backups, avec ses autres dossiers de sauvegardes, et celles déjà dans le cloud GOG ne sont pas touchées.",diff --git a/Sources/HighballKit/EpicSaves.swift b/Sources/HighballKit/EpicSaves.swiftindex 1d932b0..73d4e63 100644--- a/Sources/HighballKit/EpicSaves.swift+++ b/Sources/HighballKit/EpicSaves.swift@@ -211,7 +211,7 @@ public struct EpicSaves: Sendable {return (existing.resolvingSymlinksInPath().pathComponents + rest).map { $0.lowercased() }}- static func isInside(_ path: URL, roots: [URL]) -> Bool {+ public static func isInside(_ path: URL, roots: [URL]) -> Bool {let parts = components(path)return roots.contains { parts.starts(with: components($0)) }}@@ -362,7 +362,7 @@ public struct EpicSaves: Sendable {/// One lock per game: a sync that starts while another runs (an upload still going when/// Play is pressed again) waits for it.private static let gameLocks = OSAllocatedUnfairLock(initialState: [String: NSLock]())- private static func lock(for app: String) -> NSLock {+ static func lock(for app: String) -> NSLock {gameLocks.withLock { locks inif let lock = locks[app] { return lock }let lock = NSLock(); locks[app] = lock@@ -382,9 +382,9 @@ public struct EpicSaves: Sendable {return Run(status: status, lines: lines.withLock { $0 })}- private enum Compared { case success(Check), failure(String) }+ enum Compared { case success(Check), failure(String) }- private func compare(_ app: String, environment: [String: String], onLine: (@Sendable (String) -> Void)?) -> Compared {+ func compare(_ app: String, environment: [String: String], onLine: (@Sendable (String) -> Void)?) -> Compared {do {let result = try run(app, direction: nil, environment: environment, onLine: onLine)guard result.status == 0, !result.lines.contains(where: Self.isFailure), let check = Self.check(in: result.lines) else {@@ -527,3 +527,156 @@ public struct EpicSaves: Sendable {return .restored(problem)}}++// MARK: Uninstalling and putting saves back++extension EpicSaves {+ /// When Highball first installed a game into an environment through legendary and when it+ /// installed over it again (an update or a repair), so an uninstall can tell the files the+ /// game wrote in its folder from legendary's (GameInstallHistory). Kept in the environment,+ /// like GOG's next to its setup marker; removed with the game.+ public static func historyFile(app: String, driveC: URL) -> URL {+ driveC.appending(path: "highball/epic-installs/\(app).history.json")+ }++ /// An install from before the history was kept has none: nothing tells its files apart.+ public static func history(app: String, driveC: URL) -> GameInstallHistory {+ GameInstallHistory.read(historyFile(app: app, driveC: driveC)) ?? GameInstallHistory()+ }++ /// A legendary install of the game into the environment ran from `start` to `end`. The first+ /// one that `finished` starts the history at its end; after that each run, finished or not,+ /// is a window whose changes are legendary's.+ public static func recordInstall(app: String, driveC: URL, start: Date, end: Date, finished: Bool) {+ var history = history(app: app, driveC: driveC)+ if history.firstSetup != nil {+ history.updates.append(.init(start: start, end: end))+ } else if finished {+ history.firstSetup = end+ } else {+ return+ }+ history.write(to: historyFile(app: app, driveC: driveC))+ }++ /// The game moved to another environment: its history goes with it.+ public static func moveHistory(app: String, from: URL, to: URL) {+ let source = historyFile(app: app, driveC: from), target = historyFile(app: app, driveC: to)+ guard FileManager.default.fileExists(atPath: source.path) else { return }+ try? FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? FileManager.default.removeItem(at: target)+ try? FileManager.default.moveItem(at: source, to: target)+ }++ public static func forgetHistory(app: String, driveC: URL) {+ try? FileManager.default.removeItem(at: historyFile(app: app, driveC: driveC))+ }++ /// The kept copy of the save folder, and of what the game wrote in its install folder.+ public static let savesName = "saves"+ public static let gameFolderName = "game-folder"++ func backupFolder(_ app: String, _ name: String, install: URL) -> URL {+ // The save folder's kept copies sit with its sync backups, so an unchanged one is reused.+ backups.folder(name == Self.gameFolderName ? "epic-\(app)-\(name)" : "epic-\(app)", install: install)+ }++ /// The save folder an uninstall deals with: the one legendary stored, when it lies in the+ /// environment, a Mac folder its user folders link to, or the install folder (where sync+ /// would look), and isn't one sync refuses for holding more than this game's saves. With+ /// `resolve`, a game whose folder legendary hasn't worked out yet (or worked out for another+ /// environment) has it resolve the folder, comparing without moving anything, as a sync+ /// starts. nil when there is none.+ public func uninstallSaveFolder(_ app: String, install: URL, prefix: URL, resolve: Bool,+ home: URL = FileManager.default.homeDirectoryForCurrentUser,+ onLine: (@Sendable (String) -> Void)? = nil) -> URL? {+ let roots = Self.allowedRoots(prefix: prefix, home: home) + [install]+ func usable(_ folder: URL?) -> URL? {+ guard let folder, Self.isInside(folder, roots: roots),+ Self.refusal(for: folder, install: install, prefix: prefix, home: home, filter: catalog(app)?.filter ?? .everything) == nil+ else { return nil }+ return folder+ }+ if let folder = usable(savePath(app)) { return folder }+ guard resolve, supportsCloudSaves(app) else { return nil }+ let gameLock = Self.lock(for: app)+ gameLock.lock()+ defer { gameLock.unlock() }+ if let stored = savePath(app), !Self.isInside(stored, roots: roots) {+ guard (try? forgetSavePath(app)) != nil else { return nil }+ }+ guard case .success = compare(app, environment: ["WINEPREFIX": prefix.path], onLine: onLine) else { return nil }+ return usable(savePath(app))+ }++ /// Before an uninstall, copies as kept backups (never pruned): the save folder's files the+ /// catalog's include and exclude lists pick, when `saveFolder` is given, and every file the+ /// game wrote in its install folder since Highball installed it there, outside the runs that+ /// installed over it (history), leaving out the save folder. Never installed through Highball+ /// here: no install-folder copy. Returns what was kept, each with where it came from; throws+ /// when a copy fails, and the uninstall must then stop.+ public func backUpForUninstall(_ app: String, install: URL, prefix: URL, saveFolder: URL?) throws -> [KeptSaves.Entry] {+ var kept: [KeptSaves.Entry] = []+ if let saveFolder,+ let copy = try backups.backUpLocal(saveFolder, into: backupFolder(app, Self.savesName, install: install),+ filter: catalog(app)?.filter ?? .everything, kept: true) {+ kept.append(KeptSaves.Entry(name: Self.savesName, folder: saveFolder, backup: copy, install: install, environment: prefix))+ }+ let history = Self.history(app: app, driveC: prefix.appending(path: "drive_c"))+ guard history.firstSetup != nil else { return kept }+ let skipped = saveFolder.map { $0.standardizedFileURL.path + "/" }+ let written = try SaveBackups.files(in: install, writtenPer: history).filter { file in+ skipped.map { !file.standardizedFileURL.path.hasPrefix($0) } ?? true+ }+ if !written.isEmpty,+ let copy = try backups.backUpLocal(install, into: backupFolder(app, Self.gameFolderName, install: install), kept: true, only: written) {+ kept.append(KeptSaves.Entry(name: Self.gameFolderName, path: "", backup: copy, place: .game))+ }+ return kept+ }++ /// For a player who asked for the saves to go with the game: deletes the save folder (only+ /// the files the include and exclude lists pick, when the catalog has them) when, links+ /// followed, it lies inside the environment's drive_c and neither holds nor sits inside+ /// Highball's save-backups or the install folder (which the uninstall removes anyway).+ /// Returns whether it was deleted.+ public func removeSaves(_ app: String, folder: URL, install: URL, prefix: URL) -> Bool {+ guard FileManager.default.fileExists(atPath: folder.path),+ SaveBackups.mayDelete(folder, driveC: prefix.appending(path: "drive_c"), sparing: [backups.root, install]) else { return false }+ let filter = catalog(app)?.filter ?? .everything+ if filter.isEverything { return (try? FileManager.default.removeItem(at: folder)) != nil }+ for file in SaveBackups.files(in: folder, matching: filter) {+ guard (try? FileManager.default.removeItem(at: file)) != nil else { return false }+ }+ return true+ }++ var keptSavesFile: KeptSavesFile { KeptSavesFile(url: store.configDir.deletingLastPathComponent().appending(path: "epic-kept-saves.json")) }++ /// Remembers what an uninstall kept of the game, in place of what an earlier one kept.+ /// legendary installs a game once, so there is no other install to leave out.+ public func keep(_ entries: [KeptSaves.Entry], of app: String) {+ keptSavesFile.keep(entries, for: app, otherInstalls: [])+ }++ public func keptSaves() -> [String: KeptSaves] { keptSavesFile.all() }++ public func markAsked(_ app: String, install: URL) { keptSavesFile.markAsked(app, install: install) }++ /// Puts kept saves back into a new install of the game: the save folder's to the same place in+ /// the environment (or the install folder, or the Mac folder it was in), the game-folder copy+ /// to the same paths in the install folder, dated now so the next uninstall counts them as the+ /// game's. A file already there is backed up first (kept). Returns how many files were put+ /// back; throws, having put back what it had, when a copy fails.+ @discardableResult+ public func putBack(_ kept: KeptSaves, app: String, install: URL, prefix: URL) throws -> Int {+ var count = 0+ for entry in kept.entries {+ guard let target = entry.folder(install: install, environment: prefix) else { continue }+ count += try SaveBackups.putBack(entry.backup, into: target, redate: entry.name == Self.gameFolderName) { there in+ try backups.backUpLocal(target, into: backupFolder(app, entry.name, install: install), kept: true, only: there)+ }+ }+ return count+ }+}diff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swiftindex da8b101..0f2225f 100644--- a/Sources/HighballKit/GOGLibrary.swift+++ b/Sources/HighballKit/GOGLibrary.swift@@ -534,20 +534,7 @@ extension GOGStore {/// When Highball first set an install up in the environment and when it updated it, so an/// uninstall can tell the files the game wrote from the ones the installer and the patches/// put down (GOGSaves.backUpGameFolder). Kept next to the setup marker.- public struct InstallHistory: Codable, Sendable, Equatable {- public struct Window: Codable, Sendable, Equatable {- public let start: Date- public let end: Date- }- public var firstSetup: Date?- public var updates: [Window] = []-- /// Written by the game: changed after the first setup, and not while an update ran.- public func isGameWritten(_ changed: Date) -> Bool {- guard let firstSetup, changed > firstSetup else { return false }- return !updates.contains { $0.start <= changed && changed <= $0.end }- }- }+ public typealias InstallHistory = GameInstallHistorypublic static func historyFile(for game: InstalledGame, driveC: URL) -> URL {driveC.appending(path: "highball/gog-setup/\(game.id).history.json")@@ -556,8 +543,7 @@ extension GOGStore {/// An install set up before the history was kept falls back to the marker's date for its/// first setup.public static func history(for game: InstalledGame, driveC: URL) -> InstallHistory {- var history = (try? Data(contentsOf: historyFile(for: game, driveC: driveC)))- .flatMap { try? JSONDecoder().decode(InstallHistory.self, from: $0) } ?? InstallHistory()+ var history = InstallHistory.read(historyFile(for: game, driveC: driveC)) ?? InstallHistory()if history.firstSetup == nil {history.firstSetup = try? setupMarker(for: game, driveC: driveC).resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate}@@ -565,9 +551,7 @@ extension GOGStore {}private static func save(_ history: InstallHistory, for game: InstalledGame, driveC: URL) {- let url = historyFile(for: game, driveC: driveC)- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)- try? JSONEncoder().encode(history).write(to: url, options: .atomic)+ history.write(to: historyFile(for: game, driveC: driveC))}/// An update ran from `start` to `end`: what changed in the game's folder then is the patch's.diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swiftindex fc7bea3..0a52ed7 100644--- a/Sources/HighballKit/GOGSaves.swift+++ b/Sources/HighballKit/GOGSaves.swift@@ -163,13 +163,9 @@ public struct GOGSaves: Sendable {/// save-backups or the game's folder is left alone too. Returns what was removed and what/// was left for that reason.public func removeSaves(_ plan: UninstallPlan, game: GOGStore.InstalledGame, driveC: URL) -> (removed: [URL], leftAlone: [URL]) {- func path(_ url: URL) -> String { url.resolvingSymlinksInPath().standardizedFileURL.path }- func overlap(_ a: String, _ b: String) -> Bool { a == b || a.hasPrefix(b + "/") || b.hasPrefix(a + "/") }- let keep = [path(backupsDir), path(game.folder)], environment = path(driveC) + "/"var removed: [URL] = [], leftAlone: [URL] = []for folder in plan.outside.map(\.folder) where FileManager.default.fileExists(atPath: folder.path) {- let real = path(folder)- guard real.hasPrefix(environment), !keep.contains(where: { overlap(real, $0) }) else { leftAlone.append(folder); continue }+ guard SaveBackups.mayDelete(folder, driveC: driveC, sparing: [backupsDir, game.folder]) else { leftAlone.append(folder); continue }if (try? FileManager.default.removeItem(at: folder)) != nil { removed.append(folder) }}return (removed, leftAlone)@@ -236,13 +232,9 @@ public struct GOGSaves: Sendable {/// location GOG names, so a game without cloud saves has one too.public static let gameFolder = Location(name: "game-folder", template: "<?INSTALL?>")- /// The files under `folder` the game wrote, by the install's history, links counted by what- /// they point at.+ /// The files under `folder` the game wrote, by the install's history (SaveBackups).static func files(in folder: URL, writtenPer history: GOGStore.InstallHistory) throws -> [URL] {- try walk(folder).filter { file in- let changed = try? file.resolvingSymlinksInPath().resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate- return history.isGameWritten(changed ?? .distantPast)- }+ try SaveBackups.files(in: folder, writtenPer: history)}/// Before an uninstall, backs up (kept) every file the game wrote in its own folder: changed@@ -263,11 +255,7 @@ public struct GOGSaves: Sendable {}/// How many files a backup holds and their size, for the log.- public static func contents(of backup: URL) -> (files: Int, bytes: Int64) {- let all = files(in: backup)- let bytes = all.reduce(Int64(0)) { $0 + Int64((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }- return (all.count, bytes)- }+ public static func contents(of backup: URL) -> (files: Int, bytes: Int64) { SaveBackups.contents(of: backup) }/// GOG's whole cloud listing for the game, from a gogdl run that can't move anything: an/// empty folder and a location name no cloud file starts with, so gogdl finds no files on@@ -558,59 +546,33 @@ public struct GOGSaves: Sendable {// MARK: Putting saves back/// What an uninstall kept of a game's saves, so installing it again can put them back.- public struct KeptSaves: Codable, Sendable, Equatable {- public struct Entry: Codable, Sendable, Equatable {- /// The location's name, or gameFolder's.- public let name: String- /// Where its files sat, relative to the game's folder; empty for the folder itself.- public let path: String- public let backup: URL- }- public var date: Date- public var entries: [Entry]- /// Install folders already asked, whatever the answer: never asked again.- public var asked: [String]- }+ public typealias KeptSaves = HighballKit.KeptSaves- var keptSavesFile: URL { store.dir.appending(path: "kept-saves.json") }+ var keptSavesFile: KeptSavesFile { KeptSavesFile(url: store.dir.appending(path: "kept-saves.json")) }/// Every game's kept saves, by game id.- public func keptSaves() -> [String: KeptSaves] {- (try? JSONDecoder().decode([String: KeptSaves].self, from: Data(contentsOf: keptSavesFile))) ?? [:]- }-- private static let keptSavesLock = NSLock()- private func updateKeptSaves(_ change: (inout [String: KeptSaves]) -> Void) {- Self.keptSavesLock.withLock {- var all = keptSaves()- change(&all)- store.secureDirectory()- try? JSONEncoder().encode(all).write(to: keptSavesFile, options: .atomic)- }- }+ public func keptSaves() -> [String: KeptSaves] { keptSavesFile.all() }/// Remembers the backups an uninstall kept of `game`, each with the folder it came from, in- /// place of what an earlier uninstall kept: a location this one had nothing for never brings- /// back an older copy. `otherInstalls` (copies of the game still in other environments) are never asked: they- /// still have their own saves.+ /// place of what an earlier uninstall kept (KeptSavesFile.keep). `otherInstalls` (copies of+ /// the game still in other environments) are never asked: they still have their own saves.public func keep(_ backups: [(name: String, folder: URL, backup: URL)], of game: GOGStore.InstalledGame,otherInstalls: [URL]) {let entries = backups.map { KeptSaves.Entry(name: $0.name, path: $0.folder == game.folder ? "" : Self.relativePath(of: $0.folder, in: game.folder),backup: $0.backup) }- updateKeptSaves { all in- all[game.id] = entries.isEmpty ? nil : KeptSaves(date: Date(), entries: entries, asked: otherInstalls.map(\.standardizedFileURL.path))- }+ store.secureDirectory()+ keptSavesFile.keep(entries, for: game.id, otherInstalls: otherInstalls)}/// The install was asked about putting saves back: it is not asked again.public func markAsked(_ game: GOGStore.InstalledGame) {- updateKeptSaves { $0[game.id]?.asked.append(game.folder.standardizedFileURL.path) }+ store.secureDirectory()+ keptSavesFile.markAsked(game.id, install: game.folder)}/// The kept saves to offer this install: nil when there are none or it was asked already.public static func toOffer(_ kept: KeptSaves?, to game: GOGStore.InstalledGame) -> KeptSaves? {- guard let kept, !kept.asked.contains(game.folder.standardizedFileURL.path) else { return nil }- return kept+ KeptSavesFile.toOffer(kept, install: game.folder)}/// Puts kept saves back into an install of the game: each backup's files to the same place@@ -622,23 +584,10 @@ public struct GOGSaves: Sendable {public func putBack(_ kept: KeptSaves, into game: GOGStore.InstalledGame) throws -> Int {var count = 0for entry in kept.entries {- let target = entry.path.isEmpty ? game.folder : game.folder.appending(path: entry.path)- let files = try Self.walk(entry.backup).map { ($0, Self.relativePath(of: $0, in: entry.backup)) }- let there = files.map { target.appending(path: $0.1) }.filter { FileManager.default.fileExists(atPath: $0.path) }- if !there.isEmpty {+ guard let target = entry.folder(install: game.folder, environment: nil) else { continue }+ count += try SaveBackups.putBack(entry.backup, into: target, redate: entry.name == Self.gameFolder.name) { there intry backUpLocal(game, location: Location(name: entry.name, template: ""), folder: target, kept: true, only: there)}- for (file, path) in files {- // Through a link, as gogdl writes.- let copy = target.appending(path: path).resolvingSymlinksInPath()- try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)- if FileManager.default.fileExists(atPath: copy.path) { try FileManager.default.removeItem(at: copy) }- try FileManager.default.copyItem(at: file, to: copy)- if entry.name == Self.gameFolder.name {- try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: copy.path)- }- count += 1- }}return count}diff --git a/Sources/HighballKit/KeptSaves.swift b/Sources/HighballKit/KeptSaves.swiftnew file mode 100644index 0000000..960c0e4--- /dev/null+++ b/Sources/HighballKit/KeptSaves.swift@@ -0,0 +1,181 @@+import Foundation++/// When Highball first installed (or set up) a game in an environment and when it updated it, so+/// an uninstall can tell the files the game wrote from the ones the installer and the patches put+/// down. GOG keeps it next to its setup marker (GOGStore.InstallHistory), Epic next to its own+/// (EpicSaves.historyFile).+public struct GameInstallHistory: Codable, Sendable, Equatable {+ public struct Window: Codable, Sendable, Equatable {+ public let start: Date+ public let end: Date+ public init(start: Date, end: Date) { self.start = start; self.end = end }+ }+ public var firstSetup: Date?+ public var updates: [Window] = []++ public init(firstSetup: Date? = nil, updates: [Window] = []) { self.firstSetup = firstSetup; self.updates = updates }++ /// Written by the game: changed after the first setup, and not while an update ran.+ public func isGameWritten(_ changed: Date) -> Bool {+ guard let firstSetup, changed > firstSetup else { return false }+ return !updates.contains { $0.start <= changed && changed <= $0.end }+ }++ public static func read(_ url: URL) -> GameInstallHistory? {+ (try? Data(contentsOf: url)).flatMap { try? JSONDecoder().decode(GameInstallHistory.self, from: $0) }+ }++ public func write(to url: URL) {+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? JSONEncoder().encode(self).write(to: url, options: .atomic)+ }+}++/// What an uninstall kept of a game's saves, so installing it again can put them back (GOG and+/// Epic).+public struct KeptSaves: Codable, Sendable, Equatable {+ public struct Entry: Codable, Sendable, Equatable {+ /// What `path` is relative to.+ public enum Place: String, Codable, Sendable {+ /// The game's folder, as GOG writes every entry (no place stored).+ case game+ /// The environment's folder: an Epic save folder elsewhere in it.+ case environment+ /// Nothing: an absolute path, such as a Mac folder an environment links to.+ case absolute+ }+ /// The location's name, or the game-folder copy's.+ public let name: String+ /// Where its files sat, relative to `place`; empty for that folder itself.+ public let path: String+ public let backup: URL+ public var place: Place? = nil++ public init(name: String, path: String, backup: URL, place: Place? = nil) {+ self.name = name; self.path = path; self.backup = backup; self.place = place+ }++ /// Where `folder` is recorded from: below the game's folder, else below the environment,+ /// else as it is.+ public init(name: String, folder: URL, backup: URL, install: URL, environment: URL?) {+ func below(_ root: URL) -> String? {+ let path = folder.standardizedFileURL.path, base = root.standardizedFileURL.path+ if path == base { return "" }+ return path.hasPrefix(base + "/") ? SaveBackups.relativePath(folder, in: root) : nil+ }+ if let path = below(install) {+ self.init(name: name, path: path, backup: backup, place: .game)+ } else if let environment, let path = below(environment) {+ self.init(name: name, path: path, backup: backup, place: .environment)+ } else {+ self.init(name: name, path: folder.standardizedFileURL.path, backup: backup, place: .absolute)+ }+ }++ /// Where the files go back in a new install.+ public func folder(install: URL, environment: URL?) -> URL? {+ func below(_ root: URL) -> URL { path.isEmpty ? root : root.appending(path: path) }+ switch place ?? .game {+ case .game: return below(install)+ case .environment: return environment.map(below)+ case .absolute: return URL(fileURLWithPath: path, isDirectory: true)+ }+ }+ }+ public var date: Date+ public var entries: [Entry]+ /// Install folders already asked, whatever the answer: never asked again.+ public var asked: [String]++ public init(date: Date, entries: [Entry], asked: [String]) { self.date = date; self.entries = entries; self.asked = asked }+}++/// Every game's kept saves for one store, by game id, in one file (gog/kept-saves.json,+/// epic-kept-saves.json).+public struct KeptSavesFile: Sendable {+ public let url: URL+ public init(url: URL) { self.url = url }++ public func all() -> [String: KeptSaves] {+ (try? JSONDecoder().decode([String: KeptSaves].self, from: Data(contentsOf: url))) ?? [:]+ }++ private static let lock = NSLock()+ public func update(_ change: (inout [String: KeptSaves]) -> Void) {+ Self.lock.withLock {+ var all = all()+ change(&all)+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? JSONEncoder().encode(all).write(to: url, options: .atomic)+ }+ }++ /// Remembers what an uninstall kept of a game in place of what an earlier one kept: a location+ /// this one had nothing for never brings back an older copy, and keeping nothing offers+ /// nothing. `otherInstalls` (copies of the game still installed elsewhere) are never asked:+ /// they still have their own saves.+ public func keep(_ entries: [KeptSaves.Entry], for id: String, otherInstalls: [URL]) {+ update { all in+ all[id] = entries.isEmpty ? nil : KeptSaves(date: Date(), entries: entries, asked: otherInstalls.map(\.standardizedFileURL.path))+ }+ }++ /// The install was asked about putting saves back: it is not asked again.+ public func markAsked(_ id: String, install: URL) {+ update { $0[id]?.asked.append(install.standardizedFileURL.path) }+ }++ /// Kept saves this install hasn't been asked about, from what all() read.+ public static func toOffer(_ kept: KeptSaves?, install: URL) -> KeptSaves? {+ guard let kept, !kept.asked.contains(install.standardizedFileURL.path) else { return nil }+ return kept+ }+}++extension SaveBackups {+ /// The files under `folder` the game wrote, by the install's history, links counted by what+ /// they point at. Throws for a folder inside it that can't be read.+ public static func files(in folder: URL, writtenPer history: GameInstallHistory) throws -> [URL] {+ try walk(folder).filter { file in+ let changed = try? file.resolvingSymlinksInPath().resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate+ return history.isGameWritten(changed ?? .distantPast)+ }+ }++ /// How many files a backup holds and their size, for the log.+ public static func contents(of backup: URL) -> (files: Int, bytes: Int64) {+ let all = files(in: backup)+ let bytes = all.reduce(Int64(0)) { $0 + Int64((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }+ return (all.count, bytes)+ }++ /// Whether a save folder may be deleted with its game, for a player who asked for that: with+ /// links followed, it lies inside the environment's drive_c (an environment's Documents is+ /// often a link to the Mac's own, whose folders are the Mac's), and it neither holds nor sits+ /// inside any of `sparing` (Highball's save-backups, the game's folder).+ public static func mayDelete(_ folder: URL, driveC: URL, sparing: [URL]) -> Bool {+ func path(_ url: URL) -> String { url.resolvingSymlinksInPath().standardizedFileURL.path }+ func overlap(_ a: String, _ b: String) -> Bool { a == b || a.hasPrefix(b + "/") || b.hasPrefix(a + "/") }+ let real = path(folder)+ return real.hasPrefix(path(driveC) + "/") && !sparing.map(path).contains { overlap(real, $0) }+ }++ /// Puts a kept backup's files back into `target`, each to the same place below it, through a+ /// link as the store tools write. `backUpFirst` is handed the files already there before any+ /// is replaced, so a newer one is never lost. `redate` dates the copies now (a game-folder+ /// copy, so the next uninstall counts them as the game's). Returns how many files were put+ /// back; throws, having put back what it had, when a copy fails.+ public static func putBack(_ backup: URL, into target: URL, redate: Bool, backUpFirst: ([URL]) throws -> Void) throws -> Int {+ let files = try walk(backup).map { ($0, relativePath($0, in: backup)) }+ let there = files.map { target.appending(path: $0.1) }.filter { FileManager.default.fileExists(atPath: $0.path) }+ if !there.isEmpty { try backUpFirst(there) }+ for (file, path) in files {+ let copy = target.appending(path: path).resolvingSymlinksInPath()+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)+ if FileManager.default.fileExists(atPath: copy.path) { try FileManager.default.removeItem(at: copy) }+ try FileManager.default.copyItem(at: file, to: copy)+ if redate { try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: copy.path) }+ }+ return files.count+ }+}diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swiftindex ea3d6f6..6483600 100644--- a/Sources/HighballKit/Uninstall.swift+++ b/Sources/HighballKit/Uninstall.swift@@ -65,7 +65,7 @@ public enum Uninstall {case .steam:return "Steam does the uninstalling and asks you to confirm in its own window, so its library stays right.\(size)"case .epic:- return "The Epic tools do the uninstalling, so their library stays right.\(size)"+ return "The Epic tools do the uninstalling, so their library stays right. Keep save data first copies the game's save folder, and every file the game changed in its folder since Highball installed it, to Highball's save-backups, and offers to put them back if you install the game again. Delete save data too copies nothing and also deletes the game's save folder when it is inside this environment. Saves in Epic's cloud stay there either way.\(size)"case .gog:return "Highball deletes the game's folder from this environment. Keep save data first copies your saves from it, and every file the game changed there since you first played it, to Highball's save-backups, and offers to put them back if you install the game again. Delete save data too copies nothing and also deletes the game's save folders elsewhere in this environment. Saves in GOG's cloud stay there either way, and the game stays in your GOG library to install again.\(size)"case .windowsUninstaller:diff --git a/Tests/HighballKitTests/EpicFakeLegendaryTests.swift b/Tests/HighballKitTests/EpicFakeLegendaryTests.swiftindex 2d63379..e771f46 100644--- a/Tests/HighballKitTests/EpicFakeLegendaryTests.swift+++ b/Tests/HighballKitTests/EpicFakeLegendaryTests.swift@@ -192,6 +192,20 @@ final class EpicFakeLegendaryTests: XCTestCase {XCTAssertEqual(read(folder.appending(path: "slot.sav")), "v1")}+ /// An uninstall has legendary work out a save folder it hasn't stored yet, or stored for+ /// another environment, comparing without moving anything; told not to, it doesn't.+ func testAnUninstallResolvesTheSaveFolder() throws {+ try write("save", to: folder.appending(path: "slot.sav"), at: hourAgo)+ try cloudSave("v1", at: dayAgo)+ XCTAssertNil(saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: false, home: userHome))+ XCTAssertNil(saves.savePath(app))+ try installed(savePath: root.appending(path: "OtherEnv/drive_c/users/player/AppData/Local/Game/Saved").path)+ let found = saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: true, home: userHome)+ XCTAssertEqual(found?.standardizedFileURL.path, folder.standardizedFileURL.path)+ XCTAssertEqual(read(folder.appending(path: "slot.sav")), "save")+ XCTAssertEqual(cloudSaveCount, 1)+ }+/// A download Highball was in the middle of when it quit: its backup goes back first.func testAnInterruptedDownloadIsUndoneNextTime() throws {try syncedOnce()diff --git a/Tests/HighballKitTests/EpicUninstallSavesTests.swift b/Tests/HighballKitTests/EpicUninstallSavesTests.swiftnew file mode 100644index 0000000..d56ba55--- /dev/null+++ b/Tests/HighballKitTests/EpicUninstallSavesTests.swift@@ -0,0 +1,194 @@+import XCTest+@testable import HighballKit++/// What an Epic uninstall does with the game's saves (EpicSaves, uninstalling): which files are+/// kept, what Delete save data too may delete, and putting kept saves back into a new install.+final class EpicUninstallSavesTests: XCTestCase {+ private var root: URL!+ private var home: URL { root.appending(path: "home") }+ private var config: URL { home.appending(path: "legendary") }+ private var prefix: URL { root.appending(path: "Env") }+ private var driveC: URL { prefix.appending(path: "drive_c") }+ private var install: URL { driveC.appending(path: "Games/Game") }+ private var user: URL { driveC.appending(path: "users/player") }+ private var folder: URL { user.appending(path: "AppData/Local/Game/Saved") }+ private var userHome: URL { root.appending(path: "user") }+ private let app = "Game"+ private var saves: EpicSaves { EpicSaves(store: EpicStore(paths: HighballPaths(home: home))) }++ override func setUpWithError() throws {+ root = FileManager.default.temporaryDirectory.appending(path: "epic-uninstall-\(UUID().uuidString)")+ for dir in [config.appending(path: "metadata"), install, userHome, user] {+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ }+ try catalog(include: nil)+ }+ override func tearDown() {+ if let root { try? FileManager.default.removeItem(at: root) }+ }++ private func catalog(include: String?) throws {+ var attributes: [String: Any] = ["CloudSaveFolder": ["type": "STRING", "value": "{AppData}/Game/Saved"]]+ if let include { attributes["CloudIncludeList"] = ["type": "STRING", "value": include] }+ let obj: [String: Any] = ["app_name": app, "metadata": ["customAttributes": attributes]]+ try JSONSerialization.data(withJSONObject: obj).write(to: config.appending(path: "metadata/\(app).json"))+ }+ private func installed(savePath: URL?) throws {+ let game: [String: Any] = ["app_name": app, "install_path": install.path, "save_path": savePath?.path ?? NSNull()]+ try JSONSerialization.data(withJSONObject: [app: game]).write(to: config.appending(path: "installed.json"))+ }+ private func write(_ text: String, to url: URL, dated date: Date? = nil) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data(text.utf8).write(to: url)+ if let date { try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: url.path) }+ }+ private func read(_ url: URL) -> String? { try? String(contentsOf: url, encoding: .utf8) }+ private func relative(_ backup: URL) -> [String] { SaveBackups.files(in: backup).map { SaveBackups.relativePath($0, in: backup) } }++ /// The first install that finishes starts the history; one that failed before it doesn't, and+ /// every run after it (an update, a repair, a failed one) is legendary's window.+ func testTheHistoryStartsAtTheFirstFinishedInstall() {+ let t = Date(timeIntervalSince1970: 1_800_000_000)+ EpicSaves.recordInstall(app: app, driveC: driveC, start: t, end: t.addingTimeInterval(60), finished: false)+ XCTAssertNil(EpicSaves.history(app: app, driveC: driveC).firstSetup)+ EpicSaves.recordInstall(app: app, driveC: driveC, start: t.addingTimeInterval(100), end: t.addingTimeInterval(200), finished: true)+ EpicSaves.recordInstall(app: app, driveC: driveC, start: t.addingTimeInterval(1000), end: t.addingTimeInterval(1100), finished: false)+ let history = EpicSaves.history(app: app, driveC: driveC)+ XCTAssertEqual(history.firstSetup, t.addingTimeInterval(200))+ XCTAssertEqual(history.updates, [.init(start: t.addingTimeInterval(1000), end: t.addingTimeInterval(1100))])+ let other = root.appending(path: "Other/drive_c")+ EpicSaves.moveHistory(app: app, from: driveC, to: other)+ XCTAssertEqual(EpicSaves.history(app: app, driveC: other), history, "moves with the game")+ XCTAssertNil(EpicSaves.history(app: app, driveC: driveC).firstSetup)+ }++ /// Keep copies the save folder (the files the include list picks) and what the game wrote in+ /// its folder outside legendary's runs, leaving out a save folder inside it. Never installed+ /// through Highball: no install-folder copy.+ func testKeepCopiesTheSaveFolderAndWhatTheGameWrote() throws {+ try catalog(include: "*.sav")+ let now = Date()+ try write("exe", to: install.appending(path: "Game.exe"), dated: now.addingTimeInterval(-7200))+ try write("profile", to: install.appending(path: "Profiles/p1.ini"), dated: now.addingTimeInterval(-600))+ try write("save", to: folder.appending(path: "slot1.sav"))+ try write("cache", to: folder.appending(path: "shader.cache"))+ var kept = try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: folder)+ XCTAssertEqual(kept.map(\.name), [EpicSaves.savesName], "no history: the save folder only")+ XCTAssertEqual(relative(kept[0].backup), ["slot1.sav"])+ XCTAssertTrue(SaveBackups.isKept(kept[0].backup))+ XCTAssertEqual(kept[0].place, .environment)+ XCTAssertEqual(kept[0].path, "drive_c/users/player/AppData/Local/Game/Saved")++ let installed = now.addingTimeInterval(-3600)+ EpicSaves.recordInstall(app: app, driveC: driveC, start: installed.addingTimeInterval(-60), end: installed, finished: true)+ EpicSaves.recordInstall(app: app, driveC: driveC, start: now.addingTimeInterval(-1900), end: now.addingTimeInterval(-1700), finished: true)+ try write("patch", to: install.appending(path: "Data/patch.pak"), dated: now.addingTimeInterval(-1800))+ try write("inside", to: install.appending(path: "Saved/slot2.sav"), dated: now.addingTimeInterval(-60))+ kept = try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: install.appending(path: "Saved"))+ XCTAssertEqual(kept.map(\.name), [EpicSaves.savesName, EpicSaves.gameFolderName])+ XCTAssertEqual(kept[0].place, .game)+ XCTAssertEqual(kept[0].path, "Saved")+ XCTAssertEqual(relative(kept[1].backup), ["Profiles/p1.ini"], "not the installer's, the patch's or the save folder's")+ XCTAssertTrue(SaveBackups.isKept(kept[1].backup))+ }++ /// A save folder that can't be read stops the removal.+ func testAFailedCopyThrows() throws {+ try write("save", to: folder.appending(path: "Sub/slot1.sav"))+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: folder.appending(path: "Sub").path)+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.appending(path: "Sub").path) }+ XCTAssertThrowsError(try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: folder))+ }++ /// The folder an uninstall deals with is the one legendary stored, inside the environment, and+ /// not one sync refuses for holding more than this game's saves.+ func testTheUninstallSaveFolderIsOneSyncWouldUse() throws {+ XCTAssertNil(saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: false, home: userHome))+ try installed(savePath: folder)+ XCTAssertEqual(saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: false, home: userHome)?.path, folder.path)+ try installed(savePath: user.appending(path: "Documents"))+ XCTAssertNil(saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: false, home: userHome), "holds more than the game's saves")+ try installed(savePath: root.appending(path: "Elsewhere/drive_c/users/player/AppData/Local/Game/Saved"))+ XCTAssertNil(saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: false, home: userHome), "another environment's")+ }++ /// Delete save data too removes a save folder inside the environment's drive_c, only the files+ /// the include list picks when there is one, and never one that is the Mac's through a link,+ /// Highball's save-backups or the install folder.+ func testDeletingSavesStaysInsideTheEnvironment() throws {+ try write("save", to: folder.appending(path: "slot1.sav"))+ XCTAssertTrue(saves.removeSaves(app, folder: folder, install: install, prefix: prefix))+ XCTAssertFalse(FileManager.default.fileExists(atPath: folder.path))++ try catalog(include: "*.sav")+ try write("save", to: folder.appending(path: "slot1.sav"))+ try write("other", to: folder.appending(path: "settings.ini"))+ XCTAssertTrue(saves.removeSaves(app, folder: folder, install: install, prefix: prefix))+ XCTAssertEqual(SaveBackups.files(in: folder).map(\.lastPathComponent), ["settings.ini"])++ let mac = userHome.appending(path: "Documents")+ try write("mac", to: mac.appending(path: "My Games/Game/slot.sav"))+ try FileManager.default.createSymbolicLink(at: user.appending(path: "Documents"), withDestinationURL: mac)+ let linked = user.appending(path: "Documents/My Games/Game")+ XCTAssertFalse(saves.removeSaves(app, folder: linked, install: install, prefix: prefix))+ XCTAssertNotNil(read(mac.appending(path: "My Games/Game/slot.sav")))++ try write("kept", to: saves.backups.root.appending(path: "epic-Game-1/2026-mac-kept/slot.sav"))+ try FileManager.default.createSymbolicLink(at: user.appending(path: "Backups"), withDestinationURL: saves.backups.root)+ XCTAssertFalse(saves.removeSaves(app, folder: user.appending(path: "Backups"), install: install, prefix: prefix))+ XCTAssertFalse(saves.removeSaves(app, folder: driveC.appending(path: "Games"), install: install, prefix: prefix), "holds the game")+ XCTAssertTrue(FileManager.default.fileExists(atPath: saves.backups.root.appending(path: "epic-Game-1/2026-mac-kept/slot.sav").path))+ }++ /// Kept saves go back where they were in a new install, in another environment too: the save+ /// folder by its place in the environment, the game-folder copy by its paths, dated now. What+ /// is there already is copied first, the install is asked once, and only the latest+ /// uninstall's backups are offered.+ func testPuttingSavesBackPlacesThemInTheNewInstall() throws {+ let now = Date()+ EpicSaves.recordInstall(app: app, driveC: driveC, start: now.addingTimeInterval(-7200), end: now.addingTimeInterval(-3600), finished: true)+ try write("cloud slot", to: folder.appending(path: "slot1.sav"))+ try write("profile", to: install.appending(path: "Profiles/p1.ini"), dated: now.addingTimeInterval(-60))+ let kept = try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: folder)+ XCTAssertEqual(kept.count, 2)+ saves.keep(kept, of: app)++ let newPrefix = root.appending(path: "Env2")+ let newInstall = newPrefix.appending(path: "drive_c/Games/Game")+ let newFolder = newPrefix.appending(path: "drive_c/users/player/AppData/Local/Game/Saved")+ try write("fresh", to: newFolder.appending(path: "slot1.sav"))+ let offer = try XCTUnwrap(KeptSavesFile.toOffer(saves.keptSaves()[app], install: newInstall))+ XCTAssertEqual(try saves.putBack(offer, app: app, install: newInstall, prefix: newPrefix), 2)+ XCTAssertEqual(read(newFolder.appending(path: "slot1.sav")), "cloud slot")+ XCTAssertEqual(read(newInstall.appending(path: "Profiles/p1.ini")), "profile")+ let dated = try XCTUnwrap(try newInstall.appending(path: "Profiles/p1.ini").resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate)+ XCTAssertGreaterThan(dated, now.addingTimeInterval(-5), "counts as the game's at the next uninstall")+ let before = try XCTUnwrap(saves.backups.backups(in: saves.backupFolder(app, EpicSaves.savesName, install: newInstall)).first)+ XCTAssertEqual(read(before.appending(path: "slot1.sav")), "fresh", "what was there is copied first")+ XCTAssertTrue(SaveBackups.isKept(before))+ saves.markAsked(app, install: newInstall)+ XCTAssertNil(KeptSavesFile.toOffer(saves.keptSaves()[app], install: newInstall), "asked once")+ XCTAssertNotNil(KeptSavesFile.toOffer(saves.keptSaves()[app], install: install))++ saves.keep([kept[1]], of: app)+ XCTAssertEqual(KeptSavesFile.toOffer(saves.keptSaves()[app], install: newInstall)?.entries.map(\.name), [EpicSaves.gameFolderName], "the latest uninstall only")+ saves.keep([], of: app)+ XCTAssertNil(KeptSavesFile.toOffer(saves.keptSaves()[app], install: newInstall))+ }++ /// GOG's kept-saves.json from before entries had a place still reads, each under the game's+ /// folder.+ func testAnEntryWithNoPlaceIsUnderTheGamesFolder() throws {+ let json = #"{"date":0,"entries":[{"name":"saves","path":"SAVES","backup":"file:///tmp/b"}],"asked":[]}"#+ let kept = try JSONDecoder().decode(KeptSaves.self, from: Data(json.utf8))+ XCTAssertEqual(kept.entries[0].folder(install: install, environment: prefix), install.appending(path: "SAVES"))+ }++ /// The removal message says what each answer does to the saves.+ func testTheEpicMessageSaysWhatEachAnswerDoesToTheSaves() {+ let text = Uninstall.confirmation(route: .epic(appName: app), sizeOnDisk: 0)+ XCTAssertTrue(text.contains("Keep save data first copies"), text)+ XCTAssertTrue(text.contains("Delete save data too copies nothing"), text)+ XCTAssertTrue(text.contains("Epic's cloud stay there either way"), text)+ }+}