Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Epic cloud saves: synced before and after a Windows Epic game, a copy kept first
Gabeefb2ec40e35f
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex c5203b3..1a3bc8a 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -7,14 +7,16 @@ import os/// The three Settings tabs, so a deep link can select one.enum SettingsTab: Hashable { case environments, engine, troubleshooting }-/// A GOG cloud-save conflict: this Mac's saves and GOG's both changed since the last sync, so-/// gogdl moved nothing and the player picks which copy wins (GOGSaves).+/// A cloud-save conflict: this Mac's saves and the cloud's both changed since the last sync, so+/// nothing moved and the player picks which copy wins (GOGSaves, EpicSaves).struct GOGSaveConflict: Identifiable {enum Choice { case useCloud, keepMac, skip }let id = UUID()let title: String/// Asked before Play (the launch waits) or after the game ended.let beforePlay: Bool+ /// An Epic game's: Epic's cloud keeps its earlier saves when the Mac's go up.+ var epic = falselet resolve: (Choice) -> Void}@@ -2675,11 +2677,16 @@ final class AppState {/// Work a launch leaves for the end of its session (a GOG game's comet and save upload).@ObservationIgnored private var sessionEndActions: [UUID: (SessionRecord) -> Void] = [:]+ /// An Epic game's save upload, for the end of its session: apart from sessionEndActions, which+ /// gogStartComet reads as GOG sessions with a comet.+ @ObservationIgnored private var epicSessionEnds: [UUID: () -> Void] = [:]+private func endSession(_ session: GameSession, reason: String) {guard runningSessions.contains(session) else { return }runningSessions.removeAll { $0.id == session.id }defer {if let action = sessionEndActions.removeValue(forKey: session.id), let record = lastEndedSession { action(record) }+ epicSessionEnds.removeValue(forKey: session.id)?()}discordEnvironments[session.id] = nilif runningSessions.isEmpty { stopDiscordWatch() }@@ -3396,6 +3403,15 @@ final class AppState {await removeMacMetadataFiles(from: folder, of: game.app_title)// Fresh single-use token, fetched off the main thread right before launch.let info = try await Task.detached { try store.launchInfo(game.app_name) }.value+ // Saves down from Epic's cloud first, where the game keeps them there and the player+ // has not turned it off (EpicSaves).+ let syncSaves = epicSignedIn && !epicCloudSavesOff.contains(game.app_name) && folder != nil+ && EpicSaves(store: store).supportsCloudSaves(game.app_name)+ if syncSaves, let folder {+ stage = L("Bringing your saves down from Epic")+ try await epicSync(game, install: folder, in: bottle, direction: .download, beforePlay: true)+ }+ try Task.checkCancellation()let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)let box = LaunchOutcome()let log = logLine(box)@@ -3434,9 +3450,68 @@ final class AppState {alternateEngine: self.alternateEngine(for: bottle))}guard handedOff else { return }- beginSession(GameSession(title: game.app_title, bottleName: bottle.name, appid: nil, markers: markers,- renderer: (renderer ?? bottle.settings.renderer).rawValue, libraryID: "epic:\(game.app_name)",- startNotice: row?.startNotice, startNoticeMinutes: row?.startNoticeMinutes), processList: box.processList)+ let session = GameSession(title: game.app_title, bottleName: bottle.name, appid: nil, markers: markers,+ renderer: (renderer ?? bottle.settings.renderer).rawValue, libraryID: "epic:\(game.app_name)",+ startNotice: row?.startNotice, startNoticeMinutes: row?.startNoticeMinutes)+ if syncSaves, let folder {+ epicSessionEnds[session.id] = { [weak self] in+ Task { @MainActor in _ = try? await self?.epicSync(game, install: folder, in: bottle, direction: .upload, beforePlay: false) }+ }+ }+ beginSession(session, processList: box.processList)+ }+ }++ // MARK: Epic cloud saves++ static let epicCloudSavesOffKey = "epicCloudSavesOff"+ /// Epic games the player turned cloud saves off for, by app name.+ var epicCloudSavesOff = Set(UserDefaults.standard.stringArray(forKey: epicCloudSavesOffKey) ?? []) {+ didSet { UserDefaults.standard.set(epicCloudSavesOff.sorted(), forKey: Self.epicCloudSavesOffKey) }+ }++ func epicSetCloudSaves(_ on: Bool, for app: String) {+ if on { epicCloudSavesOff.remove(app) } else { epicCloudSavesOff.insert(app) }+ }++ /// One Epic sync, asking the player on a conflict, as gogSync does. Whether the Mac's saves and+ /// the cloud's ended up in step.+ @discardableResult+ private func epicSync(_ game: EpicStore.Game, install: URL, in bottle: Bottle, direction: EpicSaves.Direction,+ beforePlay: Bool) async throws -> Bool {+ let saves = EpicSaves(store: epicStore)+ let title = game.app_title, app = game.app_name, prefix = bottle.url+ let log: @Sendable (String) -> Void = { line in Task { @MainActor in self.appendLog(line) } }+ let outcome = await Task.detached { saves.sync(app, install: install, prefix: prefix, direction: direction, onLine: log) }.value+ switch outcome {+ case .synced:+ return true+ case let .failed(why):+ appendLog("\(title): Epic 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+ if let pending = gogSaveConflict {+ appendLog("\(pending.title): cloud saves left as they are this time (\(title) needed the question)")+ resolveGOGSaveConflict(.skip)+ }+ gogSaveConflict = GOGSaveConflict(title: title, beforePlay: beforePlay, epic: true) { continuation.resume(returning: $0) }+ }+ let forced: EpicSaves.Direction+ switch choice {+ case .useCloud: forced = .forceDownload+ case .keepMac: forced = .forceUpload+ case .skip:+ appendLog("\(title): Epic cloud saves left as they are this time")+ return false+ }+ let again = await Task.detached { saves.sync(app, install: install, prefix: prefix, direction: forced, onLine: log) }.value+ switch again {+ case .synced: appendLog("\(title): Epic cloud saves \(choice == .useCloud ? "replaced this Mac's, a copy of them kept first" : "now hold this Mac's, beside their earlier saves")")+ case let .failed(why): appendLog("\(title): Epic cloud saves did not sync (\(why))")+ case .conflict: appendLog("\(title): Epic cloud saves did not sync")+ }+ return again == .synced}}diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex f25ad0a..cf5e36b 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -14,6 +14,8 @@ struct GameDetailView: View {/// The launch arguments being typed; saved on Return, on Play and when the page closes, so a/// space typed between two arguments is not normalised away mid-word.@State private var argsText = ""+ /// The game keeps saves in Epic's cloud (EpicSaves.supportsCloudSaves): read once per page.+ @State private var epicCloudSaves = false@State private var argsLoaded = false/// Saves a line still being typed, so the Play that follows launches with it. Skipped until the/// field has loaded, or its empty text would clear the stored arguments.@@ -86,6 +88,9 @@ struct GameDetailView: View {}.background(BottleBackdrop()).navigationTitle(state.displayTitle(item))+ .task(id: item.id) {+ epicCloudSaves = item.epicAppName.map { EpicSaves(store: state.epicStore).supportsCloudSaves($0) } ?? false+ }.task(id: storeAppID) {storeDetails = nilexpandedDescription = false@@ -135,6 +140,20 @@ struct GameDetailView: View {/// A GOG game's own settings, one row each like the rest of the page: comet (achievements and/// stats), cloud saves, which launch task Play runs, and an update for a game gogdl installed.++ private func epicSettings(_ app: String) -> some View {+ HStack(alignment: .top, spacing: 12) {+ Text(L("Cloud saves")).font(.caption).foregroundStyle(.secondary).frame(width: 110, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ Toggle(L("Sync saves with Epic"), isOn: Binding(+ get: { !state.epicCloudSavesOff.contains(app) }, set: { state.epicSetCloudSaves($0, for: app) }))+ .toggleStyle(.checkbox).disabled(!state.epicSignedIn)+ Text(L("Saves come down from Epic's cloud before Play, after a copy of this Mac's is kept, and go back up when the game ends. If both changed, Highball asks which one wins."))+ .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ }+@ViewBuilder private func gogSettings(_ game: GOGStore.InstalledGame) -> some View {let cometOff = state.gogSettings.cometOff[game.id]HStack(alignment: .top, spacing: 12) {@@ -583,6 +602,9 @@ struct GameDetailView: View {if item.source == .gog, let game = state.gogInstalled(item, in: bottle) {gogSettings(game)}+ if item.source == .epic, let app = item.epicAppName, epicCloudSaves {+ epicSettings(app)+ }// The engine is the environment's, so the page says so and can change it// through the same switch page as the environment's settings, which lists// every program that moves along (highball#262: an engine shown here thatdiff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex 65acd08..bc9baa7 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -551,11 +551,12 @@ private extension View {self.alert(state.gogSaveConflict.map { String(format: L("Which %@ saves should win?"), $0.title) } ?? "",isPresented: .init(get: { state.gogSaveConflict != nil }, set: { if !$0 { state.resolveGOGSaveConflict(.skip) } }),presenting: state.gogSaveConflict) { _ in- Button(L("Use GOG's cloud saves")) { state.resolveGOGSaveConflict(.useCloud) }+ Button(state.gogSaveConflict?.epic == true ? L("Use Epic's cloud saves") : L("Use GOG's cloud saves")) { state.resolveGOGSaveConflict(.useCloud) }Button(L("Keep this Mac's saves")) { state.resolveGOGSaveConflict(.keepMac) }Button(L("Decide later"), role: .cancel) { state.resolveGOGSaveConflict(.skip) }} message: { conflict in- Text(Self.saveConflictMessage(beforePlay: conflict.beforePlay, backups: GOGSaves(store: state.gogStore).backupsDir))+ Text(conflict.epic ? Self.epicSaveConflictMessage(beforePlay: conflict.beforePlay, backups: EpicSaves(store: state.epicStore).backups.root)+ : Self.saveConflictMessage(beforePlay: conflict.beforePlay, backups: GOGSaves(store: state.gogStore).backupsDir))}}@@ -589,6 +590,17 @@ private extension View {}}+ /// Epic's: the Mac's saves changed since the last sync and the cloud has newer ones. Epic's cloud+ /// keeps its earlier saves when the Mac's go up, so only the Mac's need a copy (EpicSaves).+ static func epicSaveConflictMessage(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 changed since they were last synced, and Epic's cloud has newer ones, so neither was copied."),+ String(format: L("Use Epic's cloud saves replaces this Mac's, after a copy of them is kept in %@; Keep this Mac's saves adds them to Epic's cloud, which keeps its earlier saves."),+ (backups.path as NSString).abbreviatingWithTildeInPath),+ decideLater].joined(separator: " ")+ }+/// 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.")diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex f9ff6d2..e319723 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -229,6 +229,15 @@ enum L10n {"Decide later": "Décider plus tard","The saves on this Mac and the ones in GOG's cloud have both changed since they were last 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 Epic's cloud saves": "Utiliser les sauvegardes du cloud Epic",+ "The saves on this Mac changed since they were last synced, and Epic's cloud has newer ones, so neither was copied.":+ "Les sauvegardes de ce Mac ont changé depuis leur dernière synchronisation, et le cloud Epic en a de plus récentes : aucune n’a été copiée.",+ "Use Epic's cloud saves replaces this Mac's, after a copy of them is kept in %@; Keep this Mac's saves adds them to Epic's cloud, which keeps its earlier saves.":+ "Utiliser les sauvegardes du cloud Epic remplace celles de ce Mac, après en avoir gardé une copie dans %@ ; Garder les sauvegardes de ce Mac les ajoute au cloud Epic, qui garde ses sauvegardes précédentes.",+ "Bringing your saves down from Epic": "Récupération de vos sauvegardes depuis Epic",+ "Sync saves with Epic": "Synchroniser avec Epic",+ "Saves come down from Epic's cloud before Play, after a copy of this Mac's is kept, and go back up when the game ends. If both changed, Highball asks which one wins.":+ "Les sauvegardes arrivent du cloud Epic avant de jouer, après une copie de celles de ce Mac, et y repartent quand le jeu se termine. Si les deux ont changé, Highball demande laquelle garder.","Use GOG's cloud saves replaces this Mac's; Keep this Mac's saves replaces the cloud's. Either way, a copy of what gets replaced is kept first, in %@.":"Utiliser les sauvegardes du cloud GOG remplace celles de ce Mac ; Garder les sauvegardes de ce Mac remplace celles du cloud. Dans les deux cas, une copie de ce qui est remplacé est d’abord conservée dans %@.","Remove %@ without a copy of every save?": "Supprimer %@ sans copie de toutes ses sauvegardes ?",diff --git a/Sources/HighballKit/EpicSaves.swift b/Sources/HighballKit/EpicSaves.swiftnew file mode 100644index 0000000..24ab8e9--- /dev/null+++ b/Sources/HighballKit/EpicSaves.swift@@ -0,0 +1,165 @@+import Foundation+import os++/// Epic cloud saves, through legendary's `sync-saves`, before and after a Windows Epic game plays.+///+/// legendary decides by age alone: whichever of the newest local file and the newest cloud save is+/// newer wins, with no notion of both having changed (legendary/cli.py `sync_saves`). A download+/// empties the save folder first (`download_saves(clean_dir=True)`); an upload adds a save to+/// Epic's cloud, which keeps the earlier ones. So here:+/// - the folder legendary resolves (from the game's CloudSaveFolder, inside the environment's+/// registry) is copied before any download (SaveBackups), and a failed copy stops it;+/// - a download over saves changed since Highball last synced them is a conflict, asked, never+/// decided by age;+/// - an upload needs no copy: the cloud keeps what it had.+/// legendary runs with `-y` (it would otherwise stop at a question with no terminal to answer)+/// and `--accept-path` (to take the path it resolved).+public struct EpicSaves: Sendable {+ public let store: EpicStore+ public init(store: EpicStore) { self.store = store }++ public enum Direction: Sendable { case download, upload, forceDownload, forceUpload }++ public enum Outcome: Sendable, Equatable {+ case synced+ /// Saves changed on the Mac since the last sync, and the cloud has newer ones: nothing+ /// moved, the player chooses.+ case conflict+ case failed(String)+ }++ /// What legendary found, from its log; nil when it said nothing about this game (no cloud+ /// saves, or no save folder it could resolve).+ public enum State: Sendable, Equatable { case nothing, inStep, cloudNewer, localNewer }++ static func state(in lines: [String]) -> State? {+ for line in lines {+ if line.contains("No cloud or local savegame found") { return .nothing }+ if line.contains("is up to date") { return .inStep }+ if line.contains("Cloud save for"), line.contains("is newer") { return .cloudNewer }+ if line.contains("Local save for"), line.contains("is newer") { return .localNewer }+ }+ return nil+ }++ /// legendary's lines for something it could not do and carried on past.+ static func isFailure(_ line: String) -> Bool { line.contains(" ERROR: ") || line.contains(" CRITICAL: ") }++ static func arguments(app: String, direction: Direction?) -> [String] {+ let flags: [String]+ switch direction {+ case nil: flags = ["--skip-upload", "--skip-download"] // only resolve the folder and compare+ case .download?: flags = ["--skip-upload"]+ case .upload?: flags = ["--skip-download"]+ case .forceDownload?: flags = ["--force-download"]+ case .forceUpload?: flags = ["--force-upload"]+ }+ return ["sync-saves", app, "-y", "--accept-path"] + flags+ }++ /// Whether the game's catalog item names a cloud save folder for Windows, from the metadata+ /// legendary keeps (metadata/<app>.json customAttributes.CloudSaveFolder).+ public func supportsCloudSaves(_ app: String) -> Bool {+ let file = store.configDir.appending(path: "metadata/\(app).json")+ guard let data = try? Data(contentsOf: file),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let attributes = (obj["metadata"] as? [String: Any])?["customAttributes"] as? [String: Any],+ let folder = (attributes["CloudSaveFolder"] as? [String: Any])?["value"] as? String else { return false }+ return !folder.isEmpty+ }++ // MARK: Sync++ /// Copies kept before a download (SaveBackups), beside GOG's.+ public var backups: SaveBackups { SaveBackups(root: store.configDir.deletingLastPathComponent().appending(path: "save-backups", directoryHint: .isDirectory)) }++ var lastSyncsFile: URL { store.configDir.deletingLastPathComponent().appending(path: "epic-saves.json") }++ /// When each install's saves were last in step with the cloud: per install, like GOG's.+ func lastSyncs() -> [String: Date] {+ let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601+ return (try? decoder.decode([String: Date].self, from: Data(contentsOf: lastSyncsFile))) ?? [:]+ }++ private static let lastSyncsLock = NSLock()+ private func noteSynced(_ key: String) {+ Self.lastSyncsLock.withLock {+ var all = lastSyncs()+ all[key] = Date()+ let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys]+ try? encoder.encode(all).write(to: lastSyncsFile, options: .atomic)+ }+ }++ /// Syncs a Windows Epic game's saves. `prefix` is the environment it is installed in, which+ /// legendary reads to resolve the save folder; `install` keys the backups and sync history.+ public func sync(_ app: String, install: URL, prefix: URL, direction: Direction,+ onLine: (@Sendable (String) -> Void)? = nil) -> Outcome {+ let key = "\(app)@\(install.standardizedFileURL.path)"+ let environment = ["WINEPREFIX": prefix.path]+ // First, only where the saves are and which side is newer: nothing moves.+ let lines = OSAllocatedUnfairLock(initialState: [String]())+ let checked: Int32+ do {+ checked = try store.runStreaming(Self.arguments(app: app, direction: nil), environment: environment) { line in+ lines.withLock { $0.append(line) }+ onLine?(line)+ }+ } catch { return .failed(error.localizedDescription) }+ let log = lines.withLock { $0 }+ guard checked == 0, !log.contains(where: Self.isFailure) else { return .failed("legendary could not compare the saves") }+ guard let state = Self.state(in: log) else { return .failed("legendary found no save folder for this game") }+ guard let folder = (try? store.installedGames())?.first(where: { $0.app_name == app })?.save_path.map({ URL(fileURLWithPath: $0) })+ else { return .failed("legendary kept no save folder for this game") }++ let downloads: Bool+ switch Self.decide(state, direction: direction, lastChange: Self.latestChange(in: folder), lastSync: lastSyncs()[key]) {+ case .inStep: noteSynced(key); return .synced+ case .leave: return .synced+ case .conflict: return .conflict+ case .transfer(let download): downloads = download+ }+ if downloads {+ do { try backups.backUpLocal(folder, into: backups.folder("epic-\(app)", install: install)) } catch {+ return .failed("the saves could not be backed up first (\(error.localizedDescription)), so nothing was synced")+ }+ }+ let failed = OSAllocatedUnfairLock(initialState: false)+ let status: Int32+ do {+ status = try store.runStreaming(Self.arguments(app: app, direction: direction), environment: environment) { line in+ if Self.isFailure(line) { failed.withLock { $0 = true } }+ onLine?(line)+ }+ } catch { return .failed(error.localizedDescription) }+ guard status == 0, !failed.withLock({ $0 }) else { return .failed("legendary sync-saves did not finish (status \(status))") }+ noteSynced(key)+ return .synced+ }++ enum Decision: Equatable { case inStep, leave, conflict, transfer(download: Bool) }++ /// What a sync does once legendary has compared the two sides. A download over saves changed+ /// here since the last sync (or never synced) is a conflict: legendary would let the newer+ /// side win and empty the folder. Newer here before Play, or newer in the cloud after the+ /// game, is left for the other direction to take.+ static func decide(_ state: State, direction: Direction, lastChange: Date?, lastSync: Date?) -> Decision {+ switch direction {+ case .forceDownload: return .transfer(download: true)+ case .forceUpload: return .transfer(download: false)+ case .download:+ if state == .nothing || state == .inStep { return .inStep }+ guard state == .cloudNewer else { return .leave }+ let changedHere = lastChange.map { change in lastSync.map { change > $0.addingTimeInterval(60) } ?? true } ?? false+ return changedHere ? .conflict : .transfer(download: true)+ case .upload:+ if state == .nothing || state == .inStep { return .inStep }+ return state == .localNewer ? .transfer(download: false) : .leave+ }+ }++ /// The newest change among a folder's files, nil when it holds none.+ static func latestChange(in folder: URL) -> Date? {+ SaveBackups.files(in: folder).compactMap { try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate }.max()+ }+}diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swiftindex 0512165..1cb4e3c 100644--- a/Sources/HighballKit/EpicStore.swift+++ b/Sources/HighballKit/EpicStore.swift@@ -61,14 +61,15 @@ public struct EpicStore: Sendable {}/// Runs legendary streaming each output line (installs are long and progress matters).- /// `control` lets the caller stop it the way Ctrl-C in a terminal does.+ /// `control` lets the caller stop it the way Ctrl-C in a terminal does; `extra` adds to its+ /// environment (WINEPREFIX, for a save folder legendary resolves inside an environment).@discardableResult- public func runStreaming(_ args: [String], control: LegendaryControl? = nil,+ public func runStreaming(_ args: [String], control: LegendaryControl? = nil, environment extra: [String: String] = [:],onLine: (@Sendable (String) -> Void)? = nil) throws -> Int32 {let p = Process()p.executableURL = binaryp.arguments = args- p.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }+ p.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }.merging(extra) { $1 }let pipe = Pipe()p.standardOutput = pipep.standardError = pipe@@ -153,6 +154,8 @@ public struct EpicStore: Sendable {public struct InstalledGame: Codable, Sendable {public let app_name: Stringpublic let install_path: String?+ /// Where the game keeps the saves legendary syncs, once it has resolved it (EpicSaves).+ public var save_path: String? = nil}/// Everything legendary has installed, with where. Legendary's install state is globaldiff --git a/Sources/HighballKit/SaveBackups.swift b/Sources/HighballKit/SaveBackups.swiftnew file mode 100644index 0000000..a562a9d--- /dev/null+++ b/Sources/HighballKit/SaveBackups.swift@@ -0,0 +1,108 @@+import Foundation++/// Copies of a game's saves taken before a sync could replace them, in the Highball folder:+/// save-backups/<game>-<location>-<install>/<date>-<mac|cloud>/. Store tools replace saves+/// wholesale (gogdl deletes what the other side lacks, legendary empties the folder before a+/// download), so whatever a sync could replace is copied first, and a failed copy stops the sync.+/// The newest `keep` copies per install and location stay.+public struct SaveBackups: Sendable {+ public let root: URL+ static let keep = 10++ public init(root: URL) { self.root = root }++ /// One install's backups of one location: the install is in the name, so a second copy of the+ /// game never rotates out the first one's backups.+ public func folder(_ name: String, install: URL) -> URL {+ // FNV-1a over the install's path: short, and the same from one run to the next.+ let hash = install.standardizedFileURL.path.utf8.reduce(UInt64(0xcbf2_9ce4_8422_2325)) { ($0 ^ UInt64($1)) &* 0x100_0000_01b3 }+ return root.appending(path: "\(name)-\(String(hash, radix: 16).prefix(8))", directoryHint: .isDirectory)+ }++ private func newBackup(in dir: URL, label: String) -> URL {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ let stamp = formatter.string(from: Date()).replacingOccurrences(of: ":", with: "")+ var name = "\(stamp)-\(label)", n = 1+ while FileManager.default.fileExists(atPath: dir.appending(path: name).path) { n += 1; name = "\(stamp)-\(label)-\(n)" }+ return dir.appending(path: name, directoryHint: .isDirectory)+ }++ /// Every file a sync sees: hidden files and links too, which the store tools replace or delete.+ public static func files(in folder: URL) -> [URL] {+ let keys: Set<URLResourceKey> = [.isRegularFileKey, .isSymbolicLinkKey]+ let walker = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: Array(keys))+ var files: [URL] = []+ while let file = walker?.nextObject() as? URL {+ let values = try? file.resourceValues(forKeys: keys)+ if values?.isRegularFile == true || values?.isSymbolicLink == true { files.append(file) }+ }+ return files+ }++ /// What a folder holds, in brief (files, bytes, latest change): two equal mean a new copy would+ /// only repeat the last one.+ static func fingerprint(_ folder: URL) -> String {+ let keys: Set<URLResourceKey> = [.fileSizeKey, .contentModificationDateKey]+ let values = files(in: folder).map { try? $0.resourceValues(forKeys: keys) }+ let bytes = values.reduce(0) { $0 + ($1?.fileSize ?? 0) }+ let latest = values.compactMap { $0?.contentModificationDate?.timeIntervalSince1970 }.max() ?? 0+ return "\(values.count) \(bytes) \(latest)"+ }++ /// Beside a copy, not in it: a copy restored by hand never carries it into the game's folder,+ /// where a sync would upload it with the saves.+ static func fingerprintFile(of backup: URL) -> URL {+ backup.deletingLastPathComponent().appending(path: backup.lastPathComponent + ".fingerprint")+ }++ /// A copy of the saves on the Mac, before a download could replace them: the newest copy when+ /// nothing changed since it, nil when there is nothing to copy. Throws when the copy fails, and+ /// leaves no half copy behind: then nothing may replace them.+ @discardableResult+ public func backUpLocal(_ folder: URL, into dir: URL) throws -> URL? {+ guard !Self.files(in: folder).isEmpty else { return nil }+ 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 backUp(into: dir, label: "mac") { partial in+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: folder, to: partial)+ }+ try? fingerprint.write(to: Self.fingerprintFile(of: target), atomically: true, encoding: .utf8)+ return target+ }++ /// A new copy, filled by `fill` under a ".partial" name and given its own name only once+ /// complete, so a failed copy never sits among the real ones; then the newest `keep` stay,+ /// never this one.+ public func backUp(into dir: URL, label: String, fill: (URL) throws -> Void) throws -> URL {+ let target = newBackup(in: dir, label: label)+ 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.+ 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: dir).filter({ $0.lastPathComponent != target.lastPathComponent }).dropFirst(Self.keep - 1) {+ try? FileManager.default.removeItem(at: old)+ try? FileManager.default.removeItem(at: Self.fingerprintFile(of: old))+ }+ return target+ }++ /// A location's complete backups, newest first by when they were made (not by name: a Mac+ /// whose clock was wrong once must not prune today's copy as the oldest).+ public 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) }+ }+}diff --git a/Tests/HighballKitTests/EpicSavesTests.swift b/Tests/HighballKitTests/EpicSavesTests.swiftnew file mode 100644index 0000000..d8b2d15--- /dev/null+++ b/Tests/HighballKitTests/EpicSavesTests.swift@@ -0,0 +1,59 @@+import XCTest+@testable import HighballKit++/// Epic cloud saves through legendary's sync-saves (EpicSaves): what legendary found, what a sync+/// then does, and that nothing replaces the Mac's saves without a copy and, when both changed, a+/// question.+final class EpicSavesTests: XCTestCase {+ /// legendary's log lines, as 0.21.0 writes them (legendary/cli.py sync_saves).+ func testStateComesFromLegendarysLog() {+ XCTAssertEqual(EpicSaves.state(in: ["[cli] INFO: No cloud or local savegame found."]), .nothing)+ XCTAssertEqual(EpicSaves.state(in: [#"[cli] INFO: Save game for "Game" is up to date, skipping..."#]), .inStep)+ XCTAssertEqual(EpicSaves.state(in: [#"[cli] INFO: Cloud save for "Game" is newer:"#, "[cli] INFO: - Cloud save date: 2026-10-31 12:00:00"]), .cloudNewer)+ XCTAssertEqual(EpicSaves.state(in: [#"[cli] INFO: Local save for "Game" is newer"#]), .localNewer)+ XCTAssertNil(EpicSaves.state(in: ["[cli] INFO: Got 0 remote save game(s)"]), "said nothing about the game: no folder resolved")+ XCTAssertTrue(EpicSaves.isFailure("[Core] ERROR: Failed to download save"))+ }++ /// Always -y and --accept-path: legendary would otherwise stop at a question no one can answer.+ func testArguments() {+ XCTAssertEqual(EpicSaves.arguments(app: "Garlic", direction: nil),+ ["sync-saves", "Garlic", "-y", "--accept-path", "--skip-upload", "--skip-download"])+ XCTAssertEqual(EpicSaves.arguments(app: "Garlic", direction: .download).suffix(1), ["--skip-upload"])+ XCTAssertEqual(EpicSaves.arguments(app: "Garlic", direction: .upload).suffix(1), ["--skip-download"])+ XCTAssertEqual(EpicSaves.arguments(app: "Garlic", direction: .forceDownload).suffix(1), ["--force-download"])+ }++ /// A download over saves changed since the last sync is asked, never decided by age.+ func testADownloadOverChangedSavesIsAConflict() {+ let synced = Date(timeIntervalSince1970: 1_790_000_000)+ let later = synced.addingTimeInterval(3_600)+ XCTAssertEqual(EpicSaves.decide(.cloudNewer, direction: .download, lastChange: later, lastSync: synced), .conflict)+ XCTAssertEqual(EpicSaves.decide(.cloudNewer, direction: .download, lastChange: later, lastSync: nil), .conflict, "never synced: asked")+ XCTAssertEqual(EpicSaves.decide(.cloudNewer, direction: .download, lastChange: synced, lastSync: synced), .transfer(download: true))+ XCTAssertEqual(EpicSaves.decide(.cloudNewer, direction: .download, lastChange: nil, lastSync: nil), .transfer(download: true), "nothing here to lose")+ }++ func testEachDirectionTakesOnlyItsOwnSide() {+ XCTAssertEqual(EpicSaves.decide(.localNewer, direction: .download, lastChange: nil, lastSync: nil), .leave)+ XCTAssertEqual(EpicSaves.decide(.cloudNewer, direction: .upload, lastChange: nil, lastSync: nil), .leave)+ XCTAssertEqual(EpicSaves.decide(.localNewer, direction: .upload, lastChange: nil, lastSync: nil), .transfer(download: false))+ XCTAssertEqual(EpicSaves.decide(.inStep, direction: .download, lastChange: nil, lastSync: nil), .inStep)+ XCTAssertEqual(EpicSaves.decide(.inStep, direction: .forceUpload, lastChange: nil, lastSync: nil), .transfer(download: false))+ }++ /// Cloud saves are a game's when its catalog item names a folder for them.+ func testCloudSaveSupportComesFromLegendarysMetadata() throws {+ let home = FileManager.default.temporaryDirectory.appending(path: "epic-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: home) }+ let saves = EpicSaves(store: EpicStore(paths: HighballPaths(home: home)))+ let metadata = home.appending(path: "legendary/metadata")+ try FileManager.default.createDirectory(at: metadata, withIntermediateDirectories: true)+ try #"{"app_name":"Garlic","metadata":{"customAttributes":{"CloudSaveFolder":{"type":"STRING","value":"{AppData}/../LocalLow/Dodge Roll/Enter the Gungeon"}}}}"#+ .write(to: metadata.appending(path: "Garlic.json"), atomically: true, encoding: .utf8)+ try #"{"app_name":"Duck","metadata":{"customAttributes":{}}}"#.write(to: metadata.appending(path: "Duck.json"), atomically: true, encoding: .utf8)+ XCTAssertTrue(saves.supportsCloudSaves("Garlic"))+ XCTAssertFalse(saves.supportsCloudSaves("Duck"))+ XCTAssertFalse(saves.supportsCloudSaves("Missing"))+ }+}