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: backups kept per kind and before uninstalls, cheaper cloud copies, links copied as what they hold

Gabe82297d835384
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 339ce12..336e5cf 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -1352,6 +1352,9 @@ final class AppState {
if let h = ProgressParser.hint(for: line) { stageHint = h }
}
+ /// Set by a busy operation that ends by handing over to a question instead of its done row.
+ private var busyDoneOverride: DoneState?
+
/// Runs one long operation on the activity strip. The strip is the surface: the log sheet
/// opens only from its Details button (or `showLogSheet` for the rare case that needs it).
private func runBusy(_ title: String, expected: String? = nil, showLogSheet: Bool = false,
@@ -1361,7 +1364,7 @@ final class AppState {
// first and end it early when the second finishes (found in review, 2026-09-04).
guard !busy else { return }
busy = true; busyTitle = title; stage = ""; stageHint = ""; logLines = []; showLog = showLogSheet
- busyStartedAt = Date(); busyExpected = expected; lastOutputAt = nil; doneState = nil
+ busyStartedAt = Date(); busyExpected = expected; lastOutputAt = nil; doneState = nil; busyDoneOverride = nil
busyStop = stop; busyProgress = nil; transferRate = nil; transferSamples = []; stopRequested = false
busyTask = Task {
// On failure, dismiss the log sheet ourselves: SwiftUI defers the error alert
@@ -1369,7 +1372,7 @@ final class AppState {
// and hid the alert until the user clicked Close (issues #27/#28).
do {
try await work()
- let d = done ?? DoneState(title: L("Done"), ctaTitle: nil, cta: nil)
+ let d = busyDoneOverride ?? done ?? DoneState(title: L("Done"), ctaTitle: nil, cta: nil)
doneState = d.silent ? nil : d
} catch {
showLog = false
@@ -3815,7 +3818,8 @@ final class AppState {
guard let self, !saveFolders.isEmpty else { return }
Task { @MainActor 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)
}
}
}
@@ -3869,7 +3873,7 @@ final class AppState {
let running = comet.isRunning // read before the log, so the last lines are never missed
let unlocks = reader.newUnlocks().filter { shown.insert($0.key).inserted }
if !unlocks.isEmpty {
- if clientID == nil { clientID = try? GOGSaves(store: store).clientID(for: game) }
+ if clientID == nil { clientID = GOGSaves(store: store).clientID(for: game) }
let database = clientID.flatMap { $0 }.flatMap { GOGComet(store: store).achievementDatabase(clientID: $0) }
for unlock in unlocks {
let achievement = GOGAchievements.details(key: unlock.key, name: unlock.name, database: database)
@@ -3919,12 +3923,23 @@ final class AppState {
AchievementToast.shared.show(sample)
}
- /// The game's cloud-save folders in this environment: empty for a game GOG keeps no saves
- /// for (no client id, or cloud saves off), nil when GOG could not be asked (offline).
- private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)]? {
+ /// The game's cloud-save locations. Returns an empty array for a game without cloud saves
+ /// (no client id, or no configuration at GOG), and nil when GOG couldn't be reached. Both
+ /// lookups can need GOG: an offline install's client id comes from its build manifest.
+ private func gogCloudLocations(_ game: GOGStore.InstalledGame) async -> [GOGSaves.Location]? {
let saves = GOGSaves(store: gogStore)
- // Both can reach GOG (an offline install's client id comes from its build manifest).
- guard let locations = await Task.detached(operation: { try? saves.cloudLocations(for: game) }).value else { return nil }
+ return await Task.detached { () -> [GOGSaves.Location]? in
+ do {
+ guard let client = try saves.lookUpClientID(for: game) else { return [] }
+ return try saves.locations(clientID: client) ?? []
+ } catch { return nil }
+ }.value
+ }
+
+ /// The game's cloud-save folders in this environment: empty for a game without cloud saves,
+ /// nil when GOG couldn't be reached.
+ private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)]? {
+ guard let locations = await gogCloudLocations(game) else { return nil }
return locations.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")
@@ -3943,21 +3958,27 @@ 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.
+ /// after the game it is asked whenever the player is back. Returns true when the local and
+ /// cloud saves end up in sync.
+ @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) async throws -> Bool {
let saves = GOGSaves(store: gogStore)
let outcome = await Task.detached { saves.sync(game, location: location, folder: folder, direction: direction) { 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
+ // Before Play: this Mac's saves are newer, and the upload after the game takes them.
+ // After the game: GOG's cloud is newer and this Mac's saves didn't change, so there was
+ // nothing to upload; the download before the next Play brings the cloud's down.
+ if !beforePlay { appendLog("\(title): GOG's cloud has newer saves, so nothing was uploaded; they come down before the next Play") }
+ 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
@@ -3974,14 +3995,16 @@ 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
+ // The backup made before the side the player picked replaces the other is kept for good.
+ let again = await Task.detached { saves.sync(game, location: location, folder: folder, direction: forced, keepBackups: true) }.value
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
}
}
@@ -4002,25 +4025,56 @@ final class AppState {
rebuildLibrary() // a program added by hand shows its own tile only while the GOG tile plays another
}
- /// Removes a GOG game from an environment: its own uninstaller first when an offline installer
- /// left one (it cleans the registry), then the folder, then what gogdl kept about it.
- private func gogUninstall(id: String, title: String, in bottle: Bottle) {
+ /// A GOG game the player is asked about before it is removed, because some of its saves
+ /// can't be backed up first. Nothing is removed until the player agrees.
+ struct GOGRemovalWithoutBackup {
+ let id: String
+ let title: String
+ let bottle: Bottle
+ /// What can still be backed up, and the locations that can't; nil when GOG couldn't be
+ /// reached to say where the saves are.
+ let plan: GOGSaves.UninstallPlan?
+ }
+ var gogRemovalWithoutBackup: GOGRemovalWithoutBackup?
+
+ /// 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 }
+ gogRemovalWithoutBackup = nil
+ appendLog("\(pending.title): removing it without a backup of every save, as asked")
+ 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) {
guard let game = gogInstalledByBottle[bottle.name]?.first(where: { $0.id == id }) else { return }
let store = gogStore
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
- // GOG's cloud-save locations inside the game's 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; a game with no client id or with
- // cloud saves off has none to copy. Nothing else in the folder is copied.
- 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 plan: GOGSaves.UninstallPlan
+ if let agreed {
+ plan = agreed.plan ?? GOGSaves.UninstallPlan()
+ } 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 {
+ gogRemovalWithoutBackup = GOGRemovalWithoutBackup(id: id, title: title, bottle: bottle, plan: found)
+ busyDoneOverride = .handedOff // the question takes over; nothing was removed
+ return
+ }
+ 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.
let saves = GOGSaves(store: store)
- for (location, folder) in locations where folder.standardizedFileURL.path.hasPrefix(game.folder.standardizedFileURL.path + "/") {
+ for (location, folder) in plan.backUp {
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 {
+ 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)")
}
}
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index 3883977..4822e28 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -256,6 +256,7 @@ struct ContentView: View {
.sheet(isPresented: $state.showEpicSignIn) { EpicSignInSheet() }
.sheet(isPresented: $state.showGOGSignIn) { GOGSignInSheet() }
.gogSaveConflictAsk(state)
+ .gogRemovalWithoutBackupAsk(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
@@ -553,11 +554,26 @@ private extension View {
}
}
- /// Each answer says what it replaces, and that a copy of it is kept first (GOGSaves' backups).
+ /// 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) } ?? "",
+ 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("Cancel"), role: .cancel) { state.gogRemovalWithoutBackup = nil }
+ } message: { pending in
+ Text(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))
+ }
+ }
+
+ /// Each choice says what it replaces and that a backup is made 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."),
+ return [L("The saves on this Mac and the ones in GOG's cloud have both changed since they were last synced, or haven't been synced from this install yet, 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: " ")
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 9477f5f..8b453f8 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -227,12 +227,17 @@ 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 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.",
+ "The saves on this Mac and the ones in GOG's cloud have both changed since they were last synced, or haven't been synced from this install yet, so neither was copied.":
+ "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 %@.",
- "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.",
+ "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.",
+ "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.",
"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/GOGSaves.swift b/Sources/HighballKit/GOGSaves.swift
index c034569..2e35f36 100644
--- a/Sources/HighballKit/GOGSaves.swift
+++ b/Sources/HighballKit/GOGSaves.swift
@@ -1,3 +1,4 @@
+import CryptoKit
import Foundation
import os
@@ -17,20 +18,19 @@ public struct GOGSaves: Sendable {
public let name: String
/// GOG's template, e.g. "<?SAVED_GAMES?>/Remedy/Control".
public let template: String
- /// Another of the game's locations has a name that starts with this one's (saves and
- /// saves_profiles). gogdl picks a location's cloud files by that prefix alone (saves.py,
- /// is_in_our_dir), so it also lists the other one's, asks for them under this name, and
- /// logs "Downloading file failed" for each, naming no file: here that line says nothing
- /// about this location's own files.
- public var sharesItsPrefix = false
}
/// The client id cloud storage is keyed by: the info file's, else the manifest gogdl kept
/// (Control's info file has none; its manifest does), else GOG's latest build manifest for an
/// install with neither (an offline installer, a gogdl install from elsewhere), remembered.
- /// Nil when the game has none: GOG's own manifest names none (Beyond Good & Evil's), and gogdl
- /// cannot sync such a game either. Throws when GOG could not be asked, which says nothing.
- public func clientID(for game: GOGStore.InstalledGame) throws -> String? {
+ /// nil when GOG couldn't be reached; lookUpClientID tells that apart from a game without one.
+ public func clientID(for game: GOGStore.InstalledGame) -> String? {
+ (try? lookUpClientID(for: game)) ?? nil
+ }
+
+ /// The client id, or nil when the game has none: then it has no cloud saves. Throws when GOG
+ /// had to be asked and couldn't be reached.
+ public func lookUpClientID(for game: GOGStore.InstalledGame) throws -> String? {
if let id = game.clientID, !id.isEmpty { return id }
if let data = try? Data(contentsOf: store.installManifest(game)),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
@@ -44,52 +44,32 @@ public struct GOGSaves: Sendable {
return id
}
- /// The client id in the newest Windows build's manifest, nil when GOG has none for the game
- /// (no Windows build, or a manifest that names none). The build list and manifests are public;
- /// a v2 manifest is zlib-compressed JSON. Throws when either cannot be fetched or read.
+ /// The client id in the newest Windows build's manifest. The build list and manifests are
+ /// public; a v2 manifest is zlib-compressed JSON. nil when GOG has no such build or manifest
+ /// (HTTP 404); throws only when GOG can't be reached or answers with another error.
static func publishedClientID(productID: String) throws -> String? {
let list = URL(string: "https://content-system.gog.com/products/\(productID)/os/windows/builds?generation=2")!
- guard let link = try newestBuild(inBuildList: GOGStore.fetch(URLRequest(url: list))) else { return nil }
- return try clientID(inPublishedManifest: GOGStore.fetch(URLRequest(url: link)))
- }
-
- /// The newest build's manifest address, nil for a game with no build for Windows.
- static func newestBuild(inBuildList data: Data) throws -> URL? {
- guard let builds = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
- let items = builds["items"] as? [[String: Any]] else { throw HighballError.invalid("GOG's build list could not be read") }
- guard let newest = items.first else { return nil }
- guard let link = (newest["link"] as? String).flatMap(URL.init(string:)) else { throw HighballError.invalid("GOG's build list names no manifest") }
- return link
- }
-
- /// A manifest GOG served: its client id, nil when it names none. Throws when it cannot be read,
- /// as that is no answer.
- static func clientID(inPublishedManifest data: Data) throws -> String? {
- guard let obj = manifestObject(data) else { throw HighballError.invalid("GOG's build manifest could not be read") }
- return obj["clientId"] as? String
+ guard let listing = try GOGStore.fetchIfFound(URLRequest(url: list)),
+ let builds = try? JSONSerialization.jsonObject(with: listing) as? [String: Any],
+ let link = ((builds["items"] as? [[String: Any]])?.first?["link"] as? String).flatMap(URL.init(string:)),
+ let manifest = try GOGStore.fetchIfFound(URLRequest(url: link)) else { return nil }
+ return clientID(inManifest: manifest)
}
- static func clientID(inManifest data: Data) -> String? { manifestObject(data)?["clientId"] as? String }
-
- private static func manifestObject(_ data: Data) -> [String: Any]? {
+ static func clientID(inManifest data: Data) -> String? {
// zlib = a 2-byte header, raw DEFLATE, then a checksum; Foundation's .zlib reads raw DEFLATE.
let json = data.first == 0x78 ? (try? (data.dropFirst(2) as NSData).decompressed(using: .zlib) as Data) : data
guard let json, let obj = try? JSONSerialization.jsonObject(with: json) as? [String: Any] else { return nil }
- return obj
- }
-
- /// Where the game keeps its cloud saves: none for a game with no client id or with cloud saves
- /// off, both answers from GOG. Throws when GOG could not be asked: then nobody can say.
- public func cloudLocations(for game: GOGStore.InstalledGame) throws -> [Location] {
- guard let client = try clientID(for: game) else { return [] }
- return try locations(clientID: client) ?? []
+ return obj["clientId"] as? String
}
- /// Where the game keeps its saves, nil when it has no cloud saves. An empty list from GOG means
- /// the SDK's own storage folder, which Galaxy names __default.
+ /// Where the game keeps its saves, nil when it has no cloud saves (including when GOG has no
+ /// configuration for the client: HTTP 404). An empty list from GOG means the SDK's own storage
+ /// folder, which Galaxy names __default. Throws only when GOG can't be reached or answers with
+ /// another error.
public func locations(clientID: String) throws -> [Location]? {
let url = URL(string: "https://remote-config.gog.com/components/galaxy_client/clients/\(clientID)?component_version=2.0.45")!
- let data = try GOGStore.fetch(URLRequest(url: url))
+ guard let data = try GOGStore.fetchIfFound(URLRequest(url: url)) else { return nil }
return Self.parseLocations(data, clientID: clientID)
}
@@ -97,14 +77,10 @@ public struct GOGSaves: Sendable {
guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let windows = (obj["content"] as? [String: Any])?["Windows"] as? [String: Any],
let cloud = windows["cloudStorage"] as? [String: Any], cloud["enabled"] as? Bool == true else { return nil }
- let named = (cloud["locations"] as? [[String: Any]] ?? []).compactMap { l -> Location? in
+ let list = (cloud["locations"] as? [[String: Any]] ?? []).compactMap { l -> Location? in
guard let name = l["name"] as? String, let location = l["location"] as? String else { return nil }
return Location(name: name, template: location)
}
- let list = named.map { l in
- Location(name: l.name, template: l.template,
- sharesItsPrefix: named.contains { $0.name != l.name && $0.name.hasPrefix(l.name) })
- }
return list.isEmpty
? [Location(name: "__default", template: "<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/\(clientID)/Storage/Shared/Files")]
: list
@@ -141,33 +117,73 @@ public struct GOGSaves: Sendable {
return parts.reduce(base) { $0.appending(path: $1) }
}
+ /// What an uninstall does about a game's cloud-save locations, worked out before anything is
+ /// deleted.
+ public struct UninstallPlan: Sendable {
+ /// Folders inside the game's folder, to back up before it is deleted.
+ public var backUp: [(location: Location, folder: URL)] = []
+ /// 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] = []
+ 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,
+ /// 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,
+ userName: String = NSUserName()) -> UninstallPlan {
+ let root = game.folder.standardizedFileURL.path
+ 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)) }
+ continue
+ }
+ let template = location.template.replacingOccurrences(of: "\\", with: "/")
+ guard template.hasPrefix("<?INSTALL?>") else { continue }
+ let parts = template.dropFirst("<?INSTALL?>".count).split(separator: "/").map(String.init)
+ let known = parts.prefix { !$0.contains("%") && !$0.contains("<?") && $0 != "." && $0 != ".." }
+ if known.isEmpty || parts.contains("..") {
+ plan.cannotBackUp.append(location)
+ } else {
+ plan.backUp.append((location, known.reduce(game.folder) { $0.appending(path: $1) }))
+ }
+ }
+ return plan
+ }
+
// MARK: Sync
public enum Direction: Sendable { case download, upload, forceDownload, forceUpload }
public enum Outcome: Sendable, Equatable {
case synced
- /// Both sides changed since the last sync, or neither was synced before and both hold saves:
- /// nothing moved, the player chooses.
+ /// Both sides changed since the last sync, or this is the first sync and both sides have
+ /// saves. Nothing was moved; the player decides.
case conflict
- /// gogdl refused the one direction asked for (newer files on the other side): nothing moved.
+ /// gogdl refused the requested direction because the other side has newer files. Nothing
+ /// was moved.
case refused
case failed(String)
}
- // MARK: Never losing a save
+ // MARK: Backups
- /// 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.
+ /// Backups taken before a sync could replace saves, stored at
+ /// save-backups/<game id>-<location>-<install>/<date>-<mac|cloud>/. gogdl syncs both ways and
+ /// deletes whatever the other side lacks: a download deletes local files missing from the
+ /// cloud, and an upload deletes cloud files missing locally. The newest `keep` backups per
+ /// install and location are kept.
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.
+ /// The backup folder for one install and location. The install is part of the name (sync
+ /// history is per install too), 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.
+ // FNV-1a of the install path: short and stable across runs.
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)
}
@@ -181,114 +197,335 @@ public struct GOGSaves: Sendable {
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) }
+ /// Every file a sync touches, as gogdl walks a folder (create_directory_map): hidden files
+ /// too, and into a linked folder, since its os.path.isdir follows links. A folder reached
+ /// twice through links is walked once. Throws for a folder inside it that can't be read: its
+ /// saves would go uncopied. A folder that isn't there holds nothing.
+ static func files(in folder: URL) throws -> [URL] {
+ guard FileManager.default.fileExists(atPath: folder.path) else { return [] }
+ var files: [URL] = [], walked = Set<String>()
+ func walk(_ dir: URL) throws {
+ guard walked.insert(dir.resolvingSymlinksInPath().path).inserted else { return }
+ for name in try FileManager.default.contentsOfDirectory(atPath: dir.path).sorted() {
+ let item = dir.appending(path: name)
+ var isFolder: ObjCBool = false
+ if FileManager.default.fileExists(atPath: item.path, isDirectory: &isFolder), isFolder.boolValue { try walk(item) } else { files.append(item) }
+ }
}
+ try walk(folder)
return files
}
- /// What a folder holds, in brief (files, bytes, latest change): two equal mean a new copy would
- /// only repeat the last one.
+ /// Where a file from files(in:) sits under `folder`, as gogdl names it: by the path walked,
+ /// not where a link leads.
+ static func relativePath(of file: URL, in folder: URL) -> String {
+ String(file.standardizedFileURL.path.dropFirst(folder.standardizedFileURL.path.count + 1))
+ }
+
+ /// 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 {
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)"
+ let lines = ((try? files(in: folder)) ?? []).map { file -> String in
+ let values = try? file.resolvingSymlinksInPath().resourceValues(forKeys: keys)
+ return "\(relativePath(of: file, in: folder))\t\(values?.fileSize ?? 0)\t\(values?.contentModificationDate?.timeIntervalSince1970 ?? 0)"
+ }
+ return "mac " + digest(lines)
}
+ /// A digest of a location's files in GOG's cloud: each one's path and hash.
+ static func fingerprint(cloud listing: [CloudFile], location: Location) -> String {
+ let own = listing.filter { $0.hash != deletedMark && $0.name.hasPrefix(location.name + "/") }
+ return "cloud " + digest(own.map { "\($0.name)\t\($0.hash)" })
+ }
+
+ private static func digest(_ lines: [String]) -> String {
+ SHA256.hash(data: Data(lines.sorted().joined(separator: "\n").utf8)).map { String(format: "%02x", $0) }.joined()
+ }
- /// 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.
+ /// What a backup holds: the Mac's saves or GOG's cloud's.
+ enum BackupKind: String, Sendable { case mac, cloud }
+
+ /// Backups are named <date>-<kind>[-kept]. Kept backups (made before an uninstall, or before
+ /// the player picked a side in a conflict) are never pruned; the others are pruned per kind.
+ static func kind(of backup: URL) -> BackupKind? {
+ let name = backup.lastPathComponent
+ return name.contains("-cloud") ? .cloud : name.contains("-mac") ? .mac : nil
+ }
+ static func isKept(_ backup: URL) -> Bool { backup.lastPathComponent.contains("-kept") }
+
+ /// The newest backup of that kind when it holds exactly `fingerprint`. A kept backup asked
+ /// for when the match isn't kept yet turns the match into a kept one instead of copying again.
+ private func reuse(in dir: URL, kind: BackupKind, fingerprint: String, kept: Bool) -> URL? {
+ guard let newest = backups(in: dir).first(where: { Self.kind(of: $0) == kind }),
+ (try? String(contentsOf: Self.fingerprintFile(of: newest), encoding: .utf8)) == fingerprint else { return nil }
+ guard kept, !Self.isKept(newest) else { return newest }
+ let promoted = dir.appending(path: newest.lastPathComponent + "-kept", directoryHint: .isDirectory)
+ guard (try? FileManager.default.moveItem(at: newest, to: promoted)) != nil else { return nil }
+ try? FileManager.default.moveItem(at: Self.fingerprintFile(of: newest), to: Self.fingerprintFile(of: promoted))
+ return promoted
+ }
+
+ /// 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.
@discardableResult
- public func backUpLocal(_ game: GOGStore.InstalledGame, location: Location, folder: URL) throws -> URL? {
- guard !Self.files(in: folder).isEmpty else { return nil }
+ public func backUpLocal(_ game: GOGStore.InstalledGame, location: Location, folder: URL, kept: Bool = false) throws -> URL? {
+ let files = try Self.files(in: folder)
+ guard !files.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)
+ 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
+ // the file it points to. A link to nothing holds nothing to keep.
+ for file in files {
+ let source = file.resolvingSymlinksInPath()
+ guard FileManager.default.fileExists(atPath: source.path) else { continue }
+ let copy = partial.appending(path: Self.relativePath(of: file, in: folder))
+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: source, to: copy)
+ }
}
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.
+ /// 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 {
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.
+ /// 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
+ /// either side and only logs the listing (saves.py `sync`). nil when gogdl logged none
+ /// (it logs none when GOG has no cloud storage for the game at all).
+ func listCloud(_ game: GOGStore.InstalledGame) throws -> [CloudFile]? {
+ let empty = FileManager.default.temporaryDirectory.appending(path: "highball-listing-\(UUID().uuidString)", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: empty) }
+ let nothing = Location(name: "highball-listing-only-\(UUID().uuidString)", template: "")
+ let result = try run(game, location: nothing, folder: empty, timestamp: "0", direction: .download)
+ guard result.status == 0, result.downloadFailures + result.otherFailures == 0 else {
+ throw HighballError.failed("gogdl could not list GOG's cloud saves (status \(result.status))")
+ }
+ return result.listing
+ }
+
+ /// Backs up GOG's cloud saves before an upload could replace or delete them. The listing
+ /// comes first: when the location has no files in the cloud there is nothing to back up
+ /// (nil), and when they match the newest cloud backup that one is returned. Otherwise gogdl
+ /// downloads them into an empty backup folder (with nothing local, it only downloads), which
+ /// touches neither the cloud nor the game's folder. gogdl exits 0 even when a file fails to
+ /// download, so the backup also checks that every file of this location in the listing came
+ /// down. `kept` backups are never pruned. Throws if the backup fails; the upload must then stop.
@discardableResult
- public func backUpCloud(_ game: GOGStore.InstalledGame, location: Location) throws -> URL {
+ public func backUpCloud(_ game: GOGStore.InstalledGame, location: Location, kept: Bool = false) 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, location: location) { failed.withLock { $0 = true } }
+ if let listing = try listCloud(game) {
+ guard !Self.ownFiles(for: location, in: listing).isEmpty else { return nil }
+ if let same = reuse(in: dir, kind: .cloud, fingerprint: Self.fingerprint(cloud: listing, location: location), kept: kept) {
+ return same
+ }
+ }
+ let fingerprint = OSAllocatedUnfairLock<String?>(initialState: nil)
+ do {
+ let target = try finish(newBackup(in: dir, label: kept ? "cloud-kept" : "cloud")) { partial in
+ try FileManager.default.createDirectory(at: partial, withIntermediateDirectories: true)
+ let result = try run(game, location: location, folder: partial, timestamp: "0", direction: .forceDownload)
+ let missing = result.listing.map { Self.ownFiles(for: location, in: $0).filter { !FileManager.default.fileExists(atPath: partial.appending(path: $0).path) } } ?? []
+ guard result.status == 0, Self.unexplainedFailures(result, location: location, folder: partial, since: 0) == 0, missing.isEmpty else {
+ throw HighballError.failed("gogdl could not copy all of GOG's cloud saves (status \(result.status))")
}
+ guard !(try Self.files(in: partial)).isEmpty else { throw NothingToBackUp() }
+ fingerprint.withLock { $0 = result.listing.map { Self.fingerprint(cloud: $0, location: location) } }
}
- guard status == 0, !failed.withLock({ $0 }) else {
- throw HighballError.failed("gogdl could not copy all of GOG's cloud saves (status \(status))")
+ if let value = fingerprint.withLock({ $0 }) {
+ try? value.write(to: Self.fingerprintFile(of: target), atomically: true, encoding: .utf8)
}
+ return target
+ } catch is NothingToBackUp {
+ return nil
}
}
- /// gogdl's lines for a file it could not move, or an error it logs and carries on past. Its
- /// "Downloading file failed" names no file, so for a location whose name another one's starts
- /// with it may be one of the other location's files, asked for at the wrong path, and does
- /// not count (the other location's own sync fetches those).
- static func isFailure(_ line: String, location: Location) -> Bool {
- if line.contains("Downloading file failed") { return !location.sharesItsPrefix }
- return line.contains(" ERROR: ")
- }
+ private struct NothingToBackUp: Error {}
+
+ /// gogdl's log line when a file fails to download. It names no file.
+ static func isDownloadFailure(_ line: String) -> Bool { line.contains("Downloading file failed") }
+ /// Any other error gogdl logs and continues past, such as a failed upload.
+ static func isFailure(_ line: String) -> Bool { isDownloadFailure(line) || 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.
+ /// Fills a backup under a ".partial" name and renames it only once complete, so a failed
+ /// backup never sits among the real ones. Then prunes that kind's backups to the newest
+ /// `keep`, never removing this one or a kept one.
private func finish(_ target: URL, fill: (URL) throws -> Void) throws -> URL {
- let partial = target.deletingLastPathComponent().appending(path: target.lastPathComponent + ".partial", directoryHint: .isDirectory)
+ let dir = target.deletingLastPathComponent()
+ removeStalePartials(in: dir)
+ let partial = dir.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.
+ // A copied folder keeps the source's creation date, often years old. Date the backup
+ // now so pruning keeps the newest ones.
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) {
+ let kind = Self.kind(of: target)
+ // Compare by name: the same folder can appear under both /var and /private/var.
+ let rotating = backups(in: dir).filter {
+ $0.lastPathComponent != target.lastPathComponent && Self.kind(of: $0) == kind && !Self.isKept($0)
+ }
+ for old in rotating.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).
+ /// A backup left half-filled by a crash or a forced quit: older than an hour, so no sync
+ /// running now is still filling it.
+ private func removeStalePartials(in dir: URL) {
+ let all = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.creationDateKey])) ?? []
+ for partial in all where partial.pathExtension == "partial" {
+ let made = (try? partial.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast
+ if made < Date().addingTimeInterval(-3600) { try? FileManager.default.removeItem(at: partial) }
+ }
+ }
+
+ /// A location's complete backups, newest first by creation date rather than by name, so a
+ /// clock that was once wrong never gets today's backup pruned 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) }
}
+ // MARK: Locations sharing a prefix
+
+ /// A file in GOG's cloud storage, as gogdl lists it.
+ struct CloudFile: Equatable, Sendable {
+ let name: String
+ let hash: String
+ let modified: Date?
+ }
+
+ /// The hash gogdl skips: GOG's mark for a file deleted from the cloud.
+ static let deletedMark = "aadd86936a80ee8a369579c3926f1b3c"
+
+ /// With --debug, gogdl logs the client's whole cloud listing on one line, as a Python list of
+ /// dicts (saves.py `get_cloud_files_list`). Returns nil for any other line, or one that can't
+ /// be read.
+ static func cloudListing(in line: String) -> [CloudFile]? {
+ guard let start = line.range(of: "[SAVES] DEBUG: Files: ") else { return nil }
+ var reader = PythonLiteral(line[start.upperBound...])
+ guard let entries = reader.value() as? [Any], reader.atEnd else { return nil }
+ var files: [CloudFile] = []
+ for entry in entries {
+ guard let dict = entry as? [String: Any], let name = dict["name"] as? String else { return nil }
+ files.append(CloudFile(name: name, hash: dict["hash"] as? String ?? "",
+ modified: (dict["last_modified"] as? String).flatMap(Self.date(iso:))))
+ }
+ return files
+ }
+
+ /// gogdl reads these with Python's `fromisoformat` and then `astimezone()`, so a date with
+ /// no offset is local time. GOG writes an offset and microseconds; any fraction length, "Z",
+ /// a space for the "T" and missing seconds are read too.
+ static func date(iso: String) -> Date? {
+ let pattern = #/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?(Z|[+-]\d{2}(?::?\d{2})?)?/#
+ guard let m = iso.trimmingCharacters(in: .whitespaces).wholeMatch(of: pattern) else { return nil }
+ var parts = DateComponents()
+ parts.year = Int(m.1); parts.month = Int(m.2); parts.day = Int(m.3)
+ parts.hour = Int(m.4); parts.minute = Int(m.5); parts.second = m.6.flatMap { Int($0) } ?? 0
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = .current
+ if let offset = m.8 {
+ if offset == "Z" { calendar.timeZone = TimeZone(secondsFromGMT: 0)! } else {
+ let digits = offset.dropFirst().filter(\.isNumber)
+ let hours = Int(digits.prefix(2)) ?? 0, minutes = Int(digits.dropFirst(2)) ?? 0
+ let seconds = (hours * 3600 + minutes * 60) * (offset.first == "-" ? -1 : 1)
+ guard let zone = TimeZone(secondsFromGMT: seconds) else { return nil }
+ calendar.timeZone = zone
+ }
+ }
+ guard let date = calendar.date(from: parts) else { return nil }
+ return date.addingTimeInterval(m.7.flatMap { Double("0.\($0)") } ?? 0)
+ }
+
+ /// The paths, relative to the location's folder, of the location's own files in the cloud.
+ static func ownFiles(for location: Location, in listing: [CloudFile]) -> [String] {
+ listing.filter { $0.hash != deletedMark && $0.name.hasPrefix(location.name + "/") }
+ .map { String($0.name.dropFirst(location.name.count + 1)).replacingOccurrences(of: "\\", with: "/") }
+ }
+
+ /// Cloud files that gogdl picks up for `location` but that belong to another location.
+ /// gogdl matches a location's files with `startswith(name)` (saves.py `is_in_our_dir`), so
+ /// `saves` also picks up `saves_profiles/...`. It then requests them at the wrong path
+ /// (`saves/saves_profiles/...`), where the download fails, and any delete it sends for them
+ /// goes to that same wrong path and removes nothing.
+ static func strays(for location: Location, in listing: [CloudFile]) -> [CloudFile] {
+ listing.filter { $0.hash != deletedMark && $0.name.hasPrefix(location.name) && !$0.name.hasPrefix(location.name + "/") }
+ }
+
+ /// What one gogdl save-sync run reported.
+ struct Run: Sendable {
+ var status: Int32 = 0
+ var downloadFailures = 0
+ var otherFailures = 0
+ var conflict = false
+ var refused = false
+ /// gogdl downloaded something.
+ var downloaded = false
+ /// gogdl downloaded every file in the listing: the folder was empty, or the download was forced.
+ var downloadedAll = false
+ var timestamp: String?
+ var listing: [CloudFile]?
+
+ mutating func note(_ line: String) {
+ // A debug line can quote anything (file names, arguments): only the listing is read
+ // from one.
+ if GOGSaves.isDebug(line) {
+ if let files = GOGSaves.cloudListing(in: line) { listing = files }
+ return
+ }
+ if GOGSaves.isConflict(line) { conflict = true }
+ if GOGSaves.isRefusal(line) { refused = true }
+ if GOGSaves.isDownloadFailure(line) { downloadFailures += 1 } else if GOGSaves.isFailure(line) { otherFailures += 1 }
+ if line.contains("No files locally, downloading") || line.contains("Forcing download") { downloaded = true; downloadedAll = true }
+ if line.contains("Downloading files") { downloaded = true }
+ }
+ }
+
+ /// The failures that can't be put down to strays. Each stray gogdl tried to download fails,
+ /// so those failures are expected; any beyond them are this location's own files. Without a
+ /// listing to check against, every failure counts.
+ static func unexplainedFailures(_ run: Run, location: Location, folder: URL, since ts: Double) -> Int {
+ guard run.downloadFailures > 0, run.downloaded, let listing = run.listing else { return run.downloadFailures + run.otherFailures }
+ let tried = strays(for: location, in: listing).filter { stray in
+ run.downloadedAll || (stray.modified.map { $0.timeIntervalSince1970 > ts } ?? false)
+ }
+ // A stray that did come down, at the path gogdl asked for, did not fail.
+ let failed = tried.filter { !FileManager.default.fileExists(atPath: folder.appending(path: $0.name).path) }.count
+ return max(0, run.downloadFailures - failed) + run.otherFailures
+ }
+
+ /// Whether a conflict gogdl reported comes from strays alone: none of this location's own
+ /// cloud files changed since the last sync, but a stray did. Then only the Mac's saves
+ /// changed, which makes it an upload.
+ static func conflictIsOnlyStrays(_ run: Run, location: Location, since ts: Double) -> Bool {
+ guard run.conflict, let listing = run.listing else { return false }
+ func newer(_ file: CloudFile) -> Bool { file.modified.map { $0.timeIntervalSince1970 > ts } ?? true }
+ let own = listing.filter { $0.hash != deletedMark && $0.name.hasPrefix(location.name + "/") }
+ return !own.contains(where: newer) && strays(for: location, in: listing).contains(where: newer)
+ }
+
+ // MARK: Running gogdl
+
var timestampsFile: URL { store.dir.appending(path: "saves.json") }
func timestamps() -> [String: String] {
@@ -312,6 +549,8 @@ public struct GOGSaves: Sendable {
"\(game.id).\(location.name)@\(game.folder.standardizedFileURL.path)"
}
+ /// `--debug` makes gogdl log the cloud listing (cloudListing). Debug lines stay out of
+ /// Highball's log.
static func arguments(folder: URL, id: String, location: Location, timestamp: String, direction: Direction) -> [String] {
let flag: String
switch direction {
@@ -320,9 +559,11 @@ public struct GOGSaves: Sendable {
case .forceDownload: flag = "--force-download"
case .forceUpload: flag = "--force-upload"
}
- return ["save-sync", folder.path, id, "--os", "windows", "--ts", timestamp, "--name", location.name, flag]
+ return ["save-sync", folder.path, id, "--os", "windows", "--ts", timestamp, "--name", location.name, "--debug", flag]
}
+ static func isDebug(_ line: String) -> Bool { line.contains("] DEBUG: ") }
+
/// gogdl's only stdout is the new timestamp, a bare number written without a newline, so on
/// the shared pipe it usually arrives glued to the log line after it ("1793193913.87[SAVES] INFO:
/// Done"). Returns the number and what follows it.
@@ -335,51 +576,61 @@ 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.
+ /// gogdl's line when it refuses the requested direction ("Refused to download files, newer
+ /// files locally"). Nothing was transferred.
static func isRefusal(_ line: String) -> Bool { line.contains("Refused to") }
+ private func run(_ game: GOGStore.InstalledGame, location: Location, folder: URL, timestamp: String, direction: Direction,
+ onLine: (@Sendable (String) -> Void)? = nil) throws -> Run {
+ let run = OSAllocatedUnfairLock(initialState: Run())
+ // save-sync refreshes the game's own token into auth.json.
+ let status = try store.withAuthFile {
+ try store.runStreaming(Self.arguments(folder: folder, id: game.id, location: location, timestamp: timestamp, direction: direction)) { line in
+ let stamp = Self.timestamp(in: line)
+ let text = stamp?.1 ?? line
+ run.withLock { if let stamp { $0.timestamp = stamp.0 }; $0.note(text) }
+ if !text.isEmpty, !Self.isDebug(text) { onLine?(text) }
+ }
+ }
+ return run.withLock { $0.status = status; return $0 }
+ }
+
/// Syncs one location. The new timestamp is kept only when something was decided.
+ /// `keepBackups`: the backup made first is never pruned (the player picked a side in a
+ /// conflict).
public func sync(_ game: GOGStore.InstalledGame, location: Location, folder: URL, direction: Direction,
- onLine: (@Sendable (String) -> Void)? = nil) -> Outcome {
+ keepBackups: 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 copies the cloud even after a session whose saves came down first: a download
- // brings only cloud files newer than the last sync, so one older than it and missing on
- // the Mac stays in the cloud alone, and the upload deletes it.
+ // Back up whatever the sync could replace or delete, and stop if the backup fails: the
+ // Mac's saves before a download, GOG's before an upload.
do {
switch direction {
- case .download, .forceDownload: try backUpLocal(game, location: location, folder: folder)
- case .upload, .forceUpload: try backUpCloud(game, location: location)
+ case .download, .forceDownload: try backUpLocal(game, location: location, folder: folder, kept: keepBackups)
+ case .upload, .forceUpload: try backUpCloud(game, location: location, kept: keepBackups)
}
} 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
+ var result: Run
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, location: location) { failed.withLock { $0 = true } }
- if let (value, rest) = Self.timestamp(in: line) {
- stdout.withLock { $0 = value }
- if !rest.isEmpty { onLine?(rest) }
- } else { onLine?(line) }
- } }
+ result = try run(game, location: location, folder: folder, timestamp: ts, direction: direction, onLine: onLine)
+ if result.status == 0, Self.conflictIsOnlyStrays(result, location: location, since: Double(ts) ?? 0) {
+ // Without the strays, only the Mac's saves changed: an upload, which a download
+ // leaves for after the game. The cloud was backed up above.
+ guard direction == .upload else { return .refused }
+ result = try run(game, location: location, folder: folder, timestamp: ts, direction: .forceUpload, onLine: onLine)
+ }
} 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 }) {
+ guard result.status == 0 else { return .failed("gogdl save-sync exited with \(result.status)") }
+ // gogdl exits 0 even after failing to transfer a file, and still prints a new timestamp.
+ // Saving that timestamp would make the next sync skip the failed file, so it isn't saved.
+ if Self.unexplainedFailures(result, location: location, folder: folder, since: Double(ts) ?? 0) > 0 {
+ return .failed("gogdl could not move every file")
+ }
+ if result.conflict { return .conflict }
+ if result.refused { return .refused }
+ if let new = result.timestamp {
updateTimestamps { $0[key(game, location)] = new }
}
return .synced
@@ -392,3 +643,87 @@ public struct GOGSaves: Sendable {
updateTimestamps { all in all = all.filter { !($0.key.hasPrefix(game.id + ".") && $0.key.hasSuffix(suffix)) } }
}
}
+
+/// Reads the Python literals gogdl logs (lists, dicts, strings, numbers, None, True, False), as
+/// `repr` writes them. Works on Unicode scalars, so a quote followed by a combining mark is still
+/// a quote.
+struct PythonLiteral {
+ private let chars: [Unicode.Scalar]
+ private var i = 0
+ init(_ text: Substring) { chars = Array(text.trimmingCharacters(in: .whitespacesAndNewlines).unicodeScalars) }
+
+ var atEnd: Bool { i == chars.count }
+
+ private mutating func skipSpace() { while i < chars.count, chars[i].properties.isWhitespace { i += 1 } }
+
+ /// The next value, or nil when the text isn't a literal this reads.
+ mutating func value() -> Any? {
+ skipSpace()
+ guard i < chars.count else { return nil }
+ switch chars[i] {
+ case "[": return sequence(close: "]").map { $0 as Any }
+ case "{":
+ i += 1
+ var dict: [String: Any] = [:]
+ while true {
+ skipSpace()
+ if i < chars.count, chars[i] == "}" { i += 1; return dict }
+ guard let key = value() as? String else { return nil }
+ skipSpace()
+ guard i < chars.count, chars[i] == ":" else { return nil }
+ i += 1
+ guard let v = value() else { return nil }
+ dict[key] = v
+ skipSpace()
+ if i < chars.count, chars[i] == "," { i += 1 }
+ }
+ case "'", "\"": return string()
+ default:
+ let start = i
+ while i < chars.count, !",]}:".unicodeScalars.contains(chars[i]), !chars[i].properties.isWhitespace { i += 1 }
+ let word = String(String.UnicodeScalarView(chars[start..<i]))
+ return word.isEmpty ? nil : word
+ }
+ }
+
+ private mutating func sequence(close: Unicode.Scalar) -> [Any]? {
+ i += 1
+ var items: [Any] = []
+ while true {
+ skipSpace()
+ if i < chars.count, chars[i] == close { i += 1; return items }
+ guard let item = value() else { return nil }
+ items.append(item)
+ skipSpace()
+ if i < chars.count, chars[i] == "," { i += 1 }
+ }
+ }
+
+ private mutating func string() -> String? {
+ let quote = chars[i]
+ i += 1
+ var out = ""
+ while i < chars.count {
+ let c = chars[i]
+ i += 1
+ if c == quote { return out }
+ guard c == "\\" else { out.unicodeScalars.append(c); continue }
+ guard i < chars.count else { return nil }
+ let e = chars[i]
+ i += 1
+ switch e {
+ case "n": out.append("\n")
+ case "t": out.append("\t")
+ case "r": out.append("\r")
+ case "x", "u", "U":
+ let n = e == "x" ? 2 : e == "u" ? 4 : 8
+ guard i + n <= chars.count, let code = UInt32(String(String.UnicodeScalarView(chars[i..<i + n])), radix: 16),
+ let scalar = Unicode.Scalar(code) else { return nil }
+ out.unicodeScalars.append(scalar)
+ i += n
+ default: out.unicodeScalars.append(e) // \\ \' \"
+ }
+ }
+ return nil
+ }
+}
diff --git a/Sources/HighballKit/GOGStore.swift b/Sources/HighballKit/GOGStore.swift
index 3ee8e7e..5b8df4d 100644
--- a/Sources/HighballKit/GOGStore.swift
+++ b/Sources/HighballKit/GOGStore.swift
@@ -365,16 +365,29 @@ public struct GOGStore: Sendable {
/// A blocking GET for callers already off the main thread (gogdl-side work, one request at a time).
static func fetch(_ request: URLRequest) throws -> Data {
+ guard let data = try fetch(request, missingIsNil: false) else { throw HighballError.invalid("no data") }
+ return data
+ }
+
+ /// The same, but nil when the server answers 404: the thing asked for doesn't exist. Network
+ /// failures and other statuses still throw.
+ static func fetchIfFound(_ request: URLRequest) throws -> Data? {
+ try fetch(request, missingIsNil: true)
+ }
+
+ private static func fetch(_ request: URLRequest, missingIsNil: Bool) throws -> Data? {
var request = request
request.timeoutInterval = 30
- let result = OSAllocatedUnfairLock<(data: Data, failure: String?)>(initialState: (Data(), nil))
+ let result = OSAllocatedUnfairLock<(data: Data?, failure: String?)>(initialState: (nil, nil))
let address = request.url?.absoluteString ?? ""
let done = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: request) { data, response, error in
- let failure: String? = if let error { error.localizedDescription }
- else if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { "HTTP \(http.statusCode) for \(address)" }
- else { nil }
- result.withLock { $0 = (data ?? Data(), failure) }
+ let status = (response as? HTTPURLResponse)?.statusCode
+ let found: (Data?, String?) = if let error { (nil, error.localizedDescription) }
+ else if missingIsNil, status == 404 { (nil, nil) }
+ else if let status, !(200..<300).contains(status) { (nil, "HTTP \(status) for \(address)") }
+ else { (data ?? Data(), nil) }
+ result.withLock { $0 = found }
done.signal()
}.resume()
done.wait()
diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swift
index 740aa88..121fb01 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 any of those the game keeps inside its own folder are copied to Highball's save-backups first. Other saves in the game's folder, ones GOG does not sync, are deleted with it. 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, 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)"
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 745051c..fadfb16 100644
--- a/Sources/highball/main.swift
+++ b/Sources/highball/main.swift
@@ -837,9 +837,9 @@ 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)] = []
- if !noSaves, !settings.cloudSavesOff.contains(id), store.isAuthenticated, let locations = try? saves.cloudLocations(for: game) {
+ 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 { print("saves \(l.name) down: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .download), direction: .download))") }
}
var comet: Process?
if !noComet, settings.cometOff[id] == nil, store.isAuthenticated {
@@ -873,14 +873,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 { print("saves \(l.name) up: \(Self.describe(saves.sync(game, location: l, folder: f, direction: .upload), direction: .upload))") }
}
- static func describe(_ outcome: GOGSaves.Outcome) -> String {
+ static func describe(_ outcome: GOGSaves.Outcome, direction: GOGSaves.Direction) -> 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 .refused:
+ return direction == .upload
+ ? "GOG's cloud has newer saves, nothing uploaded; they come down at the next play"
+ : "this Mac's saves are newer, nothing downloaded; they go up after the game"
case .failed(let why): return "failed (\(why))"
}
}
diff --git a/Tests/HighballKitTests/GOGFakeGogdlTests.swift b/Tests/HighballKitTests/GOGFakeGogdlTests.swift
new file mode 100644
index 0000000..3c839a3
--- /dev/null
+++ b/Tests/HighballKitTests/GOGFakeGogdlTests.swift
@@ -0,0 +1,291 @@
+import XCTest
+@testable import HighballKit
+
+/// GOGSaves against a stand-in for gogdl 1.3.1's save-sync: the same decisions as saves.py
+/// (including matching a location's cloud files with `startswith(name)`), over a folder that
+/// plays GOG's cloud.
+final class GOGFakeGogdlTests: XCTestCase {
+ private var root: URL!
+ private var home: URL { root.appending(path: "home") }
+ private var cloud: URL { home.appending(path: "fake-cloud") }
+ private let saves = GOGSaves.Location(name: "saves", template: "<?INSTALL?>/saves")
+ private let profiles = GOGSaves.Location(name: "saves_profiles", template: "<?INSTALL?>/profiles")
+
+ override func setUpWithError() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("needs python3") }
+ root = FileManager.default.temporaryDirectory.appending(path: "fake-gogdl-\(UUID().uuidString)")
+ let tools = home.appending(path: "tools")
+ try FileManager.default.createDirectory(at: tools, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: cloud, withIntermediateDirectories: true)
+ let gogdl = tools.appending(path: "gogdl")
+ try Self.script.write(to: gogdl, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: gogdl.path)
+ }
+ override func tearDown() { try? FileManager.default.removeItem(at: root) }
+
+ private var store: GOGSaves { GOGSaves(store: GOGStore(paths: HighballPaths(home: home))) }
+ private var game: GOGStore.InstalledGame {
+ GOGStore.InstalledGame(id: "1", title: "Game", folder: root.appending(path: "Game"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])
+ }
+
+ private func write(_ text: String, to url: URL, age: TimeInterval = 0) throws {
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: url)
+ let date = Date().addingTimeInterval(-age)
+ try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: url.path)
+ }
+ private func read(_ url: URL) -> String? { try? String(contentsOf: url, encoding: .utf8) }
+ private func folder(_ location: GOGSaves.Location) -> URL { root.appending(path: "Game/\(location.name)") }
+
+ /// `saves` also picks up `saves_profiles/...`, which gogdl fails to download: that failure
+ /// belongs to the other location, so the sync still goes through.
+ func testAnotherLocationsFilesDoNotFailTheSync() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ try write("profile", to: cloud.appending(path: "saves_profiles/p.dat"))
+ let outcome = store.sync(game, location: saves, folder: folder(saves), direction: .download)
+ XCTAssertEqual(outcome, .synced)
+ XCTAssertEqual(read(folder(saves).appending(path: "slot1.sav")), "cloud save")
+ XCTAssertNotNil(store.timestamps()[store.key(game, saves)])
+ XCTAssertEqual(store.sync(game, location: profiles, folder: folder(profiles), direction: .download), .synced)
+ XCTAssertEqual(read(folder(profiles).appending(path: "p.dat")), "profile")
+ }
+
+ /// A file of the location's own that fails to download still fails the sync, also with
+ /// another location's failures beside it.
+ func testAnOwnFileThatFailsStillFails() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ try write("profile", to: cloud.appending(path: "saves_profiles/p.dat"))
+ try "saves/slot1.sav".write(to: home.appending(path: "fake-fail"), atomically: true, encoding: .utf8)
+ guard case .failed = store.sync(game, location: saves, folder: folder(saves), direction: .download) else { return XCTFail() }
+ XCTAssertNil(store.timestamps()[store.key(game, saves)], "no timestamp kept, so the next sync tries again")
+ }
+
+ /// The cloud backup fails when one of the location's own files didn't come down, and no
+ /// upload follows.
+ func testACloudBackupMissingAFileStopsTheUpload() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ try write("local", to: folder(saves).appending(path: "slot1.sav"))
+ try "saves/slot1.sav".write(to: home.appending(path: "fake-fail"), atomically: true, encoding: .utf8)
+ guard case let .failed(why) = store.sync(game, location: saves, folder: folder(saves), direction: .upload) else { return XCTFail() }
+ XCTAssertTrue(why.contains("backed up"))
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "cloud save", "the cloud is untouched")
+ }
+
+ /// An upload deletes cloud files missing on the Mac. Even right after a download, a cloud
+ /// file older than the last sync may not have come down, so the cloud is backed up before
+ /// every upload.
+ func testEveryUploadBacksUpTheCloudFirst() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ // An old cloud file the download skipped (older than the last sync), and a new local save.
+ try write("old", to: cloud.appending(path: "saves/old.sav"), age: 3600)
+ try write("new", to: folder(saves).appending(path: "slot2.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ XCTAssertNil(read(cloud.appending(path: "saves/old.sav")), "gogdl deleted it from the cloud")
+ let backup = try XCTUnwrap(store.backups(in: store.backupsFolder(game, saves)).first { $0.lastPathComponent.hasSuffix("-cloud") })
+ XCTAssertEqual(read(backup.appending(path: "old.sav")), "old", "but a backup has it")
+ }
+
+ /// Another location's newer cloud files make gogdl see a conflict where only the Mac changed:
+ /// the upload still goes through, and the download before Play leaves it for the upload.
+ func testAnotherLocationsNewerFilesAreNoConflict() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ try write("played", to: folder(saves).appending(path: "slot1.sav"))
+ try write("profile", to: cloud.appending(path: "saves_profiles/p.dat"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .refused)
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "played")
+ XCTAssertEqual(read(cloud.appending(path: "saves_profiles/p.dat")), "profile", "the other location's file is untouched")
+ }
+
+ /// A real conflict (both sides of this location changed) is still asked.
+ func testARealConflictIsStillAsked() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ try write("played here", to: folder(saves).appending(path: "slot1.sav"))
+ try write("played elsewhere", to: cloud.appending(path: "saves/slot2.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .conflict)
+ XCTAssertNil(read(folder(saves).appending(path: "slot2.sav")))
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "cloud save")
+ }
+
+ func testTheListingIsReadFromGogdlsDebugLine() {
+ let line = #"[SAVES] DEBUG: Files: [{'name': "saves/it's.sav", 'hash': 'abc', 'bytes': 3, 'last_modified': '2024-05-01T10:00:00.250000+00:00'}, {'name': 'saves/\xe9.sav', 'hash': 'def', 'bytes': None}]"#
+ let files = GOGSaves.cloudListing(in: line)
+ XCTAssertEqual(files?.map(\.name), ["saves/it's.sav", "saves/é.sav"])
+ XCTAssertEqual(files?.first?.modified?.timeIntervalSince1970 ?? 0, 1_714_557_600.25, accuracy: 0.001)
+ XCTAssertNil(GOGSaves.cloudListing(in: "[SAVES] DEBUG: Files: [{'name': 'broken"))
+ }
+
+ /// A deleted file's mark (GOG's hash of nothing) is neither downloaded nor counted.
+ func testDeletedMarksAreSkipped() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ try write("", to: cloud.appending(path: "saves/gone.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ XCTAssertEqual(read(folder(saves).appending(path: "slot1.sav")), "cloud save")
+ XCTAssertNil(read(folder(saves).appending(path: "gone.sav")))
+ }
+
+ /// GOG has no cloud storage for the game at all (gogdl gets a 404 and logs no listing): the
+ /// first upload has nothing to back up and goes through.
+ func testNoCloudStorageAtAll() throws {
+ try write("local", to: folder(saves).appending(path: "slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "local")
+ XCTAssertTrue(store.backups(in: store.backupsFolder(game, saves)).isEmpty, "no empty cloud backup")
+ }
+
+ /// A location with no files in the cloud (only another location's) makes no cloud backup.
+ func testAnEmptyCloudLocationMakesNoBackup() throws {
+ try write("profile", to: cloud.appending(path: "saves_profiles/p.dat"))
+ try write("local", to: folder(saves).appending(path: "slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "local")
+ XCTAssertTrue(store.backups(in: store.backupsFolder(game, saves)).isEmpty)
+ }
+
+ /// An unchanged cloud is not backed up again: the listing matches the newest cloud backup.
+ func testAnUnchangedCloudIsBackedUpOnce() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .synced)
+ let cloudBackups = store.backups(in: store.backupsFolder(game, saves)).filter { GOGSaves.kind(of: $0) == .cloud }
+ XCTAssertEqual(cloudBackups.count, 1)
+ }
+
+ /// Picking "Keep this Mac's saves" after an upload conflict keeps the cloud backup the
+ /// conflicting upload made, without downloading the cloud a second time.
+ func testKeepingTheMacsSavesKeepsTheCloudBackupForGood() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ try write("played here", to: folder(saves).appending(path: "slot1.sav"))
+ try write("played elsewhere", to: cloud.appending(path: "saves/slot2.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .upload), .conflict)
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .forceUpload, keepBackups: true), .synced)
+ let cloudBackups = store.backups(in: store.backupsFolder(game, saves)).filter { GOGSaves.kind(of: $0) == .cloud }
+ XCTAssertEqual(cloudBackups.count, 1)
+ XCTAssertTrue(cloudBackups.allSatisfy(GOGSaves.isKept))
+ XCTAssertEqual(read(cloudBackups[0].appending(path: "slot2.sav")), "played elsewhere")
+ XCTAssertEqual(read(cloud.appending(path: "saves/slot1.sav")), "played here")
+ }
+
+ /// A refusal leaves the last sync's timestamp: gogdl prints back the one it was given.
+ func testARefusalKeepsTheLastTimestamp() throws {
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .synced)
+ let before = store.timestamps()[store.key(game, saves)]
+ try write("played", to: folder(saves).appending(path: "slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: folder(saves), direction: .download), .refused)
+ XCTAssertEqual(store.timestamps()[store.key(game, saves)], before)
+ }
+
+ /// Dates with no offset are local time, as Python reads them.
+ func testAnotherLocationsNewerFilesWithLocalDates() throws {
+ try Data().write(to: home.appending(path: "fake-naive-dates"))
+ try testAnotherLocationsNewerFilesAreNoConflict()
+ }
+
+ /// Debug lines quote paths and arguments: a phrase in one is not read as gogdl's result.
+ func testDebugLinesAreNotReadAsResults() throws {
+ let odd = root.appending(path: "Files in conflict Downloading file failed/saves")
+ try write("cloud save", to: cloud.appending(path: "saves/slot1.sav"))
+ XCTAssertEqual(store.sync(game, location: saves, folder: odd, direction: .download), .synced)
+ XCTAssertEqual(read(odd.appending(path: "slot1.sav")), "cloud save")
+ }
+
+ /// gogdl 1.3.1's save-sync, cut down to what decides what moves (saves.py), with the log
+ /// lines it prints around that.
+ static let script = #"""
+ #!/usr/bin/python3
+ import os, sys, shutil, hashlib, datetime
+ home = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ cloud_root = os.path.join(home, "fake-cloud")
+ naive = os.path.exists(os.path.join(home, "fake-naive-dates"))
+ DELETED = "aadd86936a80ee8a369579c3926f1b3c"
+ try:
+ failing = set(open(os.path.join(home, "fake-fail")).read().split())
+ except OSError:
+ failing = set()
+ a = sys.argv[1:]
+ debug = "--debug" in a
+ a = a[a.index("save-sync") + 1:]
+ path, raw_ts, name = a[0], a[a.index("--ts") + 1], a[a.index("--name") + 1]
+ ts = float(raw_ts)
+ pref = {"--skip-upload": "download", "--skip-download": "upload", "--force-upload": "forceupload", "--force-download": "forcedownload"}
+ prefered = next((pref[x] for x in a if x in pref), None)
+ def log(who, level, msg): sys.stderr.write(f"[{who}] {level}: {msg}\n"); sys.stderr.flush()
+ def info(msg): log("SAVES", "INFO", msg)
+ def warn(msg): log("SAVES", "WARNING", msg)
+ def iso(t):
+ if naive: return datetime.datetime.fromtimestamp(t).isoformat()
+ return datetime.datetime.fromtimestamp(t, tz=datetime.timezone.utc).isoformat()
+ if debug: log("MAIN", "DEBUG", f"Namespace(path={path!r}, dirname={name!r}, timestamp={raw_ts!r})")
+ os.makedirs(path, exist_ok=True)
+ local = []
+ for d, _, fs in os.walk(path):
+ for f in fs:
+ p = os.path.join(d, f); local.append((os.path.relpath(p, path), p, os.stat(p).st_mtime))
+ if not local: info("No files in directory")
+ info(f"Local files: {len(local)}")
+ if debug: log("urllib3.connectionpool", "DEBUG", "https://cloudstorage.gog.com:443 \"GET /v1/0/0 HTTP/1.1\" 200 None")
+ listing = []
+ for d, _, fs in os.walk(cloud_root):
+ for f in fs:
+ p = os.path.join(d, f); data = open(p, "rb").read()
+ listing.append({"name": os.path.relpath(p, cloud_root), "hash": DELETED if not data else hashlib.md5(data).hexdigest(),
+ "bytes": len(data), "last_modified": iso(os.stat(p).st_mtime)})
+ if listing: # an empty client is a 404, which gogdl answers with [] before logging anything
+ info(f"Files in cloud: {len(listing)}")
+ if debug: log("SAVES", "DEBUG", f"Files: {listing}")
+ cloud = []
+ for e in listing:
+ if e["name"].startswith(name):
+ rel = e["name"].replace(f"{name}/", "", 1)
+ cloud.append((rel, os.path.join(path, rel), datetime.datetime.fromisoformat(e["last_modified"]).astimezone().timestamp(), e["hash"]))
+ downloadable = [f for f in cloud if f[3] != DELETED]
+ def download(f):
+ src = os.path.join(cloud_root, name, f[0])
+ if not os.path.exists(src) or f"{name}/{f[0]}" in failing:
+ log("SAVES", "ERROR", "Downloading file failed"); return
+ os.makedirs(os.path.dirname(f[1]), exist_ok=True); shutil.copy2(src, f[1])
+ def upload(f):
+ dst = os.path.join(cloud_root, name, f[0]); os.makedirs(os.path.dirname(dst), exist_ok=True); shutil.copyfile(f[1], dst)
+ def delete(f):
+ p = os.path.join(cloud_root, name, f[0])
+ if os.path.exists(p): os.remove(p)
+ def done():
+ sys.stdout.write(str(datetime.datetime.now().timestamp())); sys.stdout.flush(); info("Done"); sys.exit(0)
+ if local and not cloud:
+ info("No files in cloud, uploading"); [upload(f) for f in local]; info("Done")
+ sys.stdout.write(str(datetime.datetime.now().timestamp())); sys.exit(0)
+ if not local and cloud:
+ info("No files locally, downloading"); [download(f) for f in downloadable]; info("Done")
+ sys.stdout.write(str(datetime.datetime.now().timestamp())); sys.exit(0)
+ lp, cp = [f[0] for f in local], [f[0] for f in cloud]
+ updated_local = [f for f in local if f[2] > ts]
+ updated_cloud = [f for f in cloud if f[3] != DELETED and f[2] > ts]
+ not_remote = [f for f in local if f[0] not in cp]
+ not_local = [f for f in cloud if f[3] != DELETED and f[0] not in lp]
+ if not updated_local and updated_cloud: action = "download"
+ elif updated_local and not updated_cloud: action = "upload"
+ elif not updated_local and not updated_cloud: action = "none"
+ else: action = "conflict"
+ if prefered == "forceupload": warn("Forcing upload"); updated_local = local; action = "upload"
+ elif prefered == "forcedownload": warn("Forcing download"); updated_cloud = downloadable; action = "download"
+ if prefered == "upload" and action == "download": warn("Refused to upload files, newer files in the cloud"); print(raw_ts); sys.exit(0)
+ if prefered == "download" and action == "upload": warn("Refused to download files, newer files locally"); print(raw_ts); sys.exit(0)
+ if action == "upload":
+ info("Uploading files"); [upload(f) for f in updated_local]
+ for f in not_local: info(f"DELETING IN CLOUD {f[0]}"); delete(f)
+ elif action == "download":
+ info("Downloading files"); [download(f) for f in updated_cloud]
+ for f in not_remote: info(f"DELETING LOCALLY {f[1]}"); os.remove(f[1])
+ elif action == "conflict":
+ warn("Files in conflict force downloading or uploading of files")
+ elif action == "none":
+ info("Nothing to do")
+ done()
+ """#
+}
diff --git a/Tests/HighballKitTests/GOGSaveSafetyTests.swift b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
index 0bdefc0..fd157fa 100644
--- a/Tests/HighballKitTests/GOGSaveSafetyTests.swift
+++ b/Tests/HighballKitTests/GOGSaveSafetyTests.swift
@@ -1,7 +1,7 @@
import XCTest
@testable import HighballKit
-/// No sync replaces or deletes a save without a copy of it kept first (GOGSaves' backups).
+/// No sync replaces or deletes a save without backing it up first (GOGSaves backups).
final class GOGSaveSafetyTests: XCTestCase {
private var root: URL!
override func setUp() { root = FileManager.default.temporaryDirectory.appending(path: "saves-\(UUID().uuidString)") }
@@ -19,7 +19,7 @@ final class GOGSaveSafetyTests: XCTestCase {
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.
+ /// The backup happens before gogdl runs: gogdl isn't installed here, and the backup is still 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") }
@@ -35,8 +35,8 @@ final class GOGSaveSafetyTests: XCTestCase {
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.
+ /// Pruning goes by creation date, not name, and never removes the backup just made, even when
+ /// a clock that was once ahead left backups named after today.
func testPruningKeepsTheNewestTenAndNeverTheCopyJustMade() throws {
let (saves, game, location, folder) = try fixture()
let dir = saves.backupsFolder(game, location)
@@ -64,12 +64,33 @@ final class GOGSaveSafetyTests: XCTestCase {
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.
+ /// gogdl lists and deletes hidden files too, so they are backed up like any save.
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"])
+ XCTAssertEqual(try GOGSaves.files(in: folder).map(\.lastPathComponent), [".save"])
+ }
+
+ /// gogdl walks into a linked folder and writes through a linked file, so the copy holds what
+ /// they point at, not the links; a link to nothing holds nothing to keep.
+ func testACopyHoldsWhatLinksPointAt() throws {
+ let (saves, game, location, folder) = try fixture()
+ let elsewhere = root.appending(path: "Elsewhere")
+ try FileManager.default.createDirectory(at: elsewhere.appending(path: "profile"), withIntermediateDirectories: true)
+ try Data("linked file".utf8).write(to: elsewhere.appending(path: "one.dat"))
+ try Data("in a linked folder".utf8).write(to: elsewhere.appending(path: "profile/two.dat"))
+ let fm = FileManager.default
+ try fm.createSymbolicLink(at: folder.appending(path: "one.dat"), withDestinationURL: elsewhere.appending(path: "one.dat"))
+ try fm.createSymbolicLink(at: folder.appending(path: "profile"), withDestinationURL: elsewhere.appending(path: "profile"))
+ try fm.createSymbolicLink(at: folder.appending(path: "gone.dat"), withDestinationURL: elsewhere.appending(path: "nothing"))
+ try fm.createSymbolicLink(at: folder.appending(path: "slot1/loop"), withDestinationURL: folder)
+ let copy = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder))
+ XCTAssertEqual(try String(contentsOf: copy.appending(path: "one.dat"), encoding: .utf8), "linked file")
+ XCTAssertEqual(try String(contentsOf: copy.appending(path: "profile/two.dat"), encoding: .utf8), "in a linked folder")
+ XCTAssertNil(try? fm.destinationOfSymbolicLink(atPath: copy.appending(path: "one.dat").path), "a file, not a link")
+ XCTAssertFalse(fm.fileExists(atPath: copy.appending(path: "gone.dat").path))
+ XCTAssertEqual(try String(contentsOf: copy.appending(path: "slot1/save.dat"), encoding: .utf8), "progress", "a loop is walked once")
}
func testTwoInstallsKeepTheirOwnBackups() throws {
@@ -79,26 +100,20 @@ final class GOGSaveSafetyTests: XCTestCase {
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,
- /// except for a location whose name another one's starts with: gogdl lists the other's files
- /// for it too and fails each at the wrong path, in a line that names no file.
+ /// gogdl exits 0 when a file fails to download; its log line is what fails the sync.
func testAFileGogdlFailedToFetchFailsTheCopy() {
- let own = GOGSaves.Location(name: "saves_profiles", template: "")
- XCTAssertTrue(GOGSaves.isFailure("[SAVES] ERROR: Downloading file failed", location: own))
- XCTAssertFalse(GOGSaves.isFailure("[SAVES] INFO: Files in cloud: 3", location: own))
- let prefix = GOGSaves.Location(name: "saves", template: "", sharesItsPrefix: true)
- XCTAssertFalse(GOGSaves.isFailure("[SAVES] ERROR: Downloading file failed", location: prefix))
- XCTAssertTrue(GOGSaves.isFailure("[SAVES] ERROR: There was an error uploading a file ", location: prefix))
+ XCTAssertTrue(GOGSaves.isFailure("[SAVES] ERROR: Downloading file failed"))
+ XCTAssertFalse(GOGSaves.isFailure("[SAVES] INFO: Files in cloud: 3"))
}
- /// An upload always copies GOG's cloud first: with gogdl absent here, the copy is what fails.
- func testAnUploadCopiesTheCloudFirst() throws {
+ /// Every upload backs up GOG's cloud first: with gogdl absent here, that backup is what fails.
+ func testAnUploadBacksUpTheCloudFirst() throws {
let (saves, game, location, folder) = try fixture()
guard case let .failed(why) = saves.sync(game, location: location, folder: folder, direction: .upload) else { return XCTFail() }
XCTAssertTrue(why.contains("backed up"))
}
- /// A save folder years old: its copy is dated now, so the newest copies are still the ones kept.
+ /// Backing up a years-old save folder dates the backup now, so pruning still keeps the newest.
func testACopyOfAnOldFolderIsDatedNow() throws {
let (saves, game, location, folder) = try fixture()
try FileManager.default.setAttributes([.creationDate: Date(timeIntervalSince1970: 1_500_000_000)], ofItemAtPath: folder.path)
@@ -114,164 +129,92 @@ final class GOGSaveSafetyTests: XCTestCase {
XCTAssertFalse(GOGSaves.isRefusal("[SAVES] INFO: Done"))
}
- // MARK: Against a stand-in gogdl
-
- /// A stand-in for gogdl at the path GOGStore runs, keeping its cloud in a folder: listing by
- /// name prefix, downloads of newer cloud files only, an upload deleting cloud files the Mac
- /// lacks, refusals, conflicts, a timestamp glued to the next line, as gogdl 1.3.1 does.
- private func fakeGogdl(for saves: GOGSaves) throws -> URL {
- let cloud = root.appending(path: "cloud", directoryHint: .isDirectory)
- let binary = saves.store.gogdlBinary
- try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true)
- try FileManager.default.createDirectory(at: cloud, withIntermediateDirectories: true)
- try #"""
- #!/bin/sh
- # gogdl 1.3.1's save-sync (gogdl/saves.py), with a folder standing in for GOG's cloud: a cloud
- # file's modification date is its last_modified.
- cloud="\#(cloud.path)"
- [ "$1" = --auth-config-path ] && shift 2
- [ "$1" = save-sync ] || exit 2
- dir="$2"; ts=0; tsArg=0; name=__default; prefered=""
- shift 3
- while [ $# -gt 0 ]; do
- case "$1" in
- --ts) tsArg="$2"; ts="${2%%.*}"; shift 2 ;;
- --name) name="$2"; shift 2 ;;
- --os) shift 2 ;;
- --skip-download) prefered=upload; shift ;;
- --skip-upload) prefered=download; shift ;;
- --force-upload) prefered=forceupload; shift ;;
- --force-download) prefered=forcedownload; shift ;;
- *) shift ;;
- esac
- done
- mkdir -p "$dir" "$cloud"
- mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1"; }
- localFiles() { (cd "$dir" && find . -type f | sed 's|^\./||'); }
- # is_in_our_dir: startswith(name), so "saves" lists "saves_profiles/..." too.
- cloudNames() { (cd "$cloud" && find . -type f | sed 's|^\./||' | while IFS= read -r n; do case "$n" in "$name"*) echo "$n" ;; esac; done); }
- # name.replace(f"{dirname}/", "", 1): the first occurrence, wherever it is.
- rel() { case "$1" in *"$name/"*) echo "${1%%"$name/"*}${1#*"$name/"}" ;; *) echo "$1" ;; esac; }
- # GOG answers an error for a path it has no file at; a file named *.unserved stands for one it
- # fails to serve.
- download() {
- case "$1" in *.unserved) echo "[SAVES] ERROR: Downloading file failed"; return ;; esac
- [ -f "$cloud/$name/$1" ] || { echo "[SAVES] ERROR: Downloading file failed"; return; }
- mkdir -p "$(dirname "$dir/$1")"; cp -p "$cloud/$name/$1" "$dir/$1"
- }
- upload() { mkdir -p "$(dirname "$cloud/$name/$1")"; cp -p "$dir/$1" "$cloud/$name/$1"; }
- lines() { printf '%s\n' "$1" | while IFS= read -r r; do [ -n "$r" ] && echo "$r"; done; }
- finish() { printf '%s' "$(date +%s)"; echo "[SAVES] INFO: Done"; exit 0; }
- localList=$(localFiles); remote=$(cloudNames)
- echo "[SAVES] INFO: Local files: $(lines "$localList" | wc -l | tr -d ' ')"
- if [ -n "$localList" ] && [ -z "$remote" ]; then
- echo "[SAVES] INFO: No files in cloud, uploading"
- lines "$localList" | while IFS= read -r r; do upload "$r"; done; finish
- elif [ -z "$localList" ] && [ -n "$remote" ]; then
- echo "[SAVES] INFO: No files locally, downloading"
- lines "$remote" | while IFS= read -r n; do download "$(rel "$n")"; done; finish
- fi
- newerLocal=$(lines "$localList" | while IFS= read -r r; do [ "$(mtime "$dir/$r")" -gt "$ts" ] && echo "$r"; done)
- newerCloud=$(lines "$remote" | while IFS= read -r n; do [ "$(mtime "$cloud/$n")" -gt "$ts" ] && rel "$n"; done)
- if [ -z "$newerLocal" ] && [ -n "$newerCloud" ]; then action=download
- elif [ -n "$newerLocal" ] && [ -z "$newerCloud" ]; then action=upload
- elif [ -z "$newerLocal" ] && [ -z "$newerCloud" ]; then action=none
- else action=conflict; fi
- case "$prefered" in
- forceupload) echo "[SAVES] WARNING: Forcing upload"; newerLocal="$localList"; action=upload ;;
- forcedownload) echo "[SAVES] WARNING: Forcing download"; newerCloud=$(lines "$remote" | while IFS= read -r n; do rel "$n"; done); action=download ;;
- upload) [ "$action" = download ] && { echo "[SAVES] WARNING: Refused to upload files, newer files in the cloud"; echo "$tsArg"; exit 0; } ;;
- download) [ "$action" = upload ] && { echo "[SAVES] WARNING: Refused to download files, newer files locally"; echo "$tsArg"; exit 0; } ;;
- esac
- case "$action" in
- upload)
- lines "$newerLocal" | while IFS= read -r r; do upload "$r"; done
- lines "$remote" | while IFS= read -r n; do r=$(rel "$n"); [ -f "$dir/$r" ] || { echo "[SAVES] INFO: DELETING IN CLOUD $r"; rm -f "$cloud/$name/$r"; }; done ;;
- download)
- lines "$newerCloud" | while IFS= read -r r; do download "$r"; done
- lines "$localList" | while IFS= read -r r; do [ -f "$cloud/$name/$r" ] || { echo "[SAVES] INFO: DELETING LOCALLY $r"; rm -f "$dir/$r"; }; done ;;
- conflict) echo "[SAVES] WARNING: Files in conflict force downloading or uploading of files" ;;
- none) echo "[SAVES] INFO: Nothing to do" ;;
- esac
- finish
- """#.write(to: binary, atomically: true, encoding: .utf8)
- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path)
- return cloud
+ private func oldBackup(_ name: String, in dir: URL, daysAgo: Double) throws -> URL {
+ let url = dir.appending(path: name)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ try FileManager.default.setAttributes([.creationDate: Date().addingTimeInterval(-86_400 * daysAgo)], ofItemAtPath: url.path)
+ return url
}
- private func write(_ text: String, to file: URL, at date: Date) throws {
- try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
- try Data(text.utf8).write(to: file)
- try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: file.path)
- }
-
- private func setLastSync(_ saves: GOGSaves, _ game: GOGStore.InstalledGame, _ location: GOGSaves.Location, _ date: Date) throws {
- var all = saves.timestamps()
- all[saves.key(game, location)] = String(Int(date.timeIntervalSince1970))
- try FileManager.default.createDirectory(at: saves.timestampsFile.deletingLastPathComponent(), withIntermediateDirectories: true)
- try JSONEncoder().encode(all).write(to: saves.timestampsFile)
+ /// Mac and cloud backups are pruned separately, and kept ones never.
+ func testPruningIsPerKindAndSparesKeptBackups() throws {
+ let (saves, game, location, folder) = try fixture()
+ let dir = saves.backupsFolder(game, location)
+ for i in 0..<12 { _ = try oldBackup("2020-01-\(String(format: "%02d", i + 1))T000000Z-cloud", in: dir, daysAgo: Double(30 + i)) }
+ for i in 0..<3 { _ = try oldBackup("2019-01-0\(i + 1)T000000Z-mac-kept", in: dir, daysAgo: Double(400 + i)) }
+ for i in 0..<12 {
+ try Data("progress \(i)".utf8).write(to: folder.appending(path: "slot1/save.dat"))
+ try saves.backUpLocal(game, location: location, folder: folder)
+ }
+ let all = saves.backups(in: dir)
+ XCTAssertEqual(all.filter { GOGSaves.kind(of: $0) == .mac && !GOGSaves.isKept($0) }.count, 10)
+ XCTAssertEqual(all.filter { GOGSaves.kind(of: $0) == .cloud }.count, 12, "cloud backups untouched by Mac ones")
+ XCTAssertEqual(all.filter(GOGSaves.isKept).count, 3)
}
- /// Owner review on #589: with `saves` and `saves_profiles` (Crysis's layout), gogdl lists
- /// saves_profiles' files for `saves` too and fails each at the wrong path. That fails neither
- /// `saves`' sync nor its cloud copy, so the timestamp is kept and the next sync does not wedge;
- /// a file that really fails to come down still fails a location that shares no prefix.
- func testTwoLocationsSharingAPrefixSyncAgainstGogdl() throws {
- let (saves, game, _, folder) = try fixture()
- let cloud = try fakeGogdl(for: saves)
- let json = #"{"content":{"Windows":{"cloudStorage":{"enabled":true,"locations":[{"name":"saves","location":"<?INSTALL?>/saves"},{"name":"saves_profiles","location":"<?INSTALL?>/saves_profiles"}]}}}}"#
- let locations = try XCTUnwrap(GOGSaves.parseLocations(Data(json.utf8), clientID: "c"))
- XCTAssertEqual(locations.map(\.sharesItsPrefix), [true, false])
- let (ownSaves, profiles) = (locations[0], locations[1])
- let profilesFolder = root.appending(path: "Game/saves_profiles")
- let now = Date()
- try FileManager.default.setAttributes([.modificationDate: now.addingTimeInterval(-3000)], ofItemAtPath: folder.appending(path: "slot1/save.dat").path)
- try write("from the cloud", to: cloud.appending(path: "saves/slot1/save.dat"), at: now.addingTimeInterval(-1000))
- try write("profile", to: cloud.appending(path: "saves_profiles/profile.dat"), at: now.addingTimeInterval(-1000))
- try setLastSync(saves, game, ownSaves, now.addingTimeInterval(-2000))
- let before = saves.timestamps()[saves.key(game, ownSaves)]
-
- XCTAssertEqual(saves.sync(game, location: ownSaves, folder: folder, direction: .download), .synced)
- XCTAssertEqual(try String(contentsOf: folder.appending(path: "slot1/save.dat"), encoding: .utf8), "from the cloud")
- XCTAssertNotEqual(saves.timestamps()[saves.key(game, ownSaves)], before, "the sync's timestamp is kept")
- XCTAssertEqual(saves.sync(game, location: profiles, folder: profilesFolder, direction: .download), .synced)
- XCTAssertEqual(try String(contentsOf: profilesFolder.appending(path: "profile.dat"), encoding: .utf8), "profile")
-
- let copy = try saves.backUpCloud(game, location: ownSaves)
- XCTAssertEqual(try String(contentsOf: copy.appending(path: "slot1/save.dat"), encoding: .utf8), "from the cloud")
- XCTAssertFalse(FileManager.default.fileExists(atPath: copy.appending(path: "saves_profiles").path), "nothing of the other location's")
- XCTAssertEqual(saves.sync(game, location: ownSaves, folder: folder, direction: .forceUpload), .synced, "keeping this Mac's saves works")
-
- // GOG failing to serve one of saves_profiles' own files still fails its copy and its sync.
- try write("lost", to: cloud.appending(path: "saves_profiles/broken.unserved"), at: now.addingTimeInterval(600))
- XCTAssertThrowsError(try saves.backUpCloud(game, location: profiles))
- let names = (try? FileManager.default.contentsOfDirectory(atPath: saves.backupsFolder(game, profiles).path)) ?? []
- XCTAssertFalse(names.contains { $0.hasSuffix(".partial") }, "no half copy")
- let kept = saves.timestamps()[saves.key(game, profiles)]
- guard case .failed = saves.sync(game, location: profiles, folder: profilesFolder, direction: .download) else { return XCTFail() }
- XCTAssertEqual(saves.timestamps()[saves.key(game, profiles)], kept, "a failed sync keeps no timestamp")
+ /// A kept backup of unchanged saves turns the matching backup into a kept one.
+ func testAKeptBackupOfUnchangedSavesKeepsTheLastOne() throws {
+ let (saves, game, location, folder) = try fixture()
+ let first = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder))
+ let kept = try XCTUnwrap(try saves.backUpLocal(game, location: location, folder: folder, kept: true))
+ XCTAssertTrue(GOGSaves.isKept(kept))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: first.path))
+ XCTAssertEqual(saves.backups(in: saves.backupsFolder(game, location)).count, 1)
+ }
+
+ /// The fingerprint tells apart folders that only differ in names.
+ func testTheFingerprintCountsNames() throws {
+ let a = root.appending(path: "A"), b = root.appending(path: "B")
+ let date = Date(timeIntervalSince1970: 1_700_000_000)
+ for (folder, name) in [(a, "one.sav"), (b, "two.sav")] {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: folder.appending(path: name))
+ try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: folder.appending(path: name).path)
+ }
+ XCTAssertNotEqual(GOGSaves.fingerprint(a), GOGSaves.fingerprint(b))
}
- /// Owner review on #589: a cloud file older than the last sync and missing on the Mac does not
- /// come down before Play, and the upload after the session deletes it from the cloud; the copy
- /// of the cloud taken before that upload still holds it.
- func testAnUploadAfterADownloadKeepsACopyOfACloudFileTheMacLacks() throws {
+ /// A backup a crash left half-filled is cleared at the next backup once it is an hour old.
+ func testStalePartialBackupsAreCleared() throws {
let (saves, game, location, folder) = try fixture()
- let cloud = try fakeGogdl(for: saves)
- let now = Date()
- let save = folder.appending(path: "slot1/save.dat")
- try FileManager.default.setAttributes([.modificationDate: now.addingTimeInterval(-3000)], ofItemAtPath: save.path)
- try write("progress", to: cloud.appending(path: "saves/slot1/save.dat"), at: now.addingTimeInterval(-3000))
- try write("old", to: cloud.appending(path: "saves/old.dat"), at: now.addingTimeInterval(-3000))
- try setLastSync(saves, game, location, now.addingTimeInterval(-2000))
-
- XCTAssertEqual(saves.sync(game, location: location, folder: folder, direction: .download), .synced)
- XCTAssertFalse(FileManager.default.fileExists(atPath: folder.appending(path: "old.dat").path), "gogdl brings only newer files")
- try write("more progress", to: save, at: now.addingTimeInterval(600)) // the session
- XCTAssertEqual(saves.sync(game, location: location, folder: folder, direction: .upload), .synced)
- XCTAssertFalse(FileManager.default.fileExists(atPath: cloud.appending(path: "saves/old.dat").path), "gogdl deleted it from the cloud")
- XCTAssertEqual(try String(contentsOf: cloud.appending(path: "saves/slot1/save.dat"), encoding: .utf8), "more progress")
- let copy = try XCTUnwrap(saves.backups(in: saves.backupsFolder(game, location)).first { $0.lastPathComponent.contains("-cloud") })
- XCTAssertEqual(try String(contentsOf: copy.appending(path: "old.dat"), encoding: .utf8), "old")
+ let dir = saves.backupsFolder(game, location)
+ let stale = try oldBackup("2020-01-01T000000Z-mac.partial", in: dir, daysAgo: 1)
+ let fresh = try oldBackup("2020-01-02T000000Z-mac.partial", in: dir, daysAgo: 0)
+ try saves.backUpLocal(game, location: location, folder: folder)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: stale.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: fresh.path), "maybe still being filled")
+ }
+
+ /// gogdl reads GOG's dates with Python's fromisoformat, then astimezone().
+ func testCloudDatesAreReadAsPythonReadsThem() throws {
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T10:00:00+00:00")?.timeIntervalSince1970, 1_714_557_600)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T10:00:00Z")?.timeIntervalSince1970, 1_714_557_600)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T19:00:00+09:00")?.timeIntervalSince1970, 1_714_557_600)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T05:00:00-0500")?.timeIntervalSince1970, 1_714_557_600)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01 10:00+00:00")?.timeIntervalSince1970, 1_714_557_600)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T10:00:00.5+00:00")?.timeIntervalSince1970 ?? 0, 1_714_557_600.5, accuracy: 0.0001)
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T10:00:00.123456+00:00")?.timeIntervalSince1970 ?? 0, 1_714_557_600.123456, accuracy: 0.000001)
+ var local = DateComponents(year: 2024, month: 5, day: 1, hour: 10)
+ local.timeZone = .current
+ XCTAssertEqual(GOGSaves.date(iso: "2024-05-01T10:00:00"), Calendar(identifier: .gregorian).date(from: local), "no offset: local time")
+ XCTAssertNil(GOGSaves.date(iso: "yesterday"))
+ }
+
+ /// What an uninstall backs up, leaves alone, or needs the player's go-ahead for.
+ func testUninstallPlan() throws {
+ let game = GOGStore.InstalledGame(id: "1", title: "Game", folder: root.appending(path: "drive_c/Games/Game"), buildID: nil, clientID: nil, dlcIDs: [], tasks: [])
+ let driveC = root.appending(path: "drive_c")
+ func plan(_ templates: [String]) -> GOGSaves.UninstallPlan {
+ GOGSaves.uninstallPlan(templates.enumerated().map { GOGSaves.Location(name: "l\($0.offset)", template: $0.element) },
+ game: game, driveC: driveC, userName: "player")
+ }
+ let inside = plan(["<?INSTALL?>/saves"])
+ XCTAssertEqual(inside.backUp.map(\.folder.lastPathComponent), ["saves"])
+ XCTAssertTrue(inside.cannotBackUp.isEmpty)
+ XCTAssertTrue(plan(["<?SAVED_GAMES?>/Studio/Game", "<?DOCUMENTS?>/%USERNAME%", "<?MAC_LIBRARY?>/x"]).backUp.isEmpty, "outside the game's folder: left alone")
+ let partly = plan(["<?INSTALL?>/saves/%USERNAME%"])
+ XCTAssertEqual(partly.backUp.map { $0.folder.path }, [game.folder.appending(path: "saves").path], "up to the part Highball can't resolve")
+ XCTAssertEqual(plan(["<?INSTALL?>", "<?INSTALL?>/", "<?INSTALL?>/%SAVES%", "<?INSTALL?>/../Other"]).cannotBackUp.count, 4)
+ XCTAssertEqual(plan(["<?INSTALL?>\\Save Data"]).backUp.map(\.folder.lastPathComponent), ["Save Data"])
}
}
diff --git a/Tests/HighballKitTests/GOGStoreTests.swift b/Tests/HighballKitTests/GOGStoreTests.swift
index cc8fa70..8a4bcdf 100644
--- a/Tests/HighballKitTests/GOGStoreTests.swift
+++ b/Tests/HighballKitTests/GOGStoreTests.swift
@@ -213,9 +213,6 @@ final class GOGStoreTests: XCTestCase {
"<?APPLICATION_DATA_LOCAL?>/GOG.com/Galaxy/Applications/533/Storage/Shared/Files")
let off = #"{"content":{"Windows":{"cloudStorage":{"enabled":false}}}}"#
XCTAssertNil(GOGSaves.parseLocations(Data(off.utf8), clientID: "c"))
- // gogdl lists a location's cloud files by name prefix, so `saves` also sees saves_profiles'.
- let shared = #"{"content":{"Windows":{"cloudStorage":{"enabled":true,"locations":[{"name":"saves_profiles","location":"<?INSTALL?>/p"},{"name":"saves","location":"<?INSTALL?>/s"},{"name":"config","location":"<?INSTALL?>/c"}]}}}}"#
- XCTAssertEqual(GOGSaves.parseLocations(Data(shared.utf8), clientID: "c")?.map(\.sharesItsPrefix), [false, true, false])
}
func testClientIDFromCompressedBuildManifest() throws {
@@ -227,19 +224,6 @@ final class GOGStoreTests: XCTestCase {
XCTAssertNil(GOGSaves.clientID(inManifest: Data([0x78, 0x9c, 0x00])))
}
- /// Owner review on #589: a game whose build manifest names no client id (Beyond Good & Evil's)
- /// has no cloud saves, an answer, where GOG out of reach or answering something unreadable is
- /// none: only the second may keep an uninstall waiting.
- func testAGameWithoutAClientIDIsAnAnswerNotAFailure() throws {
- XCTAssertNil(try GOGSaves.clientID(inPublishedManifest: Data(#"{"baseProductId":"1207658746"}"#.utf8)))
- XCTAssertEqual(try GOGSaves.clientID(inPublishedManifest: Data(#"{"clientId":"5353"}"#.utf8)), "5353")
- XCTAssertThrowsError(try GOGSaves.clientID(inPublishedManifest: Data([0x78, 0x9c, 0x00])))
- XCTAssertNil(try GOGSaves.newestBuild(inBuildList: Data(#"{"total_count":0,"items":[]}"#.utf8)), "no build for Windows")
- XCTAssertEqual(try GOGSaves.newestBuild(inBuildList: Data(#"{"items":[{"link":"https://cdn.gog.com/a"},{"link":"https://cdn.gog.com/b"}]}"#.utf8)),
- URL(string: "https://cdn.gog.com/a"))
- XCTAssertThrowsError(try GOGSaves.newestBuild(inBuildList: Data("<html>".utf8)))
- }
-
func testSaveFoldersResolveInsideTheEnvironment() throws {
let driveC = FileManager.default.temporaryDirectory.appending(path: "gogsaves-\(UUID().uuidString)/drive_c")
defer { try? FileManager.default.removeItem(at: driveC.deletingLastPathComponent()) }
@@ -264,7 +248,7 @@ final class GOGStoreTests: XCTestCase {
func testSaveSyncArgumentsAndConflictLine() {
let location = GOGSaves.Location(name: "saves", template: "")
let down = GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "0", direction: .download)
- XCTAssertEqual(down, ["save-sync", "/s", "1", "--os", "windows", "--ts", "0", "--name", "saves", "--skip-upload"])
+ XCTAssertEqual(down, ["save-sync", "/s", "1", "--os", "windows", "--ts", "0", "--name", "saves", "--debug", "--skip-upload"])
XCTAssertEqual(GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "5", direction: .upload).last, "--skip-download")
XCTAssertEqual(GOGSaves.arguments(folder: URL(fileURLWithPath: "/s"), id: "1", location: location, timestamp: "5", direction: .forceDownload).last, "--force-download")
XCTAssertTrue(GOGSaves.isConflict("[SAVES] WARNING: Files in conflict force downloading or uploading of files"))
diff --git a/Tests/HighballKitTests/UninstallTests.swift b/Tests/HighballKitTests/UninstallTests.swift
index 034a167..318a321 100644
--- a/Tests/HighballKitTests/UninstallTests.swift
+++ b/Tests/HighballKitTests/UninstallTests.swift
@@ -55,14 +55,6 @@ final class UninstallTests: XCTestCase {
XCTAssertTrue(text.contains("delete the environment"), text)
}
- /// Owner review on #589: only GOG's cloud-save locations are copied before the folder goes, so
- /// a game with cloud saves off that saves beside its exe loses those saves, and the text says so.
- func testTheGOGMessagePromisesACopyOnlyOfWhatGOGSyncs() {
- let text = Uninstall.confirmation(route: .gog(id: "1"), sizeOnDisk: 0)
- XCTAssertTrue(text.contains("ones GOG does not sync, are deleted with it"), text)
- XCTAssertFalse(text.contains("saves the game keeps inside its own folder are copied"), text)
- }
-
func testTheReasonIsWhatAnUnroutableGameShows() {
let route = Uninstall.route(for: item(.steam))
guard case let .none(reason) = route else { return XCTFail("expected none") }