Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

feat(migration): move a NotProton install to the Bridgeplay 3.0.0 names

raymondchinsbc3db3825a4d
diff --git a/app/Sources/NotProtonApp/Model/BrandMigration.swift b/app/Sources/NotProtonApp/Model/BrandMigration.swift
new file mode 100644
index 0000000..88197bf
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/BrandMigration.swift
@@ -0,0 +1,563 @@
+// One-time move of a NotProton (<= 2.x) install to the Bridgeplay 3.0.0 names.
+//
+// Every root is a parameter so tests run against temporary directories; live() builds the
+// real ones. The steps are idempotent and recorded in a marker file inside the support
+// directory, so a crash part way through resumes on the next launch. Nothing the user owns
+// is deleted: directories are moved, Steam's config files are copied into a backup folder
+// before they are edited, and anything that would overwrite an existing file is left alone
+// and reported in Summary.notes.
+
+import Darwin
+import Foundation
+
+struct BrandMigration: Sendable {
+
+ // Where the old and new names live. Steam's userData is Application Support/Steam.
+ let legacySupport: URL
+ let support: URL
+ let legacyCaches: URL
+ let caches: URL
+ let legacyHome: URL
+ let home: URL
+ let steamUserData: URL
+
+ var steamRunning: @Sendable () -> Bool = { Shell.processIsRunning(named: "steam_osx") }
+ var gameRunning: @Sendable () -> Bool = { Shell.processIsRunning(named: "wineserver") }
+
+ static let markerName = ".migrated-3.0.0"
+ static let backupFolder = "backups/migration-3.0.0"
+
+ static func live() -> BrandMigration {
+ let home = URL(filePath: NSHomeDirectory())
+ let applicationSupport = home.appending(path: "Library/Application Support")
+ let caches = home.appending(path: "Library/Caches")
+ return BrandMigration(
+ legacySupport: applicationSupport.appending(path: "notproton"),
+ support: applicationSupport.appending(path: "bridgeplay"),
+ legacyCaches: caches.appending(path: "notproton"),
+ caches: caches.appending(path: "bridgeplay"),
+ legacyHome: home.appending(path: ".notproton"),
+ home: home.appending(path: ".bridgeplay"),
+ steamUserData: applicationSupport.appending(path: "Steam"))
+ }
+
+ enum Blocker: Equatable, Sendable {
+ case steamRunning
+ case gameRunning
+ }
+
+ enum Failure: Error, Equatable {
+ case blocked(Blocker)
+ }
+
+ enum Step: String, CaseIterable, Sendable {
+ case backup, move, symlinks, supportFiles = "support-files", compatTools = "compat-tools"
+ case compatMapping = "compat-mapping", launchOptions = "launch-options", done
+ }
+
+ struct Summary: Equatable, Sendable {
+ var toolsRenamed = 0
+ var mappingsRewritten = 0
+ var launchOptionsRewritten = 0
+ var symlinksFixed = 0
+ var logsRenamed = 0
+ var filesRewritten = 0
+ var backups: URL?
+ var notes: [String] = []
+
+ var description: String {
+ "Moved NotProton data to Bridgeplay 3.0.0: \(toolsRenamed) compatibility tools renamed, "
+ + "\(mappingsRewritten) Steam mappings and \(launchOptionsRewritten) launch options rewritten, "
+ + "\(symlinksFixed) symlinks fixed, \(logsRenamed) logs renamed, \(filesRewritten) files rewritten."
+ + (notes.isEmpty ? "" : " " + notes.joined(separator: " "))
+ }
+ }
+
+ // MARK: When to run
+
+ // Cheap enough to call at every launch: a few stat calls and one small read.
+ static func isNeeded(legacySupport: URL, support: URL) -> Bool {
+ let legacyMarker = steps(at: legacySupport.appending(path: markerName))
+ let marker = steps(at: support.appending(path: markerName))
+ if marker?.contains(.done) == true || legacyMarker?.contains(.done) == true { return false }
+ return exists(legacySupport) || marker != nil
+ }
+
+ var isNeeded: Bool { Self.isNeeded(legacySupport: legacySupport, support: support) }
+
+ func canRun() -> Blocker? {
+ if steamRunning() { return .steamRunning }
+ if gameRunning() { return .gameRunning }
+ return nil
+ }
+
+ // MARK: Running
+
+ @discardableResult
+ func run() throws -> Summary {
+ var summary = Summary()
+ guard isNeeded else { return summary }
+ if let blocker = canRun() { throw Failure.blocked(blocker) }
+
+ // Until the support directory moves, the marker lives in the legacy one and moves with it.
+ var done = Set(Self.steps(at: support.appending(path: Self.markerName)) ?? [])
+ .union(Self.steps(at: legacySupport.appending(path: Self.markerName)) ?? [])
+ func record(_ step: Step) throws {
+ done.insert(step)
+ try writeMarker(done)
+ }
+ try writeMarker(done)
+
+ if !done.contains(.backup) {
+ summary.backups = try backUpSteamConfig()
+ try record(.backup)
+ } else {
+ summary.backups = support.appending(path: Self.backupFolder)
+ }
+ if !done.contains(.move) {
+ try moveDirectories(&summary)
+ try record(.move)
+ }
+ if !done.contains(.symlinks) {
+ summary.symlinksFixed = try fixSymlinks()
+ try record(.symlinks)
+ }
+ if !done.contains(.supportFiles) {
+ try migrateSupportFiles(&summary)
+ try record(.supportFiles)
+ }
+ if !done.contains(.compatTools) {
+ try migrateCompatTools(&summary)
+ try record(.compatTools)
+ }
+ if !done.contains(.compatMapping) {
+ summary.mappingsRewritten = try rewriteFile(steamConfig) { Self.migratedCompatMapping($0) }
+ try record(.compatMapping)
+ }
+ if !done.contains(.launchOptions) {
+ for file in localConfigs() {
+ summary.launchOptionsRewritten += try rewriteFile(file) { Self.migratedLaunchOptions($0) }
+ }
+ try record(.launchOptions)
+ }
+ try record(.done)
+ return summary
+ }
+
+ // MARK: Marker
+
+ private var markerHome: URL {
+ Self.exists(support) || !Self.exists(legacySupport) ? support : legacySupport
+ }
+
+ private func writeMarker(_ steps: Set<Step>) throws {
+ let directory = markerHome
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let text = Step.allCases.filter(steps.contains).map(\.rawValue).joined(separator: "\n") + "\n"
+ try text.write(to: directory.appending(path: Self.markerName), atomically: true, encoding: .utf8)
+ // A merge leaves the legacy marker behind; the one in markerHome now holds both.
+ if directory == support {
+ let stale = legacySupport.appending(path: Self.markerName)
+ if Self.exists(stale) { try? FileManager.default.removeItem(at: stale) }
+ }
+ }
+
+ private static func steps(at url: URL) -> [Step]? {
+ guard let text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
+ return text.split(whereSeparator: \.isNewline).compactMap { Step(rawValue: String($0)) }
+ }
+
+ // MARK: Step 1, backups
+
+ private var steamConfig: URL { steamUserData.appending(path: "config/config.vdf") }
+
+ private func localConfigs() -> [URL] { userConfigs(named: "localconfig.vdf") }
+
+ private func userConfigs(named name: String) -> [URL] {
+ let userdata = steamUserData.appending(path: "userdata")
+ let users = (try? FileManager.default.contentsOfDirectory(atPath: userdata.path(percentEncoded: false))) ?? []
+ return users.sorted().map { userdata.appending(path: "\($0)/config/\(name)") }
+ .filter { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) }
+ }
+
+ // Copies go into whichever support directory exists now, so they move along in step 2.
+ // A copy already there is the older one and is kept.
+ private func backUpSteamConfig() throws -> URL {
+ let files = FileManager.default
+ let backups = markerHome.appending(path: Self.backupFolder)
+ let root = steamUserData.path(percentEncoded: false)
+ let sources = [steamConfig] + localConfigs() + userConfigs(named: "compat.vdf")
+ for source in sources where files.fileExists(atPath: source.path(percentEncoded: false)) {
+ let relative = String(source.path(percentEncoded: false).dropFirst(root.count))
+ .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ let destination = backups.appending(path: relative)
+ guard !Self.exists(destination) else { continue }
+ try files.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try files.copyItem(at: source, to: destination)
+ }
+ return support.appending(path: Self.backupFolder)
+ }
+
+ // MARK: Step 2, moving directories
+
+ private func moveDirectories(_ summary: inout Summary) throws {
+ for (from, to) in [(legacySupport, support), (legacyCaches, caches), (legacyHome, home)] {
+ try Self.merge(from, into: to, notes: &summary.notes)
+ }
+ }
+
+ // Moves source to destination; when destination exists, moves in only what it lacks and
+ // never overwrites. The source is removed only once empty.
+ static func merge(_ source: URL, into destination: URL, notes: inout [String]) throws {
+ let files = FileManager.default
+ guard exists(source) else { return }
+ guard exists(destination) else {
+ try files.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try files.moveItem(at: source, to: destination)
+ return
+ }
+ guard isDirectory(source), isDirectory(destination) else {
+ if source.lastPathComponent == ".DS_Store" || source.lastPathComponent == markerName {
+ try? files.removeItem(at: source)
+ } else {
+ notes.append("Kept \(source.path(percentEncoded: false)): \(destination.path(percentEncoded: false)) already exists.")
+ }
+ return
+ }
+ let children = (try? files.contentsOfDirectory(atPath: source.path(percentEncoded: false))) ?? []
+ for child in children.sorted() {
+ try merge(source.appending(path: child), into: destination.appending(path: child), notes: &notes)
+ }
+ Darwin.rmdir(source.path(percentEncoded: false))
+ }
+
+ // MARK: Step 3, symlinks
+
+ // Absolute links into the old roots (launcher bundles link every Wine .so into runners/)
+ // are repointed. Links are never followed, and links pointing elsewhere are left alone.
+ private func fixSymlinks() throws -> Int {
+ let root = support.path(percentEncoded: false)
+ guard let walker = FileManager.default.enumerator(atPath: root) else { return 0 }
+ var fixed = 0
+ while let relative = walker.nextObject() as? String {
+ let path = root + "/" + relative
+ guard walker.fileAttributes?[.type] as? FileAttributeType == .typeSymbolicLink,
+ let target = try? FileManager.default.destinationOfSymbolicLink(atPath: path),
+ target.hasPrefix("/"),
+ let moved = movedPath(target)
+ else { continue }
+ let temporary = path + ".bridgeplay-link"
+ unlink(temporary)
+ try FileManager.default.createSymbolicLink(atPath: temporary, withDestinationPath: moved)
+ guard Darwin.rename(temporary, path) == 0 else {
+ unlink(temporary)
+ throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: path])
+ }
+ fixed += 1
+ }
+ return fixed
+ }
+
+ // The same path under the new roots, or nil when it is under none of the old ones.
+ func movedPath(_ path: String) -> String? {
+ for (old, new) in [(legacySupport, support), (legacyCaches, caches), (legacyHome, home)] {
+ let oldPath = old.path(percentEncoded: false).trimmingSuffix("/")
+ if path == oldPath || path.hasPrefix(oldPath + "/") {
+ return new.path(percentEncoded: false).trimmingSuffix("/") + path.dropFirst(oldPath.count)
+ }
+ }
+ return nil
+ }
+
+ // MARK: Step 4, files inside the support directory
+
+ static let logNames = [
+ ("notproton-run.log", "bridgeplay-run.log"),
+ ("notproton-wine.log", "bridgeplay-wine.log"),
+ ("notproton.log", "bridgeplay.log"),
+ ]
+
+ private func migrateSupportFiles(_ summary: inout Summary) throws {
+ let launchers = support.appending(path: "launchers")
+ let launcherDirs = ((try? FileManager.default.contentsOfDirectory(
+ atPath: launchers.path(percentEncoded: false))) ?? []).sorted().map { launchers.appending(path: $0) }
+ for directory in [support] + launcherDirs {
+ for (old, new) in Self.logNames {
+ if try Self.renameIfFree(directory.appending(path: old), to: directory.appending(path: new)) {
+ summary.logsRenamed += 1
+ }
+ }
+ }
+
+ let tools = support.appending(path: "tools")
+ if try rewriteFile(tools, { Self.migratedToolList($0) }) > 0 { summary.filesRewritten += 1 }
+
+ // Launcher scripts carry absolute paths; Steam rewrites them on the next game launch,
+ // but a launcher started from the Dock before that would point at the old directory.
+ for file in Self.textFiles(under: launchers) {
+ if try rewriteFile(file, { text in
+ let result = rewrittenPaths(text)
+ return (result, result == text ? 0 : 1)
+ }) > 0 { summary.filesRewritten += 1 }
+ }
+ }
+
+ static func migratedToolList(_ text: String) -> (String, Int) {
+ var count = 0
+ let lines = text.components(separatedBy: "\n").map { line -> String in
+ var fields = line.components(separatedBy: "\t")
+ guard let name = fields.first, let moved = migratedToolName(name) else { return line }
+ fields[0] = moved
+ count += 1
+ return fields.joined(separator: "\t")
+ }
+ return (lines.joined(separator: "\n"), count)
+ }
+
+ // MARK: Step 5, compatibilitytools.d
+
+ private func migrateCompatTools(_ summary: inout Summary) throws {
+ let directory = steamUserData.appending(path: "compatibilitytools.d")
+ let entries = (try? FileManager.default.contentsOfDirectory(atPath: directory.path(percentEncoded: false))) ?? []
+ for name in entries.sorted() {
+ guard let moved = Self.migratedToolName(name) else { continue }
+ let old = directory.appending(path: name)
+ guard Self.isDirectory(old) else { continue }
+ let new = directory.appending(path: moved)
+ if Self.exists(new) {
+ summary.notes.append("Kept compatibility tool \(name): \(moved) already exists.")
+ continue
+ }
+ try FileManager.default.moveItem(at: old, to: new)
+ summary.toolsRenamed += 1
+ }
+ // Rewriting is idempotent, so a crash between a rename and its rewrite is caught here.
+ let current = (try? FileManager.default.contentsOfDirectory(atPath: directory.path(percentEncoded: false))) ?? []
+ for name in current.sorted() where name == "bridgeplay" || name.hasPrefix("bridgeplay-") {
+ let folder = directory.appending(path: name)
+ guard Self.isDirectory(folder) else { continue }
+ let oldName = "notproton" + name.dropFirst("bridgeplay".count)
+ for file in Self.textFiles(under: folder) {
+ if try rewriteFile(file, { text in
+ let result = rewrittenPaths(text)
+ .replacingOccurrences(of: "\"\(oldName)\"", with: "\"\(name)\"")
+ return (result, result == text ? 0 : 1)
+ }) > 0 { summary.filesRewritten += 1 }
+ }
+ }
+ }
+
+ // Absolute old roots, the $HOME-relative spellings scripts use, and log names.
+ func rewrittenPaths(_ text: String) -> String {
+ var result = text
+ for (old, new) in [(legacySupport, support), (legacyCaches, caches), (legacyHome, home)] {
+ result = Self.replacingBounded(
+ result, old.path(percentEncoded: false).trimmingSuffix("/"),
+ new.path(percentEncoded: false).trimmingSuffix("/"))
+ }
+ result = Self.replacingBounded(result, "Library/Application Support/notproton", "Library/Application Support/bridgeplay")
+ result = Self.replacingBounded(result, "Library/Caches/notproton", "Library/Caches/bridgeplay")
+ result = Self.replacingBounded(result, "/.notproton", "/.bridgeplay")
+ for (old, new) in Self.logNames {
+ result = Self.replacingBounded(result, old, new)
+ }
+ return result
+ }
+
+ // MARK: Step 6, config.vdf
+
+ // Rewrites "name" values naming one of our tools inside CompatToolMapping. Everything else,
+ // whitespace and order included, stays byte for byte.
+ static func migratedCompatMapping(_ text: String) -> (String, Int) {
+ var lines = text.components(separatedBy: "\n")
+ guard let header = lines.firstIndex(where: { quotedKey($0)?.caseInsensitiveCompare("CompatToolMapping") == .orderedSame }),
+ header + 1 < lines.count, lines[header + 1].trimmingCharacters(in: .whitespaces) == "{"
+ else { return (text, 0) }
+ var depth = 0
+ var count = 0
+ for index in header + 1 ..< lines.count {
+ let trimmed = lines[index].trimmingCharacters(in: .whitespaces)
+ if trimmed == "{" { depth += 1 }
+ if trimmed == "}" {
+ depth -= 1
+ if depth == 0 { break }
+ }
+ guard let (key, value, range) = keyValue(lines[index]),
+ key.caseInsensitiveCompare("name") == .orderedSame,
+ let moved = migratedToolName(value)
+ else { continue }
+ lines[index].replaceSubrange(range, with: moved)
+ count += 1
+ }
+ return (lines.joined(separator: "\n"), count)
+ }
+
+ // MARK: Step 7, localconfig.vdf
+
+ // Only LaunchOptions values change: the np-native path and NOTPROTON_ variables.
+ static func migratedLaunchOptions(_ text: String) -> (String, Int) {
+ var count = 0
+ let lines = text.components(separatedBy: "\n").map { line -> String in
+ guard let (key, value, range) = keyValue(line),
+ key.caseInsensitiveCompare("LaunchOptions") == .orderedSame
+ else { return line }
+ var moved = replacingBounded(value, "/.notproton", "/.bridgeplay")
+ moved = replacingVariablePrefix(moved, "NOTPROTON_", "BRIDGEPLAY_")
+ guard moved != value else { return line }
+ count += 1
+ var line = line
+ line.replaceSubrange(range, with: moved)
+ return line
+ }
+ return (lines.joined(separator: "\n"), count)
+ }
+
+ // MARK: Names
+
+ // notproton -> bridgeplay, notproton-<x> -> bridgeplay-<x>; nil when the tool is not ours.
+ static func migratedToolName(_ name: String) -> String? {
+ guard name == "notproton" || name.hasPrefix("notproton-") else { return nil }
+ return "bridgeplay" + name.dropFirst("notproton".count)
+ }
+
+ // MARK: Text helpers
+
+ // A line holding only a quoted key, as in SteamDefaultTool.
+ private static func quotedKey(_ line: String) -> String? {
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ guard trimmed.count >= 2, trimmed.hasPrefix("\""), trimmed.hasSuffix("\""),
+ !trimmed.dropFirst().dropLast().contains("\"")
+ else { return nil }
+ return String(trimmed.dropFirst().dropLast())
+ }
+
+ // `"key"<ws>"value"` on one line; value is the raw text between its quotes (escapes kept)
+ // and range is where that text sits in the line.
+ static func keyValue(_ line: String) -> (String, String, Range<String.Index>)? {
+ var index = line.startIndex
+ func skipSpace() {
+ while index < line.endIndex, line[index] == " " || line[index] == "\t" { index = line.index(after: index) }
+ }
+ func quoted() -> Range<String.Index>? {
+ guard index < line.endIndex, line[index] == "\"" else { return nil }
+ let start = line.index(after: index)
+ var cursor = start
+ while cursor < line.endIndex {
+ if line[cursor] == "\\" {
+ cursor = line.index(after: cursor)
+ if cursor < line.endIndex { cursor = line.index(after: cursor) }
+ continue
+ }
+ if line[cursor] == "\"" {
+ index = line.index(after: cursor)
+ return start ..< cursor
+ }
+ cursor = line.index(after: cursor)
+ }
+ return nil
+ }
+ skipSpace()
+ guard let key = quoted() else { return nil }
+ skipSpace()
+ guard let value = quoted() else { return nil }
+ return (String(line[key]), String(line[value]), value)
+ }
+
+ private static func isNameCharacter(_ character: Character) -> Bool {
+ character.isLetter || character.isNumber || character == "-" || character == "_" || character == "."
+ }
+
+ // Replaces old only where the next character cannot continue a name, so
+ // ".notproton-msync" and "notproton-backends" survive "/.notproton" and "notproton".
+ static func replacingBounded(_ text: String, _ old: String, _ new: String) -> String {
+ guard !old.isEmpty, text.contains(old) else { return text }
+ var result = ""
+ var rest = text[...]
+ while let found = rest.range(of: old) {
+ let bounded = found.upperBound == rest.endIndex || !isNameCharacter(rest[found.upperBound])
+ result += rest[..<found.lowerBound]
+ result += bounded ? new : old
+ rest = rest[found.upperBound...]
+ }
+ return result + rest
+ }
+
+ // Replaces a variable prefix only at the start of a word, so FOO_NOTPROTON_X is kept.
+ static func replacingVariablePrefix(_ text: String, _ old: String, _ new: String) -> String {
+ guard text.contains(old) else { return text }
+ var result = ""
+ var rest = text[...]
+ while let found = rest.range(of: old) {
+ let before = found.lowerBound == rest.startIndex ? result.last : rest[rest.index(before: found.lowerBound)]
+ let atWordStart = before.map { !($0.isLetter || $0.isNumber || $0 == "_") } ?? true
+ result += rest[..<found.lowerBound]
+ result += atWordStart ? new : old
+ rest = rest[found.upperBound...]
+ }
+ return result + rest
+ }
+
+ // MARK: File helpers
+
+ static let textLimit = 1 << 20
+
+ // Small UTF-8 files under a folder, skipping symlinks, backups and logs.
+ static func textFiles(under folder: URL) -> [URL] {
+ let root = folder.path(percentEncoded: false)
+ guard let walker = FileManager.default.enumerator(atPath: root) else { return [] }
+ var found: [URL] = []
+ while let relative = walker.nextObject() as? String {
+ let name = (relative as NSString).lastPathComponent
+ guard walker.fileAttributes?[.type] as? FileAttributeType == .typeRegular,
+ let size = walker.fileAttributes?[.size] as? Int, size <= textLimit,
+ !name.contains(".bak"), !name.hasSuffix(".log"), name != ".DS_Store"
+ else { continue }
+ found.append(folder.appending(path: relative))
+ }
+ return found.sorted { $0.path < $1.path }
+ }
+
+ // Applies transform to a text file and writes it back atomically with its permissions,
+ // only when it changed. Returns the transform's count; 0 for a missing or binary file.
+ private func rewriteFile(_ file: URL, _ transform: (String) -> (String, Int)) throws -> Int {
+ let path = file.path(percentEncoded: false)
+ guard let data = FileManager.default.contents(atPath: path), data.count <= Self.textLimit,
+ !data.contains(0), let text = String(data: data, encoding: .utf8)
+ else { return 0 }
+ let (result, count) = transform(text)
+ guard result != text else { return 0 }
+ let attributes = try FileManager.default.attributesOfItem(atPath: path)
+ let temporary = file.deletingLastPathComponent().appending(path: ".\(file.lastPathComponent).bridgeplay")
+ try Data(result.utf8).write(to: temporary)
+ if let permissions = attributes[.posixPermissions] {
+ try FileManager.default.setAttributes([.posixPermissions: permissions], ofItemAtPath: temporary.path(percentEncoded: false))
+ }
+ guard Darwin.rename(temporary.path(percentEncoded: false), path) == 0 else {
+ try? FileManager.default.removeItem(at: temporary)
+ throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: path])
+ }
+ return count
+ }
+
+ private static func renameIfFree(_ old: URL, to new: URL) throws -> Bool {
+ guard exists(old), !exists(new) else { return false }
+ try FileManager.default.moveItem(at: old, to: new)
+ return true
+ }
+
+ // lstat-based, so a dangling symlink still counts.
+ static func exists(_ url: URL) -> Bool {
+ (try? FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false))) != nil
+ }
+
+ static func isDirectory(_ url: URL) -> Bool {
+ (try? FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false)))?[.type]
+ as? FileAttributeType == .typeDirectory
+ }
+}
+
+private extension String {
+ func trimmingSuffix(_ suffix: String) -> String {
+ hasSuffix(suffix) && count > suffix.count ? String(dropLast(suffix.count)) : self
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/BrandMigrationTests.swift b/app/Tests/NotProtonAppTests/BrandMigrationTests.swift
new file mode 100644
index 0000000..5400aaa
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/BrandMigrationTests.swift
@@ -0,0 +1,404 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Moving a NotProton install to Bridgeplay 3.0.0")
+struct BrandMigrationTests {
+
+ // A fake home holding the 2.x layout, laid out like the real one.
+ private struct Fixture {
+ let root: URL
+ let migration: BrandMigration
+
+ var legacySupport: URL { migration.legacySupport }
+ var support: URL { migration.support }
+ var steam: URL { migration.steamUserData }
+ var tools: URL { steam.appending(path: "compatibilitytools.d") }
+ var config: URL { steam.appending(path: "config/config.vdf") }
+ var localConfig: URL { steam.appending(path: "userdata/123/config/localconfig.vdf") }
+
+ func path(_ url: URL) -> String { url.path(percentEncoded: false) }
+ func read(_ url: URL) throws -> String { try String(contentsOf: url, encoding: .utf8) }
+ func exists(_ url: URL) -> Bool { BrandMigration.exists(url) }
+ func link(_ url: URL) throws -> String {
+ try FileManager.default.destinationOfSymbolicLink(atPath: path(url))
+ }
+ }
+
+ private static func write(_ text: String, to url: URL, executable: Bool = false) throws {
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try text.write(to: url, atomically: true, encoding: .utf8)
+ if executable {
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path(percentEncoded: false))
+ }
+ }
+
+ private static func symlink(_ url: URL, to target: String) throws {
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(atPath: url.path(percentEncoded: false), withDestinationPath: target)
+ }
+
+ static let configText = """
+ "InstallConfigStore"
+ {
+ \t"Software"
+ \t{
+ \t\t"Valve"
+ \t\t{
+ \t\t\t"Steam"
+ \t\t\t{
+ \t\t\t\t"CompatToolMapping"
+ \t\t\t\t{
+ \t\t\t\t\t"3764200"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"name"\t\t"notproton-winecx-11.17"
+ \t\t\t\t\t\t"config"\t\t""
+ \t\t\t\t\t\t"priority"\t\t"250"
+ \t\t\t\t\t}
+ \t\t\t\t\t"2651280"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"name"\t\t"notproton"
+ \t\t\t\t\t\t"config"\t\t""
+ \t\t\t\t\t\t"priority"\t\t"250"
+ \t\t\t\t\t}
+ \t\t\t\t\t"570"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"name"\t\t"proton_experimental"
+ \t\t\t\t\t\t"config"\t\t""
+ \t\t\t\t\t\t"priority"\t\t"250"
+ \t\t\t\t\t}
+ \t\t\t\t}
+ \t\t\t\t"name"\t\t"notproton-outside-mapping"
+ \t\t\t}
+ \t\t}
+ \t}
+ }
+
+ """
+
+ static func localConfigText(home: String) -> String {
+ """
+ "UserLocalConfigStore"
+ {
+ \t"Software"
+ \t{
+ \t\t"Valve"
+ \t\t{
+ \t\t\t"Steam"
+ \t\t\t{
+ \t\t\t\t"apps"
+ \t\t\t\t{
+ \t\t\t\t\t"3764200"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"LaunchOptions"\t\t"\(home)/.notproton/np-native NP_PAD_MODE=hid NOTPROTON_FRAMEGEN=2 %command% -novid"
+ \t\t\t\t\t}
+ \t\t\t\t\t"570"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"LaunchOptions"\t\t"MTL_HUD_ENABLED=1 %command% -title \\"NOTPROTON_ text\\""
+ \t\t\t\t\t}
+ \t\t\t\t\t"10"
+ \t\t\t\t\t{
+ \t\t\t\t\t\t"LaunchOptions"\t\t"FOO_NOTPROTON_BAR=1 %command%"
+ \t\t\t\t\t\t"Note"\t\t"NOTPROTON_KEEP /.notproton/np-native"
+ \t\t\t\t\t}
+ \t\t\t\t}
+ \t\t\t}
+ \t\t}
+ \t}
+ }
+
+ """
+ }
+
+ static let runScript = """
+ #!/bin/sh
+ # notproton CrossOver compatibility tool shim
+ np_support="$HOME/Library/Application Support/notproton"
+ loader_root="$HOME/Library/Application Support/notproton/launchers/$app_id"
+ log="$STEAM_COMPAT_DATA_PATH/notproton-run.log"
+ marker="$STEAM_COMPAT_DATA_PATH/notproton-msync"
+ backends="$CX_ROOT/lib/notproton-backends"
+ lock="$CX_ROOT/.notproton-msync"
+ pad="$HOME/.notproton/libnp_gamepad.dylib"
+ id="com.notproton.launcher.$app_id"
+ frames="${NOTPROTON_FRAMEGEN:-0}"
+
+ """
+
+ private static func toolFiles(_ name: String) -> [(String, String)] {
+ [
+ ("toolmanifest.vdf", "\"manifest\"\n{\n \"version\" \"2\"\n \"commandline\" \"/run %verb%\"\n}\n"),
+ ("compatibilitytool.vdf", """
+ "compatibilitytools"
+ {
+ "compat_tools"
+ {
+ "\(name)"
+ {
+ "install_path" "."
+ "display_name" "WineCX 11.17 (msync, D3DMetal)"
+ }
+ }
+ }
+
+ """),
+ ]
+ }
+
+ private func fixture() throws -> Fixture {
+ let root = try scratchDirectory("brand-migration")
+ let home = root.appending(path: "home")
+ let appSupport = home.appending(path: "Library/Application Support")
+ let migration = BrandMigration(
+ legacySupport: appSupport.appending(path: "notproton"),
+ support: appSupport.appending(path: "bridgeplay"),
+ legacyCaches: home.appending(path: "Library/Caches/notproton"),
+ caches: home.appending(path: "Library/Caches/bridgeplay"),
+ legacyHome: home.appending(path: ".notproton"),
+ home: home.appending(path: ".bridgeplay"),
+ steamUserData: appSupport.appending(path: "Steam"),
+ steamRunning: { false }, gameRunning: { false })
+ let fixture = Fixture(root: root, migration: migration)
+ let old = fixture.legacySupport
+ let oldPath = fixture.path(old)
+
+ // Support directory: a runner, an engine and a launcher linking into it absolutely,
+ // a relative link, and a link to somewhere else entirely.
+ try Self.write("so", to: old.appending(path: "runners/crossover-x/CrossOver/lib/wine/ntdll.so"))
+ try Self.symlink(old.appending(path: "engines/WineCX.app/Contents/SharedSupport/CrossOver"),
+ to: oldPath + "/runners/crossover-x/CrossOver")
+ try Self.symlink(old.appending(path: "launchers/42/Game.app/Contents/MacOS/ntdll.so"),
+ to: oldPath + "/runners/crossover-x/CrossOver/lib/wine/ntdll.so")
+ try Self.symlink(old.appending(path: "launchers/42/Game.app/Contents/MacOS/relative.so"), to: "../../../x.so")
+ try Self.symlink(old.appending(path: "launchers/42/elsewhere"), to: "/usr/lib/libSystem.B.dylib")
+ try Self.write("#!/bin/sh\nexec \"\(oldPath)/launchers/42/Game.app/Contents/MacOS/wine\" \"$@\"\n",
+ to: old.appending(path: "launchers/42/Game.app/Contents/MacOS/launcher"), executable: true)
+ try Self.write("<string>com.notproton.launcher.42</string>\n", to: old.appending(path: "launchers/42/Game.app/Contents/Info.plist"))
+ try Self.write("wine log\n", to: old.appending(path: "launchers/42/notproton-wine.log"))
+ try Self.write("""
+ notproton-winecx-11.17\twinecx-11.17\trosetta\tWineCX 11.17 (msync, D3DMetal)
+ notproton\twinecx-11.17\trosetta\tLegacy
+ other-tool\twinehq-11.15\trosetta\tNot ours
+
+ """, to: old.appending(path: "tools"))
+ try Self.write("old tools\n", to: old.appending(path: "tools.bak-1115default"))
+ try Self.write("dylib log\n", to: old.appending(path: "notproton.log"))
+ try Self.write("app log\n", to: old.appending(path: "app.log"))
+
+ try Self.write("tarball", to: migration.legacyCaches.appending(path: "engines/wine.tar.xz"))
+ try Self.write("binary", to: migration.legacyHome.appending(path: "np-native"), executable: true)
+
+ // Steam.
+ for name in ["notproton-winecx-11.17", "notproton"] {
+ let folder = fixture.tools.appending(path: name)
+ for (file, text) in Self.toolFiles(name) { try Self.write(text, to: folder.appending(path: file)) }
+ try Self.write(Self.runScript, to: folder.appending(path: "run"), executable: true)
+ try Self.write(Self.runScript, to: folder.appending(path: "run.bak-tcc"), executable: true)
+ }
+ for (file, text) in Self.toolFiles("GE-Proton9") {
+ try Self.write(text, to: fixture.tools.appending(path: "GE-Proton9/\(file)"))
+ }
+ try Self.write(Self.configText, to: fixture.config)
+ try Self.write(Self.localConfigText(home: fixture.path(home)), to: fixture.localConfig)
+ try Self.write("\"platform_overrides\"\n{\n}\n", to: fixture.steam.appending(path: "userdata/123/config/compat.vdf"))
+ return fixture
+ }
+
+ private func expectMigrated(_ f: Fixture) throws {
+ let new = f.support
+ let newPath = f.path(new)
+ let home = f.path(f.root.appending(path: "home"))
+
+ #expect(!f.exists(f.legacySupport))
+ #expect(!f.exists(f.migration.legacyCaches))
+ #expect(!f.exists(f.migration.legacyHome))
+ #expect(f.exists(f.migration.caches.appending(path: "engines/wine.tar.xz")))
+ #expect(f.exists(f.migration.home.appending(path: "np-native")))
+
+ // Symlinks.
+ #expect(try f.link(new.appending(path: "engines/WineCX.app/Contents/SharedSupport/CrossOver"))
+ == newPath + "/runners/crossover-x/CrossOver")
+ #expect(try f.link(new.appending(path: "launchers/42/Game.app/Contents/MacOS/ntdll.so"))
+ == newPath + "/runners/crossover-x/CrossOver/lib/wine/ntdll.so")
+ #expect(try f.link(new.appending(path: "launchers/42/Game.app/Contents/MacOS/relative.so")) == "../../../x.so")
+ #expect(try f.link(new.appending(path: "launchers/42/elsewhere")) == "/usr/lib/libSystem.B.dylib")
+ #expect(f.exists(new.appending(path: "engines/WineCX.app/Contents/SharedSupport/CrossOver/lib/wine/ntdll.so")))
+
+ // Support files.
+ #expect(try f.read(new.appending(path: "tools")) == """
+ bridgeplay-winecx-11.17\twinecx-11.17\trosetta\tWineCX 11.17 (msync, D3DMetal)
+ bridgeplay\twinecx-11.17\trosetta\tLegacy
+ other-tool\twinehq-11.15\trosetta\tNot ours
+
+ """)
+ #expect(try f.read(new.appending(path: "tools.bak-1115default")) == "old tools\n")
+ #expect(f.exists(new.appending(path: "bridgeplay.log")))
+ #expect(!f.exists(new.appending(path: "notproton.log")))
+ #expect(f.exists(new.appending(path: "app.log")))
+ #expect(f.exists(new.appending(path: "launchers/42/bridgeplay-wine.log")))
+ #expect(try f.read(new.appending(path: "launchers/42/Game.app/Contents/MacOS/launcher"))
+ == "#!/bin/sh\nexec \"\(newPath)/launchers/42/Game.app/Contents/MacOS/wine\" \"$@\"\n")
+ #expect(try f.read(new.appending(path: "launchers/42/Game.app/Contents/Info.plist"))
+ == "<string>com.notproton.launcher.42</string>\n")
+
+ // Compatibility tools.
+ #expect(!f.exists(f.tools.appending(path: "notproton-winecx-11.17")))
+ #expect(!f.exists(f.tools.appending(path: "notproton")))
+ for name in ["bridgeplay-winecx-11.17", "bridgeplay"] {
+ let folder = f.tools.appending(path: name)
+ #expect(try f.read(folder.appending(path: "compatibilitytool.vdf")) == Self.toolFiles(name)[1].1)
+ #expect(try f.read(folder.appending(path: "toolmanifest.vdf")) == Self.toolFiles(name)[0].1)
+ #expect(try f.read(folder.appending(path: "run")) == """
+ #!/bin/sh
+ # notproton CrossOver compatibility tool shim
+ np_support="$HOME/Library/Application Support/bridgeplay"
+ loader_root="$HOME/Library/Application Support/bridgeplay/launchers/$app_id"
+ log="$STEAM_COMPAT_DATA_PATH/bridgeplay-run.log"
+ marker="$STEAM_COMPAT_DATA_PATH/notproton-msync"
+ backends="$CX_ROOT/lib/notproton-backends"
+ lock="$CX_ROOT/.notproton-msync"
+ pad="$HOME/.bridgeplay/libnp_gamepad.dylib"
+ id="com.notproton.launcher.$app_id"
+ frames="${NOTPROTON_FRAMEGEN:-0}"
+
+ """)
+ let permissions = try FileManager.default.attributesOfItem(
+ atPath: f.path(folder.appending(path: "run")))[.posixPermissions] as? Int
+ #expect(permissions == 0o755)
+ #expect(try f.read(folder.appending(path: "run.bak-tcc")) == Self.runScript)
+ }
+ #expect(try f.read(f.tools.appending(path: "GE-Proton9/compatibilitytool.vdf")) == Self.toolFiles("GE-Proton9")[1].1)
+
+ // config.vdf: only the two mappings that are ours.
+ #expect(try f.read(f.config) == Self.configText
+ .replacingOccurrences(of: "\"notproton-winecx-11.17\"", with: "\"bridgeplay-winecx-11.17\"")
+ .replacingOccurrences(of: "\"name\"\t\t\"notproton\"\n", with: "\"name\"\t\t\"bridgeplay\"\n"))
+
+ // localconfig.vdf: only LaunchOptions values, only word-initial NOTPROTON_.
+ #expect(try f.read(f.localConfig) == Self.localConfigText(home: home)
+ .replacingOccurrences(of: "\(home)/.notproton/np-native NP_PAD_MODE=hid NOTPROTON_FRAMEGEN=2",
+ with: "\(home)/.bridgeplay/np-native NP_PAD_MODE=hid BRIDGEPLAY_FRAMEGEN=2")
+ .replacingOccurrences(of: "\\\"NOTPROTON_ text\\\"", with: "\\\"BRIDGEPLAY_ text\\\""))
+
+ // Backups hold the originals.
+ let backups = new.appending(path: BrandMigration.backupFolder)
+ #expect(try f.read(backups.appending(path: "config/config.vdf")) == Self.configText)
+ #expect(try f.read(backups.appending(path: "userdata/123/config/localconfig.vdf")) == Self.localConfigText(home: home))
+ #expect(f.exists(backups.appending(path: "userdata/123/config/compat.vdf")))
+
+ #expect(try f.read(new.appending(path: BrandMigration.markerName)).contains("done"))
+ #expect(!f.migration.isNeeded)
+ }
+
+ @Test("Moves every name over and is a no-op the second time")
+ func migratesAndIsIdempotent() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ #expect(f.migration.isNeeded)
+
+ let summary = try f.migration.run()
+ #expect(summary.toolsRenamed == 2)
+ #expect(summary.mappingsRewritten == 2)
+ #expect(summary.launchOptionsRewritten == 2)
+ #expect(summary.symlinksFixed == 2)
+ #expect(summary.logsRenamed == 2)
+ #expect(summary.notes.isEmpty)
+ try expectMigrated(f)
+
+ #expect(try f.migration.run() == BrandMigration.Summary())
+ try expectMigrated(f)
+ }
+
+ @Test("A crash after the move resumes from the marker")
+ func resumesAfterMove() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+
+ // Do steps 1 and 2 by hand the way run() records them, then "crash".
+ var notes: [String] = []
+ let backups = f.legacySupport.appending(path: BrandMigration.backupFolder)
+ try Self.write(Self.configText, to: backups.appending(path: "config/config.vdf"))
+ try Self.write(Self.localConfigText(home: f.path(f.root.appending(path: "home"))),
+ to: backups.appending(path: "userdata/123/config/localconfig.vdf"))
+ try Self.write("x", to: backups.appending(path: "userdata/123/config/compat.vdf"))
+ try Self.write("backup\nmove\n", to: f.legacySupport.appending(path: BrandMigration.markerName))
+ try BrandMigration.merge(f.legacySupport, into: f.support, notes: &notes)
+ try BrandMigration.merge(f.migration.legacyCaches, into: f.migration.caches, notes: &notes)
+ try BrandMigration.merge(f.migration.legacyHome, into: f.migration.home, notes: &notes)
+ // Half of step 5 too: one tool folder renamed but not rewritten.
+ try FileManager.default.moveItem(at: f.tools.appending(path: "notproton"), to: f.tools.appending(path: "bridgeplay"))
+
+ #expect(!f.exists(f.legacySupport))
+ #expect(f.migration.isNeeded)
+ let summary = try f.migration.run()
+ #expect(summary.toolsRenamed == 1)
+ #expect(summary.symlinksFixed == 2)
+ try expectMigrated(f)
+ }
+
+ @Test("An existing bridgeplay directory is merged without overwriting")
+ func mergesIntoExistingDestination() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ try Self.write("new app log\n", to: f.support.appending(path: "app.log"))
+ try Self.write("already\n", to: f.support.appending(path: "launchers/7/kept"))
+ try Self.write("dsstore", to: f.support.appending(path: ".DS_Store"))
+ try Self.write("dsstore", to: f.legacySupport.appending(path: ".DS_Store"))
+
+ let summary = try f.migration.run()
+ #expect(try f.read(f.support.appending(path: "app.log")) == "new app log\n")
+ #expect(f.exists(f.support.appending(path: "launchers/7/kept")))
+ #expect(f.exists(f.support.appending(path: "launchers/42/Game.app/Contents/MacOS/launcher")))
+ // The conflicting app.log stays where it was, with the legacy directory around it.
+ #expect(try f.read(f.legacySupport.appending(path: "app.log")) == "app log\n")
+ #expect(summary.notes.count == 1)
+ #expect(summary.notes.first?.contains("app.log") == true)
+ #expect(!f.exists(f.legacySupport.appending(path: BrandMigration.markerName)))
+ #expect(!f.migration.isNeeded)
+ #expect(try f.read(f.support.appending(path: "tools")).hasPrefix("bridgeplay-winecx-11.17\t"))
+ }
+
+ @Test("A compatibility tool whose new name exists is left in place")
+ func keepsToolWhenTargetExists() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ try Self.write("mine\n", to: f.tools.appending(path: "bridgeplay-winecx-11.17/run"))
+
+ let summary = try f.migration.run()
+ #expect(summary.toolsRenamed == 1)
+ #expect(f.exists(f.tools.appending(path: "notproton-winecx-11.17/run")))
+ #expect(try f.read(f.tools.appending(path: "bridgeplay-winecx-11.17/run")) == "mine\n")
+ #expect(summary.notes.contains { $0.contains("notproton-winecx-11.17") })
+ }
+
+ @Test("Refuses while Steam or a game runs, and does nothing for a fresh install")
+ func preconditions() throws {
+ let f = try fixture()
+ defer { try? FileManager.default.removeItem(at: f.root) }
+ var steam = f.migration
+ steam.steamRunning = { true }
+ #expect(steam.canRun() == .steamRunning)
+ #expect(throws: BrandMigration.Failure.blocked(.steamRunning)) { try steam.run() }
+ var game = f.migration
+ game.gameRunning = { true }
+ #expect(game.canRun() == .gameRunning)
+ #expect(f.exists(f.legacySupport))
+ #expect(f.migration.canRun() == nil)
+
+ let fresh = try scratchDirectory("brand-migration-fresh")
+ defer { try? FileManager.default.removeItem(at: fresh) }
+ #expect(!BrandMigration.isNeeded(
+ legacySupport: fresh.appending(path: "notproton"), support: fresh.appending(path: "bridgeplay")))
+ }
+
+ @Test("Tool names: only ours are renamed")
+ func toolNames() {
+ #expect(BrandMigration.migratedToolName("notproton") == "bridgeplay")
+ #expect(BrandMigration.migratedToolName("notproton-winecx-11.17") == "bridgeplay-winecx-11.17")
+ #expect(BrandMigration.migratedToolName("notproton-fex-winecx-11.17") == "bridgeplay-fex-winecx-11.17")
+ #expect(BrandMigration.migratedToolName("notprotonx") == nil)
+ #expect(BrandMigration.migratedToolName("proton_experimental") == nil)
+ #expect(BrandMigration.migratedToolName("bridgeplay-winehq") == nil)
+ }
+}