Skip to content

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

home location: stream a copy onto a share, and warn instead of refusing

Silverdragon1224b983f0c0df4
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index a753039..6151350 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -416,16 +416,18 @@ final class AppState {
/// A location chosen in Settings, waiting for the move to be confirmed.
var pendingHome: URL?
- /// Settings › Environments › Change…: a folder on any APFS volume, checked before anything moves.
+ /// Settings › Environments › Change…: a folder that can hold an environment, checked before
+ /// anything moves. A network share is allowed and warned about, not refused.
func chooseHome() {
let panel = NSOpenPanel()
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true
panel.prompt = L("Use this folder")
panel.message = L("Highball will keep its engines and environments in this folder. Pick a drive with room to spare: Highball checks the folder before moving anything, and says so if the drive cannot hold an environment.")
guard panel.runModal() == .OK, let url = panel.url else { return }
- if let why = HighballPaths.locationProblem(url) { errorMessage = why; return }
- if url.standardizedFileURL == paths.home.standardizedFileURL { return }
- pendingHome = url
+ let folder = URL(fileURLWithPath: url.path, isDirectory: true)
+ if let why = HighballPaths.locationProblem(folder) { errorMessage = why; return }
+ if folder.standardizedFileURL == paths.home.standardizedFileURL { return }
+ pendingHome = folder
}
/// Moves everything, records the location, then relaunches: the running app keeps its old paths.
@@ -436,8 +438,8 @@ final class AppState {
expected: L("as long as copying your games takes; nothing is removed until the copy checks out"),
done: DoneState(title: L("Moved. Highball needs a relaunch to use the new location."), ctaTitle: L("Relaunch"), cta: { Self.relaunch() })) { [self] in
try await Task.detached {
- try HomeMove.move(from: source, to: target) { name in
- Task { @MainActor in self.stage = String(format: L("Copying %@…"), name) }
+ try HomeMove.move(from: source, to: target) { name, copied, items in
+ Task { @MainActor in self.reportHomeCopy(name: name, copied: copied, items: items) }
}
try HighballPaths.setConfiguredHome(target)
}.value
@@ -453,8 +455,30 @@ final class AppState {
}
pendingHome = nil
runBusy(L("Moving Highball's data back to the default location"), done: DoneState(title: L("Moved. Highball needs a relaunch."), ctaTitle: L("Relaunch"), cta: { Self.relaunch() })) { [self] in
- try await Task.detached { try HomeMove.move(from: self.paths.home, to: target); try HighballPaths.setConfiguredHome(nil) }.value
+ try await Task.detached {
+ try HomeMove.move(from: self.paths.home, to: target) { name, copied, items in
+ Task { @MainActor in self.reportHomeCopy(name: name, copied: copied, items: items) }
+ }
+ try HighballPaths.setConfiguredHome(nil)
+ }.value
+ }
+ }
+
+ /// File count in the stage line so a tree of tiny files is not stuck on "0 MB".
+ private func reportHomeCopy(name: String, copied: Int64, items: Int) {
+ stage = items <= 0
+ ? String(format: L("Copying %@…"), name)
+ : items == 1
+ ? String(format: L("Copying %@ — 1 file"), name)
+ : String(format: L("Copying %@ — %d files"), name, items)
+ lastOutputAt = Date()
+ if let last = transferSamples.last, copied < last.bytes { transferSamples = [] }
+ transferSamples.append(.init(bytes: copied, at: Date()))
+ if transferSamples.count > 40 {
+ transferSamples.removeFirst(transferSamples.count - 40)
}
+ transferRate = ActivityText.rate(transferSamples)
+ busyProgress = Transfer(received: copied, total: nil)
}
static func relaunch() {
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index b57f4c4..48e01ed 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -266,6 +266,12 @@ struct ContentView: View {
}
}
+private func homeMoveAskMessage(to target: URL, from source: URL) -> String {
+ let copy = String(format: L("Engines, environments and downloads copy to %@, get checked, and are then removed from %@. Highball relaunches when it is done. Nothing is removed until the copy checks out."), target.path, source.path)
+ guard let warning = HighballPaths.locationWarning(target) else { return copy }
+ return L(warning) + "\n\n" + copy
+}
+
// The main window's dialogs, one function each. Chained in `body` they were a single
// expression that Xcode 16's type checker gave up on ("unable to type-check this expression
// in reasonable time", CI and the nightly E2E on 2026-09-08) while Xcode 26 took it fine.
@@ -336,7 +342,7 @@ private extension View {
Button(L("Move now")) { state.moveHome(to: target) }
Button(L("Cancel"), role: .cancel) { state.pendingHome = nil }
} message: { target in
- Text(String(format: L("Engines, environments and downloads copy to %@, get checked, and are then removed from %@. Highball relaunches when it is done. Nothing is removed until the copy checks out."), target.path, state.paths.home.path))
+ Text(homeMoveAskMessage(to: target, from: state.paths.home))
}
}
@MainActor func errorAlert(_ state: AppState) -> some View {
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index e87009e..48ad3cc 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -124,6 +124,10 @@ enum L10n {
"Move Highball's data to %@?": "Déplacer les données de Highball vers %@ ?",
"Moving Highball's data to %@": "Déplacement des données de Highball vers %@",
"Copying %@…": "Copie de %@…",
+ "Copying %@ — 1 file": "Copie de %@ — 1 fichier",
+ "Copying %@ — %d files": "Copie de %@ — %d fichiers",
+ "This folder is on a network share. Games can be slower there, and file locks sometimes get in the way. You can still use it.":
+ "Ce dossier est sur un partage réseau. Les jeux peuvent y être plus lents, et les verrous de fichiers gênent parfois. Vous pouvez tout de même l'utiliser.",
"Relaunch": "Relancer",
"Use the default location": "Utiliser l'emplacement par défaut",
"Your Highball folder is not connected": "Votre dossier Highball n'est pas connecté",
diff --git a/Sources/HighballKit/HomeMove.swift b/Sources/HighballKit/HomeMove.swift
new file mode 100644
index 0000000..ebd3a2c
--- /dev/null
+++ b/Sources/HighballKit/HomeMove.swift
@@ -0,0 +1,388 @@
+import Darwin
+import Foundation
+
+/// Moves Highball's data between homes (#24, #68): every top-level entry except the pointer file
+/// and the trash is copied, checked, and only then removed at the source, so a failure part way
+/// leaves the old home intact.
+///
+/// The copy is descriptor-relative and does not follow symbolic links. A Wine prefix contains
+/// `dosdevices/z:` pointing at `/` and `drive_c/users/<user>/{Documents,Desktop,Downloads}` at
+/// the real home folders. `FileManager.copyItem` is the wrong tool on a network share: it also
+/// copies ACLs, `com.apple.provenance` and Spotlight's `.metadata_never_index` marker, and SMB
+/// commonly refuses those — the failure reads as ".metadata_never_index couldn’t be copied
+/// because you don’t have permission to access drive_c". Data and the link structure are what
+/// an environment needs; Apple extra files are not, and a new marker is planted at the
+/// destination so Spotlight stays out.
+///
+/// File bytes go through `read`/`write` whenever the destination is not the same local APFS
+/// volume. `fclonefileat` (and `fcopyfile`) on smbfs can return success or hang without sending
+/// a byte — macOS asks the server to clone, the source is this Mac, and the share sits idle
+/// while the strip still says "Copying…". On a stream copy the check is the bytes actually
+/// written, not a walk of the destination, because a flaky share can stall that walk.
+public enum HomeMove {
+ public static let skipped: Set<String> = ["config.json", ".trash", ".DS_Store", ".metadata_never_index"]
+
+ /// Apple extra files that are not part of a Windows environment. Skipped at every level so a
+ /// share that vetoes them (Samba often lists `.metadata_never_index`) cannot abort a move,
+ /// and so a marker inside `drive_c` is not required to exist at the destination.
+ static let ephemeral: Set<String> = [
+ ".DS_Store",
+ ".metadata_never_index",
+ ".metadata_never_index_unless_rootfs",
+ ".localized",
+ ".Spotlight-V100",
+ ".fseventsd",
+ ".TemporaryItems",
+ ".Trashes",
+ ".Trash",
+ ".AppleDouble",
+ ".AppleDB",
+ ".AppleDesktop",
+ ]
+
+ /// `entry` is the top-level name (`bottles`, `engines`, …); `copied` is bytes written and
+ /// `items` is files and folders created, so a tree of tiny files is not stuck on "0 MB".
+ public static func move(from source: URL, to target: URL,
+ progress: (_ entry: String, _ copied: Int64, _ items: Int) -> Void = { _, _, _ in }) throws {
+ // NSOpenPanel sometimes hands back a file URL without a directory hint; appending
+ // "bottles" would then replace the folder name and write into the share's root.
+ let source = URL(fileURLWithPath: source.path, isDirectory: true)
+ let target = URL(fileURLWithPath: target.path, isDirectory: true)
+ try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
+ // Decide clone after the destination exists: a missing path makes statfs fail closed,
+ // which would stream a same-disk copy.
+ try move(from: source, to: target, clone: sameLocalVolume(source, target), progress: progress)
+ }
+
+ /// `clone` is the same-disk APFS fast path. Tests pass `false` to prove the stream copy
+ /// (network shares, and clonefile falling back) still lands a complete tree on this disk.
+ static func move(from source: URL, to target: URL, clone: Bool,
+ progress: (_ entry: String, _ copied: Int64, _ items: Int) -> Void) throws {
+ let fm = FileManager.default
+ try fm.createDirectory(at: target, withIntermediateDirectories: true)
+ // Plant the marker before the bulk copy so Spotlight does not start on a 90 GB tree mid-move.
+ // A share that vetoes the name is fine: ensure() retries after relaunch, and a missing
+ // marker must not block the move (that is the bug).
+ HighballPaths(home: target).excludeFromSpotlight()
+ let entries = try fm.contentsOfDirectory(atPath: source.path)
+ .filter { !skipped.contains($0) && !isEphemeral($0) }
+ .sorted()
+ for name in entries {
+ let from = source.appending(path: name), to = target.appending(path: name)
+ // Do not walk the tree first: on a large environment that is minutes of zero
+ // network while the strip already says Copying. Bytes start moving immediately.
+ progress(name, 0, 0)
+ try replaceDestination(to, name: name)
+ var copied: Int64 = 0
+ var items = 0
+ var lastReport = Date.distantPast
+ func publish() {
+ let now = Date()
+ guard now.timeIntervalSince(lastReport) >= 0.1 else { return }
+ lastReport = now
+ progress(name, copied, items)
+ }
+ func wrote(_ n: Int64) { copied += n; publish() }
+ func item() { items += 1; publish() }
+ try copyTree(from: from, to: to, clone: clone, wrote: wrote, item: item)
+ progress(name, copied, items)
+ let sourceTally = try tally(from)
+ if clone {
+ let destTally = try tally(to)
+ guard sourceTally == destTally else {
+ throw HighballError.failed("'\(name)' did not copy completely (\(sourceTally.files) files, \(sourceTally.bytes) bytes at the source, \(destTally.files) files, \(destTally.bytes) bytes at the destination); nothing was removed")
+ }
+ } else if sourceTally.bytes != copied {
+ // Walking the destination on a network share is slow and can stall; the bytes
+ // we actually wrote still have to match the source before anything is removed.
+ throw HighballError.failed("'\(name)' did not copy completely (\(sourceTally.files) files, \(sourceTally.bytes) bytes at the source, \(copied) bytes written); nothing was removed")
+ }
+ }
+ for name in entries { try fm.removeItem(at: source.appending(path: name)) }
+ }
+
+ /// File count and byte total under a path, links counted as themselves and not followed.
+ /// Ephemeral Apple files are omitted so a skipped marker cannot make a complete copy look short.
+ public static func tally(_ root: URL) throws -> (files: Int, bytes: Int64) {
+ let fm = FileManager.default
+ var files = 0, bytes: Int64 = 0
+ let keys: [URLResourceKey] = [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]
+ guard let rootValues = try? root.resourceValues(forKeys: Set(keys + [.isDirectoryKey])) else { return (0, 0) }
+ if isEphemeral(root.lastPathComponent) { return (0, 0) }
+ if rootValues.isDirectory != true { return (1, Int64(rootValues.fileSize ?? 0)) }
+ guard let e = fm.enumerator(at: root, includingPropertiesForKeys: keys, options: []) else { return (0, 0) }
+ for case let url as URL in e {
+ if isEphemeral(url.lastPathComponent) { continue }
+ let v = try url.resourceValues(forKeys: Set(keys))
+ if v.isSymbolicLink == true { files += 1; continue }
+ if v.isRegularFile == true { files += 1; bytes += Int64(v.fileSize ?? 0) }
+ }
+ return (files, bytes)
+ }
+
+ static func isEphemeral(_ name: String) -> Bool {
+ ephemeral.contains(name) || name.hasPrefix("._")
+ }
+
+ /// Clonefile is APFS and same-volume only. smbfs often advertises copy-offload; clonefile
+ /// then hangs or "succeeds" without putting bytes on the wire.
+ static func sameLocalVolume(_ a: URL, _ b: URL) -> Bool {
+ var sa = statfs(), sb = statfs()
+ guard statfs(a.path, &sa) == 0, statfs(b.path, &sb) == 0 else { return false }
+ let local = UInt32(MNT_LOCAL)
+ guard (UInt32(sa.f_flags) & local) != 0, (UInt32(sb.f_flags) & local) != 0 else { return false }
+ guard fsTypeName(sa) == "apfs", fsTypeName(sb) == "apfs" else { return false }
+ return sa.f_fsid.val.0 == sb.f_fsid.val.0 && sa.f_fsid.val.1 == sb.f_fsid.val.1
+ }
+
+ private static func fsTypeName(_ s: statfs) -> String {
+ withUnsafeBytes(of: s.f_fstypename) { raw in
+ raw.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
+ }
+ }
+
+ /// Removes a leftover destination entry without following it. `removeItem` is enough on a
+ /// healthy tree; Purge is the fallback when a previous failed copy left SMB permissions that
+ /// Foundation will not unlink, so a retry is not stuck on the debris.
+ private static func replaceDestination(_ to: URL, name: String) throws {
+ var st = stat()
+ guard lstat(to.path, &st) == 0 else { return }
+ do {
+ try FileManager.default.removeItem(at: to)
+ } catch {
+ if to.pathComponents.count >= 4 { _ = Purge.tree(at: to) }
+ }
+ guard lstat(to.path, &st) != 0 else {
+ throw HighballError.failed("Could not replace “\(name)” in the destination folder. Remove that folder and try again. Nothing was removed from the original location.")
+ }
+ }
+
+ private static func copyTree(from src: URL, to dst: URL, clone: Bool,
+ wrote: (Int64) -> Void, item: () -> Void) throws {
+ raiseFileLimit()
+ let name = src.lastPathComponent
+ let srcParent = open(src.deletingLastPathComponent().path, O_RDONLY | O_DIRECTORY | O_CLOEXEC)
+ guard srcParent >= 0 else { throw fail(name) }
+ defer { close(srcParent) }
+ let dstParent = open(dst.deletingLastPathComponent().path, O_RDONLY | O_DIRECTORY | O_CLOEXEC)
+ guard dstParent >= 0 else { throw fail(name) }
+ defer { close(dstParent) }
+
+ var stack: [DirLevel] = []
+ defer {
+ while let level = stack.popLast() {
+ close(level.srcFd)
+ close(level.dstFd)
+ }
+ }
+ try copyEntry(name, from: srcParent, to: dstParent, display: name,
+ clone: clone, wrote: wrote, item: item, stack: &stack)
+ while var level = stack.last {
+ if level.next < level.kids.count {
+ let kid = level.kids[level.next]
+ level.next += 1
+ stack[stack.count - 1] = level
+ try copyEntry(kid, from: level.srcFd, to: level.dstFd,
+ display: level.display + "/" + kid,
+ clone: clone, wrote: wrote, item: item, stack: &stack)
+ } else {
+ stack.removeLast()
+ close(level.srcFd)
+ close(level.dstFd)
+ }
+ }
+ }
+
+ private struct DirLevel {
+ let srcFd: Int32, dstFd: Int32
+ let kids: [String]
+ var next: Int
+ let display: String
+ }
+
+ private static func copyEntry(_ name: String, from srcParent: Int32, to dstParent: Int32,
+ display: String, clone: Bool, wrote: (Int64) -> Void, item: () -> Void,
+ stack: inout [DirLevel]) throws {
+ guard isSafeName(name) else { throw fail(display, EINVAL) }
+ if isEphemeral(name) { return }
+ var st = stat()
+ guard fstatat(srcParent, name, &st, AT_SYMLINK_NOFOLLOW) == 0 else { throw fail(display) }
+ switch st.st_mode & S_IFMT {
+ case S_IFLNK:
+ try copySymlink(name, from: srcParent, to: dstParent, display: display)
+ item()
+ case S_IFDIR:
+ try copyDirectory(name, from: srcParent, to: dstParent, observed: st,
+ display: display, stack: &stack)
+ item()
+ case S_IFREG:
+ try copyFile(name, from: srcParent, to: dstParent, observed: st,
+ display: display, clone: clone, wrote: wrote)
+ item()
+ default:
+ // Sockets, FIFOs and device nodes are runtime leftovers, not environment data.
+ return
+ }
+ }
+
+ private static func copyDirectory(_ name: String, from srcParent: Int32, to dstParent: Int32,
+ observed: stat, display: String, stack: inout [DirLevel]) throws {
+ let mode = (observed.st_mode & 0o777) | 0o700
+ if mkdirat(dstParent, name, mode) != 0 {
+ try makeWritable(dstParent)
+ guard mkdirat(dstParent, name, mode) == 0 else { throw fail(display) }
+ }
+ _ = fchmodat(dstParent, name, mode, AT_SYMLINK_NOFOLLOW)
+
+ let srcFd = openat(srcParent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ guard srcFd >= 0 else { throw fail(display) }
+ var dstFd = openat(dstParent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ if dstFd < 0 {
+ try makeWritable(dstParent)
+ dstFd = openat(dstParent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ }
+ guard dstFd >= 0 else {
+ close(srcFd)
+ throw fail(display)
+ }
+ guard let kids = entries(of: srcFd) else {
+ let code = errno
+ close(srcFd)
+ close(dstFd)
+ throw fail(display, code)
+ }
+ stack.append(DirLevel(srcFd: srcFd, dstFd: dstFd, kids: kids, next: 0, display: display))
+ }
+
+ private static func copyFile(_ name: String, from srcParent: Int32, to dstParent: Int32,
+ observed: stat, display: String, clone: Bool,
+ wrote: (Int64) -> Void) throws {
+ let srcFd = openat(srcParent, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
+ guard srcFd >= 0 else {
+ // Became a symlink between lstat and open: copy the link, never the target.
+ if errno == ELOOP { try copySymlink(name, from: srcParent, to: dstParent, display: display); return }
+ throw fail(display)
+ }
+ defer { close(srcFd) }
+
+ if clone, fclonefileat(srcFd, dstParent, name, 0) == 0 {
+ wrote(Int64(observed.st_size))
+ return
+ }
+
+ let mode = observed.st_mode & 0o777
+ var dstFd = openat(dstParent, name, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode)
+ if dstFd < 0 {
+ try makeWritable(dstParent)
+ dstFd = openat(dstParent, name, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode)
+ }
+ guard dstFd >= 0 else { throw fail(display) }
+
+ do {
+ try writeCopy(from: srcFd, to: dstFd, display: display, wrote: wrote)
+ } catch {
+ close(dstFd)
+ _ = unlinkat(dstParent, name, 0)
+ throw error
+ }
+ _ = fchmod(dstFd, mode)
+ close(dstFd)
+ }
+
+ /// Plain POSIX copy. `fcopyfile` is not used: on smbfs it can take the server-side copy
+ /// path and stall the same way clonefile does.
+ private static func writeCopy(from srcFd: Int32, to dstFd: Int32, display: String,
+ wrote: (Int64) -> Void) throws {
+ let bufSize = 256 * 1024
+ let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: bufSize)
+ defer { buf.deallocate() }
+ while true {
+ let n = read(srcFd, buf, bufSize)
+ if n == 0 { return }
+ if n < 0 {
+ if errno == EINTR { continue }
+ throw fail(display, errno)
+ }
+ var off = 0
+ while off < n {
+ let w = write(dstFd, buf + off, n - off)
+ if w < 0 {
+ if errno == EINTR { continue }
+ throw fail(display, errno)
+ }
+ off += w
+ }
+ wrote(Int64(n))
+ }
+ }
+
+ private static func copySymlink(_ name: String, from srcParent: Int32, to dstParent: Int32,
+ display: String) throws {
+ var buf = [CChar](repeating: 0, count: 4096)
+ var n = readlinkat(srcParent, name, &buf, buf.count)
+ while n == buf.count {
+ buf = [CChar](repeating: 0, count: buf.count * 2)
+ n = readlinkat(srcParent, name, &buf, buf.count)
+ }
+ guard n >= 0 else { throw fail(display) }
+ var target = [CChar](repeating: 0, count: n + 1)
+ for i in 0..<n { target[i] = buf[i] }
+ if symlinkat(target, dstParent, name) != 0 {
+ try makeWritable(dstParent)
+ guard symlinkat(target, dstParent, name) == 0 else { throw fail(display) }
+ }
+ }
+
+ private static func makeWritable(_ dirFd: Int32) throws {
+ var st = stat()
+ guard fstat(dirFd, &st) == 0 else { return }
+ _ = fchmod(dirFd, (st.st_mode & 0o777) | 0o700)
+ }
+
+ private static func isSafeName(_ name: String) -> Bool {
+ !name.isEmpty && name != "." && name != ".." && !name.contains("/") && !name.contains("\0")
+ }
+
+ private static func entries(of fd: Int32) -> [String]? {
+ let copy = dup(fd)
+ guard copy >= 0, let dir = fdopendir(copy) else {
+ let e = errno
+ if copy >= 0 { close(copy) }
+ errno = e
+ return nil
+ }
+ defer { closedir(dir) }
+ var names: [String] = []
+ while let entry = readdir(dir) {
+ var e = entry.pointee
+ let name = withUnsafePointer(to: &e.d_name) {
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(e.d_namlen) + 1) { String(cString: $0) }
+ }
+ if name == "." || name == ".." { continue }
+ names.append(name)
+ }
+ return names
+ }
+
+ private static func raiseFileLimit() {
+ var lim = rlimit()
+ guard getrlimit(RLIMIT_NOFILE, &lim) == 0 else { return }
+ let target = min(rlim_t(65536), lim.rlim_max)
+ guard lim.rlim_cur < target else { return }
+ lim.rlim_cur = target
+ _ = setrlimit(RLIMIT_NOFILE, &lim)
+ }
+
+ private static func fail(_ display: String, _ code: Int32 = errno) -> HighballError {
+ let reason = String(cString: strerror(code))
+ let shown = display.count <= 96 ? display : (display.split(separator: "/").suffix(2).joined(separator: "/"))
+ switch code {
+ case EACCES, EPERM:
+ return .failed("“\(shown)” couldn’t be copied onto that drive (\(reason)). On a network share, sign in with an account that can create files. Nothing was removed from the original location.")
+ case ENOTSUP, EOPNOTSUPP, EILSEQ:
+ return .failed("That drive rejected “\(shown)”. An environment needs symbolic links and names like c:. Nothing was removed from the original location.")
+ default:
+ return .failed("Could not copy “\(shown)” (\(reason)). Nothing was removed from the original location.")
+ }
+ }
+}
diff --git a/Sources/HighballKit/Paths.swift b/Sources/HighballKit/Paths.swift
index 03c8f32..818addc 100644
--- a/Sources/HighballKit/Paths.swift
+++ b/Sources/HighballKit/Paths.swift
@@ -1,3 +1,4 @@
+import Darwin
import Foundation
/// GitHub repo that receives community compatibility reports (owner/name).
@@ -67,6 +68,9 @@ public struct HighballPaths: Sendable {
/// refusal the release notes promised never happened. Measured 2026-09-09 on an exFAT volume:
/// the flag reads true, links are created, and a bottle moved there launches and runs. Asking
/// the volume directly also catches what a format name never could.
+ ///
+ /// A network share is not refused. Prefixes there have locking and speed problems of their
+ /// own, so `locationWarning` tells the picker; the folder can still be used.
public static func locationProblem(_ url: URL, defaultHome: URL = defaultHome) -> String? {
let fm = FileManager.default
var isDir: ObjCBool = false
@@ -87,6 +91,20 @@ public struct HighballPaths: Sendable {
return volumeProblem(url)
}
+ /// Why a usable folder is still a poor place for a prefix, or nil. Shown before the move,
+ /// never as a hard stop.
+ public static func locationWarning(_ url: URL) -> String? {
+ guard isNetworkVolume(url) else { return nil }
+ return "This folder is on a network share. Games can be slower there, and file locks sometimes get in the way. You can still use it."
+ }
+
+ /// Unknown paths fail closed as local, so a missing folder is not a scare.
+ static func isNetworkVolume(_ url: URL) -> Bool {
+ var st = statfs()
+ guard statfs(url.path, &st) == 0 else { return false }
+ return UInt32(st.f_flags) & UInt32(MNT_LOCAL) == 0
+ }
+
/// Makes and removes a scratch folder inside `url` to check what Wine actually needs from the
/// volume. Leaves nothing behind, including when a check fails.
static func volumeProblem(_ url: URL, uuid: String = UUID().uuidString) -> String? {
@@ -151,45 +169,6 @@ public struct HighballPaths: Sendable {
}
}
-/// Moves Highball's data between homes (#24, #68): every top-level entry except the pointer file
-/// and the trash is copied, checked file by file for count and bytes, and only then removed at
-/// the source, so a failure part way leaves the old home intact. Symbolic links are copied as
-/// links; the engine's absolute ones are re-made by the engine on its next use.
-public enum HomeMove {
- public static let skipped: Set<String> = ["config.json", ".trash", ".DS_Store"]
-
- public static func move(from source: URL, to target: URL, progress: (String) -> Void = { _ in }) throws {
- let fm = FileManager.default
- try fm.createDirectory(at: target, withIntermediateDirectories: true)
- let entries = try fm.contentsOfDirectory(atPath: source.path).filter { !skipped.contains($0) }.sorted()
- for name in entries {
- let from = source.appending(path: name), to = target.appending(path: name)
- progress(name)
- if fm.fileExists(atPath: to.path) { try fm.removeItem(at: to) }
- try fm.copyItem(at: from, to: to)
- let a = try tally(from), b = try tally(to)
- guard a == b else { throw HighballError.failed("'\(name)' did not copy completely (\(a.files) files, \(a.bytes) bytes at the source, \(b.files) files, \(b.bytes) bytes at the destination); nothing was removed") }
- }
- for name in entries { try fm.removeItem(at: source.appending(path: name)) }
- }
-
- /// File count and byte total under a path, links counted as themselves and not followed.
- public static func tally(_ root: URL) throws -> (files: Int, bytes: Int64) {
- let fm = FileManager.default
- var files = 0, bytes: Int64 = 0
- let keys: [URLResourceKey] = [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]
- guard let rootValues = try? root.resourceValues(forKeys: Set(keys + [.isDirectoryKey])) else { return (0, 0) }
- if rootValues.isDirectory != true { return (1, Int64(rootValues.fileSize ?? 0)) }
- guard let e = fm.enumerator(at: root, includingPropertiesForKeys: keys, options: []) else { return (0, 0) }
- for case let url as URL in e {
- let v = try url.resourceValues(forKeys: Set(keys))
- if v.isSymbolicLink == true { files += 1; continue }
- if v.isRegularFile == true { files += 1; bytes += Int64(v.fileSize ?? 0) }
- }
- return (files, bytes)
- }
-}
-
/// Builds a pre-filled GitHub bug-report URL: system info and a digest of the most relevant
/// log land in the issue form (field ids: what/chip/version/log in .github/ISSUE_TEMPLATE/bug.yml),
/// so every report arrives with the context that triage always needs.
diff --git a/Sources/highball/main.swift b/Sources/highball/main.swift
index 4bd0a5f..0076ccd 100644
--- a/Sources/highball/main.swift
+++ b/Sources/highball/main.swift
@@ -641,7 +641,7 @@ extension HighballKit.Renderer: ExpressibleByArgument {}
struct Config: AsyncParsableCommand {
static let configuration = CommandConfiguration(abstract: "Where Highball keeps engines and environments (#24): `config` shows it, `config home <folder>` moves there, `config home --default` goes back.")
@Argument(help: "'home' to change the location.") var setting: String?
- @Argument(help: "A folder on any APFS volume, or --default.") var value: String?
+ @Argument(help: "A folder Highball can keep data in, or --default.") var value: String?
@Flag(name: .customLong("default"), help: "Back to ~/Library/Application Support/Highball.") var useDefault = false
func run() async throws {
@@ -655,18 +655,26 @@ struct Config: AsyncParsableCommand {
if useDefault {
let target = HighballPaths.defaultHome
if paths.home.standardizedFileURL != target.standardizedFileURL, paths.hasData {
- print("moving data back to \(target.path)…"); try HomeMove.move(from: paths.home, to: target) { print(" \($0)") }
+ print("moving data back to \(target.path)…"); try moveHomePrinting(from: paths.home, to: target)
}
try HighballPaths.setConfiguredHome(nil); print("home: \(target.path) (default)"); return
}
guard let value else { throw ValidationError("usage: highball config home <folder> | --default") }
let target = URL(fileURLWithPath: value, isDirectory: true)
if let why = HighballPaths.locationProblem(target) { throw ValidationError(why) }
+ if let warning = HighballPaths.locationWarning(target) { print("warning: \(warning)") }
if paths.hasData, target.standardizedFileURL != paths.home.standardizedFileURL {
print("moving engines, environments and downloads to \(target.path)…")
- try HomeMove.move(from: paths.home, to: target) { print(" \($0)") }
+ try moveHomePrinting(from: paths.home, to: target)
}
try HighballPaths.setConfiguredHome(target)
print("home: \(target.path). Relaunch the Highball app to use it.")
}
}
+
+private func moveHomePrinting(from source: URL, to target: URL) throws {
+ var last = ""
+ try HomeMove.move(from: source, to: target) { name, _, _ in
+ if name != last { last = name; print(" \(name)") }
+ }
+}
diff --git a/Tests/HighballKitTests/HomeLocationTests.swift b/Tests/HighballKitTests/HomeLocationTests.swift
index 5583f9f..23ac423 100644
--- a/Tests/HighballKitTests/HomeLocationTests.swift
+++ b/Tests/HighballKitTests/HomeLocationTests.swift
@@ -1,3 +1,4 @@
+import Darwin
import XCTest
@testable import HighballKit
@@ -39,6 +40,7 @@ final class HomeLocationTests: XCTestCase {
XCTAssertNotNil(HighballPaths.locationProblem(tmp.appending(path: "missing"), defaultHome: def))
XCTAssertNotNil(HighballPaths.locationProblem(inside, defaultHome: def), "inside the default home would move the data into itself")
XCTAssertNotNil(HighballPaths.locationProblem(tmp, defaultHome: tmp.appending(path: "default")), "the default's own parent is refused too")
+ XCTAssertNil(HighballPaths.locationWarning(good), "a local folder is not a share warning")
}
// The volume check asks the volume instead of trusting a name. The old check read
@@ -85,25 +87,140 @@ final class HomeLocationTests: XCTestCase {
}
func testMoveCopiesChecksThenRemovesAndKeepsLinks() throws {
- let src = tmp.appending(path: "src"), dst = tmp.appending(path: "dst")
+ XCTAssertTrue(HomeMove.sameLocalVolume(tmp, tmp), "this disk is the clonefile path")
+ try assertMoveCopiesChecksThenRemovesAndKeepsLinks(clone: true)
+ }
+
+ func testMoveStreamsACompleteTreeWhenCloneIsOff() throws {
+ try assertMoveCopiesChecksThenRemovesAndKeepsLinks(clone: false)
+ }
+
+ private func assertMoveCopiesChecksThenRemovesAndKeepsLinks(clone: Bool) throws {
+ let src = tmp.appending(path: clone ? "src-clone" : "src-stream")
+ let dst = tmp.appending(path: clone ? "dst-clone" : "dst-stream")
let fm = FileManager.default
try fm.createDirectory(at: src.appending(path: "bottles/Games/dosdevices"), withIntermediateDirectories: true)
try fm.createDirectory(at: src.appending(path: "engines/e/wine"), withIntermediateDirectories: true)
try Data(repeating: 7, count: 5000).write(to: src.appending(path: "bottles/Games/system.reg"))
+ try Data().write(to: src.appending(path: "bottles/Games/empty.dat"))
try Data("x".utf8).write(to: src.appending(path: "engines/e/wine/w"))
try Data("{}".utf8).write(to: src.appending(path: "library.json"))
try Data("{\"home\":\"/x\"}".utf8).write(to: src.appending(path: "config.json"))
try fm.createSymbolicLink(atPath: src.appending(path: "bottles/Games/dosdevices/c:").path, withDestinationPath: "../drive_c")
let before = try HomeMove.tally(src.appending(path: "bottles"))
var seen: [String] = []
- try HomeMove.move(from: src, to: dst) { seen.append($0) }
+ var lastCopied: Int64 = 0
+ var lastItems = 0
+ try HomeMove.move(from: src, to: dst, clone: clone) { name, copied, items in
+ if seen.last != name { seen.append(name) }
+ lastCopied = copied
+ lastItems = items
+ }
XCTAssertEqual(seen, ["bottles", "engines", "library.json"], "the pointer file is not data")
+ XCTAssertGreaterThan(lastCopied, 0, "byte progress has to move or a network copy looks stuck")
+ XCTAssertGreaterThan(lastItems, 0, "file count has to move or a tree of tiny files looks stuck")
XCTAssertTrue(fm.fileExists(atPath: dst.appending(path: "bottles/Games/system.reg").path))
+ XCTAssertEqual(try Data(contentsOf: dst.appending(path: "bottles/Games/empty.dat")).count, 0)
let after = try HomeMove.tally(dst.appending(path: "bottles"))
XCTAssertEqual(after.files, before.files); XCTAssertEqual(after.bytes, before.bytes)
XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: dst.appending(path: "bottles/Games/dosdevices/c:").path), "../drive_c", "links travel as links")
XCTAssertFalse(fm.fileExists(atPath: src.appending(path: "bottles").path), "removed at the source only after the check")
XCTAssertTrue(fm.fileExists(atPath: src.appending(path: "config.json").path), "the pointer stays put")
+ XCTAssertTrue(fm.fileExists(atPath: dst.appending(path: ".metadata_never_index").path),
+ "Spotlight stays off at the destination even when the source marker is not copied")
+ }
+
+ /// A Wine prefix has `z:` → `/` and user folders → a directory outside the tree. The mover
+ /// copies those as links and never walks through them. Spotlight's `.metadata_never_index`
+ /// is skipped at every level: that name inside `drive_c` is what `copyItem` died on over SMB.
+ func testMoveDoesNotFollowOutboundLinksOrCopySpotlightMarkers() throws {
+ let src = tmp.appending(path: "src"), dst = tmp.appending(path: "dst")
+ let outside = tmp.appending(path: "outside")
+ let fm = FileManager.default
+ try fm.createDirectory(at: outside, withIntermediateDirectories: true)
+ try "canary".write(to: outside.appending(path: "canary.txt"), atomically: true, encoding: .utf8)
+
+ let bottle = src.appending(path: "bottles/Games")
+ try fm.createDirectory(at: bottle.appending(path: "dosdevices"), withIntermediateDirectories: true)
+ try fm.createDirectory(at: bottle.appending(path: "drive_c/users/tester"), withIntermediateDirectories: true)
+ try Data("reg".utf8).write(to: bottle.appending(path: "system.reg"))
+ try fm.createSymbolicLink(atPath: bottle.appending(path: "dosdevices/c:").path, withDestinationPath: "../drive_c")
+ try fm.createSymbolicLink(atPath: bottle.appending(path: "dosdevices/z:").path, withDestinationPath: "/")
+ try fm.createSymbolicLink(atPath: bottle.appending(path: "drive_c/users/tester/Documents").path,
+ withDestinationPath: outside.path)
+ XCTAssertTrue(fm.createFile(atPath: src.appending(path: ".metadata_never_index").path, contents: nil))
+ XCTAssertTrue(fm.createFile(atPath: bottle.appending(path: "drive_c/.metadata_never_index").path, contents: nil))
+ let fifo = bottle.appending(path: "drive_c/run.sock")
+ guard mkfifo(fifo.path, 0o644) == 0 else { return XCTFail("mkfifo: \(errno)") }
+
+ try HomeMove.move(from: src, to: dst)
+
+ XCTAssertTrue(fm.fileExists(atPath: src.appending(path: ".metadata_never_index").path),
+ "the source marker is not data and is left in place")
+ XCTAssertTrue(fm.fileExists(atPath: dst.appending(path: ".metadata_never_index").path))
+ XCTAssertFalse(fm.fileExists(atPath: dst.appending(path: "bottles/Games/drive_c/.metadata_never_index").path),
+ "a marker inside drive_c is Spotlight junk, not Windows data")
+ XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: dst.appending(path: "bottles/Games/dosdevices/z:").path), "/")
+ var zst = stat()
+ XCTAssertEqual(lstat(dst.appending(path: "bottles/Games/dosdevices/z:").path, &zst), 0)
+ XCTAssertEqual(zst.st_mode & S_IFMT, S_IFLNK, "z: must be a link, not a copy of /")
+ XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: dst.appending(path: "bottles/Games/dosdevices/c:").path), "../drive_c")
+ var dstSt = stat()
+ XCTAssertEqual(lstat(dst.appending(path: "bottles/Games/drive_c/users/tester/Documents").path, &dstSt), 0)
+ XCTAssertEqual(dstSt.st_mode & S_IFMT, S_IFLNK)
+ XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: dst.appending(path: "bottles/Games/drive_c/users/tester/Documents").path),
+ outside.path)
+ XCTAssertEqual(try String(contentsOf: outside.appending(path: "canary.txt"), encoding: .utf8), "canary")
+ XCTAssertTrue(fm.fileExists(atPath: "/usr"), "/ must be untouched")
+ var fifoSt = stat()
+ XCTAssertNotEqual(lstat(dst.appending(path: "bottles/Games/drive_c/run.sock").path, &fifoSt), 0,
+ "runtime sockets and FIFOs are not environment data")
+ }
+
+ func testTallySkipsSpotlightMarker() throws {
+ let root = tmp.appending(path: "bottle")
+ try FileManager.default.createDirectory(at: root.appending(path: "drive_c"), withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: root.appending(path: "drive_c/f"))
+ XCTAssertTrue(FileManager.default.createFile(atPath: root.appending(path: "drive_c/.metadata_never_index").path, contents: nil))
+ let t = try HomeMove.tally(root)
+ XCTAssertEqual(t.files, 1)
+ XCTAssertEqual(t.bytes, 1)
+ }
+
+ func testSameLocalVolumeIsTrueOnTheSameFolder() throws {
+ XCTAssertTrue(HomeMove.sameLocalVolume(tmp, tmp),
+ "a copy on this disk may clone; a network share must not")
+ }
+
+ func testSameLocalVolumeFailsClosedWhenTheDestinationIsMissing() {
+ let missing = URL(fileURLWithPath: "/Volumes/HighballMissingVolume", isDirectory: true)
+ XCTAssertFalse(HomeMove.sameLocalVolume(tmp, missing),
+ "a path that cannot be probed must not clonefile")
+ XCTAssertNil(HighballPaths.locationWarning(missing),
+ "a missing folder is not a share warning")
+ }
+
+ func testSameLocalVolumeIsFalseOnANetworkVolume() throws {
+ guard let remote = firstNetworkVolume() else {
+ throw XCTSkip("no network volume mounted")
+ }
+ XCTAssertFalse(HomeMove.sameLocalVolume(tmp, remote),
+ "a network share must stream bytes, never clonefile")
+ XCTAssertNotNil(HighballPaths.locationWarning(remote),
+ "a share is a warning, not a refusal")
+ }
+
+ /// Any non-local mount under /Volumes, so the test does not name a particular share.
+ private func firstNetworkVolume() -> URL? {
+ let root = URL(fileURLWithPath: "/Volumes", isDirectory: true)
+ guard let names = try? FileManager.default.contentsOfDirectory(atPath: root.path) else { return nil }
+ for name in names {
+ let url = root.appending(path: name, directoryHint: .isDirectory)
+ var st = statfs()
+ guard statfs(url.path, &st) == 0 else { continue }
+ if UInt32(st.f_flags) & UInt32(MNT_LOCAL) == 0 { return url }
+ }
+ return nil
}
func testHasData() throws {