Compare commits

..

No commits in common. "9f848be87530054d2efcec13ae92f423b5c08ad1" and "4ab3cc1e709d1c32a5d1136802e9ff1322b6a5c9" have entirely different histories.

View file

@ -14,8 +14,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem! var statusItem: NSStatusItem!
var statusMenuItem: NSMenuItem! var statusMenuItem: NSMenuItem!
var outdatedItem: NSMenuItem!
var upgradeAllItem: NSMenuItem!
var outdatedSubmenu: NSMenu! var outdatedSubmenu: NSMenu!
var versionItem: NSMenuItem! var versionItem: NSMenuItem!
@ -37,8 +35,9 @@ class AppDelegate: NSObject, NSApplicationDelegate {
} }
} }
/// last known outdated list, shown in the Upgrade All confirmation // cache to prevent duplicate outdated calls
var cachedOutdated: [String] = [] var cachedOutdated: [String] = []
var lastOutdatedFetch: Date?
// MARK: - Menu // MARK: - Menu
@ -54,13 +53,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
menu.addItem(NSMenuItem.separator()) menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "🔄 Refresh", action: #selector(refreshAction), keyEquivalent: "r")) menu.addItem(NSMenuItem(title: "🔄 Refresh", action: #selector(refreshAction), keyEquivalent: "r"))
upgradeAllItem = NSMenuItem(title: "📦 Upgrade All", action: #selector(upgradeAll), keyEquivalent: "u") menu.addItem(NSMenuItem(title: "📦 Upgrade All", action: #selector(upgradeAll), keyEquivalent: "u"))
upgradeAllItem.isHidden = true // shown once a fetch finds outdated packages let outdatedItem = NSMenuItem(title: "📋 Outdated", action: nil, keyEquivalent: "")
menu.addItem(upgradeAllItem)
outdatedItem = NSMenuItem(title: "📋 Outdated", action: nil, keyEquivalent: "")
outdatedSubmenu = NSMenu() outdatedSubmenu = NSMenu()
outdatedSubmenu.addItem(NSMenuItem(title: "Refresh List", action: #selector(forceRefreshOutdated), keyEquivalent: ""))
outdatedItem.submenu = outdatedSubmenu outdatedItem.submenu = outdatedSubmenu
outdatedItem.isHidden = true // shown once a fetch finds outdated packages
menu.addItem(outdatedItem) menu.addItem(outdatedItem)
menu.addItem(NSMenuItem(title: "📜 Logs", action: #selector(showLogs), keyEquivalent: "l")) menu.addItem(NSMenuItem(title: "📜 Logs", action: #selector(showLogs), keyEquivalent: "l"))
@ -177,40 +174,17 @@ class AppDelegate: NSObject, NSApplicationDelegate {
return "brew" return "brew"
} }
/// Written once per launch; sudo runs it to show a GUI password dialog
/// whenever brew needs admin rights (no terminal is attached to Process).
static let askpassURL: URL = {
let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("BrewBar", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let url = dir.appendingPathComponent("askpass.sh")
let script = """
#!/bin/zsh
osascript -e 'display dialog "BrewBar needs your administrator password to continue:" default answer "" with hidden answer with title "BrewBar" with icon caution buttons {"Cancel", "OK"} default button "OK"' -e 'text returned of result'
"""
try? script.write(to: url, atomically: true, encoding: .utf8)
try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)
return url
}()
func runBrew(_ command: String, completion: @escaping (String) -> Void = { _ in }) { func runBrew(_ command: String, completion: @escaping (String) -> Void = { _ in }) {
DispatchQueue.global().async { DispatchQueue.global().async {
let brew = self.resolveBrewPath() let brew = self.resolveBrewPath()
let cleaned = command.replacingOccurrences(of: "brew ", with: "") let cleaned = command.replacingOccurrences(of: "brew ", with: "")
let arguments = [brew] + cleaned.split(separator: " ").map(String.init) let fullCommand = "\(brew) \(cleaned)"
self.log("\(arguments.joined(separator: " "))\n") self.log("\(fullCommand)\n")
// env resolves brew via PATH (covers the bare "brew" fallback) and
// execs it directly no shell, so no metacharacter interpretation
let process = Process() let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env") process.executableURL = URL(fileURLWithPath: "/bin/zsh")
process.arguments = arguments process.arguments = ["-c", fullCommand]
var environment = ProcessInfo.processInfo.environment
environment["SUDO_ASKPASS"] = Self.askpassURL.path
process.environment = environment
let pipe = Pipe() let pipe = Pipe()
process.standardOutput = pipe process.standardOutput = pipe
@ -220,7 +194,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
try process.run() try process.run()
} catch { } catch {
self.log("ERROR: \(error)\n") self.log("ERROR: \(error)\n")
DispatchQueue.main.async { completion("") } completion("")
return return
} }
@ -230,8 +204,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let output = String(data: data, encoding: .utf8) ?? "" let output = String(data: data, encoding: .utf8) ?? ""
self.log(output) self.log(output)
// completion always on main: callers update AppKit UI, which is main-thread only completion(output)
DispatchQueue.main.async { completion(output) }
} }
} }
@ -242,8 +215,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {
} }
@objc func upgradeAll() { @objc func upgradeAll() {
guard confirmUpgrade() else { return }
statusMenuItem.title = "Upgrading..." statusMenuItem.title = "Upgrading..."
runBrew("update") { _ in runBrew("update") { _ in
@ -253,28 +224,20 @@ class AppDelegate: NSObject, NSApplicationDelegate {
} }
} }
func confirmUpgrade() -> Bool { /// SMART refresh (uses cache)
let alert = NSAlert() @objc func refreshOutdatedList() {
alert.alertStyle = .warning // if fetched in last 5s uses cache
if let last = lastOutdatedFetch, Date().timeIntervalSince(last) < 5 {
if cachedOutdated.isEmpty { updateOutdatedMenu(with: cachedOutdated)
alert.messageText = "Upgrade all outdated packages?" return
} else {
alert.messageText = "Upgrade \(cachedOutdated.count) package\(cachedOutdated.count == 1 ? "" : "s")?"
} }
var info = "Apps upgraded as casks (like a web browser) may be closed and replaced while running, without further warning. Save your work first." fetchOutdated()
if !cachedOutdated.isEmpty { }
info += "\n\n" + cachedOutdated.joined(separator: "\n")
}
alert.informativeText = info
alert.addButton(withTitle: "Upgrade") /// FORCE refresh (menu button)
alert.addButton(withTitle: "Cancel") @objc func forceRefreshOutdated() {
fetchOutdated()
// accessory app: bring the alert to the front, otherwise it can appear behind other windows
NSApp.activate(ignoringOtherApps: true)
return alert.runModal() == .alertFirstButtonReturn
} }
func fetchOutdated() { func fetchOutdated() {
@ -284,21 +247,28 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let lines = BrewParser.parseOutdated(output) let lines = BrewParser.parseOutdated(output)
self.cachedOutdated = lines self.cachedOutdated = lines
self.lastOutdatedFetch = Date()
self.updateOutdatedMenu(with: lines) DispatchQueue.main.async {
self.updateStatus(count: lines.count) self.updateOutdatedMenu(with: lines)
if lines.isEmpty { self.updateStatus(count: lines.count)
self.setMenuBarIcon("brewbar-uptodate") if lines.isEmpty {
} else { self.setMenuBarIcon("brewbar-uptodate")
self.setMenuBarIcon("brewbar-outdated") } else {
self.setMenuBarIcon("brewbar-outdated")
}
} }
} }
} }
func updateOutdatedMenu(with lines: [String]) { func updateOutdatedMenu(with lines: [String]) {
outdatedSubmenu.removeAllItems() outdatedSubmenu.removeAllItems()
outdatedItem.isHidden = lines.isEmpty outdatedSubmenu.addItem(NSMenuItem(title: "Refresh List", action: #selector(forceRefreshOutdated), keyEquivalent: ""))
upgradeAllItem.isHidden = lines.isEmpty
if lines.isEmpty {
outdatedSubmenu.addItem(NSMenuItem(title: "✅ All up to date", action: nil, keyEquivalent: ""))
return
}
for formula in lines { for formula in lines {
let item = NSMenuItem(title: formula, action: #selector(upgradeSingle(_:)), keyEquivalent: "") let item = NSMenuItem(title: formula, action: #selector(upgradeSingle(_:)), keyEquivalent: "")
@ -335,22 +305,18 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func refreshBrewVersion() { func refreshBrewVersion() {
runBrew("--version") { output in runBrew("--version") { output in
let firstLine = BrewParser.parseVersion(output) let firstLine = BrewParser.parseVersion(output)
self.versionItem.title = "🏷 \(firstLine)"
DispatchQueue.main.async {
self.versionItem.title = "🏷 \(firstLine)"
}
} }
} }
// MARK: - Logs // MARK: - Logs
/// oldest content is dropped past this size, or the buffer grows forever
/// and every log() re-renders an ever-larger string into the text view
let maxLogLength = 100_000
func log(_ text: String) { func log(_ text: String) {
DispatchQueue.main.async { DispatchQueue.main.async {
self.logBuffer += text self.logBuffer += text
if self.logBuffer.count > self.maxLogLength {
self.logBuffer = String(self.logBuffer.suffix(self.maxLogLength))
}
self.logWindow?.update(text: self.logBuffer) self.logWindow?.update(text: self.logBuffer)
} }
} }