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
GOG saves: uninstall asks to keep or delete them, and a reinstall puts kept ones back
Gabe33ec87aa9aa9
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 336e5cf..7317ac7 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -2253,8 +2253,8 @@ final class AppState {}}- /// Carries out the route the ask offered.- func uninstallConfirmed() {+ /// Carries out the route the ask offered. `deleteSaves`: a GOG game's saves go with it.+ func uninstallConfirmed(deleteSaves: Bool = false) {guard let (item, route) = pendingUninstall else { return }pendingUninstall = nilguard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }) else { return }@@ -2290,7 +2290,7 @@ final class AppState {await MainActor.run { self.refresh() }}case let .gog(id):- gogUninstall(id: id, title: item.title, in: bottle)+ gogUninstall(id: id, title: item.title, in: bottle, deleteSaves: deleteSaves)case .windowsUninstaller:openUninstaller(in: bottle)case .none:@@ -3490,6 +3490,7 @@ final class AppState {/// The disk half of `gogRefresh`: goggame-<id>.info files under each environment's install/// folders. Runs on every install-record change, like Steam's.private func refreshGOGInstalls() {+ defer { offerKeptGOGSaves() }let found = Dictionary(bottles.map { ($0.name, GOGStore.installedGames(driveC: $0.driveC)) }, uniquingKeysWith: { a, _ in a })let store = gogStorefor game in found.values.joined() { store.adoptManifest(for: game) }@@ -3601,6 +3602,10 @@ final class AppState {runBusy(String(format: L("Updating %@"), item.title), expected: L("a large download; you can leave it running"),stop: .cancelTask(label: L("Stop")), cleanup: { [weak self] in self?.gogInstallControl = nil }) { [self] inlet store = gogStore+ // What changes in the game's folder while the update and its setup run is the patch's,+ // not saves (GOGStore.InstallHistory).+ let start = Date()+ defer { GOGStore.recordUpdate(for: game, driveC: bottle.driveC, start: start, end: Date()) }try await store.ensureInstalled()let info = try await Task.detached { try store.info(game.id) }.valuelet language = GOGStore.language(for: info.languages)@@ -4037,6 +4042,49 @@ final class AppState {}var gogRemovalWithoutBackup: GOGRemovalWithoutBackup?+ /// Saves an uninstall kept, offered to a new install of the game (GOGSaves.KeptSaves).+ struct GOGSavesToPutBack {+ let game: GOGStore.InstalledGame+ let title: String+ let kept: GOGSaves.KeptSaves+ }+ var gogSavesToPutBack: GOGSavesToPutBack?++ /// Offers, once per install, to put back saves an uninstall kept of the same game. Only once+ /// Highball has set the install up (its setup could replace what is put back) and while the+ /// game isn't running.+ private func offerKeptGOGSaves() {+ guard gogSavesToPutBack == nil else { return }+ let saves = GOGSaves(store: gogStore)+ for bottle in bottles {+ for game in gogInstalledByBottle[bottle.name] ?? [] {+ guard let kept = saves.keptSavesToOffer(game),+ !gogStore.hasManifest(game) || GOGStore.setupDone(for: game, driveC: bottle.driveC),+ !runningSessions.contains(where: { $0.libraryID == "gog:\(game.id)" && $0.bottleName == bottle.name }) else { continue }+ gogSavesToPutBack = GOGSavesToPutBack(game: game, title: game.title, kept: kept)+ return+ }+ }+ }++ /// The answer to the put-back question; either way that install isn't asked again.+ func gogPutBackSaves(_ putBack: Bool) {+ guard let pending = gogSavesToPutBack else { return }+ gogSavesToPutBack = nil+ let saves = GOGSaves(store: gogStore)+ saves.markAsked(pending.game)+ guard putBack else { offerKeptGOGSaves(); return }+ Task {+ do {+ let count = try await Task.detached { try saves.putBack(pending.kept, into: pending.game) }.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)))+ }+ offerKeptGOGSaves()+ }+ }+/// The player agreed to remove the game although some of its saves can't be backed up.func gogRemoveWithoutBackup() {guard let pending = gogRemovalWithoutBackup else { return }@@ -4045,14 +4093,18 @@ final class AppState {gogUninstall(id: pending.id, title: pending.title, in: pending.bottle, agreed: pending)}- /// Removes a GOG game from an environment: backs up the cloud-save folders inside the game's- /// folder, runs the game's own uninstaller when an offline installer left one (it cleans the- /// registry), then deletes the folder and what gogdl kept about the game. When some saves- /// can't be backed up (GOG unreachable, or a location Highball can't resolve), the player is- /// asked first (gogRemovalWithoutBackup); `agreed` is their go-ahead.- private func gogUninstall(id: String, title: String, in bottle: Bottle, agreed: GOGRemovalWithoutBackup? = nil) {+ /// Removes a GOG game from an environment: backs up its saves inside the game's folder (the+ /// cloud-save folders, and what the game wrote there since Highball set it up), runs the+ /// game's own uninstaller when an offline installer left one (it cleans the registry), then+ /// deletes the folder and what gogdl kept about the game. When some saves can't be backed up+ /// (GOG unreachable, or a location Highball can't resolve), the player is asked first+ /// (gogRemovalWithoutBackup); `agreed` is their go-ahead. `deleteSaves` copies nothing and+ /// also deletes the game's save folders elsewhere in the environment.+ private func gogUninstall(id: String, title: String, in bottle: Bottle, deleteSaves: Bool = false,+ agreed: GOGRemovalWithoutBackup? = nil) {guard let game = gogInstalledByBottle[bottle.name]?.first(where: { $0.id == id }) else { return }let store = gogStore+ let others = gogInstalledByBottle.filter { $0.key != bottle.name }.values.joined().filter { $0.id == id }.map(\.folder)runBusy(String(format: L("Removing %@"), title),done: DoneState(title: String(format: L("%@ removed"), title), ctaTitle: nil, cta: nil),stop: .killBottle(bottle, label: L("Stop"))) { [self] in@@ -4062,20 +4114,34 @@ final class AppState {} else {stage = L("Finding the game's saves")let found = await gogCloudLocations(game).map { GOGSaves.uninstallPlan($0, game: game, driveC: bottle.driveC) }- guard let found, found.cannotBackUp.isEmpty else {+ if deleteSaves {+ plan = found ?? GOGSaves.UninstallPlan()+ if found == nil { appendLog("\(title): GOG couldn't be reached, so save folders outside the game's folder stay") }+ } else if let found, found.cannotBackUp.isEmpty {+ plan = found+ } else {gogRemovalWithoutBackup = GOGRemovalWithoutBackup(id: id, title: title, bottle: bottle, plan: found)busyDoneOverride = .handedOff // the question takes over; nothing was removedreturn}- plan = found}- // Cloud-save folders inside the game's folder would be deleted with it, so back them- // up before anything runs, and stop if a backup fails. These backups are never pruned.+ // Saves inside the game's folder would be deleted with it, so back them up before+ // anything runs, and stop if a backup fails. These backups are never pruned.let saves = GOGSaves(store: store)- for (location, folder) in plan.backUp {+ var kept: [(name: String, folder: URL, backup: URL)] = []+ if !deleteSaves {stage = L("Keeping a copy of the game's saves")- if let copy = try await Task.detached(operation: { try saves.backUpLocal(game, location: location, folder: folder, kept: true) }).value {- appendLog("\(title): saves inside the game's folder copied to \(copy.path)")+ for (location, folder) in plan.backUp {+ if let copy = try await Task.detached(operation: { try saves.backUpLocal(game, location: location, folder: folder, kept: true) }).value {+ appendLog("\(title): saves inside the game's folder copied to \(copy.path)")+ kept.append((location.name, folder, copy))+ }+ }+ let skipping = plan.backUp.map(\.folder)+ if let copy = try await Task.detached(operation: { try saves.backUpGameFolder(game, driveC: bottle.driveC, skipping: skipping) }).value {+ let (files, bytes) = GOGSaves.contents(of: copy)+ appendLog("\(title): \(files) file\(files == 1 ? "" : "s") the game wrote in its folder (\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))) copied to \(copy.path)")+ kept.append((GOGSaves.gameFolder.name, game.folder, copy))}}let uninstaller = game.folder.appending(path: "unins000.exe")@@ -4095,6 +4161,14 @@ final class AppState {store.forget(id, otherInstallsRemain: elsewhere)GOGSaves(store: store).forget(game)try? FileManager.default.removeItem(at: GOGStore.setupMarker(for: game, driveC: bottle.driveC))+ try? FileManager.default.removeItem(at: GOGStore.historyFile(for: game, driveC: bottle.driveC))+ if deleteSaves {+ let (removed, leftAlone) = saves.removeSaves(plan, game: game, driveC: bottle.driveC)+ for folder in removed { appendLog("\(title): saves at \(folder.path) deleted, as asked") }+ for folder in leftAlone { appendLog("\(title): saves at \(folder.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: game, otherInstalls: others)appendLog("\(title): removed from \(bottle.name)")refreshInstalledGames() // the tile leaves now, not at the next folder watch}diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 4822e28..9e13da8 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -257,6 +257,7 @@ struct ContentView: View {.sheet(isPresented: $state.showGOGSignIn) { GOGSignInSheet() }.gogSaveConflictAsk(state).gogRemovalWithoutBackupAsk(state)+ .gogPutBackSavesAsk(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@@ -531,7 +532,11 @@ 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 Uninstall.isActionable(pending.route) {+ if case .gog = pending.route {+ // 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() }}Button(L("Cancel"), role: .cancel) { state.pendingUninstall = nil }@@ -554,18 +559,31 @@ private extension View {}}+ /// An uninstall kept this game's saves, and it is installed again: offered once per install.+ @MainActor func gogPutBackSavesAsk(_ state: AppState) -> some View {+ self.alert(state.gogSavesToPutBack.map { String(format: L("Put back your saves from %@?"),+ $0.kept.date.formatted(date: .abbreviated, time: .omitted)) } ?? "",+ isPresented: .init(get: { state.gogSavesToPutBack != nil }, set: { if !$0 { state.gogPutBackSaves(false) } }),+ presenting: state.gogSavesToPutBack) { _ in+ Button(L("Put them back")) { state.gogPutBackSaves(true) }.keyboardShortcut(.defaultAction)+ Button(L("Not now"), role: .cancel) { state.gogPutBackSaves(false) }+ } message: { pending in+ Text(String(format: L("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."), 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 {- self.alert(state.gogRemovalWithoutBackup.map { String(format: L("Remove %@ without backing up its saves?"), $0.title) } ?? "",+ self.alert(state.gogRemovalWithoutBackup.map { String(format: L("Remove %@ without a copy of every save?"), $0.title) } ?? "",isPresented: .init(get: { state.gogRemovalWithoutBackup != nil }, set: { if !$0 { state.gogRemovalWithoutBackup = nil } }),presenting: state.gogRemovalWithoutBackup) { _ in- Button(L("Remove without a backup"), role: .destructive) { state.gogRemoveWithoutBackup() }+ Button(L("Remove anyway"), role: .destructive) { state.gogRemoveWithoutBackup() }Button(L("Cancel"), role: .cancel) { state.gogRemovalWithoutBackup = nil }} message: { pending inText(pending.plan == nil- ? String(format: L("Highball couldn't reach GOG to find out where %@ keeps its saves, so it can't back up any saves inside the game's folder. Saves already in GOG's cloud are not affected. To keep a backup, cancel and try again once GOG can be reached."), pending.title)- : String(format: L("%@ keeps some of its saves directly in the game's folder, which Highball can't back up on its own, so removing the game deletes them. Its other saves inside the folder are backed up first, and saves already in GOG's cloud are not affected."), pending.title))+ ? String(format: L("Highball couldn't reach GOG to find out where %@ keeps its saves, so the save folders GOG names inside the game's folder are deleted with it. Files the game changed in its folder since you first played it are still copied to save-backups first, and saves already in GOG's cloud are not affected. To keep every save, cancel and try again once GOG can be reached."), pending.title)+ : String(format: L("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."), pending.title))}}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 8b453f8..f9ff6d2 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -231,13 +231,19 @@ enum L10n {"Les sauvegardes de ce Mac et celles du cloud GOG ont toutes deux changé depuis leur dernière synchronisation, ou n’ont pas encore été synchronisées depuis cette installation : aucune n’a été copiée.","Use GOG's cloud saves replaces this Mac's; Keep this Mac's saves replaces the cloud's. Either way, a copy of what gets replaced is kept first, in %@.":"Utiliser les sauvegardes du cloud GOG remplace celles de ce Mac ; Garder les sauvegardes de ce Mac remplace celles du cloud. Dans les deux cas, une copie de ce qui est remplacé est d’abord conservée dans %@.",- "Remove %@ without backing up its saves?": "Supprimer %@ sans sauvegarder ses parties ?",- "Remove without a backup": "Supprimer sans copie",- "%@ keeps some of its saves directly in the game's folder, which Highball can't back up on its own, so removing the game deletes them. Its other saves inside the folder are backed up first, and saves already in GOG's cloud are not affected.":- "%@ garde une partie de ses sauvegardes directement dans le dossier du jeu, que Highball ne peut pas copier à part : supprimer le jeu les efface. Ses autres sauvegardes du dossier sont d’abord copiées, et celles déjà dans le cloud GOG ne sont pas touchées.",+ "Remove %@ without a copy of every save?": "Supprimer %@ sans copie de toutes ses sauvegardes ?",+ "Remove anyway": "Supprimer quand même",+ "Keep save data": "Garder les sauvegardes",+ "Delete save data too": "Supprimer aussi les sauvegardes",+ "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 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.","Finding the game's saves": "Recherche des sauvegardes du jeu",- "Highball couldn't reach GOG to find out where %@ keeps its saves, so it can't back up any saves inside the game's folder. Saves already in GOG's cloud are not affected. To keep a backup, cancel and try again once GOG can be reached.":- "Highball n’a pas pu joindre GOG pour savoir où %@ garde ses sauvegardes : il ne peut donc copier aucune sauvegarde du dossier du jeu. Les sauvegardes déjà dans le cloud GOG ne sont pas touchées. Pour garder une copie, annulez et réessayez quand GOG est joignable.",+ "Highball couldn't reach GOG to find out where %@ keeps its saves, so the save folders GOG names inside the game's folder are deleted with it. Files the game changed in its folder since you first played it are still copied to save-backups first, and saves already in GOG's cloud are not affected. To keep every save, cancel and try again once GOG can be reached.":+ "Highball n’a pas pu joindre GOG pour savoir où %@ garde ses sauvegardes : les dossiers de sauvegarde que GOG indique dans le dossier du jeu sont donc supprimés avec lui. Les fichiers que le jeu a modifiés dans son dossier depuis votre première partie sont tout de même copiés d’abord dans save-backups, et les sauvegardes déjà dans le cloud GOG ne sont pas touchées. Pour garder toutes vos sauvegardes, annulez et réessayez quand GOG est joignable.","Keeping a copy of the game's saves": "Copie des sauvegardes du jeu","Decide later plays with this Mac's saves and leaves the cloud alone.": "Décider plus tard joue avec les sauvegardes de ce Mac et ne touche pas au cloud.","Decide later leaves both as they are until the next time you play.": "Décider plus tard laisse les deux telles quelles jusqu’à la prochaine partie.",diff --git a/Sources/HighballKit/GOGLibrary.swift b/Sources/HighballKit/GOGLibrary.swiftindex 7eff4cc..da8b101 100644--- a/Sources/HighballKit/GOGLibrary.swift+++ b/Sources/HighballKit/GOGLibrary.swift@@ -522,8 +522,58 @@ extension GOGStore {(try? String(contentsOf: setupMarker(for: game, driveC: driveC), encoding: .utf8)) == (game.buildID ?? "")}public static func markSetupDone(for game: InstalledGame, driveC: URL) {+ // Read before the marker is rewritten: an install from before the history falls back+ // to the marker's old date.+ var history = history(for: game, driveC: driveC)+ if history.firstSetup == nil { history.firstSetup = Date() }+ save(history, for: game, driveC: driveC)let url = setupMarker(for: game, driveC: driveC)- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)try? (game.buildID ?? "").write(to: url, atomically: true, encoding: .utf8)}++ /// 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 static func historyFile(for game: InstalledGame, driveC: URL) -> URL {+ driveC.appending(path: "highball/gog-setup/\(game.id).history.json")+ }++ /// 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()+ if history.firstSetup == nil {+ history.firstSetup = try? setupMarker(for: game, driveC: driveC).resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate+ }+ return history+ }++ 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)+ }++ /// An update ran from `start` to `end`: what changed in the game's folder then is the patch's.+ public static func recordUpdate(for game: InstalledGame, driveC: URL, start: Date, end: Date) {+ var history = history(for: game, driveC: driveC)+ history.updates.append(.init(start: start, end: end))+ save(history, for: game, driveC: driveC)+ }}diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swiftindex 2e35f36..11c148b 100644--- a/Sources/HighballKit/GOGSaves.swift+++ b/Sources/HighballKit/GOGSaves.swift@@ -125,11 +125,14 @@ public struct GOGSaves: Sendable {/// Locations inside the game's folder that can't be backed up: the game's folder itself,/// or a path that climbs out of it. Removing the game then needs the player's go-ahead.public var cannotBackUp: [Location] = []+ /// Folders elsewhere in the environment, left alone unless the player asks for the saves+ /// to go with the game (removeSaves).+ public var outside: [(location: Location, folder: URL)] = []public init() {}}- /// Locations elsewhere in the environment are left alone: they outlive the game's folder. A- /// `<?INSTALL?>` location `resolve` turns down (it refuses whole folders and unknown parts,+ /// Locations elsewhere in the environment outlive the game's folder, so they are only listed+ /// in `outside`, as far as `resolve` accepts them. A `<?INSTALL?>` location `resolve` turns down (it refuses whole folders and unknown parts,/// which sync could empty) is still backed up for an uninstall, which only copies: up to the/// first part Highball can't resolve, such as a %VARIABLE%.public static func uninstallPlan(_ locations: [Location], game: GOGStore.InstalledGame, driveC: URL,@@ -138,7 +141,7 @@ public struct GOGSaves: Sendable {var plan = UninstallPlan()for location in locations {if let folder = resolve(location.template, game: game, driveC: driveC, userName: userName) {- if folder.standardizedFileURL.path.hasPrefix(root + "/") { plan.backUp.append((location, folder)) }+ if folder.standardizedFileURL.path.hasPrefix(root + "/") { plan.backUp.append((location, folder)) } else { plan.outside.append((location, folder)) }continue}let template = location.template.replacingOccurrences(of: "\\", with: "/")@@ -154,6 +157,25 @@ public struct GOGSaves: Sendable {return plan}+ /// Deletes the save folders `plan` found outside the game's folder, for a player who asked+ /// for the saves to go with the game. Links followed, only a folder inside the environment's+ /// drive_c is deleted: an environment's Documents is often a link to the Mac's own+ /// (UserFolders), whose folders are the Mac's. One that holds or sits inside Highball's+ /// 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 }+ if (try? FileManager.default.removeItem(at: folder)) != nil { removed.append(folder) }+ }+ return (removed, leftAlone)+ }+// MARK: Syncpublic enum Direction: Sendable { case download, upload, forceDownload, forceUpload }@@ -224,9 +246,9 @@ public struct GOGSaves: Sendable {/// A digest of a folder's files: each one's path, size and last change. When it matches a/// backup's, a new backup would be a duplicate.- static func fingerprint(_ folder: URL) -> String {+ static func fingerprint(_ folder: URL, files chosen: [URL]? = nil) -> String {let keys: Set<URLResourceKey> = [.fileSizeKey, .contentModificationDateKey]- let lines = ((try? files(in: folder)) ?? []).map { file -> String in+ let lines = (chosen ?? (try? files(in: folder)) ?? []).map { file -> String inlet values = try? file.resolvingSymlinksInPath().resourceValues(forKeys: keys)return "\(relativePath(of: file, in: folder))\t\(values?.fileSize ?? 0)\t\(values?.contentModificationDate?.timeIntervalSince1970 ?? 0)"}@@ -268,14 +290,16 @@ public struct GOGSaves: Sendable {/// Backs up the local saves before something could replace or delete them. Returns the/// newest Mac backup when nothing has changed since it, or nil when there is nothing to back- /// up. `kept` backups are never pruned. Throws if the backup fails, leaving no partial copy- /// behind; the caller must then stop.+ /// up. `kept` backups are never pruned. `only` limits it to some of the folder's files, as+ /// files(in:) names them. Throws if the backup fails, leaving no partial copy behind; the+ /// caller must then stop.@discardableResult- public func backUpLocal(_ game: GOGStore.InstalledGame, location: Location, folder: URL, kept: Bool = false) throws -> URL? {- let files = try Self.files(in: folder)+ public func backUpLocal(_ game: GOGStore.InstalledGame, location: Location, folder: URL, kept: Bool = false,+ only: [URL]? = nil) throws -> URL? {+ let files = try only ?? Self.files(in: folder)guard !files.isEmpty else { return nil }let dir = backupsFolder(game, location)- let fingerprint = Self.fingerprint(folder)+ let fingerprint = Self.fingerprint(folder, files: files)if let same = reuse(in: dir, kind: .mac, fingerprint: fingerprint, kept: kept) { return same }let target = try finish(newBackup(in: dir, label: kept ? "mac-kept" : "mac")) { partial in// What a link points at, not the link: gogdl writes through it, so a download replaces@@ -292,6 +316,43 @@ public struct GOGSaves: Sendable {return target}+ /// Where the files a game wrote in its own folder are backed up (backUpGameFolder). Not a+ /// 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.+ static func files(in folder: URL, writtenPer history: GOGStore.InstallHistory) throws -> [URL] {+ try files(in: folder).filter { file in+ let changed = try? file.resolvingSymlinksInPath().resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate+ return history.isGameWritten(changed ?? .distantPast)+ }+ }++ /// Before an uninstall, backs up (kept) every file the game wrote in its own folder: changed+ /// after Highball first set it up there and outside its updates (GOGStore.InstallHistory),+ /// which is where a game without cloud saves often keeps them. Files under `skipping` (the+ /// locations backed up on their own) are left out. nil when Highball never set the game up+ /// in this environment, or it wrote nothing. Throws if the backup fails; the uninstall must+ /// then stop.+ public func backUpGameFolder(_ game: GOGStore.InstalledGame, driveC: URL, skipping: [URL] = []) throws -> URL? {+ let history = GOGStore.history(for: game, driveC: driveC)+ guard history.firstSetup != nil else { return nil }+ let skipped = skipping.map { $0.standardizedFileURL.path + "/" }+ let written = try Self.files(in: game.folder, writtenPer: history).filter { file in+ !skipped.contains { file.standardizedFileURL.path.hasPrefix($0) }+ }+ guard !written.isEmpty else { return nil }+ return try backUpLocal(game, location: Self.gameFolder, folder: game.folder, kept: true, only: written)+ }++ /// 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 = (try? files(in: backup)) ?? []+ let bytes = all.reduce(Int64(0)) { $0 + Int64((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }+ return (all.count, bytes)+ }+/// Stored next to the backup rather than inside it, so restoring a backup by hand never puts/// this file in the game's folder, where gogdl would upload it with the saves.static func fingerprintFile(of backup: URL) -> URL {@@ -636,6 +697,94 @@ public struct GOGSaves: Sendable {return .synced}+ // 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]+ }++ var 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)+ }+ }++ /// 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.+ 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))+ }+ }++ /// 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) }+ }++ /// Whether this install has kept saves it hasn't been asked about.+ public func keptSavesToOffer(_ game: GOGStore.InstalledGame) -> KeptSaves? {+ guard let kept = keptSaves()[game.id], !kept.asked.contains(game.folder.standardizedFileURL.path) else { return nil }+ return kept+ }++ /// Puts kept saves back into an install of the game: each backup's files to the same place+ /// in the game's folder. A file already there is backed up first (kept), so a newer one is+ /// never lost. The game-folder files are dated now, 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.+ @discardableResult+ public func putBack(_ kept: KeptSaves, into game: GOGStore.InstalledGame) throws -> Int {+ var count = 0+ for entry in kept.entries {+ let target = entry.path.isEmpty ? game.folder : game.folder.appending(path: entry.path)+ let files = try Self.files(in: 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 {+ try 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+ }+/// Forgets an install's sync history (uninstall), so a reinstall starts by asking the cloud./// Other environments' copies of the game keep theirs.public func forget(_ game: GOGStore.InstalledGame) {diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swiftindex 121fb01..ea3d6f6 100644--- a/Sources/HighballKit/Uninstall.swift+++ b/Sources/HighballKit/Uninstall.swift@@ -67,7 +67,7 @@ public enum Uninstall {case .epic:return "The Epic tools do the uninstalling, so their library stays right.\(size)"case .gog:- return "Highball deletes the game's folder from this environment. Saves synced to GOG's cloud stay there, and cloud-save folders inside the game's folder are copied to Highball's save-backups first. Anything else in the game's folder is deleted with it, including saves of a game without GOG cloud saves. The game stays in your GOG library to install again.\(size)"+ 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:return "Highball opens Windows' Add or Remove Programs in this environment, where you pick it from the list. A game with no uninstaller of its own will not be in that list, and then the only way to remove it is to delete the environment."case let .none(reason):diff --git a/Tests/HighballKitTests/GOGSaveSafetyTests.swift b/Tests/HighballKitTests/GOGSaveSafetyTests.swiftindex fd157fa..46afcff 100644--- a/Tests/HighballKitTests/GOGSaveSafetyTests.swift+++ b/Tests/HighballKitTests/GOGSaveSafetyTests.swift@@ -217,4 +217,125 @@ final class GOGSaveSafetyTests: XCTestCase {XCTAssertEqual(plan(["<?INSTALL?>", "<?INSTALL?>/", "<?INSTALL?>/%SAVES%", "<?INSTALL?>/../Other"]).cannotBackUp.count, 4)XCTAssertEqual(plan(["<?INSTALL?>\\Save Data"]).backUp.map(\.folder.lastPathComponent), ["Save Data"])}++ 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) }+ }++ /// What the game wrote in its folder is what changed after Highball first set it up there and+ /// not while an update ran: a save from before the last update still counts, the patch's+ /// files don't, nor what the installer put down or the locations backed up on their own.+ /// Never set up here: nothing to tell apart, so nothing is copied.+ func testTheGameFolderCopyHoldsWhatTheGameWrote() throws {+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: root.appending(path: "home"))))+ let driveC = root.appending(path: "drive_c")+ let game = GOGStore.InstalledGame(id: "7", title: "Game", folder: driveC.appending(path: "GOG Games/Game"), buildID: "b1", clientID: nil, dlcIDs: [], tasks: [])+ let now = Date()+ try write("exe", to: game.folder.appending(path: "game.exe"), dated: now.addingTimeInterval(-7200))+ XCTAssertNil(try saves.backUpGameFolder(game, driveC: driveC), "never set up through Highball")+ GOGStore.markSetupDone(for: game, driveC: driveC)+ let setUp = try XCTUnwrap(GOGStore.history(for: game, driveC: driveC).firstSetup)+ GOGStore.recordUpdate(for: game, driveC: driveC, start: setUp.addingTimeInterval(1200), end: setUp.addingTimeInterval(2400))+ GOGStore.markSetupDone(for: game, driveC: driveC) // the update's setup keeps the first date+ XCTAssertEqual(GOGStore.history(for: game, driveC: driveC).firstSetup, setUp)+ try write("before the update", to: game.folder.appending(path: "SAVES/slot1.sav"), dated: setUp.addingTimeInterval(600))+ try write("patch", to: game.folder.appending(path: "data/patch.pak"), dated: setUp.addingTimeInterval(1800))+ try write("after it", to: game.folder.appending(path: "SAVES/slot2.sav"), dated: setUp.addingTimeInterval(3000))+ try write("cloud", to: game.folder.appending(path: "cloud/a.sav"), dated: setUp.addingTimeInterval(600))+ let copy = try XCTUnwrap(try saves.backUpGameFolder(game, driveC: driveC, skipping: [game.folder.appending(path: "cloud")]))+ XCTAssertEqual(try GOGSaves.files(in: copy).map { GOGSaves.relativePath(of: $0, in: copy) }, ["SAVES/slot1.sav", "SAVES/slot2.sav"])+ XCTAssertTrue(GOGSaves.isKept(copy))+ XCTAssertEqual(GOGSaves.contents(of: copy).files, 2)+ XCTAssertEqual(GOGSaves.contents(of: copy).bytes, 25)+ }++ /// An install set up before the history was kept counts from its setup marker's date.+ func testAnInstallWithNoHistoryCountsFromItsMarker() throws {+ let driveC = root.appending(path: "drive_c")+ let game = GOGStore.InstalledGame(id: "7", title: "Game", folder: driveC.appending(path: "Game"), buildID: "b1", clientID: nil, dlcIDs: [], tasks: [])+ let marked = Date(timeIntervalSince1970: 1_700_000_000)+ try write("b1", to: GOGStore.setupMarker(for: game, driveC: driveC), dated: marked)+ let history = GOGStore.history(for: game, driveC: driveC)+ XCTAssertEqual(history.firstSetup, marked)+ XCTAssertTrue(history.isGameWritten(marked.addingTimeInterval(1)))+ XCTAssertFalse(history.isGameWritten(marked.addingTimeInterval(-1)))+ GOGStore.markSetupDone(for: game, driveC: driveC)+ XCTAssertEqual(GOGStore.history(for: game, driveC: driveC).firstSetup, marked, "the marker's old date, read before it is rewritten")+ }++ /// Deleting saves with the game removes the folders GOG names elsewhere, and never a whole or+ /// shared folder, Highball's save-backups (even through a link), or one holding the game.+ func testDeletingSavesLeavesSharedFoldersAndBackupsAlone() throws {+ let home = root.appending(path: "home")+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: home)))+ let driveC = root.appending(path: "drive_c")+ let user = driveC.appending(path: "users/player")+ let game = GOGStore.InstalledGame(id: "7", title: "Game", folder: user.appending(path: "AppData/Local/Games/Game"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])+ try write("exe", to: game.folder.appending(path: "game.exe"))+ try write("own", to: user.appending(path: "Saved Games/Studio/Game/slot.sav"))+ try write("other game", to: user.appending(path: "Saved Games/Other/slot.sav"))+ try write("kept", to: saves.backupsDir.appending(path: "7-saves-1/2026-mac-kept/slot.sav"))+ try FileManager.default.createDirectory(at: user.appending(path: "AppData/Roaming"), withIntermediateDirectories: true)+ // The environment's Documents is the Mac's own, here `home`, as UserFolders links it.+ try FileManager.default.createSymbolicLink(at: user.appending(path: "Documents"), withDestinationURL: home)+ try write("mac", to: home.appending(path: "My Games/Game/slot.sav"))+ let templates = ["<?SAVED_GAMES?>/Studio/Game", "<?SAVED_GAMES?>", "<?DOCUMENTS?>/save-backups", "<?DOCUMENTS?>",+ "<?APPLICATION_DATA_LOCAL?>/Games", "<?SAVED_GAMES?>/../Saved Games/Other", "<?INSTALL?>/saves",+ "<?DOCUMENTS?>/My Games/Game"]+ let plan = GOGSaves.uninstallPlan(templates.enumerated().map { GOGSaves.Location(name: "l\($0.offset)", template: $0.element) },+ game: game, driveC: driveC, userName: "player")+ let (removed, leftAlone) = saves.removeSaves(plan, game: game, driveC: driveC)+ XCTAssertEqual(removed.map(\.lastPathComponent), ["Game"])+ XCTAssertEqual(leftAlone.map(\.lastPathComponent), ["save-backups", "Games", "Game"])+ XCTAssertTrue(FileManager.default.fileExists(atPath: home.appending(path: "My Games/Game/slot.sav").path), "the Mac's Documents, through the link")+ XCTAssertFalse(FileManager.default.fileExists(atPath: user.appending(path: "Saved Games/Studio/Game").path))+ XCTAssertTrue(FileManager.default.fileExists(atPath: user.appending(path: "Saved Games/Other/slot.sav").path))+ XCTAssertTrue(FileManager.default.fileExists(atPath: saves.backupsDir.appending(path: "7-saves-1/2026-mac-kept/slot.sav").path))+ XCTAssertTrue(FileManager.default.fileExists(atPath: game.folder.appending(path: "game.exe").path))+ }++ /// Kept saves go back where they came from in a new install: a named location to its folder,+ /// the game-folder copy by its paths. What is there already is copied first, the install is+ /// asked once, and copies of the game still in other environments are never asked.+ func testPuttingSavesBackPlacesThemInTheNewInstall() throws {+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: root.appending(path: "home"))))+ func install(_ path: String) -> GOGStore.InstalledGame {+ GOGStore.InstalledGame(id: "7", title: "Game", folder: root.appending(path: path), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])+ }+ let old = install("A/Game"), new = install("B/Game"), elsewhere = install("C/Game")+ let location = GOGSaves.Location(name: "saves", template: "<?INSTALL?>/saves")+ try write("cloud slot", to: old.folder.appending(path: "saves/slot.sav"))+ try write("local slot", to: old.folder.appending(path: "Profiles/p1.sav"))+ let named = try XCTUnwrap(try saves.backUpLocal(old, location: location, folder: old.folder.appending(path: "saves"), kept: true))+ let written = try XCTUnwrap(try saves.backUpLocal(old, location: GOGSaves.gameFolder, folder: old.folder, kept: true,+ only: [old.folder.appending(path: "Profiles/p1.sav")]))+ saves.keep([(location.name, old.folder.appending(path: "saves"), named), (GOGSaves.gameFolder.name, old.folder, written)],+ of: old, otherInstalls: [elsewhere.folder])+ XCTAssertNil(saves.keptSavesToOffer(elsewhere))+ try write("fresh", to: new.folder.appending(path: "saves/slot.sav"))+ let kept = try XCTUnwrap(saves.keptSavesToOffer(new))+ XCTAssertEqual(try saves.putBack(kept, into: new), 2)+ XCTAssertEqual(try String(contentsOf: new.folder.appending(path: "saves/slot.sav"), encoding: .utf8), "cloud slot")+ XCTAssertEqual(try String(contentsOf: new.folder.appending(path: "Profiles/p1.sav"), encoding: .utf8), "local slot")+ let before = try XCTUnwrap(saves.backups(in: saves.backupsFolder(new, location)).first)+ XCTAssertEqual(try String(contentsOf: before.appending(path: "slot.sav"), encoding: .utf8), "fresh", "what was there is copied first")+ saves.markAsked(new)+ XCTAssertNil(saves.keptSavesToOffer(new), "asked once")+ }++ /// The latest uninstall's backups replace an earlier one's: a location it had nothing for+ /// never brings back an older copy, and an uninstall that kept nothing offers nothing.+ func testOnlyTheLatestUninstallsBackupsAreOffered() throws {+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: root.appending(path: "home"))))+ let game = GOGStore.InstalledGame(id: "7", title: "Game", folder: root.appending(path: "A/Game"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])+ let old = root.appending(path: "backups/old"), new = root.appending(path: "backups/new")+ saves.keep([("saves", game.folder.appending(path: "saves"), old), (GOGSaves.gameFolder.name, game.folder, old)], of: game, otherInstalls: [])+ saves.keep([(GOGSaves.gameFolder.name, game.folder, new)], of: game, otherInstalls: [])+ XCTAssertEqual(saves.keptSavesToOffer(game)?.entries.map(\.name), [GOGSaves.gameFolder.name])+ XCTAssertEqual(saves.keptSavesToOffer(game)?.entries.map(\.backup), [new])+ saves.keep([], of: game, otherInstalls: [])+ XCTAssertNil(saves.keptSavesToOffer(game))+ }}diff --git a/Tests/HighballKitTests/UninstallTests.swift b/Tests/HighballKitTests/UninstallTests.swiftindex 318a321..4258330 100644--- a/Tests/HighballKitTests/UninstallTests.swift+++ b/Tests/HighballKitTests/UninstallTests.swift@@ -55,6 +55,14 @@ final class UninstallTests: XCTestCase {XCTAssertTrue(text.contains("delete the environment"), text)}+ /// A GOG removal offers two answers, and the message says what each does to the saves.+ func testTheGOGMessageSaysWhatEachAnswerDoesToTheSaves() {+ let text = Uninstall.confirmation(route: .gog(id: "1"), sizeOnDisk: 0)+ XCTAssertTrue(text.contains("Keep save data first copies your saves"), text)+ XCTAssertTrue(text.contains("Delete save data too copies nothing"), text)+ XCTAssertTrue(text.contains("GOG's cloud stay there either way"), text)+ }+func testTheReasonIsWhatAnUnroutableGameShows() {let route = Uninstall.route(for: item(.steam))guard case let .none(reason) = route else { return XCTFail("expected none") }