Cotton code
140 lines · 5.9 KB · SwiftRaw
import AppKitimport Sparkleimport os/// Sparkle 2 — the only file that imports it.////// Cotton for the Mac is installed from a download, so it updates itself:/// Sparkle over a static appcast, every entry signed with the EdDSA key whose/// public half is `SUPublicEDKey`. Neither `SUFeedURL` nor `SUPublicEDKey` is/// in the committed `Resources/Info.plist`: `build-cotton-mac.sh` stamps both/// into the built bundle when it is given the public key, so the private half/// stays a secret in the vault.////// **A build with no feed has no updater at all.** [`Updates.hasFeed`] reads/// the bundle, and without an https feed and a key nothing here is/// constructed: an updater pointed at nothing would show Sparkle's own/// "could not check" alert about a channel that does not exist.////// **Nothing asks the person to install.** `SUEnableAutomaticChecks`,/// `SUScheduledCheckInterval` (hourly, Sparkle's floor) and/// `SUAutomaticallyUpdate` are on in `Info.plist`, and the app has no Dock/// icon and no window to hold a dialog. A downloaded build is installed NOW/// rather than on a quit a menu-bar importer never makes ([`InstallNow`]): a/// run in flight is cut short, which loses nothing, because a reader's cursor/// moves only after the object took the batch. And a Mac that wakes asks the/// feed at once, since a scheduled check that came while it slept was missed.@MainActorfinal class Updates {    private let controller: SPUStandardUpdaterController?    private let installNow = InstallNow()    private static let log = Logger(subsystem: "com.decemberfm.cotton.mac", category: "updates")    init(bundle: Bundle = .main) {        guard Updates.hasFeed(bundle.infoDictionary ?? [:]) else {            controller = nil            return        }        controller = SPUStandardUpdaterController(            startingUpdater: true,            updaterDelegate: installNow,            userDriverDelegate: nil        )        NSWorkspace.shared.notificationCenter.addObserver(            forName: NSWorkspace.didWakeNotification,            object: nil,            queue: .main        ) { [weak self] _ in            Task { @MainActor [weak self] in self?.checkInBackground() }        }    }    /// Whether this bundle can verify an update: an https `SUFeedURL` and a    /// non-empty `SUPublicEDKey`. Pure, so a test reads it without Sparkle.    nonisolated static func hasFeed(_ info: [String: Any]) -> Bool {        guard let feed = info["SUFeedURL"] as? String,              let url = URL(string: feed), url.scheme == "https",              let key = info["SUPublicEDKey"] as? String,              !key.trimmingCharacters(in: .whitespaces).isEmpty        else { return false }        return true    }    /// Whether this build can update itself (it has a feed).    var available: Bool { controller != nil }    /// Check for updates, asked on the panel: Sparkle says what it found.    func checkNow() {        NSApp.activate()        controller?.checkForUpdates(nil)    }    private func checkInBackground() {        guard let controller, controller.updater.automaticallyChecksForUpdates else { return }        Updates.log.info("update: checking the feed — the Mac woke")        controller.updater.checkForUpdatesInBackground()    }}/// The one delegate: "install on quit" answered by installing now.private final class InstallNow: NSObject, SPUUpdaterDelegate {    func updater(        _ updater: SPUUpdater,        willInstallUpdateOnQuit item: SUAppcastItem,        immediateInstallationBlock immediateInstallHandler: @escaping () -> Void    ) -> Bool {        let version = item.displayVersionString        // The watcher goes out FIRST: once the handler runs this process is on        // its way out, and nothing after it is promised to happen. Sparkle        // calls this delegate on the main thread.        MainActor.assumeIsolated { ComeBack.arm(version: version) }        immediateInstallHandler()        return true    }}/// The app comes back whether or not Sparkle brings it: a detached `/bin/sh`/// left behind before the install, which opens the app again if it is not/// running [`graceSeconds`] later (CottonDB's 0.15 → 0.16 night, when every/// Mac installed and stayed quit). Copied from CottonDB's `Updates.swift`.enum ComeBack {    static let graceSeconds = 90    static var bundleIdentifier: String { Bundle.main.bundleIdentifier ?? "com.decemberfm.cotton.mac" }    static var executableName: String {        (Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String) ?? "Cotton"    }    static let logPath = "~/Library/Logs/Cotton/relaunch.log"    /// Sleep, look, open if absent, and say so. `pgrep -x` matches the    /// process name exactly.    static func script(        version: String,        grace: Int = graceSeconds,        bundleIdentifier: String = ComeBack.bundleIdentifier,        executable: String = ComeBack.executableName    ) -> String {        let log = NSString(string: logPath).expandingTildeInPath        return "sleep \(grace); "            + "if ! pgrep -x \(executable) >/dev/null 2>&1; then "            + "mkdir -p \"$(dirname '\(log)')\"; "            + "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) \(executable) was not running \(grace)s after installing \(version) — opening \(bundleIdentifier)\" >> '\(log)'; "            + "open -b '\(bundleIdentifier)'; "            + "fi"    }    /// Leave the watcher behind. Never throws and never blocks: the install    /// is the thing that must not wait on it.    @MainActor    static func arm(version: String) {        let watcher = Process()        watcher.executableURL = URL(fileURLWithPath: "/bin/sh")        watcher.arguments = ["-c", script(version: version)]        watcher.standardInput = FileHandle.nullDevice        watcher.standardOutput = FileHandle.nullDevice        watcher.standardError = FileHandle.nullDevice        try? watcher.run()    }}