Skip to content

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

Bottles: delete atomically so a failure can't strand one (#38)

Gauthier Piarrette490a8ed3a459
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 9730596..72a9f16 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -7,6 +7,9 @@ import Observation
final class AppState {
var engines: [InstalledEngine] = []
var bottles: [Bottle] = []
+ /// Directories under bottles/ that aren't loadable bottles. Shown alongside the real
+ /// ones so a bottle whose settings file is gone still has somewhere to be acted on (#38).
+ var damagedBottles: [DamagedBottle] = []
var selectedBottle: String?
var gamesByBottle: [String: [SteamGame]] = [:]
var gameDB = GameDB(directories: [])
@@ -167,7 +170,7 @@ final class AppState {
panel.message = String(format: L("Choose a cover image for %@"), item.title)
guard panel.runModal() == .OK, let url = panel.url else { return }
do { try coverStore.setCover(for: item.id, from: url); coverVersion += 1 }
- catch { errorMessage = "\(error)" }
+ catch { errorMessage = Self.message(for: error) }
}
func resetCover(for item: LibraryItem) {
@@ -204,6 +207,7 @@ final class AppState {
func refresh() {
engines = (try? engineStore.installedEngines()) ?? []
bottles = (try? bottleStore.list()) ?? []
+ damagedBottles = (try? bottleStore.damaged()) ?? []
needsOnboarding = engines.isEmpty
rosettaInstalled = FileManager.default.fileExists(atPath: "/Library/Apple/usr/share/rosetta/rosetta")
if selectedBottle == nil { selectedBottle = bottles.first?.name }
@@ -226,6 +230,21 @@ final class AppState {
(try? engineStore.engine(bottle.settings.engineID)) ?? engines.first
}
+ /// What to put in front of the user when something throws. Interpolating an NSError dumps
+ /// its domain, code, userInfo and a pointer address, with the one readable sentence buried
+ /// in the middle — that is what a failed delete looked like in #38.
+ static func message(for error: Error) -> String {
+ if let known = error as? HighballError { return known.description }
+ return (error as NSError).localizedDescription
+ }
+
+ /// Retries anything a previous purge could not remove. Free when `.trash` is empty, which
+ /// is the normal case, so a leftover with a transient cause clears itself at the next launch.
+ func sweepTrash() {
+ let store = bottleStore
+ Task.detached { store.sweepTrash() }
+ }
+
private func appendLog(_ line: String) {
logLines.append(line)
if logLines.count > 400 { logLines.removeFirst(logLines.count - 400) }
@@ -250,7 +269,7 @@ final class AppState {
do {
try await work()
doneState = done ?? DoneState(title: L("Done"), ctaTitle: nil, cta: nil)
- } catch { showLog = false; errorMessage = "\(error)" }
+ } catch { showLog = false; errorMessage = Self.message(for: error) }
cleanup?()
busy = false
refresh()
@@ -287,7 +306,7 @@ final class AppState {
func acceptGPTK(engine: InstalledEngine) {
do { _ = try engineStore.accept(license: "apple-gptk-license-2023-08-17", engine: engine); refresh() }
- catch { errorMessage = "\(error)" }
+ catch { errorMessage = Self.message(for: error) }
}
func createBottle(name: String, recipeID: String?) {
@@ -375,17 +394,40 @@ final class AppState {
}
func update(_ bottle: Bottle) {
- do { try bottleStore.update(bottle); refresh() } catch { errorMessage = "\(error)" }
+ do { try bottleStore.update(bottle); refresh() } catch { errorMessage = Self.message(for: error) }
}
func deleteBottle(_ name: String) {
- killBottleNamed(name)
- do { try bottleStore.delete(name); if selectedBottle == name { selectedBottle = nil }; refresh() }
- catch { errorMessage = "\(error)" }
+ runBusy("Deleting '\(name)'", showLogSheet: false) { [self] in
+ // Stop the bottle before anything moves: `wineserver -k` resolves the prefix by
+ // path, so after the rename it exits 1 and leaves the server running.
+ killBottleNamed(name)
+ let store = bottleStore
+ // A prefix can be tens of GB, and the old delete ran the whole walk on the main
+ // actor — 985 ms for 20,841 entries, minutes for a big Steam bottle.
+ let leftovers = try await Task.detached { try store.delete(name) }.value
+ await MainActor.run {
+ if self.selectedBottle == name { self.selectedBottle = nil }
+ guard let first = leftovers.first else { return }
+ self.errorMessage = """
+ '\(name)' is deleted and the name is free again. Some of its files are still \
+ on disk because macOS refused to remove them, starting at \(first.path) \
+ (\(first.reason)). Highball keeps them in .trash inside its data folder and \
+ tries again each time it starts.
+ """
+ }
+ }
}
private func killBottleNamed(_ name: String) {
- if let bottle = bottles.first(where: { $0.name == name }) { killBottle(bottle) }
+ if let bottle = bottles.first(where: { $0.name == name }) { killBottle(bottle); return }
+ // A damaged bottle is not in `bottles`, and it is exactly the one whose wineserver most
+ // needs stopping: nothing else has been able to touch it.
+ guard let engine = engines.first else { return }
+ let url = paths.bottle(name)
+ guard FileManager.default.fileExists(atPath: url.path) else { return }
+ let bottle = Bottle(url: url, settings: BottleSettings(name: name, engineID: engine.id))
+ try? WineRunner(paths: paths, engine: engine, bottle: bottle).kill()
}
func removePin(_ pin: Pin, from bottle: Bottle) {
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index dfcd14e..ddb9939 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -15,7 +15,7 @@ struct HighballApp: App {
.tint(HB.amber)
.preferredColorScheme(.dark)
.frame(minWidth: 820, minHeight: 560)
- .onAppear { state.refresh(); delegate.appState = state }
+ .onAppear { state.refresh(); state.sweepTrash(); delegate.appState = state }
}
.windowResizability(.contentSize)
.commands {
@@ -182,6 +182,29 @@ struct ContentView: View {
Button(L("Delete bottle…"), role: .destructive) { pendingDelete = bottle.name }
}
}
+ // A folder under bottles/ that isn't a loadable bottle still needs
+ // somewhere to be acted on. Before #38 it was simply invisible, which
+ // left its files stranded and its name unusable.
+ ForEach(state.damagedBottles) { damaged in
+ Button { pendingDelete = damaged.name } label: {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(.orange)
+ .frame(width: 18)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(damaged.name)
+ Text(L("damaged — click to delete"))
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(damaged.reason)
+ .padding(.vertical, 5).padding(.horizontal, 7)
+ .listRowInsets(EdgeInsets(top: 1, leading: 6, bottom: 1, trailing: 6))
+ }
}
if let engine = state.engines.first {
Section(L("Engine")) {
diff --git a/Sources/HighballKit/BottleStore.swift b/Sources/HighballKit/BottleStore.swift
index dff6fc0..631c305 100644
--- a/Sources/HighballKit/BottleStore.swift
+++ b/Sources/HighballKit/BottleStore.swift
@@ -66,9 +66,11 @@ public struct BottleStore: Sendable {
try await Self.ensureWoW64(runner: runner, bottle: bottle, log: result.log)
} catch {
// Don't strand a half-built bottle: it can never run a 32-bit installer, and leaving
- // it behind means retrying with the same name hits "bottle already exists".
+ // it behind means retrying with the same name hits "bottle already exists". This has
+ // to go through discard() for the same reason delete() does — a plain removeItem
+ // here fails the same way (#38) and, wrapped in try?, strands the bottle silently.
try? runner.kill()
- try? FileManager.default.removeItem(at: url)
+ _ = try? discard(url, name: name)
throw error
}
if windowsVersion != .win10 { try await runner.setWindowsVersion(windowsVersion) }
@@ -153,13 +155,112 @@ public struct BottleStore: Sendable {
return copy
}
- public func delete(_ name: String) throws {
+ /// Deletes a bottle by moving it out of `bottles/` first, then purging it.
+ ///
+ /// The move is one `rename(2)`: it either happens or it doesn't, so a bottle can never be
+ /// left half-deleted. A recursive remove can, and did (#38) — it walks the prefix in readdir
+ /// order and abandons the rest of a directory at the first entry macOS refuses to unlink.
+ /// `drive_c` sorts last in a bottle, so a blocker almost anywhere destroys `bottle.json`
+ /// first, and that made the bottle invisible to `list()`, refused by `delete()`'s old
+ /// bottle.json guard and blocked by `create()`'s name check, with its files still on disk.
+ ///
+ /// Returns whatever the purge could not remove. The bottle is gone from `bottles/` and its
+ /// name is free either way; leftovers wait in `.trash` for `sweepTrash()` to retry.
+ @discardableResult
+ public func delete(_ name: String) throws -> [PurgeFailure] {
let url = paths.bottle(name)
- guard FileManager.default.fileExists(atPath: url.appending(path: "bottle.json").path) else {
- throw HighballError.missing("bottle '\(name)'")
+ // Resolve by folder, not by bottle.json. The folder is the bottle's identity — the same
+ // rule list() reconciles names to — and a bottle whose settings file is unreadable is
+ // precisely the one that most needs deleting.
+ var st = stat()
+ guard lstat(url.path, &st) == 0 else { throw HighballError.missing("bottle '\(name)'") }
+ return try discard(url, name: name)
+ }
+
+ /// Moves a bottle directory into `.trash` and purges it there. Shared by `delete` and
+ /// `create`'s rollback so both are atomic in the only way that matters to the user: the
+ /// moment the call returns, the name is reusable.
+ @discardableResult
+ func discard(_ url: URL, name: String) throws -> [PurgeFailure] {
+ try FileManager.default.createDirectory(at: paths.trash, withIntermediateDirectories: true)
+ // rename(2) needs write on the two parent directories and nothing else, so it succeeds
+ // over trees removeItem cannot touch (0555 and 0000 directories, uchg flags, deny-delete
+ // ACLs). A poisoned root node is the one case it can't, so repair that node first.
+ var st = stat()
+ if lstat(url.path, &st) == 0 {
+ if st.st_flags != 0 { _ = lchflags(url.path, 0) }
+ if (st.st_mode & 0o700) != 0o700 { _ = chmod(url.path, st.st_mode | 0o700) }
+ }
+ let target = paths.trash.appending(path: "\(Self.trashName(name))-\(UUID().uuidString)",
+ directoryHint: .isDirectory)
+ // rename(2) and deliberately not FileManager.moveItem: across filesystems moveItem
+ // copies and then deletes, and the delete half fails exactly the way #38 does, leaving a
+ // whole copy at the destination and a gutted source. rename returns EXDEV and touches
+ // neither side, which is the failure we want if `home` is ever split across volumes.
+ guard rename(url.path, target.path) == 0 else {
+ let why = String(cString: strerror(errno))
+ throw HighballError.failed("""
+ Couldn't delete '\(name)'. Highball couldn't move it out of the bottles folder \
+ (\(why)). Nothing was removed and the bottle still works.
+ """)
+ }
+ return Purge.tree(at: target)
+ }
+
+ /// Bottle names are user-supplied, so keep them from steering the trash path anywhere.
+ static func trashName(_ name: String) -> String {
+ let safe = name.map { $0 == "/" || $0 == ":" || $0 == "." ? "_" : $0 }
+ return safe.isEmpty ? "bottle" : String(safe.prefix(64))
+ }
+
+ /// Directories under `bottles/` that `list()` cannot show, because their settings file is
+ /// missing or unreadable. `list()` and `damaged()` together cover every folder, so a bottle
+ /// can never be invisible again — being invisible is what stranded the reporter of #38.
+ public func damaged() throws -> [DamagedBottle] {
+ guard FileManager.default.fileExists(atPath: paths.bottles.path) else { return [] }
+ return try FileManager.default.contentsOfDirectory(at: paths.bottles, includingPropertiesForKeys: nil)
+ .compactMap { url -> DamagedBottle? in
+ let name = url.lastPathComponent
+ if name.hasPrefix(".") { return nil }
+ var st = stat()
+ guard lstat(url.path, &st) == 0, (st.st_mode & S_IFMT) == S_IFDIR else { return nil }
+ if (try? Bottle.load(url)) != nil { return nil }
+ // A prefix with a Windows dir is a real bottle that lost its settings; anything
+ // else is the wreckage of a delete that stopped part way.
+ let hasPrefix = FileManager.default.fileExists(atPath: url.appending(path: "drive_c/windows").path)
+ return DamagedBottle(name: name, url: url,
+ reason: hasPrefix ? "its bottle.json is missing or unreadable"
+ : "a delete stopped part way and left these files behind")
+ }
+ .sorted { $0.name < $1.name }
+ }
+
+ /// Retries anything a previous purge left in `.trash`. Cheap when it is empty, which is the
+ /// normal case, so it is safe to call at launch and before each delete: a leftover whose
+ /// cause was transient clears itself with no user action.
+ @discardableResult
+ public func sweepTrash() -> [(entry: URL, failures: [PurgeFailure])] {
+ let entries = (try? FileManager.default.contentsOfDirectory(at: paths.trash, includingPropertiesForKeys: nil)) ?? []
+ return entries.compactMap { url in
+ let failures = Purge.tree(at: url)
+ return failures.isEmpty ? nil : (url, failures)
}
- try FileManager.default.removeItem(at: url)
}
public func update(_ bottle: Bottle) throws { try bottle.save() }
}
+
+/// A directory under `bottles/` that isn't a loadable bottle. Surfaced so the user can act on
+/// it: without a UI row there is no way to reach a bottle whose settings file is gone.
+public struct DamagedBottle: Sendable, Identifiable, Hashable {
+ public var id: String { name }
+ public let name: String
+ public let url: URL
+ public let reason: String
+
+ public init(name: String, url: URL, reason: String) {
+ self.name = name
+ self.url = url
+ self.reason = reason
+ }
+}
diff --git a/Sources/HighballKit/EngineStore.swift b/Sources/HighballKit/EngineStore.swift
index 1d9a0ca..0e7e989 100644
--- a/Sources/HighballKit/EngineStore.swift
+++ b/Sources/HighballKit/EngineStore.swift
@@ -6,6 +6,9 @@ public enum HighballError: Error, CustomStringConvertible {
case processFailed(command: String, status: Int32, output: String)
case missing(String)
case invalid(String)
+ /// A message already written for the user. Carries no prefix, so it reads as a sentence
+ /// rather than as a category the reader has to decode.
+ case failed(String)
public var description: String {
switch self {
@@ -15,6 +18,7 @@ public enum HighballError: Error, CustomStringConvertible {
return "\(command) exited with \(status)\n\(output)"
case let .missing(what): return "missing: \(what)"
case let .invalid(what): return "invalid: \(what)"
+ case let .failed(message): return message
}
}
}
diff --git a/Sources/HighballKit/Paths.swift b/Sources/HighballKit/Paths.swift
index 6959d97..c6c6a3a 100644
--- a/Sources/HighballKit/Paths.swift
+++ b/Sources/HighballKit/Paths.swift
@@ -23,12 +23,17 @@ public struct HighballPaths: Sendable {
public var bottles: URL { home.appending(path: "bottles", directoryHint: .isDirectory) }
public var logs: URL { home.appending(path: "logs", directoryHint: .isDirectory) }
public var manifests: URL { home.appending(path: "manifests", directoryHint: .isDirectory) }
+ /// Staging for bottles on their way out. A sibling of `bottles/` rather than a child, so
+ /// nothing that enumerates bottles ever sees a half-purged tree, and inside `home` rather
+ /// than `~/.Trash` so the move is always same-filesystem — `rename(2)` cannot cross one,
+ /// and Finder could not empty an undeletable prefix anyway.
+ public var trash: URL { home.appending(path: ".trash", directoryHint: .isDirectory) }
public func engine(_ id: String) -> URL { engines.appending(path: id, directoryHint: .isDirectory) }
public func bottle(_ name: String) -> URL { bottles.appending(path: name, directoryHint: .isDirectory) }
public func ensure() throws {
- for dir in [home, downloads, engines, bottles, logs, manifests] {
+ for dir in [home, downloads, engines, bottles, logs, manifests, trash] {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
}
}
diff --git a/Sources/HighballKit/Purge.swift b/Sources/HighballKit/Purge.swift
new file mode 100644
index 0000000..2a3f496
--- /dev/null
+++ b/Sources/HighballKit/Purge.swift
@@ -0,0 +1,133 @@
+import Foundation
+
+/// One entry a purge could not remove, with enough state to explain why.
+///
+/// Foundation's own error is useless here: a failed recursive remove reports the *top-level*
+/// path it was handed and never the entry that actually blocked it, so the app has no way to
+/// name the culprit without walking the tree itself (#38).
+public struct PurgeFailure: Sendable, Hashable, CustomStringConvertible {
+ public let path: String
+ public let code: Int32
+ public let mode: mode_t
+ public let flags: UInt32
+ public let uid: UInt32
+
+ public init(path: String, code: Int32, mode: mode_t = 0, flags: UInt32 = 0, uid: UInt32 = 0) {
+ self.path = path
+ self.code = code
+ self.mode = mode
+ self.flags = flags
+ self.uid = uid
+ }
+
+ /// The errno text, e.g. "Permission denied".
+ public var reason: String { String(cString: strerror(code)) }
+
+ /// Mode, flags and uid go in the message on purpose: they are the only evidence that can
+ /// tell us what makes a directory unremovable inside a real prefix, which #38 left open.
+ public var description: String {
+ "\(path): \(reason) (mode \(String(mode & 0o7777, radix: 8)) flags \(flags) uid \(uid))"
+ }
+}
+
+/// Removes a directory tree, doing everything a user could do without privilege escalation.
+///
+/// `FileManager.removeItem` gives up on far less than the filesystem actually allows: it stops
+/// at the first unwritable directory, immutable flag or deny ACL, and cannot delete a path over
+/// `PATH_MAX` at all. Since a Wine prefix is written by arbitrary Windows installers, any of
+/// those can appear in one.
+public enum Purge {
+ /// Best effort. Returns what is still on disk afterwards, deepest entry first, so the
+ /// caller can name the real cause rather than an ENOTEMPTY cascade above it.
+ @discardableResult
+ public static func tree(at url: URL) -> [PurgeFailure] {
+ // This deletes recursively and eventually shells out to `rm -rf`, so refuse the shallow
+ // paths a bug upstream could produce: "/", "/Users", "/Users/someone", a volume root.
+ // Everything Highball actually purges is at least <home>/.trash/<entry>, far deeper.
+ guard url.isFileURL, url.pathComponents.count >= 4 else {
+ return [PurgeFailure(path: url.path, code: EINVAL)]
+ }
+ // Healthy trees, which is nearly all of them, take the cheap path.
+ if (try? FileManager.default.removeItem(at: url)) != nil { return [] }
+
+ var failures: [PurgeFailure] = []
+ force(url.path, &failures)
+ if !exists(url.path) { return [] }
+
+ // Two things the walk above cannot clear: stripping an ACL needs acl(3), and unlink()
+ // on a path over PATH_MAX fails with ENAMETOOLONG whatever the permissions. Both fall
+ // to the system tools — chmod uses acl_set_file, and rm walks with fts, which chdirs
+ // so a long path is never formed. Ordering matters: modes are already repaired here,
+ // so chmod can descend.
+ _ = run("/bin/chmod", ["-R", "-N", url.path])
+ _ = run("/bin/rm", ["-rf", url.path])
+ if !exists(url.path) { return [] }
+
+ failures.removeAll()
+ collect(url.path, &failures)
+ return failures
+ }
+
+ /// Depth-first, repairing each node on the way down.
+ private static func force(_ path: String, _ failures: inout [PurgeFailure]) {
+ var st = stat()
+ guard lstat(path, &st) == 0 else {
+ if errno != ENOENT { failures.append(PurgeFailure(path: path, code: errno)) }
+ return
+ }
+ // uchg/uappnd block unlink and rmdir. lchflags, never chflags: every bottle links
+ // drive_c/users/<user>/{Documents,Desktop,Downloads} at the real home folders and
+ // dosdevices/z: at /, and chflags follows symlinks straight out of the tree.
+ if st.st_flags != 0 { _ = lchflags(path, 0) }
+
+ // Likewise lstat, never fileExists(atPath:isDirectory:) — that call follows symlinks
+ // and calls a link to ~/Documents a directory, so a recursion built on it would
+ // descend into and delete the user's home folders.
+ guard (st.st_mode & S_IFMT) == S_IFDIR else {
+ if unlink(path) != 0, errno != ENOENT { failures.append(fail(path, st)) }
+ return
+ }
+ // A directory's contents cannot be listed or unlinked without owner rwx on it.
+ if (st.st_mode & 0o700) != 0o700 { _ = chmod(path, st.st_mode | 0o700) }
+ for entry in (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? [] {
+ force(path + "/" + entry, &failures)
+ }
+ if rmdir(path) != 0, errno != ENOENT { failures.append(fail(path, st)) }
+ }
+
+ /// Reports what survived. Directories that are merely non-empty are skipped, so the list
+ /// holds the entries that actually refused to go rather than every parent above them.
+ private static func collect(_ path: String, _ failures: inout [PurgeFailure]) {
+ var st = stat()
+ guard lstat(path, &st) == 0 else { return }
+ guard (st.st_mode & S_IFMT) == S_IFDIR else {
+ if unlink(path) != 0 { failures.append(fail(path, st)) }
+ return
+ }
+ let entries = (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? []
+ for entry in entries { collect(path + "/" + entry, &failures) }
+ if (try? FileManager.default.contentsOfDirectory(atPath: path))?.isEmpty ?? false {
+ if rmdir(path) != 0 { failures.append(fail(path, st)) }
+ }
+ }
+
+ private static func fail(_ path: String, _ st: stat) -> PurgeFailure {
+ PurgeFailure(path: path, code: errno, mode: st.st_mode, flags: st.st_flags, uid: st.st_uid)
+ }
+
+ private static func exists(_ path: String) -> Bool {
+ var st = stat()
+ return lstat(path, &st) == 0
+ }
+
+ private static func run(_ tool: String, _ args: [String]) -> Int32 {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: tool)
+ p.arguments = args
+ p.standardOutput = FileHandle.nullDevice
+ p.standardError = FileHandle.nullDevice
+ do { try p.run() } catch { return -1 }
+ p.waitUntilExit()
+ return p.terminationStatus
+ }
+}
diff --git a/Sources/highball/main.swift b/Sources/highball/main.swift
index 6ea3e9b..48edbfb 100644
--- a/Sources/highball/main.swift
+++ b/Sources/highball/main.swift
@@ -74,11 +74,16 @@ struct Bottle: AsyncParsableCommand {
struct List: AsyncParsableCommand {
func run() async throws {
- let bottles = try BottleStore().list()
- if bottles.isEmpty { print("no bottles"); return }
+ let store = BottleStore()
+ let bottles = try store.list()
+ let damaged = (try? store.damaged()) ?? []
+ if bottles.isEmpty && damaged.isEmpty { print("no bottles"); return }
for b in bottles {
print("\(b.name)\tengine=\(b.settings.engineID)\trenderer=\(b.settings.renderer.rawValue)\tpins=\(b.settings.pins.count)\trecipes=\(b.settings.recipes.joined(separator: ","))")
}
+ // A folder that isn't a loadable bottle used to be silently skipped, which is how a
+ // half-deleted bottle became invisible and unreachable (#38).
+ for d in damaged { print("\(d.name)\tDAMAGED — \(d.reason) (delete it to free the name)") }
}
}
@@ -109,7 +114,17 @@ struct Bottle: AsyncParsableCommand {
struct Delete: AsyncParsableCommand {
@Argument var name: String
- func run() async throws { try BottleStore().delete(name); print("deleted \(name)") }
+ func run() async throws {
+ let store = BottleStore()
+ // Stop the bottle first, like every other subcommand that touches a prefix. The
+ // kill resolves the prefix by path, so it has to happen before the move.
+ if let b = try? store.get(name), let eng = try? EngineStore().engine(b.settings.engineID) {
+ try? WineRunner(engine: eng, bottle: b).kill()
+ }
+ let leftovers = try store.delete(name)
+ print("deleted \(name)")
+ for failure in leftovers { print("left behind: \(failure)") }
+ }
}
struct Set: AsyncParsableCommand {
diff --git a/Tests/HighballKitTests/BottleDeleteTests.swift b/Tests/HighballKitTests/BottleDeleteTests.swift
new file mode 100644
index 0000000..46b66a1
--- /dev/null
+++ b/Tests/HighballKitTests/BottleDeleteTests.swift
@@ -0,0 +1,210 @@
+import XCTest
+@testable import HighballKit
+
+/// Issue #38: deleting a bottle reported "you don't have permission to access it" and left the
+/// bottle half-destroyed — invisible to `list()`, refused by `delete()` and blocked by
+/// `create()`'s name check, with its files still on disk.
+final class BottleDeleteTests: XCTestCase {
+ private var home: URL!
+ private var paths: HighballPaths!
+ private var store: BottleStore!
+
+ override func setUpWithError() throws {
+ home = FileManager.default.temporaryDirectory.appending(path: "hb-del-\(UUID().uuidString)")
+ paths = HighballPaths(home: home)
+ store = BottleStore(paths: paths)
+ try paths.ensure()
+ }
+
+ override func tearDownWithError() throws {
+ if let home { Purge.tree(at: home) }
+ }
+
+ /// A bottle shaped like a real one: the same top-level entries, in a tree deep enough that
+ /// a blocker is reached only after the metadata.
+ @discardableResult
+ private func makeBottle(_ name: String, files: Int = 40) throws -> URL {
+ let url = paths.bottle(name)
+ let system32 = url.appending(path: "drive_c/windows/system32")
+ try FileManager.default.createDirectory(at: system32, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: url.appending(path: "dosdevices"), withIntermediateDirectories: true)
+ for i in 0..<files {
+ try "MZ".write(to: system32.appending(path: "lib\(i).dll"), atomically: true, encoding: .utf8)
+ }
+ for meta in ["system.reg", "user.reg", "userdef.reg", ".update-timestamp"] {
+ try "x".write(to: url.appending(path: meta), atomically: true, encoding: .utf8)
+ }
+ try Bottle(url: url, settings: BottleSettings(name: name, engineID: "test-engine")).save()
+ return url
+ }
+
+ /// Plants the thing that broke #38: a directory macOS will not let us empty.
+ private func lock(_ url: URL) throws {
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ try "locked".write(to: url.appending(path: "inside.dat"), atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: url.path)
+ }
+
+ // MARK: The bug
+
+ func testDeleteSucceedsWithAnUnwritableSubdirectory() throws {
+ let url = try makeBottle("play")
+ try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+
+ XCTAssertNoThrow(try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path), "bottles/play must be gone")
+ XCTAssertTrue(try store.list().isEmpty)
+ XCTAssertTrue(try store.damaged().isEmpty, "nothing may be left behind in bottles/")
+ }
+
+ func testDeleteSucceedsWithImmutableAndUnreadableEntries() throws {
+ let url = try makeBottle("play")
+ let dir = url.appending(path: "drive_c/Program Files/Game")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let immutable = dir.appending(path: "locked.dat")
+ try "x".write(to: immutable, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.immutable: true], ofItemAtPath: immutable.path)
+ try FileManager.default.createDirectory(at: dir.appending(path: "unreadable"), withIntermediateDirectories: true)
+ try FileManager.default.setAttributes([.posixPermissions: 0o000],
+ ofItemAtPath: dir.appending(path: "unreadable").path)
+
+ XCTAssertNoThrow(try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ }
+
+ /// The name must be reusable the instant delete returns. #38's reporter could not recreate
+ /// his bottle: `create()` refused because the gutted directory was still there.
+ func testDeleteFreesTheNameEvenWhenFilesCannotBeRemoved() throws {
+ let url = try makeBottle("play")
+ try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+
+ try store.delete("play")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: paths.bottle("play").path),
+ "the name must be free for create() to reuse")
+ }
+
+ // MARK: Atomicity
+
+ func testDeleteMovesTheBottleOutOfBottlesBeforePurging() throws {
+ let url = try makeBottle("play")
+ // An unpurgeable entry: a 0555 directory whose parent is also 0555, so even the forced
+ // walk leaves something behind and we can observe where the tree went.
+ try lock(url.appending(path: "drive_c/keep/inner"))
+ try FileManager.default.setAttributes([.posixPermissions: 0o555],
+ ofItemAtPath: url.appending(path: "drive_c/keep").path)
+
+ _ = try store.delete("play")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path),
+ "bottles/ must be clean whatever the purge managed")
+ }
+
+ /// Guards against someone "simplifying" rename(2) back into FileManager.moveItem, which
+ /// across volumes copies and then deletes — reproducing #38 with a full duplicate on the side.
+ func testDeleteIsARenameNotACopy() throws {
+ let url = try makeBottle("play")
+ try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+ let before = try FileManager.default.attributesOfItem(atPath: url.path)[.systemFileNumber] as? Int
+
+ _ = try store.delete("play")
+ let moved = (try? FileManager.default.contentsOfDirectory(at: paths.trash, includingPropertiesForKeys: nil)) ?? []
+ let after = moved.first.flatMap {
+ try? FileManager.default.attributesOfItem(atPath: $0.path)[.systemFileNumber] as? Int
+ }
+ XCTAssertNotNil(before)
+ XCTAssertEqual(before, after ?? before, "the tree must keep its inode: rename, not copy")
+ }
+
+ // MARK: Safety
+
+ /// The one mistake that would be catastrophic. Every bottle links
+ /// drive_c/users/<user>/{Documents,Desktop,Downloads} at the real home folders and
+ /// dosdevices/z: at /, so a purge that followed symlinks would delete the user's data.
+ func testPurgeNeverFollowsSymlinksOutOfTheTree() throws {
+ let url = try makeBottle("play")
+ let outside = home.appending(path: "precious")
+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
+ let canary = outside.appending(path: "canary.txt")
+ try "do not delete".write(to: canary, atomically: true, encoding: .utf8)
+
+ let users = url.appending(path: "drive_c/users/tester")
+ try FileManager.default.createDirectory(at: users, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: users.appending(path: "Documents"), withDestinationURL: outside)
+ try FileManager.default.createSymbolicLink(at: url.appending(path: "dosdevices/z:"),
+ withDestinationURL: URL(fileURLWithPath: "/"))
+ // Force the slow path, so the hand-written recursion is what gets exercised.
+ try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+
+ _ = try store.delete("play")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: canary.path),
+ "the purge followed a symlink out of the bottle")
+ XCTAssertEqual(try String(contentsOf: canary, encoding: .utf8), "do not delete")
+ }
+
+ // MARK: Recovery
+
+ /// The state #38's reporter is stuck in: a directory with no readable settings file. It was
+ /// invisible to `list()` and `delete()` refused it, so there was no way out from the app.
+ func testADamagedBottleIsListedAndDeletable() throws {
+ let url = try makeBottle("play")
+ try FileManager.default.removeItem(at: url.appending(path: "bottle.json"))
+
+ XCTAssertTrue(try store.list().isEmpty, "list() still only shows loadable bottles")
+ XCTAssertEqual(try store.damaged().map(\.name), ["play"])
+ XCTAssertNoThrow(try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ }
+
+ /// A Gin-era bottle keeps its settings in gin.json. `Bottle.load` accepts it, so `list()`
+ /// showed it while the old bottle.json guard made it permanently undeletable.
+ func testALegacyGinBottleIsDeletable() throws {
+ let url = try makeBottle("play")
+ try FileManager.default.moveItem(at: url.appending(path: "bottle.json"),
+ to: url.appending(path: "gin.json"))
+
+ XCTAssertEqual(try store.list().map(\.name), ["play"])
+ XCTAssertNoThrow(try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ }
+
+ func testDeletingAnAbsentBottleStillReportsItMissing() throws {
+ XCTAssertThrowsError(try store.delete("nope"))
+ }
+
+ func testDamagedIgnoresDotFilesAndLooseFiles() throws {
+ try "x".write(to: paths.bottles.appending(path: ".DS_Store"), atomically: true, encoding: .utf8)
+ try makeBottle("play")
+ XCTAssertTrue(try store.damaged().isEmpty)
+ }
+
+ // MARK: Leftovers
+
+ func testLeftoversAreReportedAndSweptLater() throws {
+ let url = try makeBottle("play")
+ let stubborn = url.appending(path: "drive_c/mnt")
+ try FileManager.default.createDirectory(at: stubborn, withIntermediateDirectories: true)
+
+ _ = try store.delete("play")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ // Nothing genuinely unpurgeable here, so the sweep has nothing to report and .trash empties.
+ XCTAssertTrue(store.sweepTrash().isEmpty)
+ let left = (try? FileManager.default.contentsOfDirectory(at: paths.trash, includingPropertiesForKeys: nil)) ?? []
+ XCTAssertTrue(left.isEmpty, "a purgeable tree must not linger in .trash")
+ }
+
+ /// The purge deletes recursively and shells out to rm -rf, so it must refuse a shallow
+ /// path outright rather than trust every future caller. "/" and a bare home must be inert.
+ func testPurgeRefusesShallowPaths() {
+ for dangerous in ["/", "/Users", "/Users/someone", "/Volumes"] {
+ let failures = Purge.tree(at: URL(fileURLWithPath: dangerous))
+ XCTAssertEqual(failures.first?.code, EINVAL, "\(dangerous) must be refused, not purged")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: "/Users"), "/Users must still exist")
+ }
+ }
+
+ /// Bottle names reach the trash path, so they must not be able to steer it.
+ func testTrashNameCannotEscapeTheTrashDirectory() {
+ XCTAssertFalse(BottleStore.trashName("../../etc").contains("/"))
+ XCTAssertFalse(BottleStore.trashName("..").contains("."))
+ XCTAssertFalse(BottleStore.trashName("a/b:c").contains("/"))
+ }
+}