Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

GOG saves: a copy of whatever a sync could replace, kept first

Gabed584273a7f48
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 1e5ee74..43e818c 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -3730,10 +3730,13 @@ final class AppState {
let info = try? await Task.detached { try store.info(game.id) }.value
try await gogRunSetup(game, title: item.title, in: bottle, language: GOGStore.language(for: info?.languages ?? []))
}
- let saveFolders = useSaves ? await gogSaveLocations(game, in: bottle) : []
+ let saveFolders = useSaves ? (await gogSaveLocations(game, in: bottle) ?? []) : []
+ var inStep = Set<String>() // locations whose saves came down: their upload needs no copy of the cloud's first
for (location, folder) in saveFolders {
stage = L("Bringing your saves down from GOG")
- try await gogSync(game, title: item.title, location: location, folder: folder, direction: .download, beforePlay: true)
+ if try await gogSync(game, title: item.title, location: location, folder: folder, direction: .download, beforePlay: true) {
+ inStep.insert(location.name)
+ }
}
// Stop during the steps before the game (setup, saves) ends the launch there: the
// strip already reads "Stopped", so nothing may start after it.
@@ -3813,9 +3816,10 @@ final class AppState {
sessionEndActions[session.id] = { [weak self] _ in
GOGComet(store: store).stop(comet)
guard let self, !saveFolders.isEmpty else { return }
- Task { @MainActor in
+ Task { @MainActor [inStep] in
for (location, folder) in saveFolders {
- try? await self.gogSync(game, title: item.title, location: location, folder: folder, direction: .upload, beforePlay: false)
+ _ = try? await self.gogSync(game, title: item.title, location: location, folder: folder, direction: .upload,
+ beforePlay: false, cloudInStep: inStep.contains(location.name))
}
}
}
@@ -3919,15 +3923,19 @@ final class AppState {
AchievementToast.shared.show(sample)
}
- /// The game's cloud-save folders in this environment, empty when it has none or GOG cannot say.
- private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)] {
+ /// The game's cloud-save folders in this environment: empty for a game GOG keeps no saves
+ /// for, nil when GOG could not be asked (offline, no client id), as against none: a game without
+ /// cloud saves.
+ private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)]? {
let saves = GOGSaves(store: gogStore)
// Both can reach GOG (an offline install's client id comes from its build manifest).
- let locations = await Task.detached { () -> [GOGSaves.Location]? in
+ // Kept apart: GOG unreachable (nil) and a game GOG keeps no saves for (.some(nil)).
+ let asked = await Task.detached { () -> [GOGSaves.Location]?? in
guard let client = saves.clientID(for: game) else { return nil }
- return (try? saves.locations(clientID: client)) ?? nil
+ do { return .some(try saves.locations(clientID: client)) } catch { return nil }
}.value
- return (locations ?? []).compactMap { location in
+ guard let answer = asked else { return nil }
+ return (answer ?? []).compactMap { location in
guard let folder = GOGSaves.resolve(location.template, game: game, driveC: bottle.driveC) else {
appendLog("\(game.title): cloud saves at \(location.template) have no folder here, skipping that one")
return nil
@@ -3946,17 +3954,23 @@ final class AppState {
/// One sync, asking the player on a conflict. Before Play the launch waits for the answer;
/// after the game it is asked whenever the player is back.
+ /// Whether the Mac's saves and the cloud's ended up in step.
+ @discardableResult
private func gogSync(_ game: GOGStore.InstalledGame, title: String, location: GOGSaves.Location, folder: URL,
- direction: GOGSaves.Direction, beforePlay: Bool) async throws {
+ direction: GOGSaves.Direction, beforePlay: Bool, cloudInStep: Bool = false) async throws -> Bool {
let saves = GOGSaves(store: gogStore)
- let outcome = await Task.detached { saves.sync(game, location: location, folder: folder, direction: direction) { line in
+ let outcome = await Task.detached { saves.sync(game, location: location, folder: folder, direction: direction, cloudInStep: cloudInStep) { line in
Task { @MainActor in self.appendLog(line) }
} }.value
switch outcome {
case .synced:
- return
+ return true
+ case .refused:
+ // Newer saves on the other side; the next sync in that direction takes them.
+ return false
case let .failed(why):
appendLog("\(title): cloud saves did not sync (\(why)); \(beforePlay ? "playing with the saves on this Mac" : "they stay on this Mac until the next sync")")
+ return false
case .conflict:
let choice: GOGSaveConflict.Choice = await withCheckedContinuation { continuation in
// One question at a time: an earlier one still open (another game's) is answered
@@ -3973,10 +3987,15 @@ final class AppState {
case .keepMac: forced = .forceUpload
case .skip:
appendLog("\(title): cloud saves left as they are this time")
- return
+ return false
}
let again = await Task.detached { saves.sync(game, location: location, folder: folder, direction: forced) }.value
- appendLog("\(title): cloud saves \(again == .synced ? (choice == .useCloud ? "replaced with GOG's copy" : "uploaded from this Mac") : "did not sync")")
+ switch again {
+ case .synced: appendLog("\(title): cloud saves \(choice == .useCloud ? "replaced with GOG's copy" : "uploaded from this Mac"), a copy of what was replaced kept first")
+ case let .failed(why): appendLog("\(title): cloud saves did not sync (\(why))")
+ case .conflict, .refused: appendLog("\(title): cloud saves did not sync")
+ }
+ return again == .synced
}
}
@@ -4005,6 +4024,19 @@ final class AppState {
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
+ // Saves the game keeps inside its own folder go with the folder: copied first, before
+ // anything runs, and a failed copy stops the removal. Without GOG's answer of where
+ // the saves are, nothing is removed.
+ guard let locations = await gogSaveLocations(game, in: bottle) else {
+ throw HighballError.failed(String(format: L("Highball could not ask GOG where %@ keeps its saves, so it left the game in place. Try again once GOG can be reached."), title))
+ }
+ let saves = GOGSaves(store: store)
+ for (location, folder) in locations where folder.standardizedFileURL.path.hasPrefix(game.folder.standardizedFileURL.path + "/") {
+ 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) }).value {
+ appendLog("\(title): saves inside the game's folder copied to \(copy.path)")
+ }
+ }
let uninstaller = game.folder.appending(path: "unins000.exe")
if FileManager.default.fileExists(atPath: uninstaller.path), let engine = engine(for: bottle) {
stage = L("Running the game's own uninstaller")
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index af8ccb6..3883977 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -549,12 +549,20 @@ private extension View {
Button(L("Keep this Mac's saves")) { state.resolveGOGSaveConflict(.keepMac) }
Button(L("Decide later"), role: .cancel) { state.resolveGOGSaveConflict(.skip) }
} message: { conflict in
- Text(conflict.beforePlay
- ? L("The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later plays with this Mac's saves and leaves the cloud alone.")
- : L("The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later leaves both as they are until the next time you play."))
+ Text(Self.saveConflictMessage(beforePlay: conflict.beforePlay, backups: GOGSaves(store: state.gogStore).backupsDir))
}
}
+ /// Each answer says what it replaces, and that a copy of it is kept first (GOGSaves' backups).
+ static func saveConflictMessage(beforePlay: Bool, backups: URL) -> String {
+ let decideLater = beforePlay ? L("Decide later plays with this Mac's saves and leaves the cloud alone.")
+ : L("Decide later leaves both as they are until the next time you play.")
+ return [L("The saves on this Mac and the ones in GOG's cloud are not the same, and Highball cannot tell which is newer, so neither was copied."),
+ String(format: L("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 %@."),
+ (backups.path as NSString).abbreviatingWithTildeInPath),
+ decideLater].joined(separator: " ")
+ }
+
@MainActor func rendererTrialAsk(_ state: AppState) -> some View {
self.alert(state.rendererTrial.map { String(format: L("Try %@ for %@ next time?"), GamePageCopy.plainName($0.next), $0.title) } ?? "",
isPresented: .init(get: { state.rendererTrial != nil }, set: { if !$0 { state.rendererTrial = nil } }),
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 0d60426..9477f5f 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -227,10 +227,15 @@ enum L10n {
"Use GOG's cloud saves": "Utiliser les sauvegardes du cloud GOG",
"Keep this Mac's saves": "Garder les sauvegardes de ce Mac",
"Decide later": "Décider plus tard",
- "The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later plays with this Mac's saves and leaves the cloud alone.":
- "Les sauvegardes de ce Mac et celles du cloud GOG ont toutes deux changé depuis leur dernière synchronisation, donc aucune n'a été copiée. La copie que vous ne choisissez pas est remplacée. Décider plus tard lance le jeu avec les sauvegardes de ce Mac sans toucher au cloud.",
- "The saves on this Mac and the ones in GOG's cloud have both changed since they were last in step, so neither was copied. The copy you don't pick is replaced. Decide later leaves both as they are until the next time you play.":
- "Les sauvegardes de ce Mac et celles du cloud GOG ont toutes deux changé depuis leur dernière synchronisation, donc aucune n'a été copiée. La copie que vous ne choisissez pas est remplacée. Décider plus tard laisse les deux telles quelles jusqu'à votre prochaine partie.",
+ "The saves on this Mac and the ones in GOG's cloud are not the same, and Highball cannot tell which is newer, so neither was copied.":
+ "Les sauvegardes de ce Mac et celles du cloud GOG diffèrent, et Highball ne peut pas savoir lesquelles sont les plus récentes : 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 %@.",
+ "Highball could not ask GOG where %@ keeps its saves, so it left the game in place. Try again once GOG can be reached.":
+ "Highball n’a pas pu demander à GOG où %@ garde ses sauvegardes : le jeu est resté en place. 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.",
"Installing %@": "Installation de %@",
"Updating %@": "Mise à jour de %@",
"Starting %@": "Lancement de %@",
diff --git a/Sources/HighballKit/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swift
index 65b116d..6c20c6c 100644
--- a/Sources/HighballKit/GOGSaves.swift
+++ b/Sources/HighballKit/GOGSaves.swift
@@ -110,11 +110,142 @@ public struct GOGSaves: Sendable {
public enum Outcome: Sendable, Equatable {
case synced
- /// Both sides changed since the last sync: nothing moved, the player chooses.
+ /// Both sides changed since the last sync, or neither was synced before and both hold saves:
+ /// nothing moved, the player chooses.
case conflict
+ /// gogdl refused the one direction asked for (newer files on the other side): nothing moved.
+ case refused
case failed(String)
}
+ // MARK: Never losing a save
+
+ /// Copies of saves taken before a sync could replace them, in the Highball folder:
+ /// save-backups/<game id>-<location>-<install>/<date>-<mac|cloud>/. gogdl replaces both ways,
+ /// and deletes what the other side lacks: a download deletes local files the cloud lacks, an
+ /// upload cloud files the Mac lacks. The newest `keep` copies per install and location stay.
+ public var backupsDir: URL { store.dir.deletingLastPathComponent().appending(path: "save-backups", directoryHint: .isDirectory) }
+ static let keep = 10
+
+ /// One install's backups of one location: the install is in the name, as sync history is kept
+ /// per install, so a second copy of the game never rotates out the first one's backups.
+ func backupsFolder(_ game: GOGStore.InstalledGame, _ location: Location) -> URL {
+ // FNV-1a over the install's path: short, and the same from one run to the next.
+ let hash = game.folder.standardizedFileURL.path.utf8.reduce(UInt64(0xcbf2_9ce4_8422_2325)) { ($0 ^ UInt64($1)) &* 0x100_0000_01b3 }
+ return backupsDir.appending(path: "\(game.id)-\(location.name)-\(String(hash, radix: 16).prefix(8))", directoryHint: .isDirectory)
+ }
+
+ private func newBackup(in dir: URL, label: String) -> URL {
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ let stamp = formatter.string(from: Date()).replacingOccurrences(of: ":", with: "")
+ var name = "\(stamp)-\(label)", n = 1
+ while FileManager.default.fileExists(atPath: dir.appending(path: name).path) { n += 1; name = "\(stamp)-\(label)-\(n)" }
+ return dir.appending(path: name, directoryHint: .isDirectory)
+ }
+
+ /// Every file a sync sees: gogdl lists hidden files and links too, and replaces or deletes them.
+ static func files(in folder: URL) -> [URL] {
+ let keys: Set<URLResourceKey> = [.isRegularFileKey, .isSymbolicLinkKey]
+ let walker = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: Array(keys))
+ var files: [URL] = []
+ while let file = walker?.nextObject() as? URL {
+ let values = try? file.resourceValues(forKeys: keys)
+ if values?.isRegularFile == true || values?.isSymbolicLink == true { files.append(file) }
+ }
+ return files
+ }
+
+ /// What a folder holds, in brief (files, bytes, latest change): two equal mean a new copy would
+ /// only repeat the last one.
+ static func fingerprint(_ folder: URL) -> String {
+ let keys: Set<URLResourceKey> = [.fileSizeKey, .contentModificationDateKey]
+ let values = files(in: folder).map { try? $0.resourceValues(forKeys: keys) }
+ let bytes = values.reduce(0) { $0 + ($1?.fileSize ?? 0) }
+ let latest = values.compactMap { $0?.contentModificationDate?.timeIntervalSince1970 }.max() ?? 0
+ return "\(values.count) \(bytes) \(latest)"
+ }
+
+
+ /// A copy of the saves on the Mac, before a download could replace them: the newest copy when
+ /// nothing changed since it, nil when there is nothing to copy. Throws when the copy fails, and
+ /// leaves no half copy behind: then nothing may replace them.
+ @discardableResult
+ public func backUpLocal(_ game: GOGStore.InstalledGame, location: Location, folder: URL) throws -> URL? {
+ guard !Self.files(in: folder).isEmpty else { return nil }
+ let dir = backupsFolder(game, location)
+ let fingerprint = Self.fingerprint(folder)
+ if let newest = backups(in: dir).first, (try? String(contentsOf: Self.fingerprintFile(of: newest), encoding: .utf8)) == fingerprint {
+ return newest
+ }
+ let target = try finish(newBackup(in: dir, label: "mac")) { partial in
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: folder, to: partial)
+ }
+ try? fingerprint.write(to: Self.fingerprintFile(of: target), atomically: true, encoding: .utf8)
+ return target
+ }
+
+ /// Beside a copy, not in it: a copy restored by hand never carries it into the game's folder,
+ /// where gogdl would upload it with the saves.
+ static func fingerprintFile(of backup: URL) -> URL {
+ backup.deletingLastPathComponent().appending(path: backup.lastPathComponent + ".fingerprint")
+ }
+
+ /// A copy of GOG's cloud saves, before an upload could replace them: gogdl downloads the cloud
+ /// into a fresh folder of the backups (with nothing there, it only downloads), which touches
+ /// neither the cloud nor the game's folder. A file it fails to fetch fails the whole copy, as
+ /// gogdl itself still exits 0. Throws when it fails: then nothing may replace the cloud's.
+ @discardableResult
+ public func backUpCloud(_ game: GOGStore.InstalledGame, location: Location) throws -> URL {
+ let dir = backupsFolder(game, location)
+ return try finish(newBackup(in: dir, label: "cloud")) { partial in
+ try FileManager.default.createDirectory(at: partial, withIntermediateDirectories: true)
+ let failed = OSAllocatedUnfairLock(initialState: false)
+ let status = try store.withAuthFile {
+ try store.runStreaming(Self.arguments(folder: partial, id: game.id, location: location, timestamp: "0", direction: .forceDownload)) { line in
+ if Self.isFailure(line) { failed.withLock { $0 = true } }
+ }
+ }
+ guard status == 0, !failed.withLock({ $0 }) else {
+ throw HighballError.failed("gogdl could not copy all of GOG's cloud saves (status \(status))")
+ }
+ }
+ }
+
+ /// gogdl's lines for a file it could not move, or an error it logs and carries on past.
+ static func isFailure(_ line: String) -> Bool { line.contains("Downloading file failed") || line.contains(" ERROR: ") }
+
+ /// Fills a backup under a ".partial" name and gives it its own name only once complete, so a
+ /// failed copy never sits among the real ones; then keeps the newest `keep`, never this one.
+ private func finish(_ target: URL, fill: (URL) throws -> Void) throws -> URL {
+ let partial = target.deletingLastPathComponent().appending(path: target.lastPathComponent + ".partial", directoryHint: .isDirectory)
+ do {
+ try fill(partial)
+ try FileManager.default.moveItem(at: partial, to: target)
+ // A copied folder keeps its source's creation date, often years old: the copy is
+ // dated now, so the newest copies are the ones kept.
+ try FileManager.default.setAttributes([.creationDate: Date()], ofItemAtPath: target.path)
+ } catch {
+ try? FileManager.default.removeItem(at: partial)
+ throw error
+ }
+ // By name: the same folder can be listed under /var and /private/var.
+ for old in backups(in: target.deletingLastPathComponent()).filter({ $0.lastPathComponent != target.lastPathComponent }).dropFirst(Self.keep - 1) {
+ try? FileManager.default.removeItem(at: old)
+ try? FileManager.default.removeItem(at: Self.fingerprintFile(of: old))
+ }
+ return target
+ }
+
+ /// A location's complete backups, newest first by when they were made (not by name: a Mac
+ /// whose clock was wrong once must not prune today's copy as the oldest).
+ func backups(in dir: URL) -> [URL] {
+ let all = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.creationDateKey])) ?? []
+ func made(_ url: URL) -> Date { (try? url.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast }
+ return all.filter { !["partial", "fingerprint"].contains($0.pathExtension) }.sorted { made($0) > made($1) }
+ }
+
var timestampsFile: URL { store.dir.appending(path: "saves.json") }
func timestamps() -> [String: String] {
@@ -161,18 +292,40 @@ public struct GOGSaves: Sendable {
/// gogdl's line for a conflict: it moved nothing.
static func isConflict(_ line: String) -> Bool { line.contains("Files in conflict") }
+ /// gogdl's line for refusing the direction asked for ("Refused to download files, newer files
+ /// locally"): it moved nothing.
+ static func isRefusal(_ line: String) -> Bool { line.contains("Refused to") }
+
/// Syncs one location. The new timestamp is kept only when something was decided.
+ /// `cloudInStep`: this location's saves came down from the cloud before the session, so an
+ /// upload after it needs no copy of the cloud's first.
public func sync(_ game: GOGStore.InstalledGame, location: Location, folder: URL, direction: Direction,
- onLine: (@Sendable (String) -> Void)? = nil) -> Outcome {
+ cloudInStep: Bool = false, onLine: (@Sendable (String) -> Void)? = nil) -> Outcome {
try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let ts = timestamps()[key(game, location)] ?? "0"
+ // Whatever a sync could replace or delete is copied first, and a failed copy stops it. An
+ // upload after a session whose saves came down first needs none: the cloud then held
+ // nothing the Mac did not, so it only takes what the game changed.
+ do {
+ switch direction {
+ case .download, .forceDownload: try backUpLocal(game, location: location, folder: folder)
+ case .forceUpload: try backUpCloud(game, location: location)
+ case .upload: if !cloudInStep { try backUpCloud(game, location: location) }
+ }
+ } catch {
+ return .failed("the saves could not be backed up first (\(error.localizedDescription)), so nothing was synced")
+ }
let conflict = OSAllocatedUnfairLock(initialState: false)
+ let refused = OSAllocatedUnfairLock(initialState: false)
+ let failed = OSAllocatedUnfairLock(initialState: false)
let stdout = OSAllocatedUnfairLock<String?>(initialState: nil)
let status: Int32
do {
// save-sync refreshes the game's own token into auth.json.
status = try store.withAuthFile { try store.runStreaming(Self.arguments(folder: folder, id: game.id, location: location, timestamp: ts, direction: direction)) { line in
if Self.isConflict(line) { conflict.withLock { $0 = true } }
+ if Self.isRefusal(line) { refused.withLock { $0 = true } }
+ if Self.isFailure(line) { failed.withLock { $0 = true } }
if let (value, rest) = Self.timestamp(in: line) {
stdout.withLock { $0 = value }
if !rest.isEmpty { onLine?(rest) }
@@ -180,7 +333,11 @@ public struct GOGSaves: Sendable {
} }
} catch { return .failed(error.localizedDescription) }
guard status == 0 else { return .failed("gogdl save-sync exited with \(status)") }
+ // gogdl exits 0 after a file it could not move, and still prints a new timestamp: kept,
+ // that timestamp would hide the file from the next sync, so it is not.
+ if failed.withLock({ $0 }) { return .failed("gogdl could not move every file") }
if conflict.withLock({ $0 }) { return .conflict }
+ if refused.withLock({ $0 }) { return .refused }
if let new = stdout.withLock({ $0 }) {
updateTimestamps { $0[key(game, location)] = new }
}
diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swift
index 339aaaf..c33c58f 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 the game stays in your GOG library to install again.\(size)"
+ return "Highball deletes the game's folder from this environment. Saves synced to GOG's cloud stay there, saves the game keeps inside its own folder are copied to Highball's save-backups first, 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/Sources/highball/main.swift b/Sources/highball/main.swift
index d6f2c59..76f3db8 100644
--- a/Sources/highball/main.swift
+++ b/Sources/highball/main.swift
@@ -837,9 +837,14 @@ struct GOG: AsyncParsableCommand {
let saves = GOGSaves(store: store)
let settings = GOGSettings.load(store) // the game page's choices hold here too
var folders: [(GOGSaves.Location, URL)] = []
+ var inStep = Set<String>() // locations whose saves came down: their upload needs no copy of the cloud's first
if !noSaves, !settings.cloudSavesOff.contains(id), store.isAuthenticated, let client = saves.clientID(for: game), let locations = try? saves.locations(clientID: client) {
folders = locations.compactMap { l in GOGSaves.resolve(l.template, game: game, driveC: b.driveC).map { (l, $0) } }
- for (l, f) in folders { print("saves \(l.name) down: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .download)))") }
+ for (l, f) in folders {
+ let outcome = saves.sync(game, location: l, folder: f, direction: .download)
+ if outcome == .synced { inStep.insert(l.name) }
+ print("saves \(l.name) down: \(Self.describe(outcome))")
+ }
}
var comet: Process?
if !noComet, settings.cometOff[id] == nil, store.isAuthenticated {
@@ -873,13 +878,17 @@ struct GOG: AsyncParsableCommand {
}
}
GOGComet(store: store).stop(comet)
- for (l, f) in folders { print("saves \(l.name) up: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .upload)))") }
+ for (l, f) in folders {
+ let outcome = saves.sync(game, location: l, folder: f, direction: .upload, cloudInStep: inStep.contains(l.name))
+ print("saves \(l.name) up: \(Self.describe(outcome))")
+ }
}
static func describe(_ outcome: GOGSaves.Outcome) -> String {
switch outcome {
case .synced: return "synced"
case .conflict: return "both copies changed, nothing moved; play from the app to choose which to keep"
+ case .refused: return "newer saves on the other side, nothing moved"
case .failed(let why): return "failed (\(why))"
}
}
diff --git a/Tests/HighballKitTests/GOGSaveSafetyTests.swift b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
new file mode 100644
index 0000000..da5fe6f
--- /dev/null
+++ b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
@@ -0,0 +1,113 @@
+import XCTest
+@testable import HighballKit
+
+/// No sync replaces or deletes a save without a copy of it kept first (GOGSaves' backups).
+final class GOGSaveSafetyTests: XCTestCase {
+ private var root: URL!
+ override func setUp() { root = FileManager.default.temporaryDirectory.appending(path: "saves-\(UUID().uuidString)") }
+ override func tearDown() {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: root.appending(path: "Game/saves/locked").path)
+ try? FileManager.default.removeItem(at: root)
+ }
+
+ private func fixture(install: String = "Game") throws -> (GOGSaves, GOGStore.InstalledGame, GOGSaves.Location, URL) {
+ let saves = GOGSaves(store: GOGStore(paths: HighballPaths(home: root.appending(path: "home"))))
+ let folder = root.appending(path: "\(install)/saves")
+ try FileManager.default.createDirectory(at: folder.appending(path: "slot1"), withIntermediateDirectories: true)
+ try Data("progress".utf8).write(to: folder.appending(path: "slot1/save.dat"))
+ let game = GOGStore.InstalledGame(id: "1", title: "Game", folder: root.appending(path: install), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])
+ return (saves, game, GOGSaves.Location(name: "saves", template: "<?INSTALL?>/saves"), folder)
+ }
+
+ /// The copy comes before gogdl is asked: here gogdl is not even installed, and the copy is made.
+ func testADownloadCopiesTheSavesBeforeAnythingRuns() throws {
+ let (saves, game, location, folder) = try fixture()
+ guard case .failed = saves.sync(game, location: location, folder: folder, direction: .download) else { return XCTFail("gogdl is absent here") }
+ let copy = try XCTUnwrap(saves.backups(in: saves.backupsFolder(game, location)).first)
+ XCTAssertEqual(try String(contentsOf: copy.appending(path: "slot1/save.dat"), encoding: .utf8), "progress")
+ }
+
+ func testAnUnchangedFolderIsNotCopiedTwice() throws {
+ let (saves, game, location, folder) = try fixture()
+ let first = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder))
+ XCTAssertEqual(try saves.backUpLocal(game, location: location, folder: folder)?.lastPathComponent, first.lastPathComponent)
+ try Data("more".utf8).write(to: folder.appending(path: "slot1/save.dat"))
+ XCTAssertNotEqual(try saves.backUpLocal(game, location: location, folder: folder)?.lastPathComponent, first.lastPathComponent)
+ }
+
+ /// Kept by when they were made, never by name, and never the copy just made: a clock that was
+ /// once ahead leaves copies dated later than today's.
+ func testPruningKeepsTheNewestTenAndNeverTheCopyJustMade() throws {
+ let (saves, game, location, folder) = try fixture()
+ let dir = saves.backupsFolder(game, location)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ for i in 0..<12 {
+ let old = dir.appending(path: "9999-01-\(String(format: "%02d", i + 1))-mac")
+ try FileManager.default.createDirectory(at: old, withIntermediateDirectories: true)
+ try FileManager.default.setAttributes([.creationDate: Date().addingTimeInterval(86_400 * Double(i + 1))], ofItemAtPath: old.path)
+ }
+ let copy = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder))
+ let kept = saves.backups(in: dir)
+ XCTAssertEqual(kept.count, 10)
+ XCTAssertTrue(kept.map(\.lastPathComponent).contains(copy.lastPathComponent))
+ }
+
+ func testAFailedCopyLeavesNothingBehindAndStopsTheSync() throws {
+ let (saves, game, location, folder) = try fixture()
+ let locked = folder.appending(path: "locked")
+ try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: locked.appending(path: "f"))
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path)
+ guard case let .failed(why) = saves.sync(game, location: location, folder: folder, direction: .download) else { return XCTFail() }
+ XCTAssertTrue(why.contains("backed up"))
+ let dir = saves.backupsFolder(game, location)
+ XCTAssertEqual((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [], [], "no half copy, no .partial")
+ }
+
+ /// gogdl lists and deletes hidden files too, so they count as saves to keep.
+ func testHiddenFilesCount() throws {
+ let folder = root.appending(path: "Hidden")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: folder.appending(path: ".save"))
+ XCTAssertEqual(GOGSaves.files(in: folder).map(\.lastPathComponent), [".save"])
+ }
+
+ func testTwoInstallsKeepTheirOwnBackups() throws {
+ let (saves, a, location, _) = try fixture(install: "A")
+ let (_, b, _, _) = try fixture(install: "B")
+ XCTAssertNotEqual(saves.backupsFolder(a, location), saves.backupsFolder(b, location))
+ XCTAssertEqual(saves.backupsFolder(a, location), saves.backupsFolder(a, location))
+ }
+
+ /// gogdl exits 0 when a file failed to come down; its log line fails the cloud copy instead.
+ func testAFileGogdlFailedToFetchFailsTheCopy() {
+ XCTAssertTrue(GOGSaves.isFailure("[SAVES] ERROR: Downloading file failed"))
+ XCTAssertFalse(GOGSaves.isFailure("[SAVES] INFO: Files in cloud: 3"))
+ }
+
+ /// An upload copies GOG's cloud first unless the saves came down before the session: with
+ /// gogdl absent here, the copy is what fails in the first case, and the sync in the second.
+ func testAnUploadCopiesTheCloudFirstUnlessTheSavesCameDown() throws {
+ let (saves, game, location, folder) = try fixture()
+ guard case let .failed(first) = saves.sync(game, location: location, folder: folder, direction: .upload) else { return XCTFail() }
+ XCTAssertTrue(first.contains("backed up"))
+ guard case let .failed(second) = saves.sync(game, location: location, folder: folder, direction: .upload, cloudInStep: true) else { return XCTFail() }
+ XCTAssertFalse(second.contains("backed up"))
+ }
+
+ /// A save folder years old: its copy is dated now, so the newest copies are still the ones kept.
+ func testACopyOfAnOldFolderIsDatedNow() throws {
+ let (saves, game, location, folder) = try fixture()
+ try FileManager.default.setAttributes([.creationDate: Date(timeIntervalSince1970: 1_500_000_000)], ofItemAtPath: folder.path)
+ let copy = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder))
+ let made = try XCTUnwrap(try copy.resourceValues(forKeys: [.creationDateKey]).creationDate)
+ XCTAssertLessThan(abs(made.timeIntervalSinceNow), 60)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: copy.appending(path: ".highball-backup").path), "nothing of Highball's inside the copy")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: GOGSaves.fingerprintFile(of: copy).path))
+ }
+
+ func testARefusalMovesNothing() {
+ XCTAssertTrue(GOGSaves.isRefusal("[SAVES] WARNING: Refused to download files, newer files locally"))
+ XCTAssertFalse(GOGSaves.isRefusal("[SAVES] INFO: Done"))
+ }
+}