Skip to content

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

Epic saves: an uninstall waits for legendary's record, older installs copy what no manifest names, Stop during Keep stops

Gabe99de32598632
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 1fe8f24..fbecfd6 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -3445,12 +3445,33 @@ final class AppState {
}
}
+ /// An Epic game the player is asked about before it is removed: nothing tells the files the
+ /// game wrote in its install folder from legendary's (no manifest, and installed before
+ /// Highball kept a history), so Keep can't copy them. Nothing is removed until they agree.
+ struct EpicRemovalWithoutCopy {
+ let app: String
+ let title: String
+ let bottle: Bottle
+ }
+ var epicRemovalWithoutCopy: EpicRemovalWithoutCopy?
+
+ /// The player agreed to remove the Epic game without a copy of its install folder.
+ func epicRemoveWithoutCopy() {
+ guard let pending = epicRemovalWithoutCopy else { return }
+ epicRemovalWithoutCopy = nil
+ appendLog("\(pending.title): removing it without a copy of what it wrote in its folder, as asked")
+ epicUninstall(pending.app, title: pending.title, in: pending.bottle, deleteSaves: false, agreed: true)
+ }
+
/// Removes an Epic game through legendary, so its library stays right. Keep save data (the
/// default) first copies, as kept backups, the game's Epic save folder and every file the game
- /// wrote in its install folder since Highball installed it, and stops if a copy fails; a later
- /// install is offered them back. `deleteSaves` copies nothing and also deletes the save folder
- /// when it lies inside the environment (EpicSaves.removeSaves).
- private func epicUninstall(_ app: String, title: String, in bottle: Bottle, deleteSaves: Bool) {
+ /// wrote in its install folder (EpicSaves.gameFiles), and stops if a copy fails; a later
+ /// install is offered them back. When nothing tells the game's files apart, the player is
+ /// asked first (epicRemovalWithoutCopy); `agreed` is their go-ahead. `deleteSaves` copies
+ /// nothing and also deletes the save folder when it lies inside the environment
+ /// (EpicSaves.removeSaves). What follows the uninstall waits for legendary's record of the
+ /// game to be gone, not the folder: legendary leaves the folder when the game wrote files in it.
+ private func epicUninstall(_ app: String, title: String, in bottle: Bottle, deleteSaves: Bool, agreed: Bool = false) {
let store = epicStore
let install = epicInstalls[app].map { URL(fileURLWithPath: $0, isDirectory: true) }
// Resolving the save folder runs legendary's sync-saves (moving nothing), which a player
@@ -3466,11 +3487,22 @@ final class AppState {
if let install, EpicStore.isInstalled(path: install.path, inDriveC: bottle.driveC) {
stage = L("Finding the game's saves")
saveFolder = await Task.detached { saves.uninstallSaveFolder(app, install: install, prefix: prefix, resolve: resolve, onLine: log) }.value
+ try checkStopped()
if !deleteSaves {
+ let gameFiles = await Task.detached { saves.gameFiles(app, install: install, prefix: prefix) }.value
+ try checkStopped()
+ if gameFiles == nil, !agreed {
+ epicRemovalWithoutCopy = EpicRemovalWithoutCopy(app: app, title: title, bottle: bottle)
+ busyDoneOverride = .handedOff // the question takes over; nothing was removed
+ return
+ }
// These would go with the game, so they are copied before anything runs, and a
// failed copy stops the removal. Never pruned.
stage = L("Keeping a copy of the game's saves")
- kept = try await Task.detached { try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: saveFolder) }.value
+ kept = try await Task.detached {
+ try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: saveFolder, gameFiles: gameFiles)
+ }.value
+ try checkStopped() // a detached copy runs on through a Stop: nothing is removed after one
for entry in kept {
let (files, bytes) = SaveBackups.contents(of: entry.backup)
let what = entry.name == EpicSaves.gameFolderName ? "the game wrote in its folder" : "in its save folder"
@@ -3478,19 +3510,34 @@ final class AppState {
}
}
}
+ try checkStopped()
appendLog("\(title): asking the Epic tools to uninstall it")
_ = try await Task.detached { try store.uninstall(app, onLine: log) }.value
- if let install, !FileManager.default.fileExists(atPath: install.path) {
+ // legendary's records unreadable: the folder vanishing is all there is to go by.
+ let uninstalled = store.isRecorded(app).map { !$0 } ?? install.map { !FileManager.default.fileExists(atPath: $0.path) } ?? false
+ if install != nil, !uninstalled {
+ appendLog("\(title): the Epic tools still list it as installed, so no saves were kept or deleted")
+ }
+ if let install, uninstalled {
EpicSaves.forgetHistory(app: app, driveC: bottle.driveC)
- if deleteSaves, let saveFolder, !EpicSaves.isInside(saveFolder, roots: [install]) {
+ if deleteSaves, let saveFolder {
if saves.removeSaves(app, folder: saveFolder, install: install, prefix: prefix) {
appendLog("\(title): saves at \(saveFolder.path) deleted, as asked")
} else if FileManager.default.fileExists(atPath: saveFolder.path) {
appendLog("\(title): saves at \(saveFolder.path) left in place: they are outside this environment, or hold other things Highball keeps")
}
}
- // Recorded once the folder is gone, so this install is never offered its own saves.
+ // Recorded once legendary's record is gone, so this install is never offered its own saves.
saves.keep(kept, of: app)
+ // What legendary didn't install keeps its folder, which a reinstall there can't use.
+ if FileManager.default.fileExists(atPath: install.path) {
+ let others = ((try? store.installedGames()) ?? []).compactMap { $0.install_path.map { URL(fileURLWithPath: $0) } }
+ if saves.removeLeftover(install, prefix: bottle.url, stillInstalled: others) {
+ appendLog("\(title): removed the folder the Epic tools left at \(install.path)")
+ } else {
+ appendLog("\(title): the Epic tools left \(install.path), with files they didn't install; Highball leaves it, as it holds more than this game")
+ }
+ }
}
await MainActor.run { self.refresh() }
}
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index 22ff277..ef92f7d 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -257,6 +257,7 @@ struct ContentView: View {
.sheet(isPresented: $state.showGOGSignIn) { GOGSignInSheet() }
.gogSaveConflictAsk(state)
.gogRemovalWithoutBackupAsk(state)
+ .epicRemovalWithoutCopyAsk(state)
.gogPutBackSavesAsk(state)
.epicPutBackSavesAsk(state)
.sheet(item: $state.engineTransition) { t in EngineTransitionSheet(transition: t) }
@@ -636,6 +637,19 @@ private extension View {
decideLater].joined(separator: " ")
}
+ /// Nothing tells the files an Epic game wrote in its folder from legendary's, so Keep can't
+ /// copy them. Nothing is removed unless the player agrees.
+ @MainActor func epicRemovalWithoutCopyAsk(_ state: AppState) -> some View {
+ self.alert(state.epicRemovalWithoutCopy.map { String(format: L("Remove %@ without a copy of its folder?"), $0.title) } ?? "",
+ isPresented: .init(get: { state.epicRemovalWithoutCopy != nil }, set: { if !$0 { state.epicRemovalWithoutCopy = nil } }),
+ presenting: state.epicRemovalWithoutCopy) { _ in
+ Button(L("Remove anyway"), role: .destructive) { state.epicRemoveWithoutCopy() }
+ Button(L("Cancel"), role: .cancel) { state.epicRemovalWithoutCopy = nil }
+ } message: { pending in
+ Text(String(format: L("Highball can't tell which files in %@'s folder the game wrote: the Epic tools have no file list for it, and it was installed before Highball kept a record of installs. Its save folder is still copied to save-backups first, but any other save the game kept in its folder is deleted with it. Saves in Epic'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.")
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index a854b45..8f10523 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -258,6 +258,9 @@ enum L10n {
"Put back your saves from %@?": "Remettre vos sauvegardes du %@ ?",
"Put them back": "Les remettre",
"Don't ask again": "Ne plus demander",
+ "Remove %@ without a copy of its folder?": "Supprimer %@ sans copie de son dossier ?",
+ "Highball can't tell which files in %@'s folder the game wrote: the Epic tools have no file list for it, and it was installed before Highball kept a record of installs. Its save folder is still copied to save-backups first, but any other save the game kept in its folder is deleted with it. Saves in Epic's cloud are not affected.":
+ "Highball ne peut pas savoir quels fichiers du dossier de %@ le jeu a écrits : les outils Epic n’en ont pas la liste, et il a été installé avant que Highball ne garde une trace des installations. Son dossier de sauvegardes est tout de même copié d’abord dans save-backups, mais toute autre sauvegarde que le jeu gardait dans son dossier est supprimée avec lui. Les sauvegardes dans le cloud Epic ne sont pas touchées.",
"Highball kept %@'s saves when it was removed. Put them back copies them into the game's folder; anything already there is copied to save-backups first. Not now asks again the next time Highball starts.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie dans le dossier du jeu ; ce qui s’y trouve déjà est d’abord copié dans save-backups. Pas maintenant redemandera au prochain lancement de Highball.",
"Highball kept %@'s saves when it was removed. Put them back copies them to where they were; anything already there is copied to save-backups first. Not now asks again the next time Highball starts.": "Highball a gardé les sauvegardes de %@ lors de sa suppression. Les remettre les copie là où elles étaient ; ce qui s’y trouve déjà est d’abord copié dans save-backups. Pas maintenant redemandera au prochain lancement de Highball.",
"Highball couldn't reach GOG to find out where %@ keeps its saves, and can't tell which files in the game's folder the game wrote, because nothing records when it was installed. So nothing in the game's folder is copied first, and saves there are deleted with it. Saves already in GOG's cloud are not affected. To keep its save folders, cancel and try again once GOG can be reached.":
diff --git a/Sources/HighballKit/EpicSaves.swift b/Sources/HighballKit/EpicSaves.swift
index 73d4e63..0e6a524 100644
--- a/Sources/HighballKit/EpicSaves.swift
+++ b/Sources/HighballKit/EpicSaves.swift
@@ -609,24 +609,77 @@ extension EpicSaves {
return usable(savePath(app))
}
+ /// How an uninstall tells the files the game wrote in its install folder from the ones
+ /// legendary put down.
+ public struct GameFiles: Sendable, Equatable {
+ /// The files legendary's installed manifests name there (the game's and its DLC's, which
+ /// share the folder), lowercased: Windows names ignore case. nil when it had none.
+ public let installed: Set<String>?
+ /// When Highball installed the game and ran legendary over it (no firstSetup for an
+ /// install from before the history was kept).
+ public let history: GameInstallHistory
+
+ /// A file no manifest names is the game's; so is one changed after Highball installed the
+ /// game outside legendary's runs (a config the game rewrote).
+ public func isGameWritten(_ relativePath: String, changed: Date?) -> Bool {
+ if let installed, !installed.contains(relativePath.lowercased()) { return true }
+ return history.isGameWritten(changed ?? .distantPast)
+ }
+ }
+
+ /// What tells the game's files in its install folder apart: legendary's manifests, while the
+ /// game is installed, and the install history. nil when there is neither, and then nothing
+ /// in the install folder can be copied as the game's.
+ public func gameFiles(_ app: String, install: URL, prefix: URL) -> GameFiles? {
+ let history = Self.history(app: app, driveC: prefix.appending(path: "drive_c"))
+ let installed = manifestFiles(app, install: install)
+ guard installed != nil || history.firstSetup != nil else { return nil }
+ return GameFiles(installed: installed, history: history)
+ }
+
+ /// The files legendary's manifests name in the install folder, for the game and every DLC
+ /// legendary records in the same folder. nil when any of them can't be listed, or names none
+ /// of the files on disk (an encrypted manifest lists obfuscated names), so the installer's
+ /// files are never taken for the game's.
+ func manifestFiles(_ app: String, install: URL) -> Set<String>? {
+ let path = install.standardizedFileURL.path
+ let sharing = (store.installRecords() ?? [:]).filter { URL(fileURLWithPath: $0.value).standardizedFileURL.path == path }.keys
+ let onDisk = Set(SaveBackups.files(in: install).map { SaveBackups.relativePath($0, in: install).lowercased() })
+ var names = Set<String>()
+ for each in Set(sharing).union([app]).sorted() {
+ guard let files = try? store.installedFiles(each) else { return nil }
+ let listed = Set(files.map { $0.replacingOccurrences(of: "\\", with: "/").lowercased() })
+ guard !listed.isDisjoint(with: onDisk) else { return nil }
+ names.formUnion(listed)
+ }
+ return names
+ }
+
/// Before an uninstall, copies as kept backups (never pruned): the save folder's files the
/// catalog's include and exclude lists pick, when `saveFolder` is given, and every file the
- /// game wrote in its install folder since Highball installed it there, outside the runs that
- /// installed over it (history), leaving out the save folder. Never installed through Highball
- /// here: no install-folder copy. Returns what was kept, each with where it came from; throws
- /// when a copy fails, and the uninstall must then stop.
+ /// game wrote in its install folder (gameFiles), leaving out the save folder. Nothing tells
+ /// them apart: no install-folder copy. Returns what was kept, each with where it came from;
+ /// throws when a copy fails, and the uninstall must then stop.
public func backUpForUninstall(_ app: String, install: URL, prefix: URL, saveFolder: URL?) throws -> [KeptSaves.Entry] {
+ try backUpForUninstall(app, install: install, prefix: prefix, saveFolder: saveFolder,
+ gameFiles: gameFiles(app, install: install, prefix: prefix))
+ }
+
+ /// The same, with what gameFiles found (an uninstall asks first when it is nil).
+ public func backUpForUninstall(_ app: String, install: URL, prefix: URL, saveFolder: URL?,
+ gameFiles: GameFiles?) throws -> [KeptSaves.Entry] {
var kept: [KeptSaves.Entry] = []
if let saveFolder,
let copy = try backups.backUpLocal(saveFolder, into: backupFolder(app, Self.savesName, install: install),
filter: catalog(app)?.filter ?? .everything, kept: true) {
kept.append(KeptSaves.Entry(name: Self.savesName, folder: saveFolder, backup: copy, install: install, environment: prefix))
}
- let history = Self.history(app: app, driveC: prefix.appending(path: "drive_c"))
- guard history.firstSetup != nil else { return kept }
+ guard let gameFiles else { return kept }
let skipped = saveFolder.map { $0.standardizedFileURL.path + "/" }
- let written = try SaveBackups.files(in: install, writtenPer: history).filter { file in
- skipped.map { !file.standardizedFileURL.path.hasPrefix($0) } ?? true
+ let written = try SaveBackups.walk(install).filter { file in
+ guard skipped.map({ !file.standardizedFileURL.path.hasPrefix($0) }) ?? true else { return false }
+ let changed = try? file.resolvingSymlinksInPath().resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ return gameFiles.isGameWritten(SaveBackups.relativePath(file, in: install), changed: changed)
}
if !written.isEmpty,
let copy = try backups.backUpLocal(install, into: backupFolder(app, Self.gameFolderName, install: install), kept: true, only: written) {
@@ -638,11 +691,14 @@ extension EpicSaves {
/// For a player who asked for the saves to go with the game: deletes the save folder (only
/// the files the include and exclude lists pick, when the catalog has them) when, links
/// followed, it lies inside the environment's drive_c and neither holds nor sits inside
- /// Highball's save-backups or the install folder (which the uninstall removes anyway).
+ /// Highball's save-backups, nor holds the install folder. One inside the install folder is
+ /// deleted too: legendary deletes only the files it installed, so the saves stay otherwise.
/// Returns whether it was deleted.
public func removeSaves(_ app: String, folder: URL, install: URL, prefix: URL) -> Bool {
+ let inInstall = Self.isInside(folder, roots: [install]) && Self.components(folder) != Self.components(install)
guard FileManager.default.fileExists(atPath: folder.path),
- SaveBackups.mayDelete(folder, driveC: prefix.appending(path: "drive_c"), sparing: [backups.root, install]) else { return false }
+ SaveBackups.mayDelete(folder, driveC: prefix.appending(path: "drive_c"),
+ sparing: inInstall ? [backups.root] : [backups.root, install]) else { return false }
let filter = catalog(app)?.filter ?? .everything
if filter.isEverything { return (try? FileManager.default.removeItem(at: folder)) != nil }
for file in SaveBackups.files(in: folder, matching: filter) {
@@ -651,6 +707,22 @@ extension EpicSaves {
return true
}
+ /// legendary leaves an uninstalled game's folder behind when anything it didn't install is in
+ /// it (a log, a config, a save), and installing the game there again then fails. Once its
+ /// record is gone and what was worth keeping is copied, the folder goes too, but only one at
+ /// least two levels inside the environment's drive_c, never under its users or windows
+ /// folders, holding no game legendary still has installed, and never Highball's
+ /// save-backups. Whether it was removed.
+ public func removeLeftover(_ install: URL, prefix: URL, stillInstalled: [URL]) -> Bool {
+ let driveC = prefix.appending(path: "drive_c")
+ let inside = Self.components(install).dropFirst(Self.components(driveC).count).map { $0.lowercased() }
+ guard FileManager.default.fileExists(atPath: install.path), inside.count >= 2,
+ !["users", "windows"].contains(inside[0]),
+ !stillInstalled.contains(where: { Self.isInside($0, roots: [install]) }),
+ SaveBackups.mayDelete(install, driveC: driveC, sparing: [backups.root]) else { return false }
+ return (try? FileManager.default.removeItem(at: install)) != nil
+ }
+
var keptSavesFile: KeptSavesFile { KeptSavesFile(url: store.configDir.deletingLastPathComponent().appending(path: "epic-kept-saves.json")) }
/// Remembers what an uninstall kept of the game, in place of what an earlier one kept.
diff --git a/Sources/HighballKit/EpicStore.swift b/Sources/HighballKit/EpicStore.swift
index 1cb4e3c..58be246 100644
--- a/Sources/HighballKit/EpicStore.swift
+++ b/Sources/HighballKit/EpicStore.swift
@@ -167,6 +167,36 @@ public struct EpicStore: Sendable {
return try JSONDecoder().decode([InstalledGame].self, from: Data(out.utf8))
}
+ /// Legendary's own install records (installed.json in its config folder), app name to install
+ /// path, read without running it. Empty when legendary has installed nothing; nil when the
+ /// file is there but can't be read.
+ public func installRecords() -> [String: String]? {
+ let file = configDir.appending(path: "installed.json")
+ guard FileManager.default.fileExists(atPath: file.path) else { return [:] }
+ guard let data = try? Data(contentsOf: file),
+ let all = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
+ return all.mapValues { (($0 as? [String: Any])?["install_path"] as? String) ?? "" }
+ }
+
+ /// Whether legendary still records the game as installed; nil when its records can't be
+ /// read. An uninstall is done when the record is gone: legendary deletes the files its
+ /// manifest names, then removes the folder only if nothing else is left in it (core.py
+ /// `uninstall_game`, `delete_filelist`), so a log, a config or a save keeps the folder.
+ public func isRecorded(_ appName: String) -> Bool? {
+ installRecords().map { $0[appName] != nil }
+ }
+
+ /// The files legendary installed for a game, by its installed manifest, as paths relative to
+ /// the install folder. Read locally, with no sign-in, while the game is installed (cli.py
+ /// `list_files` loads the installed manifest unless asked to download one). Throws when
+ /// legendary has no manifest for it.
+ public func installedFiles(_ appName: String) throws -> [String] {
+ struct File: Decodable { let filename: String }
+ let out = try capture(Self.listFilesArguments(appName: appName))
+ return try JSONDecoder().decode([File].self, from: Data(out.utf8)).map(\.filename)
+ }
+ static func listFilesArguments(appName: String) -> [String] { ["list-files", appName, "--json"] }
+
/// Legendary's install records, app name to path, keeping only the ones whose folder still
/// exists. Legendary never notices a removed environment or a deleted game folder, and a
/// record it keeps showed Guardians of the Galaxy as installed after its bottle was gone (#63).
diff --git a/Sources/HighballKit/Uninstall.swift b/Sources/HighballKit/Uninstall.swift
index 6483600..8b90652 100644
--- a/Sources/HighballKit/Uninstall.swift
+++ b/Sources/HighballKit/Uninstall.swift
@@ -65,7 +65,7 @@ public enum Uninstall {
case .steam:
return "Steam does the uninstalling and asks you to confirm in its own window, so its library stays right.\(size)"
case .epic:
- return "The Epic tools do the uninstalling, so their library stays right. Keep save data first copies the game's save folder, and every file the game changed in its folder since Highball installed it, to Highball's save-backups, and offers to put them back if you install the game again. Delete save data too copies nothing and also deletes the game's save folder when it is inside this environment. Saves in Epic's cloud stay there either way.\(size)"
+ return "The Epic tools do the uninstalling, so their library stays right. Keep save data first copies the game's save folder, and the files the game wrote in its folder, to Highball's save-backups, and offers to put them back if you install the game again. Delete save data too copies nothing and also deletes the game's save folder when it is inside this environment. Saves in Epic's cloud stay there either way.\(size)"
case .gog:
return "Highball deletes the game's folder from this environment. Keep save data first copies your saves from it, and every file the game changed there since you first played it, to Highball's save-backups, and offers to put them back if you install the game again. Delete save data too copies nothing and also deletes the game's save folders elsewhere in this environment. Saves in GOG's cloud stay there either way, and the game stays in your GOG library to install again.\(size)"
case .windowsUninstaller:
diff --git a/Tests/HighballKitTests/EpicFakeLegendaryTests.swift b/Tests/HighballKitTests/EpicFakeLegendaryTests.swift
index e771f46..dbe8a27 100644
--- a/Tests/HighballKitTests/EpicFakeLegendaryTests.swift
+++ b/Tests/HighballKitTests/EpicFakeLegendaryTests.swift
@@ -248,6 +248,70 @@ final class EpicFakeLegendaryTests: XCTestCase {
XCTAssertNil(read(home.appending(path: "fake-overlap")), "two legendary runs overlapped")
}
+ private func manifest(_ app: String, _ names: [String]) throws {
+ try JSONSerialization.data(withJSONObject: names).write(to: home.appending(path: "fake-manifest-\(app).json"))
+ }
+ private func relative(_ backup: URL) -> [String] { SaveBackups.files(in: backup).map { SaveBackups.relativePath($0, in: backup) } }
+
+ /// An install from before the history was kept: legendary's installed manifests (the game's
+ /// and its DLC's, sharing the folder) tell its files apart, names in any case, and what no
+ /// manifest names is the game's. With no manifest, or one whose names aren't on disk (an
+ /// encrypted one lists obfuscated names), and no history, nothing tells them apart.
+ func testKeepCopiesWhatNoManifestNames() throws {
+ let game: [String: Any] = ["app_name": app, "title": "Game", "install_path": install.path]
+ let dlc: [String: Any] = ["app_name": "GameDLC", "title": "DLC", "install_path": install.path]
+ try JSONSerialization.data(withJSONObject: [app: game, "GameDLC": dlc]).write(to: config.appending(path: "installed.json"))
+ let old = dayAgo.addingTimeInterval(-86_400)
+ for name in ["Game.exe", "Data/base.pak", "DLC/extra.pak", "Config/Default.ini"] {
+ try write("installed", to: install.appending(path: name), at: old)
+ }
+ try write("profile", to: install.appending(path: "Profiles/p1.ini"), at: old)
+ try write("log", to: install.appending(path: "Logs/game.log"), at: hourAgo)
+ XCTAssertNil(saves.gameFiles(app, install: install, prefix: prefix), "no manifest, no history")
+ try manifest(app, ["Game.exe", "data/Base.pak", "Config/Default.ini"])
+ XCTAssertNil(saves.gameFiles(app, install: install, prefix: prefix), "the DLC sharing the folder has no list")
+ try manifest("GameDLC", ["DLC/extra.pak"])
+ let files = try XCTUnwrap(saves.gameFiles(app, install: install, prefix: prefix))
+ XCTAssertNil(files.history.firstSetup)
+ let kept = try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: nil, gameFiles: files)
+ XCTAssertEqual(kept.map(\.name), [EpicSaves.gameFolderName])
+ XCTAssertEqual(relative(kept[0].backup), ["Logs/game.log", "Profiles/p1.ini"], "not what a manifest names")
+
+ try manifest(app, ["0a1b2c", "3d4e5f"])
+ XCTAssertNil(saves.gameFiles(app, install: install, prefix: prefix), "obfuscated names")
+ // With a history too, a file the game rewrote after Highball installed it also counts.
+ try manifest(app, ["Game.exe", "data/Base.pak", "Config/Default.ini"])
+ EpicSaves.recordInstall(app: app, driveC: prefix.appending(path: "drive_c"), start: old.addingTimeInterval(-60), end: old.addingTimeInterval(1), finished: true)
+ try write("rewritten", to: install.appending(path: "Config/Default.ini"), at: hourAgo)
+ let both = try saves.backUpForUninstall(app, install: install, prefix: prefix, saveFolder: nil)
+ XCTAssertEqual(relative(both[0].backup), ["Config/Default.ini", "Logs/game.log", "Profiles/p1.ini"])
+ }
+
+ /// legendary's uninstall deletes the files its manifest names and leaves the folder when the
+ /// game wrote others there, but its record of the game is gone: what an uninstall waits for.
+ /// Delete save data too then deletes a save folder left inside it.
+ func testAnUninstallIsDoneWhenLegendarysRecordIsGone() throws {
+ let store = EpicStore(paths: HighballPaths(home: home))
+ try manifest(app, ["Game.exe", "Data/base.pak"])
+ try write("exe", to: install.appending(path: "Game.exe"), at: dayAgo)
+ try write("pak", to: install.appending(path: "Data/base.pak"), at: dayAgo)
+ try write("save", to: install.appending(path: "Saved/slot1.sav"), at: hourAgo)
+ XCTAssertEqual(store.isRecorded(app), true)
+ XCTAssertEqual(try store.installedFiles(app), ["Game.exe", "Data/base.pak"])
+ XCTAssertEqual(try store.uninstall(app), 0)
+ XCTAssertEqual(store.isRecorded(app), false)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: install.path), "the save keeps the folder")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: install.appending(path: "Data").path))
+ XCTAssertThrowsError(try store.installedFiles(app), "no manifest once uninstalled")
+ XCTAssertTrue(saves.removeSaves(app, folder: install.appending(path: "Saved"), install: install, prefix: prefix))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: install.appending(path: "Saved").path))
+ XCTAssertFalse(saves.removeSaves(app, folder: install, install: install, prefix: prefix), "never the install folder itself")
+ try "not json".write(to: config.appending(path: "installed.json"), atomically: true, encoding: .utf8)
+ XCTAssertNil(store.isRecorded(app), "unreadable records say nothing")
+ try FileManager.default.removeItem(at: config.appending(path: "installed.json"))
+ XCTAssertEqual(store.isRecorded(app), false, "nothing installed")
+ }
+
/// legendary 0.21.0's sync-saves, reduced to what EpicSaves relies on.
static let script = #"""
#!/usr/bin/python3 -I
@@ -257,6 +321,35 @@ final class EpicFakeLegendaryTests: XCTestCase {
args = sys.argv[1:]
debug = args and args[0] == '-v'
if debug: args = args[1:]
+ if args[0] in ('list-files', 'uninstall'):
+ config = os.environ['LEGENDARY_CONFIG_PATH']
+ installed_file = os.path.join(config, 'installed.json')
+ installed = json.load(open(installed_file))
+ app = args[1]
+ manifest = os.path.join(os.path.dirname(config), f'fake-manifest-{app}.json')
+ names = json.load(open(manifest)) if os.path.exists(manifest) else None
+ if args[0] == 'list-files':
+ # cli.py list_files: the installed manifest, read locally; with none on disk,
+ # load_manifest(None) raises and legendary exits non-zero.
+ if app not in installed or names is None: sys.exit(1)
+ print(json.dumps([dict(filename=n, sha_hash='00', install_tags=[], file_size=0, flags=0) for n in names]))
+ sys.exit(0)
+ # core.py uninstall_game, utils.py delete_filelist: the manifest's files, the folders they
+ # leave empty, the root only if nothing else is in it (os.rmdir), then the record.
+ if app not in installed: sys.exit(0)
+ root = installed[app]['install_path']
+ dirs = set()
+ for n in names or []:
+ d = os.path.dirname(n)
+ while d: dirs.add(d); d = os.path.dirname(d)
+ try: os.remove(os.path.join(root, n))
+ except OSError: pass
+ for d in sorted(dirs, key=len, reverse=True) + ['']:
+ try: os.rmdir(os.path.join(root, d))
+ except OSError: pass
+ del installed[app]
+ json.dump(installed, open(installed_file, 'w'))
+ sys.exit(0)
assert args[0] == 'sync-saves', args
app = args[1]
flags = set(args[2:])
diff --git a/Tests/HighballKitTests/EpicUninstallSavesTests.swift b/Tests/HighballKitTests/EpicUninstallSavesTests.swift
index d56ba55..5350a64 100644
--- a/Tests/HighballKitTests/EpicUninstallSavesTests.swift
+++ b/Tests/HighballKitTests/EpicUninstallSavesTests.swift
@@ -93,6 +93,27 @@ final class EpicUninstallSavesTests: XCTestCase {
}
/// A save folder that can't be read stops the removal.
+ /// legendary leaves the game's folder when it holds files it didn't install, and a reinstall
+ /// there fails: once the record is gone the folder goes, but never a shared one.
+ func testTheLeftoverFolderGoesButNeverASharedOne() throws {
+ let prefix = FileManager.default.temporaryDirectory.appending(path: "leftover-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: prefix) }
+ let driveC = prefix.appending(path: "drive_c")
+ let games = driveC.appending(path: "Program Files/Epic Games")
+ let game = games.appending(path: "Game"), other = games.appending(path: "Other")
+ for folder in [game, other, driveC.appending(path: "users/someone/Game")] {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: folder.appending(path: "save.dat"))
+ }
+ let saves = EpicSaves(store: EpicStore(paths: HighballPaths(home: prefix.appending(path: "home"))))
+ XCTAssertFalse(saves.removeLeftover(games, prefix: prefix, stillInstalled: [other]), "holds a game still installed")
+ XCTAssertFalse(saves.removeLeftover(driveC.appending(path: "Program Files"), prefix: prefix, stillInstalled: []), "a folder every game shares")
+ XCTAssertFalse(saves.removeLeftover(driveC.appending(path: "users/someone/Game"), prefix: prefix, stillInstalled: []), "a user folder")
+ XCTAssertTrue(saves.removeLeftover(game, prefix: prefix, stillInstalled: [other]))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: game.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: other.appending(path: "save.dat").path))
+ }
+
func testAFailedCopyThrows() throws {
try write("save", to: folder.appending(path: "Sub/slot1.sav"))
try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: folder.appending(path: "Sub").path)