diff --git a/AGENTS.md b/AGENTS.md index e8e7f1a..30465cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,31 @@ file and cannot be at different versions. The two entries therefore compete for `bin/gitpic` — install one, not both — and the formula exists for Linux, Intel, CI, and anyone who wants no app. +**Two cask stanzas the app's updater depends on. Do not drop either.** + +`auto_updates true` declares that the artifact updates itself, which is what lets the in-app +installer replace a cask-managed bundle without brew fighting it — the Cask Cookbook defines the +stanza as exactly this case, an app menu with a *Check for Updates…* that really downloads and +installs. It is not "brew stops managing gitpic": current Homebrew reads the version out of +`/Applications/GitPic.app/Contents/Info.plist` and compares *that* against the tap +(`Cask#auto_updates_bundle_outdated?`; `HOMEBREW_UPGRADE_AUTO_UPDATES_CASKS` defaults on), so +`brew upgrade` still upgrades a bundle that is genuinely behind and correctly does nothing once +the app has updated itself. Without the stanza brew compares its own install receipt, which goes +stale the moment the app self-updates, and reinstalls a version already on disk. + +`uninstall quit: "dev.gitpic.app"` makes brew quit the app before it swaps the bundle and reopen +it afterwards (`Cask::Upgrade` passes `quit: true` by default). Without it a +`brew upgrade --cask gitpic` typed into a terminal replaces a bundle that is still running. It +does not interfere with the app's own update: brew skips the quit when the app is not running, so +nothing gets opened twice. + +The app-side half of this is `SelfUpdate.route` and `Updater`, whose headers carry the full +argument. **The two repositories have to move together** — the app has no Homebrew branch left, +so a cask without these stanzas means brew and the app both trying to own the bundle. + +The tap's `update-gitpic.yml` rewrites only the `version`, `sha256` and `url` lines by targeted +`sub!`, so hand-written stanzas survive a release. It does not regenerate the cask. + **How the tap learns about a release.** Two paths, and the second one exists because the first cannot be trusted alone: diff --git a/README.en.md b/README.en.md index 7c8f0a9..063d688 100644 --- a/README.en.md +++ b/README.en.md @@ -38,20 +38,24 @@ appears — and can be turned off — in 系统设置 ▸ 通用 ▸ 登录项 separate settings. **Update checks** run once a day by default, and can be run on demand from the 通用 pane or the -menu bar. A new version is shown with its release notes, and the button matches how GitPic was -installed: 立即更新 when Homebrew owns this copy, which runs `brew upgrade --cask gitpic`, and -下载并更新 when it does not, which fetches the release's disk image and replaces the bundle. -Either way GitPic quits first (nothing can replace a running bundle) and reopens when the -install finishes. - -A downloaded image is verified against the SHA-256 GitHub publishes for that file before -anything is replaced, which is the same check Homebrew makes against a cask — **no checksum, no -install** — and the download, verification and copy all happen before GitPic quits, so a failure -changes nothing. Homebrew stays the installer whenever it owns the bundle: replacing a -cask-managed app behind brew's back would leave its manifest describing a version that is no -longer on disk. The in-app installer needs GitPic to be in `/Applications` or `~/Applications`; -a copy kept elsewhere is sent to the release page, and the sheet says which reason applied. The -terminal equivalent of the check is `gitpic update check`. +menu bar. A new version is shown with its release notes and one 下载并更新 button — whether this +copy came from Homebrew or was installed by hand, GitPic fetches the release's disk image and +replaces the bundle itself. It quits first (nothing can replace a running bundle) and reopens +when the install finishes. + +The image is verified against the SHA-256 GitHub publishes for that file before anything is +replaced, which is the same check Homebrew makes against a cask — **no checksum, no install** — +and the download, verification and copy all happen before GitPic quits, so a failure changes +nothing. The installer needs GitPic to be in `/Applications` or `~/Applications`; a copy kept +elsewhere is sent to the release page, and the sheet says which reason applied. The terminal +equivalent of the check is `gitpic update check`. + +A Homebrew install can still be upgraded with `brew upgrade --cask gitpic`, or a bare +`brew upgrade`. The cask declares `auto_updates true`, so Homebrew compares the version in +`/Applications/GitPic.app` against the tap rather than its own install receipt: it does nothing +once the app has already updated itself, and upgrades when the bundle is genuinely behind. It also +declares `uninstall quit:`, so a terminal upgrade quits the app before the swap and reopens it +afterwards. **Nothing needs a terminal to get started.** Open the settings window → 图床 → 「使用 GitHub 登录」: the one-time code appears in the window and the browser opens on its own. diff --git a/README.md b/README.md index 919612c..4b35448 100644 --- a/README.md +++ b/README.md @@ -31,15 +31,18 @@ brew install tarnish233/tap/gitpic # App + 终端命令 macOS 自己的登录项,所以「系统设置 ▸ 通用 ▸ 登录项与扩展」里也能看到、也能关掉,两边永远是同一个开关。 **检查更新**默认每天自动查一次,也可以在「通用」页或菜单栏里随时手动查。发现新版本时会显示这一版 -的更新内容,按钮按安装方式给:用 Homebrew 装的是「立即更新」,走 `brew upgrade --cask gitpic`; -手动装的是「下载并更新」,由 GitPic 自己下载该版本的磁盘映像来替换。两种方式都会先退出再替换 -(没有办法替换正在运行的 bundle),装完自动重开。 - -自己下载的映像在替换之前会先核对 GitHub 为该文件公布的 SHA-256 —— 和 Homebrew 校验 cask 是同一件 -事,**拿不到校验和就不装**;而且下载、校验、复制全都发生在退出之前,失败什么都不会改动。Homebrew -管着这份 GitPic 时永远走 brew:绕过它替换会让 cask 的 manifest 描述一个已经不在磁盘上的版本。自己 -安装要求 GitPic 位于 `/Applications` 或 `~/Applications`,放在别处的副本会被指向发布页,弹窗里会 -说明是哪一种原因。终端里等价的查询命令是 `gitpic update check`。 +的更新内容,一个「下载并更新」按钮 —— 不管这份 GitPic 是 Homebrew 装的还是手动装的,都由 GitPic +自己下载该版本的磁盘映像来替换。替换前会先退出(没有办法替换正在运行的 bundle),装完自动重开。 + +替换之前会先核对 GitHub 为该文件公布的 SHA-256 —— 和 Homebrew 校验 cask 是同一件事,**拿不到校验和 +就不装**;而且下载、校验、复制全都发生在退出之前,失败什么都不会改动。安装要求 GitPic 位于 +`/Applications` 或 `~/Applications`,放在别处的副本会被指向发布页,弹窗里会说明是哪一种原因。终端里 +等价的查询命令是 `gitpic update check`。 + +用 Homebrew 装的照样可以用 `brew upgrade --cask gitpic`(或者不带参数的 `brew upgrade`)。cask 声明了 +`auto_updates true`,所以 Homebrew 比对的是 `/Applications/GitPic.app` 里的真实版本而不是它自己的安装 +记录:app 已经自己更新到位时它什么都不做,真的落后了才升。它还声明了 `uninstall quit:`,所以终端里 +升级会先退出 app、装完再打开它。 **第一次用不需要开终端。** 打开设置窗口 → 图床页 → 「使用 GitHub 登录」,一次性码会显示在窗口里、 浏览器自动打开;授权完成后下面的下拉框会列出你可以上传的仓库,选一个,按右上角「保存」写进配置文件。 diff --git a/apps/GitPic/Sources/GitPicApp/AppModel.swift b/apps/GitPic/Sources/GitPicApp/AppModel.swift index ba27ed0..6770ada 100644 --- a/apps/GitPic/Sources/GitPicApp/AppModel.swift +++ b/apps/GitPic/Sources/GitPicApp/AppModel.swift @@ -1120,7 +1120,6 @@ final class AppModel { func resolveUpgradePath() async { if upgradePathGeneration == updateGeneration { if case .unavailable(_, retryable: false) = upgradePath { return } - if case .homebrew = upgradePath { return } if case .selfInstall = upgradePath { return } } // The old guard also did not hold across the `await`, so two sheet appearances could @@ -1155,17 +1154,15 @@ final class AppModel { } } - /// Do whichever upgrade was resolved, and quit. + /// Do the upgrade that was resolved, and quit. + /// + /// One arm, where there were two. The other handed the install to `brew upgrade --cask gitpic` + /// and could fail *before* the app quit — hence the `catch` that used to be here, setting + /// 「启动升级失败」 while this process was still alive to show it. `performSelfInstall` reports + /// its own failures through `updateFailure` from inside its `Task`, so there is nothing to + /// catch at this level any more. func performUpgrade() { switch upgradePath { - case .homebrew(let brew): - do { - try Updater.upgradeAndRelaunch(brew: brew) - } catch { - // The handoff itself failed, so this process is still alive to say so. - updateFailure = "启动升级失败:\(error.localizedDescription)" - Diagnostics.log("update: handoff failed: \(String(describing: error))") - } case .selfInstall(let asset, let sha, let version): performSelfInstall(asset: asset, sha256: sha, version: version) case .unavailable, .none: diff --git a/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift b/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift index 71ffcff..f1fa8be 100644 --- a/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift +++ b/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift @@ -1,17 +1,20 @@ import SwiftUI import GitPicCore -/// What a new release says, and the two ways to act on it. +/// What a new release says, and what to do about it. /// /// A sheet rather than a pane, because it is about one moment: a version was found, here is /// what is in it, do you want it. Raised by a *manual* check, and by 「查看更新内容」 for one /// the daily check found — never by the daily check itself, which reports through /// Notification Center instead of interrupting whatever the window was being used for. +/// +/// It used to offer two actions, chosen by who installed the app: 「立即更新」 handed a +/// Homebrew-managed copy to `brew upgrade --cask gitpic`, and 「下载并更新」 was for everyone else. +/// There is one action now — see `Updater`'s header for why the split went away. struct UpdateSheet: View { @Bindable var model: AppModel let report: UpdateReport - @State private var confirmingUpgrade = false @State private var confirmingInstall = false /// The release notes, parsed once per report rather than once per redraw. @@ -114,18 +117,15 @@ struct UpdateSheet: View { } else { HStack(spacing: 8) { switch model.upgradePath { - case .homebrew: - Button("立即更新") { confirmingUpgrade = true } - .buttonStyle(.borderedProminent) case .selfInstall(let asset, _, _): Button("下载并更新") { confirmingInstall = true } .buttonStyle(.borderedProminent) Text(Self.size(asset.size)) .font(.caption).foregroundStyle(.secondary) case .unavailable, .none: - // No button at all rather than a disabled one: neither path can work + // No button at all rather than a disabled one: the install cannot work // here, and a greyed-out control with a tooltip is a worse answer than - // the one route that does. + // the reason printed below it. EmptyView() } Button("打开发布页") { @@ -156,26 +156,21 @@ struct UpdateSheet: View { } } .padding(16) - .alert("升级前需要退出 GitPic", isPresented: $confirmingUpgrade) { - Button("退出并升级") { model.performUpgrade() } - Button("取消", role: .cancel) {} - } message: { - // Says exactly what is about to happen, because all of it is visible and some - // of it is alarming: the window closes, the menu-bar icon disappears for the - // length of a download, and the app comes back on its own. - Text("Homebrew 不能替换正在运行的 App,所以 GitPic 会先退出," - + "升级完成后自动重新打开。这期间菜单栏图标会消失。\n\n" - + "升级过程记录在 GitPic-update.log 里;万一失败,原来的版本仍然可用。") - } .alert("下载并安装 GitPic \(report.latest)", isPresented: $confirmingInstall) { Button("下载并安装") { model.performUpgrade() } Button("取消", role: .cancel) {} } message: { // The order matters and is stated, because it is what makes this safe: everything // that can go wrong happens while the window is still here. - Text("这份 GitPic 不是 Homebrew 装的,所以由 GitPic 自己安装更新。\n\n" - + "会先下载并校验,全部通过之后才退出并替换,完成后自动重新打开——" + // + // It no longer opens by saying 「这份 GitPic 不是 Homebrew 装的,所以由 GitPic 自己 + // 安装更新」. That sentence explained a fork that existed — brew-installed copies were + // sent to `brew upgrade` instead — and became false for those users the moment this + // became the only path. Nothing here needs to explain where the app came from; what + // the reader wants to know is what is about to happen to it. + Text("会先下载并校验,全部通过之后才退出并替换,完成后自动重新打开——" + "下载或校验失败的话什么都不会改动。\n\n" + + "替换那一步记录在 GitPic-update.log 里;万一失败,原来的版本仍然可用。\n\n" + "校验用的是 GitHub 为这个文件公布的 SHA-256,和 Homebrew 验证 cask 的方式相同。") } } diff --git a/apps/GitPic/Sources/GitPicApp/Updater.swift b/apps/GitPic/Sources/GitPicApp/Updater.swift index 49cc4b5..e76a72f 100644 --- a/apps/GitPic/Sources/GitPicApp/Updater.swift +++ b/apps/GitPic/Sources/GitPicApp/Updater.swift @@ -1,29 +1,34 @@ import AppKit import GitPicCore -/// Installing a newer GitPic: `brew upgrade --cask gitpic` when Homebrew owns this bundle, -/// and a verified download when it does not. +/// Installing a newer GitPic: a disk image this process downloads and verifies, then a script +/// that swaps the bundle once this process is gone. /// -/// **Homebrew first, always.** Replacing a cask-managed bundle behind brew's back leaves its -/// manifest describing a version that is no longer on disk, so the next `brew upgrade` fights -/// it. Asking brew to do the install keeps one owner of what is in `/Applications`, and that -/// argument is untouched by anything below — the in-app installer is not an alternative to -/// brew, it is what happens when brew is not the owner. +/// **One path now, for every install.** There used to be two: `brew upgrade --cask gitpic` when +/// Homebrew owned the bundle, and this download when it did not. The argument for that split was +/// sound — replacing a cask-managed bundle behind brew's back leaves its manifest describing a +/// version that is no longer on disk, and the next `brew upgrade` fights it — but what brew users +/// actually got was the worse half of it. The app had to quit *before* brew was spawned, so the +/// tap refresh and the whole download happened with an `.accessory` app's menu-bar icon already +/// gone: no progress, nothing to cancel, and a 900 s watchdog as the only bound on an upgrade +/// that wedged. Worse, when the tap lagged the Release — dispatch plus a six-hourly cron, and +/// AGENTS.md records that the dispatch token has expired before — `brew upgrade` exited **0** +/// with "the latest version is already installed", the script logged that as success and +/// reopened the same build. A user who lost their app for nothing and was then offered the +/// identical update again. /// -/// **What changed, and why it is not a weakening.** This file used to argue that self-update -/// was unsafe here at all, because an ad-hoc signature gives no chain to verify a download -/// against. That is true and it is also true of the Homebrew path: a cask's `sha256` is -/// likewise a hash fetched over TLS from GitHub, and brew has no signature chain either. The -/// in-app installer verifies the SHA-256 that `api.github.com` reports for the asset, so the -/// trust root is the same one already shipped rather than a new, lower one. Neither survives -/// a compromised GitHub account; the only real improvement is a Developer ID plus -/// notarisation, which is out of reach for both. See `SelfUpdate` for the full statement. +/// What resolved the split is a stanza the cask was missing, not a change of mind about the +/// danger: `auto_updates true` tells Homebrew the artifact updates itself, and current Homebrew +/// then decides by reading the *installed bundle's* `Info.plist` rather than its own receipt. So +/// `brew upgrade` still upgrades a GitPic that is genuinely behind, and correctly does nothing +/// once this installer has moved it on. `SelfUpdate.route`'s header carries the full argument +/// with citations; the stanzas themselves live in `tarnish233/homebrew-tap`. /// -/// **Why neither can happen in this process.** The thing being replaced is the bundle this -/// code is executing from, so the work is handed to a detached script that waits for this -/// process to exit first, and the app quits. Everything else follows: the script cannot report -/// into a UI that no longer exists, so it logs; and it reopens the app whichever way the -/// install went, because the alternative is a user left with no GitPic and no explanation. +/// **Why the install cannot happen in this process.** The thing being replaced is the bundle this +/// code is executing from, so the work is handed to a detached script that waits for this process +/// to exit first, and the app quits. Everything else follows: the script cannot report into a UI +/// that no longer exists, so it logs; and it reopens the app whichever way the install went, +/// because the alternative is a user left with no GitPic and no explanation. /// /// This file used to justify that ordering with "measured: renaming a running executable's /// directory away gets the process `Killed: 9`". **That measurement was wrong** — re-run twice @@ -34,80 +39,63 @@ import GitPicCore /// recorded on ``quitForUpdate(_:)`` — it was the excuse for treating the quit as something /// that could not fail. /// -/// The two paths differ in what happens *after* the quit, and that is the interesting part. -/// brew goes to the network with the app already gone, so a stall costs the user everything — -/// hence the watchdog below. The in-app installer has already downloaded, verified and staged -/// while the window was open, so all that is left is two renames. +/// **What the trust root is, and is not.** This file once argued that self-update was unsafe here +/// at all, because an ad-hoc signature gives no chain to verify a download against. That is true, +/// and it was equally true of the Homebrew path: a cask's `sha256` is likewise a hash fetched +/// over TLS from GitHub, and brew has no signature chain either. The installer verifies the +/// SHA-256 that `api.github.com` reports for the asset, so the trust root is the one already +/// shipped rather than a new, lower one. Neither survives a compromised GitHub account; the only +/// real improvement is a Developer ID plus notarisation, which is out of reach for both. See +/// `SelfUpdate` for the full statement. @MainActor enum Updater { - /// The cask's name, which is deliberately not the formula's. - /// - /// The tap ships two entries: the cask `gitpic` installs the app, the formula - /// `gitpic_cli` installs only the binary (see AGENTS.md). `brew upgrade gitpic` without - /// `--cask` is ambiguous and Homebrew resolves it in favour of a formula, so both the - /// flag and this spelling are load-bearing. - /// - /// `nonisolated` because ``resolve(report:)`` reads it from a detached task — an immutable - /// `String` needs no actor to be read safely, and the alternative was hoisting a copy - /// into every closure that mentions it. - nonisolated static let caskName = "gitpic" - - /// Seconds `brew upgrade` gets in the generated script before the watchdog kills it. - /// - /// Interpolated into both the `sleep` and the message it logs, so the number in the log - /// cannot drift from the one that was waited. - private static let upgradeBound = 900 - - /// Its own queue rather than `Task.detached`: the probes below block for up to 8 s and - /// 20 s, and a cooperative thread parked that long is one fewer for everything else in - /// the app. Same reason `AppDelegate` gives tool discovery a `discoveryQueue` instead of - /// running it on the pool. - private nonisolated static let probeQueue = DispatchQueue(label: "dev.gitpic.app.brew-probe") + /// Its own queue rather than `Task.detached`: staging blocks on `hdiutil`, `codesign` and + /// `ditto`, bounded at 120 s, 120 s and 300 s, and a cooperative thread parked that long is + /// one fewer for everything else in the app. Same reason `AppDelegate` gives tool discovery a + /// `discoveryQueue` instead of running it on the pool. + /// + /// It was `probeQueue`, labelled `brew-probe`, and it was shared with the Homebrew ownership + /// probe — which is why ``installAndRelaunch`` still explains that staging could sit behind + /// somebody else's 20 s `brew list --cask` before it started. That probe is gone, so the + /// queue has one user and the name says which. + private nonisolated static let stagingQueue = + DispatchQueue(label: "dev.gitpic.app.staging") /// Which upgrade to offer for this install, if any. /// - /// Each question the probe asks rules out a way the button could do the wrong thing. - /// Finding `brew` says nothing about whether *this* app came from it — a drag-installed - /// copy on a machine that also has Homebrew is entirely ordinary, and `brew upgrade --cask - /// gitpic` there fails with "not installed". And the cask being installed still does not - /// make *this* bundle the one brew manages: a copy running from `dist-app/`, or a second - /// one in `~/Applications` while the cask is also installed, would upgrade - /// `/Applications/GitPic.app` and then be reopened *at its own path* — an old build, still - /// reporting the same update, with brew reporting nothing left to do. The user can repeat - /// that forever. - /// - /// The decision itself is `SelfUpdate.route`, a pure function in `GitPicCore` so that - /// every row of it is testable; what is left here is gathering the facts it needs off the - /// main actor. - /// - /// `brewOwnership` is written *inside* the call rather than computed into a local because - /// `route`'s `brew` parameter is an `@autoclosure`: the location question is free and is - /// asked first, so a copy outside the two Applications directories never pays the 8 s - /// login-shell probe or the 20 s `brew list --cask` at all. + /// The decision itself is `SelfUpdate.route`, a pure function in `GitPicCore` so that every + /// row of it is testable; what is left here is reading the two facts it needs off the running + /// bundle. + /// + /// **This used to be the expensive part of opening the sheet.** It asked whether Homebrew + /// owned this bundle, which meant up to an 8 s login-shell probe plus a 20 s + /// `brew list --cask` per Homebrew prefix, serialised on one queue — up to 28 seconds of + /// 「正在确认升级方式…」 before a button could be drawn. Each of those questions ruled out a + /// way the old brew branch could do the wrong thing: finding `brew` said nothing about + /// whether *this* app came from it, and the cask being installed still did not make *this* + /// bundle the one brew manages, so a copy in `~/Applications` beside a cask in + /// `/Applications` would have upgraded the other one and been reopened at its own path, + /// unchanged, still reporting the same update, forever. There is no brew branch to protect + /// now, so none of it is asked. + /// + /// Still `async`, though nothing in it suspends: `UpdateSheet`'s `.task(id:)` awaits it, and + /// `AppModel.resolveUpgradePath`'s guard against a report landing mid-resolve is worth + /// keeping whether or not the resolve is instant. static func resolve(report: UpdateReport) async -> SelfUpdate.Route { let bundle = Bundle.main.bundleURL // The bundle's own version, not `report.current` — that one is the CLI's, and this // replaces the bundle. let mine = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String - let asset = report.installableAsset() - let latest = report.latest - let route: SelfUpdate.Route = await withCheckedContinuation { cont in - probeQueue.async { - cont.resume(returning: SelfUpdate.route( - location: SelfUpdate.location(of: bundle), - bundleVersion: mine, - latest: latest, - brew: SelfUpdate.brewOwnership(cask: Self.caskName, bundle: bundle), - asset: asset)) - } - } + let route = SelfUpdate.route( + location: SelfUpdate.location(of: bundle), + bundleVersion: mine, + latest: report.latest, + asset: report.installableAsset()) switch route { - case .homebrew: - Diagnostics.log("update: Homebrew owns this bundle — offering brew upgrade") case .selfInstall(let asset, _, let version): - Diagnostics.log("update: Homebrew does not own this bundle — offering to install" - + " \(version) from \(asset.name) (\(asset.size) bytes)") + Diagnostics.log("update: offering to install \(version) from \(asset.name)" + + " (\(asset.size) bytes)") case .unavailable(let reason, let retryable): Diagnostics.log("update: no in-app upgrade — \(reason)" + (retryable ? " (will ask again)" : "")) @@ -135,8 +123,10 @@ enum Updater { /// costs nothing but a message — and `onProgress` is what the sheet draws. Only once a /// verified bundle is staged beside the old one does this hand off and terminate. /// - /// That ordering is the whole reason this path needs no watchdog while the brew one does: - /// brew goes to the network *after* the app is gone. + /// That ordering is why nothing here needs a watchdog. The path this replaced did: it spawned + /// brew *after* the app was gone, so a stall cost the user the whole application and only a + /// timer could end it. Here a stall costs a progress bar that stops moving, next to a 取消 + /// that works. /// /// **Cancellation is honoured all the way to the handoff**, which it was not: the staging /// step was a bare `withCheckedThrowingContinuation` that nothing could interrupt, so 取消 @@ -174,12 +164,14 @@ enum Updater { let cancelled = CancellationFlag() let staged: SelfUpdate.Staged = try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { cont in - probeQueue.async { + stagingQueue.async { cont.resume(with: Result { - // `probeQueue` is serial and shared with the upgrade-path probe, so - // this block can sit behind a 20 s `brew list --cask` before it runs. - // Nothing has been mounted at this point, so a 取消 that arrived in the - // meantime costs nothing at all. + // Checked on entry because dispatching is not instant: a 取消 can land + // between the `Task` starting and this block running. It used to be able + // to wait much longer than that — this queue was shared with the Homebrew + // ownership probe, so staging could sit behind somebody else's 20 s + // `brew list --cask` first. Nothing has been mounted at this point, so a + // 取消 that arrived in the meantime costs nothing at all. if cancelled.isSet { throw CancellationError() } // `stage` reads this between its own steps — the attach, the version // gate, the signature check, the copy — so a 取消 during a slow `ditto` @@ -268,7 +260,7 @@ enum Updater { AppModel.shared.cancelLogin() } - /// Leave now, so the staged bundle — or brew — can replace the one this is running from. + /// Leave now, so the staged bundle can replace the one this is running from. /// /// **`exit()` and not `NSApp.terminate`, and that is a measurement rather than a /// preference.** `NSApp.terminate(nil)` is what 0.20.0 shipped on both update paths, and @@ -404,140 +396,6 @@ enum Updater { } } - /// Quit, upgrade, reopen. - /// - /// Returns only if the handoff itself failed; on success this process is on its way - /// out — see ``quitForUpdate(_:)``, which is `Never` for exactly that reason. The caller - /// has already confirmed with the user — see `UpdateSheet` — because this closes their - /// window and takes the menu-bar icon away for as long as the download takes. - /// - /// The quit here had the same defect as the install path's and for the same reason: it is - /// reached from a button inside an alert on the update sheet, so `NSApp.terminate` was - /// refused here too. Untested against a real Homebrew-managed bundle, because this machine - /// has none at a path the app runs from; the code path is shared, and the one thing that - /// differs — the script — is the same shape. - static func upgradeAndRelaunch(brew: URL) throws { - let script = try writeScript(brew: brew) - if dryRun { - Diagnostics.log("update: DRY RUN — script written to \(script.path)," - + " not spawned, not quitting") - // The same reason as the install path: everything but the `exit`. - prepareToQuit() - return - } - // Detached on purpose. The child is reparented when this process exits and keeps - // running, which is exactly what has to happen: the script's first job is to wait - // for that exit. - let task = Process() - task.executableURL = URL(fileURLWithPath: "/bin/bash") - task.arguments = [script.path] - // Inherited, with `PATH` overridden — the policy `GitpicRunner.run` uses, rather than - // the two hand-picked keys this used to build. brew re-execs itself and shells out to - // `curl`, `git` and `ditto`, so it needs its own prefix on PATH; but it also needs - // whatever proxy configuration the app was launched with, and a two-key environment - // silently dropped `HTTPS_PROXY`/`ALL_PROXY` and left every fetch going direct. On a - // machine that reaches GitHub only through a local proxy that is the difference - // between an upgrade and a stall. - // - // Necessary rather than sufficient, and worth being honest about: a Finder-launched - // `.app` has no shell profile applied, so if the proxy is only exported in one there - // is nothing here to inherit. The bound in the script is what makes that survivable. - var env = ProcessInfo.processInfo.environment - env["PATH"] = "\(brew.deletingLastPathComponent().path):\(ToolPaths.childPATH)" - // `HOMEBREW_NO_AUTO_UPDATE` is deliberately *not* set: the tap has to be refreshed - // for the new cask to be visible at all, so suppressing that would reliably turn - // "upgrade" into "nothing to do". - task.environment = env - try task.run() - - Diagnostics.log("update: handed off to \(script.path) (pid \(task.processIdentifier))") - quitForUpdate("brew will replace the bundle once this pid is gone") - } - - /// The script, written to a temporary file rather than passed as `bash -c`. - /// - /// A file because it is worth being able to read afterwards when an upgrade went - /// wrong — the log names this path. - private static func writeScript(brew: URL) throws -> URL { - let log = Diagnostics.logURL.deletingLastPathComponent() - .appendingPathComponent("GitPic-update.log") - let bundle = Bundle.main.bundleURL - // Quoted with single quotes and the one escape that needs: a path containing a - // quote is absurd for an installed .app but this is shell code being generated, - // and "absurd" is not "impossible". - func q(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" } - - let script = """ - #!/bin/bash - # Written by GitPic's Updater. Safe to delete. - exec >>\(q(log.path)) 2>&1 - echo "=== $(date -u +%Y-%m-%dT%H:%M:%SZ) upgrade \(Self.caskName) ===" - - # Wait for GitPic to exit so brew is not replacing a running bundle. Bounded at - # 60 s: the app calls `exit(0)` immediately after spawning this script — see - # `Updater.quitForUpdate` — so the wait is normally a fraction of a second, and an - # app still here after a minute is in a state nothing in this script can mend. - # - # After the bound brew is allowed to try anyway. The reason is *not* that a - # surviving process is stopped by the move: this file used to claim that, citing - # `Killed: 9`, and the claim is false — re-measured twice, a `mv` of the bundle - # directory leaves the process running from the moved-aside copy, which is how - # 0.20.0's failed quit turned into `open -a` merely reactivating the old build. - # The reason is that the alternative is worse: bailing out here leaves an - # .accessory app with no upgrade and no explanation, whereas trying gets the user - # the new version and a log line either way. A brew that cannot complete the move - # reports non-zero and the old bundle stays. - for _ in $(seq 1 120); do - kill -0 \(ProcessInfo.processInfo.processIdentifier) 2>/dev/null || break - sleep 0.5 - done - - # Bounded too, and for a sharper reason than the loop above: the reopen at the - # bottom runs only after brew returns, so an upgrade that never returns costs the - # user the whole app. GitPic is .accessory — once it has quit there is no Dock - # icon, no menu-bar icon, and the dialog that named this log went with it — so the - # only way back would be `open -a GitPic` typed into a terminal. macOS ships no - # timeout(1), hence the watchdog. - # - # The bound is generous on purpose: a slow-but-progressing download must not be - # killed, and brew refreshes its taps over git before it fetches the disk image. - # What it buys is that a wedged upgrade is temporary. A killed one can leave the - # cask half-installed and the reopen below then falls through to `open -a GitPic`, - # which is worse than a clean upgrade and much better than never coming back. - \(q(brew.path)) upgrade --cask \(q(Self.caskName)) & - brew_pid=$! - ( - sleep \(Self.upgradeBound) - kill -TERM "$brew_pid" 2>/dev/null || exit 0 - echo "watchdog: brew exceeded \(Self.upgradeBound)s, sent SIGTERM" - sleep 10 - kill -KILL "$brew_pid" 2>/dev/null && echo "watchdog: escalated to SIGKILL" - ) & - watchdog_pid=$! - wait "$brew_pid" - status=$? - kill "$watchdog_pid" 2>/dev/null - - # 143 and 137 are SIGTERM and SIGKILL, so they are the watchdog's verdict rather - # than brew's. Worth telling apart in the only report this script can make. - case $status in - 143|137) echo "brew was killed by the watchdog (status $status)" ;; - 0) echo "brew exited 0" ;; - *) echo "brew failed (status $status)" ;; - esac - - # Reopen either way. A failed upgrade must not cost the user their app: the old - # bundle is still on disk in that case, and this is the only thing that puts the - # menu-bar icon back. - open -a \(q(bundle.path)) || open -a GitPic || echo "could not reopen GitPic" - exit $status - """ - let url = FileManager.default.temporaryDirectory - .appendingPathComponent("gitpic-update-\(UUID().uuidString).sh") - try script.write(to: url, atomically: true, encoding: .utf8) - return url - } - /// Delete what past upgrades left behind: the generated scripts, any disk image a /// cancelled download abandoned, and the staging or backup directories an interrupted /// install could not clean up itself. @@ -607,8 +465,16 @@ enum Updater { /// The temporary-directory names this feature owns. /// - /// `gitpic-update-*` covers both the old upgrade scripts and an abandoned `.dmg`, because - /// the download names its file the same way; `gitpic-install-*.sh` is the swap script. + /// `gitpic-update-*` covers an abandoned `.dmg`, because the download names its file that way; + /// `gitpic-install-*.sh` is the swap script. + /// + /// **`.sh` under `gitpic-update-` is kept deliberately, and nothing writes one any more.** + /// That was the Homebrew upgrade script, generated by a `writeScript` this version deleted. + /// A machine upgrading from 0.20.x can still have one sitting in `$TMPDIR` — the script + /// cannot delete itself and neither can the app it relaunches, so its cleanup always landed + /// one launch later, which is exactly the launch that may now be running this code. Drop the + /// suffix and those files are orphaned for good. Removable once no supported version writes + /// them, which is a version or two away, not now. /// /// The bundle-sized leftovers — `.GitPic-update-*` staging directories and `.GitPic-old-*` /// backups, beside wherever the app is installed — are deliberately **not** listed here. @@ -627,7 +493,7 @@ enum Updater { /// /// `NSLock` over a `Bool`, following `SelfUpdate`'s `DownloadDelegate` and `Auth`'s `LoginChild`: /// the setter runs in `withTaskCancellationHandler`'s `onCancel`, which can fire on any thread, -/// while the reader is a block on `Updater.probeQueue`. `Synchronization.Mutex` would be the +/// while the reader is a block on `Updater.stagingQueue`. `Synchronization.Mutex` would be the /// modern answer and is macOS 15; this package targets macOS 14 (`Package.swift`). private final class CancellationFlag: @unchecked Sendable { private let lock = NSLock() diff --git a/apps/GitPic/Sources/GitPicCore/SelfUpdate.swift b/apps/GitPic/Sources/GitPicCore/SelfUpdate.swift index 8e02048..09d69eb 100644 --- a/apps/GitPic/Sources/GitPicCore/SelfUpdate.swift +++ b/apps/GitPic/Sources/GitPicCore/SelfUpdate.swift @@ -161,9 +161,12 @@ public enum SelfUpdate { // `ephemeral` so nothing is written to a shared cache, and an explicit `User-Agent` // for the same reason `ThumbnailStore` sets one. // - // **No `connectionProxyDictionary`, deliberately, and this is the asymmetry with - // `Updater.upgradeAndRelaunch`** — which forwards `HTTPS_PROXY`/`ALL_PROXY` to brew - // and calls that "the difference between an upgrade and a stall". URLSession does not + // **No `connectionProxyDictionary`, deliberately.** This used to be introduced as "the + // asymmetry with `Updater.upgradeAndRelaunch`" — which forwarded `HTTPS_PROXY`/`ALL_PROXY` + // to brew and called that "the difference between an upgrade and a stall". That function + // went with the Homebrew install path, so there is no asymmetry left to explain: this is + // now the only thing that downloads an update, and it goes direct. The measurement the + // decision rests on is unchanged. URLSession does not // read those variables at all (measured: with every one of them pointed at a dead // port, a ranged GET of a real release asset still returned 206), so it honours only // System Settings. Forwarding them here was written and then rejected on the diff --git a/apps/GitPic/Sources/GitPicCore/SelfUpdateInstall.swift b/apps/GitPic/Sources/GitPicCore/SelfUpdateInstall.swift index 8ce4634..5759721 100644 --- a/apps/GitPic/Sources/GitPicCore/SelfUpdateInstall.swift +++ b/apps/GitPic/Sources/GitPicCore/SelfUpdateInstall.swift @@ -408,11 +408,43 @@ extension SelfUpdate { // `-mountpoint` rather than letting it land in `/Volumes`: the name there is chosen // from the volume label and gets a numeric suffix when it collides, so the path this // reads from would be decided by whatever else happens to be mounted. - let attach = try? ChildProcess.run( - executable: URL(fileURLWithPath: "/usr/bin/hdiutil"), - args: ["attach", dmg.url.path, "-nobrowse", "-readonly", - "-mountpoint", mount.path], - timeout: 120) + // + // **Retried, because "attach failed" is not always a fact about the image.** Measured on + // a GitHub `macos-latest` runner: seventeen seconds into a suite that attaches and + // detaches repeatedly, every remaining `hdiutil attach` started returning + // `hdiutil: attach failed - Resource temporarily unavailable` within 0.07 s and went on + // doing so for the rest of the run. That is the kernel declining one more attach, not a + // corrupt download — and the user on a machine in that state was shown + // 「磁盘映像有问题:hdiutil: attach failed - Resource temporarily unavailable」 and left + // with a failed update and nothing to do about it. + // + // **Only a fast non-zero exit is retried, never a timeout.** A timed-out attach may have + // landed anyway — the `defer` above is installed before this line for that exact reason — + // so a second attach could mount the same image twice. `stderr` is deliberately *not* + // pattern-matched to decide what is transient: that spelling is one of several the kernel + // and `hdiutil` can produce, and a list of them is a list to get wrong. The attempt count + // is what bounds the cost instead, so an image that really is unreadable is refused about + // two seconds later than it used to be. Same three-attempts-one-second shape as + // ``detachMount(at:)``, which retries for the mirror-image reason. + var attach: ProcessOutcome? + var attempt = 0 + while attempt < 3 { + attempt += 1 + try stopIfCancelled(isCancelled) + attach = try? ChildProcess.run( + executable: URL(fileURLWithPath: "/usr/bin/hdiutil"), + args: ["attach", dmg.url.path, "-nobrowse", "-readonly", + "-mountpoint", mount.path], + timeout: 120) + if let attach, attach.status == 0, !attach.timedOut { break } + // A timeout is the one failure that must not be tried again. + if attach?.timedOut == true { break } + if attempt < 3 { + Diagnostics.log("update: hdiutil attach failed, retrying" + + " (\(attempt)/3): \(reason(accepted: false, out: attach))") + Thread.sleep(forTimeInterval: 1) + } + } guard let attach, attach.status == 0, !attach.timedOut else { let detail = attach?.timedOut == true ? "打开磁盘映像超时" diff --git a/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift b/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift index 46762f8..3b21b00 100644 --- a/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift +++ b/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift @@ -2,26 +2,47 @@ import Foundation /// Putting a verified disk image in place of the running bundle. /// -/// **Why this is a detached script and not code in this process.** The thing being replaced -/// is the bundle this code is executing from, so the work has to outlive the app. Measured -/// rather than assumed: renaming a running executable's directory away and putting a new one -/// at the old path got the process `Killed: 9`. So the app quits first, and a script that -/// nothing else depends on does two renames. +/// **Why this is a detached script and not code in this process.** The thing being replaced is +/// the bundle this code is executing from, so the work has to outlive the app. This file used to +/// justify that with "measured: renaming a running executable's directory away and putting a new +/// one at the old path got the process `Killed: 9`" — the same claim `Updater.swift:28` retracts, +/// and for the same reason: re-measured twice, a `mv` of the bundle directory leaves the process +/// running happily from the moved-aside copy. The ordering stands on the plainer argument +/// instead. A half-replaced bundle is one whose executable, resources and embedded CLI need not +/// be from the same version, and nothing here can put that back. So the app quits first, and a +/// script that nothing else depends on does two renames. /// -/// **What is different from the Homebrew path, and why it is safer.** `Updater` hands brew a -/// script that then goes to the network, so a stall there costs the user the whole app — which -/// is what its 900 s watchdog exists for. Here the download, the verification, the mount and -/// the copy have all already happened while the app was alive, cancellable, and able to show -/// an error. What is left after the app quits is two same-directory renames and an `open`: -/// local, fast, and rollback-able. The irreversible window shrinks from "however long a -/// download takes" to "between two renames". +/// **This is the only install path now, including for a bundle Homebrew installed.** It used to +/// be what happened when brew was *not* the owner, and the gap between the two is why that +/// changed: brew was handed a script that went to the network *after* the app had quit, so an +/// `.accessory` app's menu-bar icon was gone for the length of a tap refresh plus a download, +/// with no progress, nothing to cancel, and a 900 s watchdog as the only bound. Here the +/// download, the verification, the mount and the copy have all already happened while the app +/// was alive, cancellable, and able to show an error. What is left after the quit is two +/// same-directory renames and an `open`: local, fast, and rollback-able. +/// +/// **What became of the argument for handing brew the install.** That argument was not wrong — a +/// bundle replaced behind brew's back leaves its manifest describing a version that is not on +/// disk, and the next `brew upgrade` fights it. Homebrew has a stanza for precisely this and the +/// cask was missing it. `auto_updates true` asserts that the artifact updates itself, which the +/// Cask Cookbook defines as the case where the app menu has a *Check for Updates…* that really +/// downloads and installs; current Homebrew then decides by reading the **installed bundle's** +/// `Info.plist` rather than its own receipt (`Cask#auto_updates_bundle_outdated?`, and +/// `HOMEBREW_UPGRADE_AUTO_UPDATES_CASKS` defaults on). So `brew upgrade` still upgrades a GitPic +/// that is genuinely behind, and now correctly does nothing when this installer has already +/// moved it on — where comparing against the stale receipt used to make it reinstall a version +/// already on disk. The cask also gained `uninstall quit: "dev.gitpic.app"`, so a +/// `brew upgrade --cask gitpic` typed into a terminal quits the app before the swap and reopens +/// it afterwards, instead of replacing a running bundle. +/// +/// **Both stanzas live in `tarnish233/homebrew-tap`'s `Casks/gitpic.rb`, and this file's +/// correctness depends on them being there** — a cross-repository premise, so it is also +/// recorded in AGENTS.md's Homebrew section. extension SelfUpdate { /// Which upgrade this install can be offered, if any. public enum Route: Equatable, Sendable { - /// Homebrew owns this bundle. It stays the installer — see ``route``. - case homebrew(brew: URL) - /// Nothing else owns the bundle and there is a verifiable image to install. + /// There is a verifiable image to install over this bundle. /// /// `version` travels with the asset because both come out of one report and the /// install has to agree with itself. Read separately — the asset from a route the sheet @@ -30,74 +51,24 @@ extension SelfUpdate { /// version gate with 「映像里是 0.20.0,不是预期的 0.21.0」, which reads like a tampered /// release rather than a stale sheet. case selfInstall(asset: ReleaseAsset, sha256: String, version: String) - /// Neither. `reason` is user-facing and therefore **Chinese**; `retryable` is whether - /// asking again could change the answer, which is what stops a one-off probe failure - /// being cached for the life of the process. + /// No install can be offered. `reason` is user-facing and therefore **Chinese**; + /// `retryable` is whether asking again could change the answer, which is what stops a + /// one-off probe failure being cached for the life of the process. /// /// `retryable` means "asking the machine again could answer differently" — a fact about /// *this install*, not about the release. Every refusal computed from the report is /// therefore `retryable: false` and relies on the caller dropping the whole route when /// the report changes; see `AppModel.resolveUpgradePath`. + /// + /// **Nothing produces `true` any more.** The one source was the Homebrew ownership + /// probe, whose "I could not get an answer" had to stay askable; ``route`` is now a pure + /// function of the report and this bundle's path, so every refusal is durable for as + /// long as the report is. The parameter and the guard in `AppModel` that reads it are + /// kept rather than collapsed because they are what documents that distinction, and + /// removing them would change nothing that runs. case unavailable(reason: String, retryable: Bool) } - /// What Homebrew has to say about this bundle. - /// - /// Collapsed to three cases by ``brewOwnership(cask:bundle:)`` before it reaches ``route``, - /// so the decision itself is a pure function over facts rather than a thing that spawns - /// processes — which is what makes the table below testable at all. - public enum BrewOwnership: Equatable, Sendable { - /// brew is here and manages this cask, as this very bundle. - case ownsThisCask(brew: URL) - /// Definitively not brew's: every brew on the machine answered "I have nothing under - /// that token" or "I installed some other bundle", or there is no brew at all. A - /// durable fact. - case doesNotOwnIt - /// No answer. `reason` is user-facing Chinese. Must not be acted on and must not be - /// cached. - case unknown(reason: String) - } - - /// What one `brew` said about one bundle. - /// - /// Gathered by ``brewOwnership(cask:bundle:)`` and reduced by ``fold(_:)``, split that way - /// so the reduction — which is where the safety rule lives — is testable without spawning - /// Homebrew. - public enum BrewVerdict: Equatable, Sendable { - /// This brew manages the cask, and one of the bundles it lists is the running one. - case ownsThisBundle(brew: URL) - /// This brew manages the cask, but as some other bundle. A drag-installed copy in - /// `~/Applications` on a machine whose cask went to `/Applications`. - case ownsAnotherBundle - /// This brew has installed nothing under this token. - case hasNothing - /// This brew gave no usable answer. - case noAnswer(reason: String) - } - - /// Reduce what every `brew` on the machine said to one answer. - /// - /// **Homebrew owning the bundle always wins, and "I could not get an answer" is never an - /// install.** Both halves matter and the order encodes them: - /// - /// 1. Any brew that says it installed *this* bundle settles it. On a machine with two - /// prefixes the cask may have been installed by either, and this is what stops - /// `/opt/homebrew/bin/brew`'s "not mine" from overruling `/usr/local/bin/brew`'s "mine". - /// 2. Otherwise a single unanswered brew makes the whole answer unknown, because that brew - /// is exactly the one that could have been the owner. Replacing a bundle brew manages - /// leaves the cask manifest describing a version that is not on disk. - /// 3. Only when every brew answered, and none of them owns this bundle, is this bundle - /// definitively not brew's. - /// - /// An empty list is `doesNotOwnIt`: no brew means nothing brew installed. That case is the - /// user this whole feature exists for, and it is only reached when - /// ``ToolDiscovery/locateBrewOutcome()`` positively established absence. - public static func fold(_ verdicts: [BrewVerdict]) -> BrewOwnership { - for case .ownsThisBundle(let brew) in verdicts { return .ownsThisCask(brew: brew) } - for case .noAnswer(let reason) in verdicts { return .unknown(reason: reason) } - return .doesNotOwnIt - } - /// Whether the running bundle sits somewhere an update may be installed. public enum BundleLocation: Equatable, Sendable { /// `/Applications` or `~/Applications`. @@ -105,41 +76,30 @@ extension SelfUpdate { case elsewhere(path: String) } - /// Decide how — or whether — to upgrade. + /// Decide whether to offer an upgrade, and for which asset. /// - /// **Homebrew wins whenever it owns the bundle**, and that is the surviving half of the - /// argument this file's predecessor made against self-update at all: replacing a - /// cask-managed bundle behind brew's back leaves its manifest describing a version that - /// is no longer on disk, and the next `brew upgrade` fights it. So the in-app installer - /// is not an alternative to brew, it is what happens when brew is not the owner. + /// **A pure function of the report and this bundle's path.** It used to spawn Homebrew: the + /// first question was who owns the bundle, and a cask-managed one was sent to + /// `brew upgrade --cask gitpic` instead. That question is gone — the cask now declares + /// `auto_updates true`, so this installer is what upgrades every copy and brew defers to it + /// (the file header has the full argument). Everything left here is a string comparison, a + /// version comparison and a lookup in the report's asset list. /// - /// **An unknown answer is never treated as "not brew's".** A probe that timed out could - /// be hiding a working Homebrew, and installing over a cask on that guess is precisely - /// the damage the paragraph above describes. + /// **What that removal bought, since it is the point of the change.** The brew questions cost + /// up to 8 s for a login-shell probe and up to 20 s per `brew list --cask`, on a serial queue, + /// every time the sheet opened — up to 28 seconds of 「正在确认升级方式…」 before a button + /// could be drawn. `brew` used to be an `@autoclosure` purely so that a bundle outside the + /// two Applications directories could refuse without paying it. There is nothing left to + /// defer, so the parameter and the laziness are both gone. /// - /// **The location rule is shared with the brew path** rather than being a second, looser - /// test, and it is asked *first* because it is the only question here that is free. `brew` - /// is an `@autoclosure` for exactly that reason: passed as a plain argument it was evaluated - /// before this function was entered, so a development build in `dist-app/` — or any copy - /// outside the two Applications directories — spawned a login shell and a `brew list --cask`, - /// serialised on one queue, before the sheet could print a refusal a string comparison had - /// already decided. Measured on a warm machine that pays it: 0.04 s for the shell and - /// 0.42–0.81 s for `brew list` across three runs — but the *bounds* are 8 s and 20 s, and - /// they exist because both really do take that long sometimes (`brew list`'s own doc comment - /// names Homebrew's housekeeping). Up to 28 seconds of 「正在确认升级方式…」, every time the - /// sheet opened, for an answer that needed none of it. - /// - /// Its cost, stated in full: a copy kept outside `/Applications` or `~/Applications` is sent - /// to the release page — **including** one Homebrew installed there with a custom - /// `--appdir`, which used to be offered `brew upgrade` because the brew question was asked - /// first. That user is not stranded: the sheet's fallback line spells out - /// `brew upgrade --cask gitpic`. What the ordering buys is that the free answer is free - /// again, and that no location gets a looser rule than the one this comment claims. + /// **The location rule survives on its own merits**, not as a shared test with a brew path + /// that no longer exists: a copy running from `dist-app/` or a Downloads folder must not have + /// its directory written into, and the sheet sends it to the release page. It is still asked + /// first, now simply because it is the one refusal that does not depend on the report. public static func route( location: BundleLocation, bundleVersion: String?, latest: String, - brew: @autoclosure () -> BrewOwnership, asset: AssetChoice ) -> Route { if case .elsewhere(let path) = location { @@ -148,14 +108,6 @@ extension SelfUpdate { + "所以不能在这里直接替换", retryable: false) } - switch brew() { - case .ownsThisCask(let brew): - return .homebrew(brew: brew) - case .unknown(let reason): - return .unavailable(reason: reason, retryable: true) - case .doesNotOwnIt: - break - } // The gate is the *bundle's* version, not the report's `current` — that one is the // CLI's, and this replaces the bundle. They are identical in any packaged install @@ -225,47 +177,4 @@ extension SelfUpdate { } return matches ? .applicationsDir : .elsewhere(path: bundle.path) } - - /// Ask Homebrew whether it owns **this** bundle. Blocking: call it off the main actor. - /// - /// The bundle is a parameter because "is the cask installed" is not the question — see - /// `ToolDiscovery.brewCaskApp`. A copy in `~/Applications` on a machine whose cask - /// installed to `/Applications` must come back `.doesNotOwnIt`, or it gets handed to brew, - /// brew replaces the *other* bundle, and this one is reopened unchanged still reporting the - /// same update. That is not hypothetical: it is what this returned before the end-to-end - /// run caught it. - /// - /// **Every brew is asked, not the first one found.** A machine that has had both an Intel - /// and an Apple Silicon Homebrew has two prefixes with two independent Caskrooms; asking - /// only `/opt/homebrew/bin/brew` about a cask installed by `/usr/local/bin/brew` gets a - /// perfectly truthful "I have nothing under that token", which folded straight into - /// "not brew's" and an install over a bundle the other brew manages. The second - /// `brew list --cask` costs a second bound, not a second 20 seconds — measured at 0.44 s on - /// this machine — and it is the price of not breaking that install. - /// - /// The reduction is ``fold(_:)``, which is where the precedence rule is written down and - /// tested. - public static func brewOwnership(cask: String, bundle: URL) -> BrewOwnership { - switch ToolDiscovery.locateBrewOutcome() { - case .unknown(let reason): - return .unknown(reason: reason) - case .absent: - // A definite answer, and the common one for the users this path exists for. - return fold([]) - case .found(let brews): - let mine = bundle.resolvingSymlinksInPath().standardizedFileURL.path - return fold(brews.map { brew in - switch ToolDiscovery.brewCaskApp(cask, brew: brew) { - case .notInstalled: - return .hasNothing - case .unusable(let reason): - return .noAnswer(reason: reason) - case .installedAt(let apps): - return apps.contains { $0.path == mine } - ? .ownsThisBundle(brew: brew) - : .ownsAnotherBundle - } - }) - } - } } diff --git a/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift b/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift index 5e635ba..9d071db 100644 --- a/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift +++ b/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift @@ -49,216 +49,6 @@ public enum ToolDiscovery { return loginShellLookup("gitpic") } - /// Which `brew`s are on this machine, keeping "none" and "could not tell" apart. - public enum BrewLocation: Equatable, Sendable { - /// Every `brew` found, in the order they were looked for. - /// - /// A **list**, not one path, and that is the whole point. A machine that has had both - /// an Intel and an Apple Silicon Homebrew has two prefixes with two independent - /// Caskrooms, and asking only the first one is how a cask installed by - /// `/usr/local/bin/brew` gets reported as "nobody's" by `/opt/homebrew/bin/brew` — - /// after which the in-app installer replaces a bundle brew manages. Never empty. - case found([URL]) - /// The login shell answered, and there is no `brew`. A durable fact about the - /// machine. - case absent - /// No answer was obtained — the probe hit its 8 s bound, the shell never reached the - /// lookup, or it could not be spawned. Says nothing either way and must not be cached. - case unknown(reason: String) - } - - /// Locate every `brew` on the machine, reporting *which* kind of "not found" this is. - /// - /// Exists for the same measured reason ``locateGitpic(bundleResourceURL:)`` does: a - /// Finder-launched app's PATH is `/usr/bin:/bin:/usr/sbin:/sbin`, so neither Homebrew - /// prefix is on it and `brew` cannot be found by name however normal it looks in a - /// terminal. - /// - /// **Why the absent/unknown distinction had to exist.** A single `nil` for both a machine - /// with no Homebrew and a probe that timed out was harmless while Homebrew was the only - /// way to upgrade — both meant "ask again later". It is not harmless now: a machine with - /// no `brew` at all is exactly the machine the in-app installer exists for, and folding it - /// in with "could not tell" left that user retrying a probe forever instead of being - /// offered the one path that works. - /// - /// The two hardcoded prefixes are Homebrew's own defaults (Apple Silicon, then Intel) and - /// answer the overwhelming majority without spawning a login shell, which costs up to - /// 8 seconds. The probe is the fallback for a custom `HOMEBREW_PREFIX`. - /// - /// **The stated gap.** Because the hardcoded paths short-circuit the probe, a machine with - /// a *vestigial* `/opt/homebrew/bin/brew` plus a custom-prefix brew that owns the cask is - /// still asked only the vestigial one. Closing it would mean paying the 8 s login shell on - /// every sheet open for everyone, including the very common "brew is here and it is not - /// mine" case. Left open deliberately; the alternative is a worse trade. - /// - /// The asymmetry in ``loginShellProbe(_:)`` is deliberate and follows its own reasoning: a - /// path found in stdout is trusted even if the shell had to be killed, because the answer - /// was already written. The bound and the two marks only decide whether the *absence* of a - /// path means anything. - public static func locateBrewOutcome() -> BrewLocation { - let hardcoded = ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"] - .filter { FileManager.default.isExecutableFile(atPath: $0) } - .map { URL(fileURLWithPath: $0) } - if !hardcoded.isEmpty { return .found(hardcoded) } - let probe = loginShellProbe("brew") - if let path = probe.path { return .found([path]) } - guard probe.conclusive else { - return .unknown(reason: probe.reason ?? "没能确认这台机器上有没有 Homebrew") - } - return .absent - } - - /// Which bundle Homebrew installed for `cask`, if any. - /// - /// Three answers, and the boundary between them is the whole safety property: only - /// ``notInstalled`` may authorise replacing a bundle, so anything short of Homebrew - /// positively saying "I have nothing under that token" has to be ``unusable``. - public enum BrewCaskApp: Equatable, Sendable { - /// brew manages this cask, and these are the bundles it lists — plural, because a - /// Caskroom can hold more than one version and each version directory has its own - /// `GitPic.app` symlink. Never empty, and every entry exists on disk. - case installedAt([URL]) - /// brew has nothing installed under this token. A durable fact, and the only answer - /// that may lead to an install. - case notInstalled(status: Int32) - /// No usable answer. `reason` is user-facing Chinese; the command line, the exit - /// status and brew's own stderr go to ``Diagnostics/log(_:)`` instead, because this - /// string is rendered in a Chinese-only sheet (`UpdateSheet`). - case unusable(reason: String) - } - - /// Ask Homebrew *which* bundle it installed for `cask`, not merely whether it did. - /// - /// Bounded at 20 seconds: a first invocation can catch Homebrew doing its own housekeeping, - /// and this runs behind a window that is waiting to draw a button. Spawning lives here - /// rather than in `GitPicApp` because `ChildProcess` is internal to this module — the same - /// reason ``locateBrewOutcome()`` is here and not beside its one caller. - /// - /// **Why the path and not a yes/no.** `brew list --cask gitpic` exits 0 whenever the cask - /// is installed *anywhere*, and that is not the question. A copy in `~/Applications` on a - /// machine whose cask installed to `/Applications` would answer "yes" and then be handed to - /// `brew upgrade`, which would replace the *other* bundle and leave this one — an old build, - /// still reporting the same update available, with brew reporting nothing left to do. The - /// user could repeat that forever. Caught by running it, not by reading it. - /// - /// Homebrew answers exactly: the Caskroom holds a symlink at - /// `/Caskroom///GitPic.app` pointing at wherever the app was - /// installed, and `brew list --cask` prints that path. Resolving it gives the bundle brew - /// owns, with no parsing of human-readable output and no guessing at `--appdir`. - /// - /// **Every ambiguous answer is ``BrewCaskApp/unusable(reason:)``, never "not mine".** Three - /// measured reasons, all on Homebrew 6.0.19 on this machine: - /// - /// 1. **Homebrew has exactly one error exit code.** `brew list --cask firefox` (a real cask, - /// not installed) exits 1 with `find: /opt/homebrew/Caskroom/firefox: No such file or - /// directory`; `env -i brew list --cask gitpic` *also* exits 1, with `Error: $HOME must - /// be set to run brew.`; and `brew list --cask definitely-not-real-xyz` exits 1 with - /// `Error: Cask '…' is unavailable: No Cask with this name exists.` So the status alone - /// distinguishes nothing. - /// 2. **Nor does the message.** That last error is printed *even when the Caskroom holds the - /// cask*: with `/opt/homebrew/Caskroom/gitpic-fixture-zzz/9.9.9/Fixture.app` created by - /// hand, `brew list --cask gitpic-fixture-zzz` still said `No Cask with this name - /// exists.` — which is what a removed tap looks like on a machine where the cask is very - /// much installed. So the wording is not evidence either. - /// 3. What *is* evidence is the Caskroom itself, asked for by ``brewCaskroom(brew:)`` and - /// then looked at. A token with no directory under `/Caskroom` is one this brew - /// has installed nothing for, whatever it said and whichever way it exited — and if brew - /// cannot even say where its Caskroom is, that is itself the "no answer" case. - /// - /// Exit **0** with no identifiable bundle is also `unusable`, and this is not theoretical: - /// `brew list --cask codex` and `brew list --cask font-maple-mono-nf-cn` both exit 0 here - /// with zero `.app` lines. Exit 0 means brew *does* have the cask, so "I cannot see which - /// bundle" is the one thing it cannot mean. - public static func brewCaskApp(_ cask: String, brew: URL) -> BrewCaskApp { - let command = "\(brew.path) list --cask \(cask)" - let out: ProcessOutcome - do { - out = try ChildProcess.run( - executable: brew, args: ["list", "--cask", cask], timeout: 20) - } catch { - Diagnostics.log("update: \(command) could not be spawned: \(error)") - return .unusable(reason: "无法运行 Homebrew,没法确认这份 GitPic 是不是它装的") - } - if out.timedOut { - Diagnostics.log("update: \(command) timed out after 20s") - return .unusable(reason: "Homebrew 20 秒内没有回答这份 GitPic 是不是它装的") - } - guard out.status == 0 else { - // Confirmed against the filesystem rather than against brew's prose — see the - // three measurements above. - let complaint = Self.firstLine(of: out.stderr) - guard let caskroom = brewCaskroom(brew: brew) else { - Diagnostics.log("update: \(command) exited \(out.status) (\(complaint)) and" - + " `brew --caskroom` gave no answer either") - return .unusable(reason: "Homebrew 没能说清这份 GitPic 是不是它装的") - } - // Homebrew keys the Caskroom by bare token, so a tap-qualified name - // (`tarnish233/tap/gitpic`) still lands in `Caskroom/gitpic`. - let entry = caskroom.appendingPathComponent( - URL(fileURLWithPath: cask).lastPathComponent) - if !FileManager.default.fileExists(atPath: entry.path) { - Diagnostics.log("update: \(command) exited \(out.status) (\(complaint)) and" - + " \(entry.path) does not exist — brew installed no \(cask)") - return .notInstalled(status: out.status) - } - Diagnostics.log("update: \(command) exited \(out.status) (\(complaint)) but" - + " \(entry.path) exists — brew may well own this cask") - return .unusable(reason: "Homebrew 没能说清这份 GitPic 是不是它装的") - } - - // One path per line. The `.app`s among them are the artifacts; the rest are the receipt - // and the cask's own JSON. **All** of them, not the first: a Caskroom holding two - // version directories lists two `GitPic.app` symlinks, and the older one can be - // dangling — measured, `resolvingSymlinksInPath()` returns a dangling symlink - // *unchanged*, so picking it would compare a path that does not exist against the - // running bundle and conclude "not brew's". - let lines = String(decoding: out.stdout, as: UTF8.self) - .split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } - let listed = lines.filter { $0.hasSuffix(".app") } - let apps = listed - .map { URL(fileURLWithPath: $0).resolvingSymlinksInPath().standardizedFileURL } - .filter { FileManager.default.fileExists(atPath: $0.path) } - guard !apps.isEmpty else { - // Exit 0 means brew has this cask; there is simply nothing here to compare the - // running bundle against. That is the definition of "no answer", not of a durable - // fact — and the log has to say which, because the remedies differ. - Diagnostics.log("update: \(command) exited 0 but named no existing .app" - + " (\(lines.count) line(s), \(listed.count) ending in .app)" - + " — brew has \(cask), its bundle is unidentifiable") - return .unusable(reason: "Homebrew 管着 gitpic,但没有报出它装的是哪一个 GitPic.app") - } - return .installedAt(apps) - } - - /// Where this `brew` keeps its Caskroom, straight from brew. - /// - /// `brew --caskroom` with no cask argument needs no tap and resolves no cask definition, so - /// it answers on a machine where `brew list --cask ` cannot — which is exactly when - /// it is asked. Measured at 46 ms, against `brew list --cask`'s 0.44 s, so this is cheap - /// enough to be the tiebreaker on the failure path. - /// - /// Deliberately *not* derived from `brew`'s own path: `/usr/local/bin/brew` is commonly a - /// symlink into `/usr/local/Homebrew/bin/brew`, and a prefix guessed from the wrong one of - /// those would point at a directory that does not exist — which on this code path reads as - /// "brew installed nothing" and authorises an install. Asking brew cannot be wrong that - /// way; failing to get an answer is the safe direction. - static func brewCaskroom(brew: URL) -> URL? { - let out = try? ChildProcess.run(executable: brew, args: ["--caskroom"], timeout: 20) - guard let out, out.status == 0, !out.timedOut else { return nil } - let path = String(decoding: out.stdout, as: UTF8.self) - .trimmingCharacters(in: .whitespacesAndNewlines) - guard path.hasPrefix("/") else { return nil } - return URL(fileURLWithPath: path) - } - - /// The first line of a child's stderr, for the log. Homebrew puts every error there — - /// measured: `brew list --cask firefox 2>/dev/null` prints nothing at all on stdout. - private static func firstLine(of stderr: Data) -> String { - let text = String(decoding: stderr, as: UTF8.self) - return text.split(whereSeparator: \.isNewline).first - .map { $0.trimmingCharacters(in: .whitespaces) } ?? "no stderr" - } - /// Ask the user's login shell where a tool is. A login shell sources the user's /// profile, so this covers nix, asdf, and custom prefixes that no hardcoded list /// would catch. Verified to return `/opt/homebrew/bin/gh` even from a @@ -307,9 +97,18 @@ public enum ToolDiscovery { /// | `.zprofile` containing `exec true` | **0** | empty | /// /// The last one is why the exit status cannot be the fix either. All four used to come back - /// `conclusive: true, path: nil` → `.absent` → "not Homebrew's" → an install over whatever - /// is in `/Applications`, and they are reachable *exactly* for the custom-`HOMEBREW_PREFIX` - /// users this probe exists to serve, since the two hardcoded paths are checked first. + /// `conclusive: true, path: nil`. + /// + /// **What that used to cost, and what it costs now.** This probe had a second caller: the + /// Homebrew ownership question, where a false "absent" folded into "not brew's" and + /// authorised replacing whatever was in `/Applications`. That caller is gone — the cask + /// declares `auto_updates true` and the app installs over every copy, so nothing asks about + /// brew any more (see `SelfUpdate.route`). The evidence below is kept as measured, because + /// the bracketing it justifies is still what makes the *remaining* caller correct: a false + /// "absent" now means `locateGitpic` reports no CLI on a machine that has one, which is a + /// milder failure than an unwanted install but still a wrong answer, and still reachable + /// exactly for the custom-prefix users this probe exists to serve — the hardcoded paths are + /// checked first, so only they get here. /// /// So the shell is made to prove it ran, and to bracket its answer. It prints /// ``probeOpen`` before the lookup — guarded by `command -v /bin/sh`, a lookup of something @@ -321,13 +120,15 @@ public enum ToolDiscovery { /// - nothing between them → the tool really is not there → conclusive. /// - something between them that is not a usable path → the tool exists as an alias or a /// shell function (measured: zsh prints `brew` for a function and `alias brew=…` for an - /// alias), which ``commandVPath(in:tool:)`` rightly refuses to spawn — but it is *not* - /// absence, and calling it absence is an install over a bundle brew may well own. + /// alias — the measurement was taken against `brew`, which is no longer a tool this + /// locates, and is left as recorded because the parse it exercises is unchanged), which + /// ``commandVPath(in:tool:)`` rightly refuses to spawn — but it is *not* absence. /// /// The closing mark is what keeps a late-flushing profile job out of that second case: /// measured, `[gpg-agent] ready` arriving after the lookup lands *after* ``probeClose`` and - /// so cannot turn "no brew" into "cannot tell". A job that flushes in the microseconds - /// between the two marks still can, and that is the safe direction — the release page. + /// so cannot turn "the tool is not here" into "cannot tell". A job that flushes in the + /// microseconds between the two marks still can, and that is the safe direction — an + /// inconclusive answer, rather than a confident wrong one. static func loginShellProbe(_ tool: String) -> ShellProbe { let shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh" guard FileManager.default.isExecutableFile(atPath: shell) else { diff --git a/apps/GitPic/Tests/GitPicCoreTests/QuitPathContractTests.swift b/apps/GitPic/Tests/GitPicCoreTests/QuitPathContractTests.swift index c7f6912..66c33b3 100644 --- a/apps/GitPic/Tests/GitPicCoreTests/QuitPathContractTests.swift +++ b/apps/GitPic/Tests/GitPicCoreTests/QuitPathContractTests.swift @@ -34,9 +34,12 @@ struct QuitPathContractTests { /// tripwire whose whole purpose was to catch it. /// /// Anchored on the receiver (`NSApp` / `NSApplication`) or on the selector's colon, never on - /// the bare word `terminate`: the generated brew script in `Updater.swift` contains `SIGTERM` - /// and `SIGKILL` inside string literals, `AppModel` speaks of "terminates the `gitpic` child", - /// and `LoginChild.terminate()` is a legitimate thing to call on a `Process`. + /// the bare word `terminate`. The original motive was the generated Homebrew upgrade script in + /// `Updater.swift`, which carried `SIGTERM` and `SIGKILL` inside string literals — that script + /// is gone, and the anchoring is kept because the other reasons never depended on it: + /// `AppModel` speaks of "terminates the `gitpic` child", `LoginChild.terminate()` is a + /// legitimate thing to call on a `Process`, and `SelfUpdateInstall`'s swap script is still + /// shell text generated in Swift. static let forbidden = [ "NSApplication.terminate", "NSApplication.shared.terminate", @@ -146,10 +149,12 @@ struct QuitPathContractTests { /// sequence, so every quit during an install was refused. /// /// **Asserted against `quit(_:)` and deliberately *not* against `prepareToQuit()`.** The - /// latter has two callers that do not exit — the `GITPIC_APP_DRY_RUN` branches of - /// `installAndRelaunch` and `upgradeAndRelaunch`, which call it and then `return` — so a - /// destructive drain there would run while the app keeps going. It is only the `exit(0)` in - /// `quit` that makes undoing this work necessary, so that is where it belongs. + /// latter has a caller that does not exit — the `GITPIC_APP_DRY_RUN` branch of + /// `installAndRelaunch`, which calls it and then `return`s — so a destructive drain there + /// would run while the app keeps going. There were two such callers until the Homebrew + /// upgrade path took its own dry-run branch with it; one is all the rule needs. It is only + /// the `exit(0)` in `quit` that makes undoing this work necessary, so that is where it + /// belongs. /// /// This is a grep, and a grep is the weaker half — what the drain *does* is covered /// behaviourally in `SelfUpdateInstallTests`, which can import `GitPicCore`. What only a diff --git a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift index 1040b04..312bad6 100644 --- a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift +++ b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift @@ -232,6 +232,32 @@ struct SelfUpdateInstallTests { .filter { $0.hasPrefix("gitpic-mount-") }) } + /// Attach a fixture image the way `stage` does, retries included. + /// + /// The one test here that mounts an image *itself* rather than through `stage` needs the same + /// tolerance `stage` now has, and for the reason that made it necessary there: measured on a + /// GitHub `macos-latest` runner, seventeen seconds into this suite every remaining + /// `hdiutil attach` began returning `Resource temporarily unavailable` inside 0.07 s and kept + /// doing so — twenty failures in a suite that had been passing, from a kernel that had simply + /// stopped accepting attaches. The run before and the run after were both green, so this is a + /// bound on how much of somebody else's machine this test is willing to depend on, not a + /// workaround for a defect of ours. + /// + /// A timeout is not retried, matching `stage`: an attach that timed out may have landed, and + /// attaching twice is worse than reporting once. + private static func attachWithRetries(_ dmg: URL, at mount: URL) throws -> ProcessOutcome { + var out: ProcessOutcome! + for attempt in 1...3 { + out = try ChildProcess.run( + executable: URL(fileURLWithPath: "/usr/bin/hdiutil"), + args: ["attach", dmg.path, "-nobrowse", "-readonly", "-mountpoint", mount.path], + timeout: 120) + if out.status == 0 || out.timedOut { break } + if attempt < 3 { Thread.sleep(forTimeInterval: 1) } + } + return out + } + /// The digest has to cover the bytes that get mounted, not a path that once held them. /// /// `download` hashes through one descriptor and `hdiutil` opens the path again, with a @@ -767,7 +793,87 @@ struct SelfUpdateInstallTests { } } - @Test("a file that is not a disk image is refused") + /// **The layout a Homebrew install leaves behind, and whether the swap survives it.** + /// + /// Until this change `route` returned `.homebrew` before `stage` could ever see a cask-managed + /// bundle, so the installer that now handles *every* copy had never once run against the shape + /// Homebrew creates. `check-self-update.sh` cannot close that gap either: it refuses to touch + /// `/Applications` by design, and that is where the cask installs. Hence a fixture, built to + /// what was measured off this machine's real install rather than to what seemed likely: + /// + /// /opt/homebrew/bin/gitpic -> /Applications/GitPic.app/Contents/Resources/gitpic + /// /opt/homebrew/Caskroom/gitpic/0.20.8/GitPic.app -> /Applications/GitPic.app + /// + /// Both are symlinks to **absolute paths inside or at** the bundle, and the swap is two renames + /// within the bundle's own directory — so both should come out resolving to the new version. + /// The CLI upgrading together with the app is nobody's feature; it is a consequence of that. + /// + /// **What this would and would not catch**, since the distinction is the point of having it: a + /// swap that left the new bundle at any other path, and anything that made the CLI link resolve + /// to the old version — the backup, say — both fail here, and the second of those is the one + /// `bundleVersion(of: target)` on its own would miss. A swap that replaced the bundle by copying + /// into the same path instead of renaming would *not* be caught, because a path-based symlink + /// cannot tell the difference. That is a real limit and not what this test is for. + /// + /// The `bin/gitpic` half is asserted by *running* it, because "the symlink still resolves" and + /// "the terminal now has the new CLI" are different claims and only the second one is the + /// promise the cask makes. + @Test("a Homebrew-shaped install comes out with its symlinks on the new bundle") + func swapKeepsCaskSymlinksOnTheNewBundle() throws { + let f = try Self.fixture() + defer { try? FileManager.default.removeItem(at: f.root) } + + // Stand in for HOMEBREW_PREFIX. Only the two links matter; the completions the cask also + // installs are real files rather than links — which is exactly why they go stale, and why + // there is nothing here to assert about them. + let prefix = f.root.appendingPathComponent("homebrew") + let caskroom = prefix.appendingPathComponent("Caskroom/gitpic/0.18.0") + try FileManager.default.createDirectory(at: prefix.appendingPathComponent("bin"), + withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: caskroom, withIntermediateDirectories: true) + let binLink = prefix.appendingPathComponent("bin/gitpic") + let caskLink = caskroom.appendingPathComponent("GitPic.app") + try FileManager.default.createSymbolicLink( + at: binLink, withDestinationURL: f.target.appendingPathComponent("Contents/Resources/gitpic")) + try FileManager.default.createSymbolicLink(at: caskLink, withDestinationURL: f.target) + + // Both point at 0.18.0 to begin with, or the assertions below would prove nothing. + let before = try ChildProcess.run(executable: binLink, args: [], timeout: 30) + #expect(String(decoding: before.stdout, as: UTF8.self).trimmingCharacters( + in: .whitespacesAndNewlines) == "0.18.0", "the fixture's link is not wired up") + + let staged = try SelfUpdate.stage(dmg: f.dmg, expectedVersion: "0.19.0", + replacing: f.target) + let log = f.root.appendingPathComponent("install.log") + let output = try Self.runScript(staged: staged, log: log, root: f.root) + #expect(SelfUpdate.bundleVersion(of: f.target) == "0.19.0", "log: \(output)") + + // The command the cask put on PATH is now the new version's, without brew having run. + let after = try ChildProcess.run(executable: binLink, args: [], timeout: 30) + #expect(String(decoding: after.stdout, as: UTF8.self).trimmingCharacters( + in: .whitespacesAndNewlines) == "0.19.0", + "the CLI on PATH still resolves to the old bundle after the swap") + + // And the Caskroom's own link still names a real bundle, so `brew list --cask` and + // `brew uninstall` keep working against the copy that is actually installed. + #expect(FileManager.default.fileExists(atPath: caskLink.path), + "the Caskroom link dangles after the swap") + #expect(SelfUpdate.bundleVersion(of: caskLink) == "0.19.0", + "the Caskroom link does not see the new version") + } + + /// Also the only observable proof that the attach is retried. + /// + /// `stage` spawns `/usr/bin/hdiutil` by absolute path, so a transient failure cannot be + /// injected — but a file that is not an image fails the same way a transient refusal does, by + /// exiting non-zero fast. Three attempts one second apart therefore cannot finish in under two + /// seconds, and a lower bound on elapsed time is deterministic in the safe direction: a + /// `Thread.sleep` can overrun, never undershoot. Delete the retry and this assertion fails. + /// + /// It is also what the two seconds are: the stated cost of not pattern-matching `hdiutil`'s + /// stderr to decide what is worth retrying — a genuinely unreadable image is refused that much + /// later than it used to be. + @Test("a file that is not a disk image is refused, after retrying the attach") func refusesGarbage() throws { let root = FileManager.default.temporaryDirectory .appendingPathComponent("gitpic-install-test-\(UUID().uuidString)") @@ -777,10 +883,13 @@ struct SelfUpdateInstallTests { let notAnImage = root.appendingPathComponent("GitPic-0.19.0-macos-arm64.dmg") try Data("this is not a disk image".utf8).write(to: notAnImage) + let started = ContinuousClock.now #expect(throws: SelfUpdate.InstallFailure.self) { _ = try SelfUpdate.stage(dmg: Self.measured(notAnImage), expectedVersion: "0.19.0", replacing: root.appendingPathComponent("GitPic.app")) } + #expect(started.duration(to: .now) >= .seconds(2), + "the attach was not retried: three attempts a second apart cannot be faster") // Nothing was mounted, so the mount point was removed by the plain `rmdir` path — no // `hdiutil detach` was needed and none of it recursed into a volume. #expect(Self.mountLeftovers() == mountsBefore) @@ -835,10 +944,7 @@ struct SelfUpdateInstallTests { let mount = FileManager.default.temporaryDirectory .appendingPathComponent("gitpic-mount-\(UUID().uuidString)") try FileManager.default.createDirectory(at: mount, withIntermediateDirectories: true) - let attach = try ChildProcess.run( - executable: URL(fileURLWithPath: "/usr/bin/hdiutil"), - args: ["attach", f.dmg.url.path, "-nobrowse", "-readonly", "-mountpoint", mount.path], - timeout: 120) + let attach = try Self.attachWithRetries(f.dmg.url, at: mount) try #require(attach.status == 0 && !attach.timedOut, "could not attach the fixture image: \(String(decoding: attach.stderr, as: UTF8.self))") // If the drain does not get it, this does — a leaked mount survives until reboot. diff --git a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift index 9fc7ce5..6291749 100644 --- a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift +++ b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift @@ -17,92 +17,68 @@ struct SelfUpdateRouteTests { private static var choice: AssetChoice { .found(dmg, sha256: String(repeating: "ab", count: 32)) } - private static let brewPath = URL(fileURLWithPath: "/opt/homebrew/bin/brew") - private static let otherBrewPath = URL(fileURLWithPath: "/usr/local/bin/brew") private static let sha = String(repeating: "ab", count: 32) - /// **Homebrew wins whenever it owns the bundle.** This is the surviving half of the - /// argument the old `Updater` doc comment made against self-update: replacing a - /// cask-managed bundle leaves brew's manifest describing a version that is not on disk, - /// and the next `brew upgrade` fights it. - @Test("a cask-managed bundle goes to brew, not to the in-app installer") - func brewWins() { + /// **One route, whoever installed the bundle.** This suite used to open with + /// `brewWins` — a cask-managed bundle went to `brew upgrade --cask gitpic` and only + /// everything else reached the installer — plus eleven rows protecting that fork: how the + /// verdicts of two Homebrew prefixes were folded, that an unanswered probe never became + /// "not brew's", and that a refusal the path already decided did not spawn brew anyway. + /// The fork is gone (the cask declares `auto_updates true`; `SelfUpdate.route`'s header has + /// the argument), and those rows went with the code they covered. What is left is the table + /// that was always about this machine rather than about brew. + @Test("an older bundle in an Applications directory gets the installer") + func installsAnOlderBundle() { let route = SelfUpdate.route( location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: .ownsThisCask(brew: Self.brewPath), asset: Self.choice) - #expect(route == .homebrew(brew: Self.brewPath)) - } - - /// brew is installed but does not manage this app — a drag-installed copy on a machine - /// that also has Homebrew, which is entirely ordinary. - @Test("brew that does not own it leaves the in-app installer") - func brewPresentButNotTheOwner() { - let route = SelfUpdate.route( - location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: .doesNotOwnIt, asset: Self.choice) + asset: Self.choice) #expect(route == .selfInstall(asset: Self.dmg, sha256: Self.sha, version: "0.19.0")) } - /// The user this whole feature exists for: no Homebrew at all. - /// - /// This is the row that the old single-`nil` brew lookup used to make unreachable — "no brew" - /// and "the probe timed out" were the same answer, and both meant "ask again later", so - /// the machine with no brew waited forever for a probe that was never going to say - /// anything different. - @Test("no brew on the machine is an answer, and it enables the installer") - func noBrewAtAll() { - // What `brewOwnership` folds a `.absent` location into: no brew, so nothing brew owns. - #expect(SelfUpdate.fold([]) == .doesNotOwnIt) - let route = SelfUpdate.route( + /// The structural claim the deleted rows used to make one case at a time: with the location, + /// the version and the asset all in order there is **no** remaining question that could send + /// this anywhere else. Nothing is asked about who installed the bundle, so nothing about the + /// machine's Homebrew can change the answer. + @Test("nothing but the location, the version and the asset decides the route") + func routeIsDecidedByThreeFactsOnly() { + let usable = SelfUpdate.route( location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: SelfUpdate.fold([]), asset: Self.choice) - guard case .selfInstall = route else { - Issue.record("a machine with no brew must be offered the in-app installer") + asset: Self.choice) + guard case .selfInstall = usable else { + Issue.record("three facts in order must produce an install and nothing else") return } - } - - /// **An unknown answer must never become "not brew's".** A probe that timed out can be - /// hiding a working Homebrew, and installing over a cask on that guess is exactly the - /// damage the precedence rule exists to prevent. Retryable, so the sheet asks again - /// instead of caching it for the life of the process. - @Test("an inconclusive brew probe is retryable, never an install") - func unknownBrewIsRetryable() { - // Verbatim what `ToolDiscovery.brewCaskApp` now mints for its 20 s bound. It used to be - // `"brew list --cask gitpic timed out"`, and this assertion used to pin that English on - // it — which was wrong in both directions: the string is rendered by `UpdateSheet` as - // `Text(reason)` in a Chinese-only window, and the command line that belongs in the log - // was the only thing the window had to show. The diagnostic half goes to - // `Diagnostics.log` now, and the sheet gets a sentence. - let reason = "Homebrew 20 秒内没有回答这份 GitPic 是不是它装的" - let route = SelfUpdate.route( - location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: .unknown(reason: reason), asset: Self.choice) - guard case .unavailable(let shown, let retryable) = route else { - Issue.record("an unknown brew answer must not install anything") - return + // Break exactly one at a time; each must refuse, and none may produce an install. + let broken: [SelfUpdate.Route] = [ + SelfUpdate.route(location: .elsewhere(path: "/Users/x/Downloads/GitPic.app"), + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice), + SelfUpdate.route(location: .applicationsDir, bundleVersion: "not-a-version", + latest: "0.19.0", asset: Self.choice), + SelfUpdate.route(location: .applicationsDir, bundleVersion: "0.18.0", + latest: "0.19.0", asset: .none(reason: "GitHub 没有报校验和")), + ] + for route in broken { + guard case .unavailable = route else { + Issue.record("a broken precondition must refuse, not install") + return + } } - #expect(retryable, "a probe that got no answer must be asked again") - #expect(shown == reason, "the sheet shows the reason it was given, verbatim") - // No developer English reaches the window. Product names are fine — 「Homebrew」 and - // 「GitPic」 are what the sheet calls them elsewhere — but a command line is not: no - // option flags, no paths, and the sentence has to actually be in Chinese. - #expect(shown.contains(where: { $0.unicodeScalars.first.map { - (0x4E00...0x9FFF).contains($0.value) - } == true }), "a reason rendered in a Chinese-only sheet has to be Chinese") - #expect(!shown.contains("--") && !shown.contains("/"), - "\(shown) reads like a command line, and it is shown in a caption at 480 pt") } /// Outside `/Applications` and `~/Applications` nothing is installed — including the /// development build in the repository's `dist-app/`, which is the case that would /// otherwise replace a developer's build with a release one. + /// + /// This also absorbs what `caskInACustomAppdirIsSentToTheReleasePage` used to pin. That row + /// existed to prove the location rule was not *looser* for a cask installed with a custom + /// `--appdir` than for anything else, back when the brew question could have overridden it. + /// With one route there is no second rule for it to be looser than, and the row said nothing + /// this one does not. @Test("a bundle outside an Applications directory is refused, permanently") func elsewhereIsRefused() { let route = SelfUpdate.route( location: .elsewhere(path: "/Users/x/src/gitpic/dist-app/GitPic.app"), - bundleVersion: "0.18.0", latest: "0.19.0", - brew: .doesNotOwnIt, asset: Self.choice) + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) guard case .unavailable(let reason, let retryable) = route else { Issue.record("only an Applications directory may be installed into") return @@ -112,99 +88,40 @@ struct SelfUpdateRouteTests { #expect(reason.contains("dist-app")) } - /// **The free question is asked first, and the expensive one is not asked at all.** + /// **No developer English reaches the window, and nothing reads like a command line.** /// - /// `brew` is an `@autoclosure` for this row alone. Passed as a plain argument it was - /// evaluated before `route` was entered, so a development build in `dist-app/` spawned a - /// login shell and a `brew list --cask`, serialised on one queue, before the sheet could - /// print a refusal a string comparison had already decided. Bounds of 8 s and 20 s, and - /// 0.04 s + 0.42–0.81 s measured on a warm machine — either way, for nothing. - @Test("a refusal the location decides never spawns Homebrew") - func locationRefusalDoesNotAskBrew() { - var asked = 0 - let route = SelfUpdate.route( - location: .elsewhere(path: "/Users/x/src/gitpic/dist-app/GitPic.app"), - bundleVersion: "0.18.0", latest: "0.19.0", - brew: { asked += 1; return .doesNotOwnIt }(), asset: Self.choice) - #expect(asked == 0, "the location answer is free; the brew answer costs up to 28 s") - guard case .unavailable = route else { - Issue.record("only an Applications directory may be installed into") - return - } - - // And it *is* asked when the location does not settle it, or nothing would ever be - // routed to brew. - var askedAgain = 0 - _ = SelfUpdate.route( - location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: { askedAgain += 1; return .doesNotOwnIt }(), asset: Self.choice) - #expect(askedAgain == 1) - } - - /// The stated cost of asking the location first, pinned so it cannot be paid by accident. + /// Inherited from `unknownBrewIsRetryable`, which is deleted: that row's reason string used + /// to be `"brew list --cask gitpic timed out"`, English and a command line both, rendered by + /// `UpdateSheet` as `Text(reason)` in a caption at 480 pt in a Chinese-only window. The + /// assertion was worth more than the row, so it is applied to every refusal `route` can mint + /// instead of to the one that happened to have the bug. /// - /// A cask installed with a custom `--appdir` — `~/Apps`, say — used to be offered - /// `brew upgrade` because the brew question came first. It now goes to the release page, - /// where the sheet's fallback line spells out `brew upgrade --cask gitpic`. That is the - /// trade the ordering makes, and the doc comment on ``SelfUpdate/route`` states it. - @Test("a cask installed outside the two Applications directories goes to the release page") - func caskInACustomAppdirIsSentToTheReleasePage() { - let route = SelfUpdate.route( - location: .elsewhere(path: "/Users/x/Apps/GitPic.app"), - bundleVersion: "0.18.0", latest: "0.19.0", - brew: .ownsThisCask(brew: Self.brewPath), asset: Self.choice) - guard case .unavailable(_, let retryable) = route else { - Issue.record("the location rule is shared with the brew path, not looser for it") - return + /// The old row also asserted `!reason.contains("/")`, and that does **not** generalise: the + /// location refusal names the path it is refusing, which is the entire information in it. + /// An option flag is the part that was never legitimate. + @Test("every refusal is a Chinese sentence, not a command line") + func refusalsAreWrittenForTheWindow() { + let refusals: [SelfUpdate.Route] = [ + SelfUpdate.route(location: .elsewhere(path: "/Users/x/Downloads/GitPic.app"), + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice), + SelfUpdate.route(location: .applicationsDir, bundleVersion: nil, latest: "0.19.0", + asset: Self.choice), + SelfUpdate.route(location: .applicationsDir, bundleVersion: "0.18.0", + latest: "not-a-version", asset: Self.choice), + SelfUpdate.route(location: .applicationsDir, bundleVersion: "0.19.0", + latest: "0.19.0", asset: Self.choice), + ] + for route in refusals { + guard case .unavailable(let shown, _) = route else { + Issue.record("expected a refusal to check the wording of") + return + } + #expect(shown.contains(where: { $0.unicodeScalars.first.map { + (0x4E00...0x9FFF).contains($0.value) + } == true }), "\(shown) is rendered in a Chinese-only sheet and has to be Chinese") + #expect(!shown.contains("--"), + "\(shown) reads like a command line, and it is shown in a caption at 480 pt") } - #expect(!retryable) - } - - // MARK: - Folding what every brew said - - /// **Homebrew owning the bundle always wins, whichever brew says so.** - /// - /// The machine this exists for: two prefixes, and the cask installed by the one that is not - /// checked first. `locateBrewOutcome()` prefers `/opt/homebrew/bin/brew`, which answers a - /// perfectly truthful "I have nothing under that token" — and folding that straight into - /// "not brew's" replaced a bundle `/usr/local/bin/brew` manages. - @Test("any brew that owns this bundle settles it, whatever the others said") - func foldPrefersTheOwner() { - #expect(SelfUpdate.fold([.hasNothing, .ownsThisBundle(brew: Self.otherBrewPath)]) - == .ownsThisCask(brew: Self.otherBrewPath)) - // Even ahead of an unanswered brew: there is nothing an unknown answer could add to a - // positive one. - #expect(SelfUpdate.fold([.noAnswer(reason: "读不到"), - .ownsThisBundle(brew: Self.brewPath)]) - == .ownsThisCask(brew: Self.brewPath)) - #expect(SelfUpdate.fold([.ownsAnotherBundle, - .ownsThisBundle(brew: Self.brewPath)]) - == .ownsThisCask(brew: Self.brewPath)) - } - - /// **One brew that could not answer makes the whole answer unknown**, because that brew is - /// exactly the one that could have been the owner. - @Test("an unanswered brew is never outvoted into an install") - func foldRefusesToGuessPastAnUnansweredBrew() { - let reason = "Homebrew 没能说清这份 GitPic 是不是它装的" - #expect(SelfUpdate.fold([.hasNothing, .noAnswer(reason: reason)]) - == .unknown(reason: reason)) - #expect(SelfUpdate.fold([.ownsAnotherBundle, .noAnswer(reason: reason)]) - == .unknown(reason: reason)) - #expect(SelfUpdate.fold([.noAnswer(reason: reason)]) == .unknown(reason: reason)) - } - - /// The only shape that may authorise replacing a bundle: every brew answered, and none of - /// them installed this one. - @Test("only a complete set of negative answers permits an install") - func foldAllowsInstallOnlyWhenEveryBrewAnswered() { - #expect(SelfUpdate.fold([.hasNothing]) == .doesNotOwnIt) - #expect(SelfUpdate.fold([.hasNothing, .hasNothing]) == .doesNotOwnIt) - // "brew installed the cask, as some *other* bundle" is equally definite — a copy in - // `~/Applications` on a machine whose cask went to `/Applications`. Handing that to - // brew upgrades the other bundle and reopens this one unchanged, forever. - #expect(SelfUpdate.fold([.ownsAnotherBundle]) == .doesNotOwnIt) - #expect(SelfUpdate.fold([.ownsAnotherBundle, .hasNothing]) == .doesNotOwnIt) } /// The gate is the *bundle's* version, not the report's `current` — that one comes from @@ -214,7 +131,7 @@ struct SelfUpdateRouteTests { for mine in ["0.19.0", "0.20.0", "1.0.0"] { let route = SelfUpdate.route( location: .applicationsDir, bundleVersion: mine, latest: "0.19.0", - brew: .doesNotOwnIt, asset: Self.choice) + asset: Self.choice) guard case .unavailable(let reason, _) = route else { Issue.record("\(mine) is not older than 0.19.0 and must not be replaced") return @@ -224,7 +141,7 @@ struct SelfUpdateRouteTests { // And older is. guard case .selfInstall = SelfUpdate.route( location: .applicationsDir, bundleVersion: "0.9.0", latest: "0.10.0", - brew: .doesNotOwnIt, asset: Self.choice) else { + asset: Self.choice) else { // 0.9.0 < 0.10.0 is the comparison a string sort gets backwards, which is why // the version is parsed into numbers rather than compared as text. Issue.record("0.9.0 must be older than 0.10.0") @@ -237,7 +154,7 @@ struct SelfUpdateRouteTests { for mine in [nil, "", "0.18", "0.18.0.1", "0.18.0-rc1", "app-v0.1.2", "abc"] { let route = SelfUpdate.route( location: .applicationsDir, bundleVersion: mine, latest: "0.19.0", - brew: .doesNotOwnIt, asset: Self.choice) + asset: Self.choice) guard case .unavailable = route else { Issue.record("\(mine ?? "nil") is not a comparable version") return @@ -251,7 +168,7 @@ struct SelfUpdateRouteTests { func assetRefusalPropagates() { let route = SelfUpdate.route( location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: .doesNotOwnIt, asset: .none(reason: "GitHub 没有报校验和")) + asset: .none(reason: "GitHub 没有报校验和")) #expect(route == .unavailable(reason: "GitHub 没有报校验和", retryable: false)) } @@ -297,8 +214,12 @@ struct SelfUpdateRouteTests { let tidied = try #require(script.range(of: #"rmdir "$stagedir""#)) #expect(reopened.upperBound < tidied.lowerBound, "the app is reopened before any tidying") - // PATH is pinned: the app's own has a Homebrew prefix prepended, and a swap script has - // no business resolving `mv` through a user-writable directory. + // PATH is pinned because a swap script has no business resolving `mv` through a + // user-writable directory. This used to add "the app's own has a Homebrew prefix + // prepended" as the motive; that was true of the deleted `upgradeAndRelaunch`, which had + // to put brew's own directory on PATH for brew to re-exec itself. Nothing prepends + // anything now — `ToolPaths.childPATH` is these four directories — so the reason is the + // general one, which was always the stronger half. #expect(script.contains("PATH=/usr/bin:/bin:/usr/sbin:/sbin")) #expect(script.contains("kill -0 4242")) } @@ -325,230 +246,6 @@ struct SelfUpdateRouteTests { #expect(names[0].contains("/Applications/")) } - // MARK: - Which bundle does brew own - - /// **The bug an end-to-end run caught, pinned.** `brew list --cask gitpic` exits 0 whenever - /// the cask is installed *anywhere*, so a copy in `~/Applications` on a machine whose cask - /// installed to `/Applications` was reported as brew's. It would then be handed to - /// `brew upgrade`, brew would replace the *other* bundle, and the script would reopen this - /// one — an old build, still reporting the same update available, with brew reporting - /// nothing left to do. Repeatable forever. - /// - /// Homebrew answers exactly, and this is the shape it answers in: `brew list --cask` prints - /// the Caskroom paths, one of which is a symlink to the installed bundle. Verbatim from a - /// machine with the cask installed. - @Test("brew owning the cask is not the same as brew owning this bundle") - func brewOwnsOneBundleNotAnyBundle() { - let listing = """ - /opt/homebrew/Caskroom/gitpic/.metadata/INSTALL_RECEIPT.json - /opt/homebrew/Caskroom/gitpic/.metadata/config.json - /opt/homebrew/Caskroom/gitpic/.metadata/0.19.0/20260824093614.436/Casks/gitpic.json - /opt/homebrew/Caskroom/gitpic/0.19.0/GitPic.app - """ - // The `.app` line is the one that matters, and it is not the first. - let app = listing.split(separator: "\n") - .map { $0.trimmingCharacters(in: .whitespaces) } - .first { $0.hasSuffix(".app") } - #expect(app == "/opt/homebrew/Caskroom/gitpic/0.19.0/GitPic.app", - "the receipt JSON must not be mistaken for the artifact") - - // With the cask's bundle resolving to /Applications/GitPic.app, a copy in - // ~/Applications is *not* brew's, so it must reach the in-app installer. - let route = SelfUpdate.route( - location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", - brew: .doesNotOwnIt, asset: Self.choice) - guard case .selfInstall = route else { - Issue.record("a copy brew did not install must not be handed to brew") - return - } - } - - /// **Every non-zero exit is not "not mine", and exit 0 is not "mine either way".** - /// - /// Driven through a stub `brew` rather than the real one, because what has to be pinned is - /// the decision, and Homebrew's answer depends on what happens to be installed on the - /// machine running the tests. The stub's shapes are all transcribed from Homebrew 6.0.19, - /// measured while writing this: - /// - /// ``` - /// $ brew list --cask firefox # real cask, not installed - /// find: /opt/homebrew/Caskroom/firefox: No such file or directory - /// Error: Failure while executing; `… find …` exited with 1. → status 1 - /// $ brew list --cask definitely-not-real-xyz - /// Error: Cask 'definitely-not-real-xyz' is unavailable: No Cask with this name exists. - /// → status 1 - /// $ env -i brew list --cask gitpic - /// Error: $HOME must be set to run brew. → status 1 - /// $ brew list --cask codex → status 0, no .app - /// $ brew list --cask font-maple-mono-nf-cn → status 0, no .app - /// ``` - /// - /// One exit code for three completely different situations, so the status cannot be the - /// evidence. Nor can the message: with `Caskroom/gitpic-fixture-zzz/9.9.9/Fixture.app` - /// created by hand, `brew list --cask gitpic-fixture-zzz` *still* said `No Cask with this - /// name exists` — which is what a removed tap looks like on a machine where the cask is - /// installed. The Caskroom directory is the only thing that answers, and `brew --caskroom` - /// is what names it. - @Test("only a Caskroom with nothing in it makes a failed `brew list` an answer") - func failedBrewListIsOnlyAnAnswerWithAnEmptyCaskroom() throws { - let fixture = try BrewStub() - defer { fixture.cleanUp() } - - // 1. brew failed *and* it has installed nothing under this token. The one shape that - // may authorise replacing a bundle. - fixture.write(status: 1, stderr: "Error: Cask 'gitpic' is unavailable: " - + "No Cask with this name exists.") - #expect(ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) - == .notInstalled(status: 1)) - - // 2. Same failure, but the Caskroom holds the token — a removed tap, a broken - // portable-ruby, a lock held by another brew. Installing here replaces a bundle brew - // manages and leaves its manifest describing a version that is not on disk. - try fixture.populateCaskroom("gitpic") - guard case .unusable = ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) else { - Issue.record("a failed brew with a populated Caskroom must not authorise an install") - return - } - - // 3. brew is broken enough that it cannot even say where its Caskroom is — measured: - // `env -i brew list --cask gitpic` exits 1 with `$HOME must be set to run brew.` - fixture.write(status: 1, stderr: "Error: $HOME must be set to run brew.", - answerCaskroom: false) - guard case .unusable = ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) else { - Issue.record("a brew that cannot answer at all is not evidence of anything") - return - } - } - - /// Exit 0 with no bundle named is "brew has this cask and I cannot see which app it is", - /// which is the definition of no answer — not of a durable fact. - /// - /// It used to be `notInstalled(status: 0)`, with a comment admitting "nothing here can be - /// compared against". Measured shapes that produce it today: `brew list --cask codex` and - /// `brew list --cask font-maple-mono-nf-cn`, both exit 0 with zero `.app` lines. A future - /// `==> Apps` header, a ` (128 files)` suffix, or an appdir path instead of the Caskroom - /// symlink would do the same. - @Test("exit 0 with no identifiable bundle is no answer, not `notInstalled`") - func exitZeroWithoutABundleIsUnusable() throws { - let fixture = try BrewStub() - defer { fixture.cleanUp() } - - fixture.write(status: 0, stdout: """ - /opt/homebrew/Caskroom/codex/.metadata/INSTALL_RECEIPT.json - /opt/homebrew/Caskroom/codex/.metadata/config.json - """) - guard case .unusable = ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) else { - Issue.record("brew exited 0, so it has the cask — that cannot mean 'not installed'") - return - } - // And the degenerate case: exit 0, nothing at all on stdout. - fixture.write(status: 0) - guard case .unusable = ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) else { - Issue.record("silence from a successful brew is not an answer either") - return - } - } - - /// A dangling `.app` line must not be read as a path, and must not hide a good one. - /// - /// Measured: `URL.resolvingSymlinksInPath()` returns a **dangling** symlink *unchanged*, so - /// `/opt/homebrew/Caskroom/gitpic/0.18.0/GitPic.app` pointing at a bundle somebody moved by - /// hand came back as itself, compared unequal to the running bundle, and produced - /// "not brew's" → an install over a cask-managed app. And with two version directories in - /// the Caskroom, `first(where:)` could pick exactly that one. - @Test("dangling Caskroom symlinks are dropped, and never hide a live one") - func danglingCaskroomLinksAreDropped() throws { - let fixture = try BrewStub() - defer { fixture.cleanUp() } - - let real = fixture.root.appendingPathComponent("Applications/GitPic.app") - try FileManager.default.createDirectory(at: real, withIntermediateDirectories: true) - let live = fixture.root.appendingPathComponent("Caskroom/gitpic/0.19.0/GitPic.app") - let dead = fixture.root.appendingPathComponent("Caskroom/gitpic/0.18.0/GitPic.app") - for link in [live, dead] { - try FileManager.default.createDirectory( - at: link.deletingLastPathComponent(), withIntermediateDirectories: true) - } - try FileManager.default.createSymbolicLink(at: live, withDestinationURL: real) - try FileManager.default.createSymbolicLink( - at: dead, withDestinationURL: fixture.root.appendingPathComponent("gone/GitPic.app")) - // The premise, measured rather than assumed. - #expect(dead.resolvingSymlinksInPath().standardizedFileURL.path == dead.path, - "resolvingSymlinksInPath leaves a dangling symlink alone") - - // Older version first, so `first(where:)` would have picked the dangling one. - fixture.write(status: 0, stdout: "\(dead.path)\n\(live.path)") - // Compared as paths, the way `brewOwnership` compares them: `resolvingSymlinksInPath` - // appends a trailing slash for an existing directory and `URL`'s `==` minds that, while - // `.path` — which is what the ownership check uses — does not. - guard case .installedAt(let apps) = ToolDiscovery.brewCaskApp("gitpic", - brew: fixture.brew) else { - Issue.record("the live Caskroom link names a bundle that exists") - return - } - #expect(apps.map(\.path) == [real.path]) - - // Nothing but a dangling link is no answer at all — brew has the cask and its bundle is - // not where it said. - fixture.write(status: 0, stdout: dead.path) - guard case .unusable = ToolDiscovery.brewCaskApp("gitpic", brew: fixture.brew) else { - Issue.record("a Caskroom link pointing nowhere identifies no bundle") - return - } - } - - /// A stub `brew` on disk, so the decisions above are tested without depending on what this - /// machine happens to have installed. - /// - /// A shell script rather than a mock, because `ToolDiscovery.brewCaskApp` spawns a real - /// child through `ChildProcess` and that spawn is part of what is being tested — the - /// argument list, the two streams, and the exit status. - private final class BrewStub { - let root: URL - let brew: URL - - init() throws { - root = FileManager.default.temporaryDirectory - .appendingPathComponent("gitpic-brewstub-\(UUID().uuidString)") - brew = root.appendingPathComponent("brew") - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - write(status: 1) - } - - /// `/Caskroom//1.0`, which is what makes a failed `brew list` inconclusive. - func populateCaskroom(_ cask: String) throws { - try FileManager.default.createDirectory( - at: root.appendingPathComponent("Caskroom/\(cask)/1.0"), - withIntermediateDirectories: true) - } - - /// Rewrite the stub. `answerCaskroom: false` makes `brew --caskroom` fail too, which is - /// the broken-environment case. - func write(status: Int32, stdout: String = "", stderr: String = "", - answerCaskroom: Bool = true) { - func q(_ s: String) -> String { - "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" - } - let caskroom = answerCaskroom - ? "printf '%s\\n' \(q(root.appendingPathComponent("Caskroom").path)); exit 0" - : "echo 'Error: $HOME must be set to run brew.' >&2; exit 1" - let script = """ - #!/bin/bash - if [ "$1" = "--caskroom" ]; then - \(caskroom) - fi - printf '%s' \(q(stdout)) - printf '%s' \(q(stderr)) >&2 - exit \(status) - """ - try? script.write(to: brew, atomically: true, encoding: .utf8) - try? FileManager.default.setAttributes([.posixPermissions: 0o755], - ofItemAtPath: brew.path) - } - - func cleanUp() { try? FileManager.default.removeItem(at: root) } - } - // MARK: - Proving the login shell ran /// **A negative answer needs evidence that the probe actually ran**, and the exit status is @@ -556,6 +253,12 @@ struct SelfUpdateRouteTests { /// between them is the lookup's own output and nothing else. /// /// Every row below is stdout measured from a real `$SHELL -l -c` on this machine. + /// + /// The rows name `brew`, which this probe no longer looks for — its remaining caller is + /// `locateGitpic`, for `swift run` during development. They are left as measured, the way + /// `loginShellLookup`'s own doc leaves its `gh` measurements: the tool name is a parameter and + /// the parse under test is unchanged, so re-labelling the evidence would only make it + /// evidence of a run that never happened. @Test("only a bracketed empty answer means the tool is absent") func probeAnswerSeparatesAbsenceFromSilence() { let open = ToolDiscovery.probeOpen @@ -596,8 +299,10 @@ struct SelfUpdateRouteTests { #expect(found.path?.lastPathComponent == "sh") #expect(found.conclusive) - // And a tool that exists nowhere must come back as a *definite* no, or the machine with - // no Homebrew never gets offered the installer this whole feature exists for. + // And a tool that exists nowhere must come back as a *definite* no, or `locateGitpic` + // reports no CLI on a machine that has one. It used to matter more than that: the same + // answer decided whether Homebrew owned the bundle, so a false "cannot tell" left a + // brew-less machine retrying a probe instead of being offered the installer. let absent = ToolDiscovery.loginShellProbe("gitpic-absent-\(UUID().uuidString)") #expect(absent.path == nil) #expect(absent.conclusive, diff --git a/scripts/check-self-update.sh b/scripts/check-self-update.sh index 99e7669..abc028b 100755 --- a/scripts/check-self-update.sh +++ b/scripts/check-self-update.sh @@ -295,10 +295,12 @@ done [[ -n "$SHEET" ]] || fail "the update sheet never appeared (is $OLD_VERSION really older than $TARGET_VERSION?)" step "waiting for the upgrade route to resolve" -# The action row is 「正在确认升级方式…」 until the route is known, and resolving it can cost -# a 20 s `brew list --cask` — so the probe is the row's shape, not a fixed sleep. Three -# buttons means a route was offered (下载并更新 or 立即更新, then 打开发布页 and 稍后); two -# means `.unavailable`, which is a different failure and worth saying so. +# The action row is 「正在确认升级方式…」 until the route is known. It is now resolved from three +# local facts and settles in a frame, where it used to cost up to a 20 s `brew list --cask` per +# Homebrew prefix — the probe is still the row's shape rather than a fixed sleep, because a +# fixed sleep would be either a guess or a delay. Three buttons means a route was offered +# (下载并更新, 打开发布页 and 稍后 — there is no 立即更新 any more, the Homebrew branch is gone); +# two means `.unavailable`, which is a different failure and worth saying so. ROUTED="" BUTTONS="" for _ in $(seq 1 60); do diff --git a/src/commands/update.rs b/src/commands/update.rs index 7d810b3..d623030 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -7,11 +7,18 @@ //! whose config is missing or broken — including one where the answer is that the fix //! shipped in a release the user does not have yet. //! -//! It checks, and it does not install. The app is distributed as a Homebrew cask and is -//! signed ad-hoc rather than with a Developer ID (see `scripts/build-app.sh`), so a -//! self-replacing updater would both fight Homebrew's manifest and have no signature chain -//! to verify a download against. `GitPic.app` runs `brew upgrade` instead; the CLI's job is -//! to report, and the human-readable output says how to upgrade rather than doing it. +//! It checks, and it does not install. That is a statement about *this binary*, and the +//! reason recorded here used to be "`GitPic.app` runs `brew upgrade` instead" — which stopped +//! being true when the app took over installing its own updates for every copy, Homebrew's +//! included. See `SelfUpdate.route` in the app for that argument and the cask stanzas it +//! leans on. +//! +//! The half that still holds is the one about the CLI. A `gitpic` on `PATH` can have come +//! from the cask (a symlink into the bundle, so it upgrades when the app upgrades itself), +//! from the `gitpic_cli` formula, from `cargo install`, or from an unpacked tarball. Those +//! want four different upgrade commands and this process could perform at most one of them, +//! so it reports instead, and the human-readable output says how to upgrade rather than +//! guessing which of the four applies. use crate::error::Result; use crate::output::Mode;