Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/StableBar/App/HelpQuestion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ struct HelpQuestion: Identifiable {

Your `~/.config/stablebar` folder, with your configuration, scripts and packages, stays unless you check **Also move ~/.config/stablebar to the Trash**.

If Homebrew installed StableBar, run **Uninstall** first and click **Quit StableBar**, then run `brew uninstall --cask stablebar`, or `brew uninstall --zap --cask stablebar` to also delete `~/.config/stablebar`. Homebrew alone only removes files, so it leaves the menu bar's auto-hide, Open at login and permissions as they are. See [Uninstall](getting-started.md#uninstall).
If Homebrew installed StableBar, `brew uninstall --cask stablebar` does the same, and `brew uninstall --zap --cask stablebar` also moves `~/.config/stablebar` to the Trash. An install from before StableBar 0.19.0 needs `brew reinstall --cask stablebar` first. See [Uninstall](getting-started.md#uninstall).

"""#
}
100 changes: 100 additions & 0 deletions Sources/StableBar/App/HomebrewUninstall.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import AppKit
import CoreServices

/// What the Homebrew cask's `uninstall` script runs, so `brew uninstall --cask stablebar` undoes the same changes as
/// Settings › Uninstall. Homebrew also runs that script when it upgrades or reinstalls StableBar, and doesn't tell the
/// script which, so the steps wait until `brew` has exited and run only when StableBar is no longer installed.
@MainActor
enum HomebrewUninstall {
/// Names the folder of the copy that waits for `brew`, so only that folder is ever deleted.
nonisolated static let copyFolderPrefix = "StableBar uninstall "

/// `--homebrew-uninstall`: runs while the app is still in place and `brew` waits for it, so it only starts the
/// copy that waits. It never fails `brew`: when it can't start that copy, it says how to finish by hand.
static func start() -> Int32 {
let app = Bundle.main.bundleURL
guard getuid() != 0, app.pathExtension == "app" else { return 0 }
var made: URL?
do {
// Not in a temporary folder: Launch Services doesn't look there, so tccutil wouldn't find StableBar.
let caches = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let folder = caches.appending(path: copyFolderPrefix + UUID().uuidString, directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
made = folder
// The steps need a whole app: Open at login and the preferences belong to its bundle, and Homebrew is
// about to delete this one.
let copy = folder.appending(path: app.lastPathComponent, directoryHint: .isDirectory)
try FileManager.default.copyItem(at: app, to: copy)
removeQuarantine(copy)
guard let executable = Bundle(url: copy)?.executablePath else { throw CommandFailure(message: "The copy has no executable.") }
// Homebrew deletes the preferences file when zapping, before StableBar could read this record.
let menuBar = MenuBarAutoHide.turnedOnByStableBar() ? ["--show-menu-bar"] : []
try spawnDetached(executable, arguments: ["--finish-homebrew-uninstall", String(getppid()), app.path] + menuBar)
print("Once Homebrew is done, StableBar undoes what it changed on this Mac, unless Homebrew installs it again.")
} catch {
if let made { try? FileManager.default.removeItem(at: made) }
print("StableBar couldn’t start undoing what it changed on this Mac: \(errorMessage(error))")
print("See https://github.com/stablebox/StableBar/blob/main/docs/getting-started.md#uninstall to undo it by hand.")
}
return 0
}

/// `--finish-homebrew-uninstall [PID] APP [--show-menu-bar]`: with `brew`'s process ID, waits for it to exit, then
/// opens this copy as an app without one. That copy does what Settings › Uninstall does, except moving the app,
/// which Homebrew removed, and an alert lists any step that failed.
static func finish(after brew: pid_t?, app: URL, showsMenuBar: Bool) async -> Int32 {
if let brew { _ = try? await Uninstall.waitForQuit(every: .milliseconds(500)) { kill(brew, 0) == 0 } }
guard !isInstalled(app) else {
removeCopy()
return 0
}
// Opened by Launch Services, the copy controls System Events, to turn off auto-hide, with StableBar's own
// permission. Started from brew, it would make macOS ask whether the terminal may.
if brew != nil, await openAsApp(["--finish-homebrew-uninstall", app.path] + (showsMenuBar ? ["--show-menu-bar"] : [])) {
return 0
}
// tccutil looks StableBar up in Launch Services, which forgot it once Homebrew deleted the app.
LSRegisterURL(Bundle.main.bundleURL as CFURL, true)
var snapshot = UninstallSystem.snapshot()
snapshot.app = nil
var options = UninstallOptions(snapshot)
options.showsMenuBar = options.showsMenuBar || showsMenuBar
let steps = snapshot.steps(options)
let outcomes = await Uninstall.run(steps, perform: UninstallSystem.perform)
removeCopy()
// Homebrew removed the app, so the alert lists every step left to do by hand, not just the quit.
return UninstallSystem.report(outcomes + Uninstall.notRun(steps, after: outcomes))
}

/// Whether StableBar is still installed once `brew` is done, as after an upgrade, a reinstall or a failed uninstall.
nonisolated static func isInstalled(_ app: URL, caskrooms: [URL] = UninstallSnapshot.caskrooms) -> Bool {
FileManager.default.fileExists(atPath: app.path) || UninstallSnapshot.installedByHomebrew(caskrooms: caskrooms)
}

/// The folder `start` made for this copy, or nil when StableBar runs from anywhere else.
nonisolated static func copyFolder(of bundle: URL) -> URL? {
let folder = bundle.deletingLastPathComponent()
return folder.lastPathComponent.hasPrefix(copyFolderPrefix) ? folder : nil
}

private static func openAsApp(_ arguments: [String]) async -> Bool {
let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = arguments
configuration.activates = false
configuration.addsToRecentItems = false
configuration.createsNewApplicationInstance = true
configuration.promptsUserIfNeeded = false
return (try? await NSWorkspace.shared.openApplication(at: Bundle.main.bundleURL, configuration: configuration)) != nil
}

/// The copy keeps the quarantine of Homebrew's download, which can make macOS ask before opening it.
private static func removeQuarantine(_ bundle: URL) {
let contents = FileManager.default.enumerator(at: bundle, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
for url in [bundle] + contents { removexattr(url.path, "com.apple.quarantine", XATTR_NOFOLLOW) }
}

private static func removeCopy() {
guard let folder = copyFolder(of: Bundle.main.bundleURL) else { return }
try? FileManager.default.removeItem(at: folder)
}
}
16 changes: 16 additions & 0 deletions Sources/StableBar/App/LaunchCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ enum LaunchCommand {
case uninstall(removesConfiguration: Bool, showsMenuBar: Bool, confirmed: Bool)
/// Started by Settings › Uninstall, not by hand: finishes the uninstall once the bar with this process ID has quit.
case finishUninstall(pid_t)
/// Run by the Homebrew cask's `uninstall` script, not by hand: see `HomebrewUninstall`.
case homebrewUninstall
/// Started by `--homebrew-uninstall`: once `brew` exits, uninstalls unless the app at this path is installed again.
case finishHomebrewUninstall(brew: pid_t?, app: URL, showsMenuBar: Bool)
/// A detached helper: wait for this bar to exit, then open the moved app with its original arguments.
case finishApplicationMove(URL, pid_t)
case version
Expand Down Expand Up @@ -172,6 +176,18 @@ enum LaunchCommand {
case "--finish-uninstall" where arguments.count == 2 && !targeted:
guard let bar = pid_t(arguments[1]), bar > 0 else { throw CommandFailure(message: Self.usage) }
self = .finishUninstall(bar)
case "--homebrew-uninstall" where arguments.count == 1 && !targeted:
self = .homebrewUninstall
case "--finish-homebrew-uninstall" where !targeted:
var rest = arguments.dropFirst()
let brew = rest.first.flatMap { pid_t($0) }
if brew != nil { rest = rest.dropFirst() }
let showsMenuBar = rest.last == "--show-menu-bar"
if showsMenuBar { rest = rest.dropLast() }
guard brew.map({ $0 > 0 }) ?? true, rest.count == 1, let app = rest.first, app.hasPrefix("/") else {
throw CommandFailure(message: Self.usage)
}
self = .finishHomebrewUninstall(brew: brew, app: URL(filePath: app, directoryHint: .isDirectory), showsMenuBar: showsMenuBar)
case "--finish-application-move" where arguments.count == 3 && !targeted:
guard let bar = pid_t(arguments[2]), bar > 0 else { throw CommandFailure(message: Self.usage) }
self = .finishApplicationMove(URL(filePath: arguments[1]), bar)
Expand Down
6 changes: 6 additions & 0 deletions Sources/StableBar/App/StableBarApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ struct StableBarApp {
case let .finishUninstall(bar):
Task { exit(await UninstallSystem.finish(after: bar)) }
dispatchMain()
case .homebrewUninstall:
exit(HomebrewUninstall.start())
case let .finishHomebrewUninstall(brew, app, showsMenuBar):
Task { exit(await HomebrewUninstall.finish(after: brew, app: app, showsMenuBar: showsMenuBar)) }
// Without brew's process ID, Launch Services opened it and waits for it to check in as an app.
if brew == nil { NSApplication.shared.run() } else { dispatchMain() }
case let .finishApplicationMove(plan, bar):
Task { exit(await ApplicationMoveRelaunch.finish(planURL: plan, parent: bar)) }
dispatchMain()
Expand Down
23 changes: 18 additions & 5 deletions Sources/StableBar/App/Uninstall.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ struct UninstallSnapshot: Equatable {
.filter { FileManager.default.fileExists(atPath: $0.path) }
}

static func installedByHomebrew(caskrooms: [URL] = ["/opt/homebrew/Caskroom", "/usr/local/Caskroom"].map {
URL(filePath: $0, directoryHint: .isDirectory)
}) -> Bool {
static let caskrooms = ["/opt/homebrew/Caskroom", "/usr/local/Caskroom"].map { URL(filePath: $0, directoryHint: .isDirectory) }

static func installedByHomebrew(caskrooms: [URL] = caskrooms) -> Bool {
caskrooms.contains { FileManager.default.fileExists(atPath: $0.appending(path: "stablebar").path) }
}
}
Expand Down Expand Up @@ -151,6 +151,11 @@ enum Uninstall {
return !isRunning()
}

/// The steps after a StableBar that wouldn't quit, which `run` didn't start, as not done.
static func notRun(_ steps: [UninstallStep], after outcomes: [UninstallOutcome]) -> [UninstallOutcome] {
steps.dropFirst(outcomes.count).map { UninstallOutcome(step: $0, error: "Not done while StableBar keeps running.") }
}

/// The steps that failed, each with what to do by hand.
static func leftToDo(_ outcomes: [UninstallOutcome]) -> String {
outcomes.compactMap { outcome in outcome.error.map { "\(outcome.step.title)\n\($0) \(outcome.step.fix)" } }
Expand Down Expand Up @@ -248,7 +253,11 @@ enum UninstallSystem {
_ = try await runCommand("/usr/bin/tccutil", arguments: ["reset", "All", bundleID])
case let .files(urls):
try Uninstall.remove(urls)
UserDefaults.standard.removePersistentDomain(forName: bundleID)
// Deleting the domain leaves an empty property list. UserDefaults writes it seconds later, even after
// StableBar has quit, while defaults writes it at once, so the file can go too. defaults fails when there's
// no domain left, as after brew uninstall --zap.
_ = try? await runCommand("/usr/bin/defaults", arguments: ["delete", bundleID])
try Uninstall.remove([FileManager.default.homeDirectoryForCurrentUser.appending(path: "Library/Preferences/\(bundleID).plist")])
}
}

Expand All @@ -263,7 +272,11 @@ enum UninstallSystem {
static func finish(after bar: pid_t) async -> Int32 {
_ = try? await Uninstall.waitForQuit { kill(bar, 0) == 0 }
let snapshot = UninstallSnapshot(files: files(), app: app, homebrew: UninstallSnapshot.installedByHomebrew())
let outcomes = await Uninstall.run(snapshot.stepsAfterQuit, perform: perform)
return report(await Uninstall.run(snapshot.stepsAfterQuit, perform: perform))
}

/// Without a bar or a terminal to tell, an alert lists the steps that failed and what to do by hand.
static func report(_ outcomes: [UninstallOutcome]) -> Int32 {
guard outcomes.contains(where: { $0.error != nil }) else { return 0 }
CFUserNotificationDisplayAlert(0, kCFUserNotificationCautionAlertLevel, nil, nil, nil,
"StableBar couldn’t finish uninstalling" as CFString,
Expand Down
91 changes: 91 additions & 0 deletions Tests/StableBarTests/HomebrewUninstallTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import Foundation
import Testing
@testable import StableBar

private func temporaryDirectory() throws -> URL {
let directory = FileManager.default.temporaryDirectory.appending(path: "Homebrew uninstall \(UUID().uuidString)", directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
return directory
}

@Test func homebrewUninstallTakesNoArguments() throws {
guard case .homebrewUninstall = try LaunchCommand(arguments: ["--homebrew-uninstall"]) else {
Issue.record("--homebrew-uninstall wasn't parsed")
return
}
for arguments in [["--homebrew-uninstall", "--yes"], ["--config", "/tmp/config.json", "--homebrew-uninstall"]] {
#expect(throws: CommandFailure.self) { try LaunchCommand(arguments: arguments) }
}
}

@Test func finishHomebrewUninstallWaitsForBrewWhenGivenItsProcessID() throws {
guard case let .finishHomebrewUninstall(brew, app, showsMenuBar) = try LaunchCommand(
arguments: ["--finish-homebrew-uninstall", "4242", "/Applications/StableBar.app", "--show-menu-bar"]) else {
Issue.record("--finish-homebrew-uninstall wasn't parsed")
return
}
#expect(brew == 4242)
#expect(app.path == "/Applications/StableBar.app")
#expect(showsMenuBar)
}

@Test func finishHomebrewUninstallWithoutAProcessIDRunsAtOnce() throws {
guard case let .finishHomebrewUninstall(brew, app, showsMenuBar) = try LaunchCommand(
arguments: ["--finish-homebrew-uninstall", "/Users/me/Applications/StableBar.app"]) else {
Issue.record("--finish-homebrew-uninstall wasn't parsed")
return
}
#expect(brew == nil)
#expect(app.path == "/Users/me/Applications/StableBar.app")
#expect(!showsMenuBar)
}

@Test func finishHomebrewUninstallRejectsOtherArguments() {
for arguments in [["--finish-homebrew-uninstall"], ["--finish-homebrew-uninstall", "4242"],
["--finish-homebrew-uninstall", "0", "/Applications/StableBar.app"],
["--finish-homebrew-uninstall", "-1", "/Applications/StableBar.app"],
["--finish-homebrew-uninstall", "4242", "StableBar.app"],
["--finish-homebrew-uninstall", "4242", "/Applications/StableBar.app", "--yes"],
["--finish-homebrew-uninstall", "4242", "/Applications/StableBar.app", "/Applications/Other.app"],
["--config", "/tmp/config.json", "--finish-homebrew-uninstall", "4242", "/Applications/StableBar.app"]] {
#expect(throws: CommandFailure.self, "\(arguments)") { try LaunchCommand(arguments: arguments) }
}
}

@Test func stableBarIsStillInstalledAfterAnUpgradeOrAReinstall() throws {
let directory = try temporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
let app = directory.appending(path: "Applications/StableBar.app", directoryHint: .isDirectory)
let caskroom = directory.appending(path: "Caskroom", directoryHint: .isDirectory)
#expect(!HomebrewUninstall.isInstalled(app, caskrooms: [caskroom]))
try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)
#expect(HomebrewUninstall.isInstalled(app, caskrooms: [caskroom]))
try FileManager.default.removeItem(at: app)
// An upgrade that failed after removing the app still leaves Homebrew's record.
try FileManager.default.createDirectory(at: caskroom.appending(path: "stablebar"), withIntermediateDirectories: true)
#expect(HomebrewUninstall.isInstalled(app, caskrooms: [caskroom]))
}

@Test func onlyTheCopysOwnFolderIsRemoved() {
let copy = URL(filePath: "/Users/me/Library/Caches/\(HomebrewUninstall.copyFolderPrefix)1234/StableBar.app", directoryHint: .isDirectory)
#expect(HomebrewUninstall.copyFolder(of: copy)?.lastPathComponent == "\(HomebrewUninstall.copyFolderPrefix)1234")
#expect(HomebrewUninstall.copyFolder(of: URL(filePath: "/Applications/StableBar.app", directoryHint: .isDirectory)) == nil)
#expect(HomebrewUninstall.copyFolder(of: URL(filePath: "/Users/me/Downloads/StableBar.app", directoryHint: .isDirectory)) == nil)
}

@Test func stepsAfterHomebrewLeaveTheAppToHomebrew() {
let copy = URL(filePath: "/Users/me/Library/Caches/\(HomebrewUninstall.copyFolderPrefix)1234/StableBar.app", directoryHint: .isDirectory)
var snapshot = UninstallSnapshot(menuBarHides: true, turnedOnMenuBarAutoHide: true, opensAtLogin: true, app: copy)
snapshot.app = nil
let steps = snapshot.steps(UninstallOptions(snapshot))
#expect(steps == [.showMenuBar, .loginItem, .permissions, .files([])])
}

@Test func stepsAStableBarThatWontQuitKeptFromRunningAreListedAsNotDone() {
let steps: [UninstallStep] = [.quit(1), .loginItem, .permissions]
let outcomes = [UninstallOutcome(step: .quit(1), error: "StableBar is still running.")]
#expect(Uninstall.notRun(steps, after: outcomes).map(\.step) == [.loginItem, .permissions])
#expect(Uninstall.notRun(steps, after: outcomes).allSatisfy { $0.error != nil })
let finished = steps.map { UninstallOutcome(step: $0, error: nil) }
#expect(Uninstall.notRun(steps, after: finished).isEmpty)
}
Loading
Loading