diff --git a/AGENTS.md b/AGENTS.md index 30465cf..4206891 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,8 @@ - `github.rs` — GitHub Contents API client (upload, dedup, health checks). - `naming.rs`, `link.rs`, `imageproc.rs`, `output.rs`, `error.rs` — path/hash, URL/markdown, compression, human/JSON output, error types. - `history.rs` — the upload log the app's 历史 pane reads. -- `release.rs` — the update check behind `gitpic update check`: version parsing and comparison, the `releases/latest` fetch, and the release's assets (name, size, download URL, GitHub's `digest`) that the app installs an update from. The feed is a compile-time constant on purpose, pinned by a test — its text is rendered inside GitPic's own window, so nothing configurable may choose its origin, and download URLs come from the API rather than a template for the same reason. +- `release.rs` — the update check behind `gitpic update check`, and the tap lookup behind `gitpic update cask`: version parsing and comparison, the `releases/latest` fetch, the release's assets (name, size, download URL, GitHub's `digest`) that the app installs an update from, and a Contents-API read of the tap's `Casks/gitpic.rb` answering what `brew upgrade --cask gitpic` would install. Both origins are compile-time constants on purpose, pinned by a test — their text is rendered inside GitPic's own window, so nothing configurable may choose them, and download URLs come from the API rather than a template for the same reason. +- `install_source.rs` — which of the five ways this binary was installed (cask app, hand-installed app, `gitpic_cli` formula, `cargo install`, or unknown), so `gitpic update` prints the one upgrade command that install actually wants instead of two to choose between. Canonicalises `current_exe()` first: the cask links `bin/gitpic` into the app bundle, and on Apple platforms the un-canonicalised path is the symlink, which classifies the commonest install of all as neither an app nor a formula. Distinct from `GitPicCore`'s `CaskOwnership`, which asks whether *the bundle* is cask-managed rather than where *this binary* came from. - `testutil.rs` — `#[cfg(test)]` only: the loopback stub server, a canned response, and the request reader shared by `github`'s and `release`'s tests. One `sock.read` is not a whole request; the module says what that cost twice. - `commands/` — one module per action (`upload`, `auth_cmd`, `repos`, `branches`, `doctor`, `list`, `config_cmd`, `completion`, `skill`, `update`). @@ -50,27 +51,46 @@ 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. +**One cask stanza the app's updater depends on. Do not drop it.** `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. +`brew upgrade --cask gitpic` typed into a terminal replaces a bundle that is still running. This +is now **load-bearing rather than a courtesy**: the app's update sheet hands that exact command to +every Homebrew user instead of installing anything itself, and GitPic is `.accessory`, so brew's +reopen is the only thing that puts the menu-bar icon back. + +**`auto_updates true` is on its way out, and the order matters.** It asserts that the artifact +updates itself, which stopped being true of a cask-managed copy when `SelfUpdate.route` began +deferring to brew for those bundles. Remove it *after* the app that defers is released, never +before: an `auto_updates`-free cask against an older app leaves brew's receipt comparison and the +app's installer both writing `/Applications/GitPic.app`. + +Two things about that stanza are worth recording, because both were stated wrongly here before: + +- **It never governed the command the app prints.** `brew upgrade --cask gitpic` names the cask + explicitly, and `Cask::Upgrade` takes the `cask.outdated?(greedy: true)` branch for a named + cask (`cask/upgrade.rb:70`), which skips the `auto_updates` comparison entirely and falls + through to plain receipt inequality (`cask/cask.rb:442`). The stanza only ever affected a bare + `brew upgrade` and `brew outdated`. +- `HOMEBREW_UPGRADE_AUTO_UPDATES_CASKS`, which the old text cited as "defaults on", is marked + `odeprecated` with `replacement: "the default behaviour"` (`env_config.rb:745-755`). It was a + knob to point at, and it is going away. + +Removing it means brew compares its own receipt again, which is correct once the app no longer +touches a cask-managed bundle. **One transitional hazard, worth a CHANGELOG line rather than +code:** a 0.20.9 cask user who self-updated has a bundle ahead of that receipt, so a bare +`brew upgrade` can reinstall an older tap version over it. The common shape (bundle 0.20.10, +receipt 0.20.9, tap 0.20.10) is one redundant download that repairs the receipt, not a downgrade; +a real downgrade needs the bundle to be ahead of the *tap*, which takes skipping a version in-app +inside the tap's lag window. It closes after one `brew upgrade`. The app itself cannot cause it: +`route` compares the tap against the installed bundle, so it never prints a command that would +move backwards. + +The app-side half of this is `SelfUpdate.route`, `CaskOwnership` and `Updater`, whose headers +carry the full argument. **The two repositories still have to move together**, just in the other +direction now: the app defers to brew for a cask-managed bundle, so a cask that drops +`uninstall quit:` means telling people to run a command that replaces a running app. 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. diff --git a/CHANGELOG.md b/CHANGELOG.md index ddc03b0..bb14fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,89 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### A Homebrew install is upgraded by Homebrew, and GitPic says so + +- Installed with `brew`? The sheet hands you `brew upgrade --cask gitpic` and installs nothing itself +- When the cask has nothing newer it says so, rather than giving you a command that does nothing +- `gitpic update` prints the one upgrade command your install wants, not two to choose between + + + +### App + +- 0.20.9 made the app install every update itself, a cask-managed bundle included. This reverses + that for Homebrew users — but not by restoring what 0.20.9 deleted. Both of that version's + measured defects came from *running* brew after the app had quit: the vanished menu-bar icon with + no progress and nothing to cancel, and `brew upgrade` exiting **0** with "the latest version is + already installed" while the script logged success and reopened the same build. Nothing is + spawned now and nothing quits. The app prints the command and stays where it is, so neither + failure has anywhere left to happen. +- The version it compares against is the **cask's**, not the release's, and that is the half that + makes it safe to hand a command over at all. Read out of Claude Code 2.1.251's own binary, which + does the same thing: it asks what the cask offers, then prints either "Update available: X → Y" + with the command or "Claude is up to date!" with none. A release exists the moment it is + published while the tap follows by dispatch with a six-hourly cron behind it, so those two facts + genuinely differ — and in that window GitPic now says 「已是 Homebrew 提供的最新版本」 rather than + offering a command that no-ops. The cost is stated rather than papered over: inside the tap's lag + a brew user waits, and the app does not install over a cask-managed bundle to fill the gap. +- Ownership is asked *before* the location rule, which fixes a case that was always broken: + `brew install --cask gitpic --appdir ~/Apps` produces a bundle the app called 「不是 /Applications + 或 ~/Applications」 and refused, when `brew upgrade --cask gitpic` was exactly right for it. +- Detection asks about the **bundle**, not the machine. `brew list --cask gitpic` — what 0.20.9 + deleted — is true whenever a cask is installed anywhere, so a copy in `~/Applications` beside a + cask in `/Applications` could be told to upgrade the other one. Reading the Caskroom's own + symlink answers about this bundle, works at any `--appdir`, and costs a directory scan instead of + up to 8 s of login shell plus 20 s per prefix. +- The tap lookup is off `GitpicRunner`'s spawn gate and bounded at 10 s. On the gate its worst case + — the CLI's 20 s request plus one anonymous retry — would have sat in front of every upload, on + the sheet-open path, which is the shape 0.20.9 was written to delete. The tap's local clone is + read first and settles the answer for free whenever it already names something newer, so the + common case costs no request at all. +- **Fixed, and it was live since before this change:** the update sheet appended 「或在终端运行 + `brew upgrade --cask gitpic`」 to *every* refusal, so a copy running from `~/Downloads` on a + machine with no cask was told to run a command that answers `Error: Cask 'gitpic' is not + installed`. That sentence now appears only for a bundle a cask really owns. + +### CLI + +- `gitpic update` printed the cask's command and the formula's side by side and left the reader to + pick, which had no answer at all for a hand-installed `GitPic.app`, a `cargo install --git` build + or an unpacked tarball. It now detects the install and prints one command. +- The detection turns on canonicalising `current_exe()`, and the naive version gets the commonest + install wrong. The cask links `HOMEBREW_PREFIX/bin/gitpic` at the copy inside the app bundle, and + on Apple platforms `current_exe()` is `_NSGetExecutablePath` with no canonicalisation — measured: + `/opt/homebrew/bin/gitpic` has no `.app` ancestor while its realpath does. Both answers it would + otherwise fall to are wrong ones, and one of them prints `brew upgrade gitpic_cli`, the exact "no + available formula" failure the two-command note existed to avoid. +- `gitpic` is not on crates.io (verified against the API), so the cargo hint carries `--git`. The + bare spelling would have been a command that cannot work. +- New `gitpic update cask`, which reports what the tap's cask declares. The origin is a + compile-time constant, pinned by the same test as the release feed: what it returns is rendered + in GitPic's own window next to a command the user is being told to run. + +### Homebrew + +- **`auto_updates true` is being removed from the cask**, after this release ships — never before, + or brew's receipt comparison and an older app's installer both write `/Applications/GitPic.app`. + It asserts that the artifact updates itself, which stops being true of a cask-managed copy now + that the app defers. +- Two claims this file and AGENTS.md made about that stanza were wrong, and are corrected there: + it never governed `brew upgrade --cask gitpic`, because a named cask takes + `outdated?(greedy: true)` (`cask/upgrade.rb:70`) and skips the `auto_updates` comparison + entirely; and `HOMEBREW_UPGRADE_AUTO_UPDATES_CASKS`, cited here as "defaults on", is marked + `odeprecated`. +- **Transitional, one release wide:** a 0.20.9 cask user who self-updated has a bundle ahead of + brew's receipt, so once the stanza is gone a bare `brew upgrade` can reinstall an older tap + version over it. The common shape is one redundant download that repairs the receipt; a real + downgrade needs the bundle ahead of the *tap*, which takes skipping a version in-app inside the + tap's lag. It closes after one `brew upgrade`. The app cannot cause it — it compares the tap + against the installed bundle, so it never prints a command that moves backwards. +- `uninstall quit: "dev.gitpic.app"` stays and is now load-bearing rather than a courtesy: it is + what makes the command the app hands out safe, and for an `.accessory` app brew's reopen is the + only thing that puts the menu-bar icon back. + ## [0.20.9] - 2026-08-28 ### A Homebrew install updates in one click, without waiting on brew diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 15c0e48..b2c4aa3 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -4,6 +4,73 @@ [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 +## [未发布] + +### Homebrew 装的交给 Homebrew 升,而且会告诉你 + +- 用 brew 装的,弹窗直接给出 `brew upgrade --cask gitpic`,自己不再替换 bundle +- cask 那边没有更新时会直说,而不是塞给你一条跑了也没用的命令 +- `gitpic update` 只打印你这份安装真正需要的那一条升级命令 + + + +### App + +- 0.20.9 让 App 自己安装所有更新,包括 cask 装的那一份。这一版对 Homebrew 用户改回去了 —— 但不是把 + 0.20.9 删掉的东西恢复原样。那一版实测到的两个缺陷都来自「App 退出之后才去跑 brew」:菜单栏图标消失、 + 没有进度也不能取消;以及 `brew upgrade` 打印「已是最新」却 exit **0**,脚本记成成功又把同一个 build + 重新打开。现在既不起进程也不退出,App 打印命令然后留在原地,这两个失败都没有发生的余地了。 +- 用来比较的是 **cask 的版本**,不是 release 的,这才是敢把命令交出去的关键。做法读自 Claude Code + 2.1.251 的二进制:它先问 cask 提供什么版本,然后要么打印「Update available: X → Y」加命令,要么 + 打印「Claude is up to date!」且不给命令。release 一发布就存在,而 tap 要靠 dispatch 跟进(后面垫了 + 六小时的 cron),所以这两件事真的会不一致 —— 这段窗口里 GitPic 现在说「已是 Homebrew 提供的最新 + 版本」,而不是给一条空转的命令。代价也照实说:tap 没跟上的时候 brew 用户需要等,App 不会为了填这个 + 空档去覆盖 cask 管理的 bundle。 +- 归属判断放在了位置判断**之前**,顺手修掉一个一直存在的问题:`brew install --cask gitpic --appdir + ~/Apps` 装出来的 bundle 会被 App 判为「不是 /Applications 或 ~/Applications」而拒绝,而 + `brew upgrade --cask gitpic` 对它恰恰是对的。 +- 判断问的是**这个 bundle**,不是这台机器。0.20.9 删掉的 `brew list --cask gitpic` 只要机器上装了 + cask 就为真,所以 `~/Applications` 里的副本可能被告知去升级 `/Applications` 里的另一份。读 Caskroom + 自己的符号链接问的是这个 bundle,任何 `--appdir` 都成立,代价是一次目录扫描 —— 而不是最多 8 秒的 + 登录 shell 加每个 prefix 20 秒。 +- tap 查询不走 `GitpicRunner` 的 spawn gate,并且限时 10 秒。放在 gate 上的话,它最坏情况(CLI 的 + 20 秒请求加一次匿名重试)会挡在每一次上传前面,而且就发生在打开弹窗这条路径上 —— 这正是 0.20.9 + 要删掉的形状。tap 的本地克隆会先读,只要它已经指向更新的版本就直接定案,所以常见情况一个请求都不花。 +- **修掉一个这次改动之前就存在的 bug**:更新弹窗会在*每一条*拒绝理由后面追加「或在终端运行 + `brew upgrade --cask gitpic`」,于是一份跑在 `~/Downloads`、机器上又没装 cask 的副本,会被告知去跑 + 一条回答 `Error: Cask 'gitpic' is not installed` 的命令。这句话现在只对真的由 cask 管理的 bundle 出现。 + +### CLI + +- `gitpic update` 过去把 cask 和 formula 两条命令并排打出来让人自己挑,而这对手动装的 `GitPic.app`、 + `cargo install --git` 的构建、解压的 tarball 三种情况根本没有答案。现在它检测安装来源,只打印一条。 +- 检测的关键是给 `current_exe()` 做 canonicalize,不做的话最常见的那种安装恰好会判错。cask 把 + `HOMEBREW_PREFIX/bin/gitpic` 链到 app bundle 里的那个副本,而 Apple 平台上 `current_exe()` 就是 + `_NSGetExecutablePath`,不做规范化 —— 实测:`/opt/homebrew/bin/gitpic` 没有 `.app` 祖先,它的 + realpath 有。不规范化会落到的两个答案都是错的,其中一个会打印 `brew upgrade gitpic_cli`,正是那条 + 两命令提示当初为了避免的「no available formula」。 +- `gitpic` 并没有发布到 crates.io(对 API 核对过),所以 cargo 那条提示带 `--git`;直接 + `cargo install gitpic` 是一条跑不通的命令。 +- 新增 `gitpic update cask`,报告 tap 里的 cask 声明的版本。这个来源是编译期常量,和 release feed 由 + 同一个测试钉住:它返回的东西会显示在 GitPic 自己的窗口里,旁边还有一条要用户去执行的命令。 + +### Homebrew + +- **cask 里的 `auto_updates true` 会被移除**,但要等这一版发布之后 —— 顺序反了的话,brew 的安装记录 + 比对和旧版 App 的安装器会同时往 `/Applications/GitPic.app` 写。这个 stanza 声明「制品自己更新」, + 而 App 对 cask 管理的副本改为让位之后,这句话就不成立了。 +- 这份文件和 AGENTS.md 之前关于这个 stanza 的两处说法是错的,已在 AGENTS.md 更正:它从来管不到 + `brew upgrade --cask gitpic`,因为点名 cask 走的是 `outdated?(greedy: true)` + (`cask/upgrade.rb:70`),会完全跳过 `auto_updates` 的比较;而这里写成「默认开启」的 + `HOMEBREW_UPGRADE_AUTO_UPDATES_CASKS` 已标记 `odeprecated`。 +- **一个只跨一个版本的过渡风险**:在 0.20.9 上自己更新过的 cask 用户,bundle 会领先 brew 的安装记录, + 所以 stanza 移除之后,不带参数的 `brew upgrade` 可能用较旧的 tap 版本覆盖它。常见形态只是多下载一次、 + 把记录修回来;真正的降级需要 bundle 领先于 **tap**,也就是要在 tap 滞后的窗口里用 App 跳过一个版本。 + 跑一次 `brew upgrade` 之后就不存在了。App 本身不会造成它 —— 它拿 tap 和已装 bundle 比较,所以永远不会 + 打印一条往回走的命令。 +- `uninstall quit: "dev.gitpic.app"` 保留,而且从「顺带做对的事」变成了必需:它是 App 交出去那条命令 + 安全的前提,而对 `.accessory` 应用来说,brew 的重新打开是唯一能把菜单栏图标放回来的东西。 + ## [0.20.9] - 2026-08-28 ### Homebrew 装的也能一键更新,不用再退出等 brew diff --git a/README.en.md b/README.en.md index 063d688..e0f23c0 100644 --- a/README.en.md +++ b/README.en.md @@ -38,24 +38,31 @@ 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 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. +menu bar. A new version is shown with its release notes, and what happens next depends on who +installed this copy. + +**Installed by hand** (the DMG's app in `/Applications` or `~/Applications`): one 下载并更新 +button, and GitPic fetches the release's disk image and replaces the bundle itself. The image is +verified against the SHA-256 GitHub publishes for that file first, 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 swap needs the app to quit +(nothing can replace a running bundle) and reopens it afterwards. A copy kept anywhere else is +sent to the release page, and the sheet says which reason applied. + +**Installed with Homebrew**: GitPic does not replace the bundle. It hands you +`brew upgrade --cask gitpic` with a 复制升级命令 button beside it, so Homebrew stays the only +thing managing that install and its records cannot drift from what is on disk. Running the command +quits the app before the swap and reopens it afterwards, because the cask declares +`uninstall quit:`. + +Before offering the command GitPic asks the tap which version its cask actually declares, rather +than assuming the release's — the two are not always in step. A release exists the moment it is +published, while the tap follows by dispatch with a six-hourly cron behind it. So when Homebrew +has not caught up you are told 已是 Homebrew 提供的最新版本 instead of being handed a command that +would do nothing; wait for Homebrew and it will arrive. When that version cannot be read at all — +offline, rate-limited, or the tap moved the file — the command is still offered, with a note that +this time it went unchecked: a network that is down says nothing about whether your upgrade path +works. The terminal equivalents are `gitpic update check` and `gitpic update cask`. **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 4b35448..2709f39 100644 --- a/README.md +++ b/README.md @@ -31,18 +31,24 @@ brew install tarnish233/tap/gitpic # App + 终端命令 macOS 自己的登录项,所以「系统设置 ▸ 通用 ▸ 登录项与扩展」里也能看到、也能关掉,两边永远是同一个开关。 **检查更新**默认每天自动查一次,也可以在「通用」页或菜单栏里随时手动查。发现新版本时会显示这一版 -的更新内容,一个「下载并更新」按钮 —— 不管这份 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、装完再打开它。 +的更新内容,接下来分两种情况,取决于这份 GitPic 是谁装的。 + +**手动装的**(DMG 解压到 `/Applications` 或 `~/Applications`):一个「下载并更新」按钮,由 GitPic +自己下载该版本的磁盘映像来替换。替换前会先核对 GitHub 为该文件公布的 SHA-256 —— 和 Homebrew 校验 +cask 是同一件事,**拿不到校验和就不装**;而且下载、校验、复制全都发生在退出之前,失败什么都不会改动。 +替换本身要先退出(没有办法替换正在运行的 bundle),装完自动重开。放在别处的副本会被指向发布页, +弹窗里会说明是哪一种原因。 + +**Homebrew 装的**:GitPic 不会自己替换 bundle,而是把 `brew upgrade --cask gitpic` 交给你,旁边有个 +「复制升级命令」。这样 Homebrew 始终是这份安装的唯一管理者,它的安装记录不会和磁盘上的版本脱节。 +按下命令之后 brew 会先退出 app、装完再打开它(cask 声明了 `uninstall quit:`)。 + +给出命令之前 GitPic 会先问 tap 里的 cask 到底是哪个版本,而不是拿 GitHub 上的发布版本充数 —— 这两个 +不一定同步:release 一发布就存在,tap 要靠 dispatch 跟进(后面还垫了一个六小时的 cron)。所以如果 +Homebrew 那边还没跟上,你看到的是「已是 Homebrew 提供的最新版本」而**不是**一条跑了也没用的命令 —— +这种情况下等 Homebrew 跟上即可。要是这个版本号一时读不到(离线、被限流、tap 改了路径),命令还是会给 +你,只是旁边会写明这次没能核对 —— 网络不通并不说明你的升级路径有问题。终端里等价的两条查询命令是 +`gitpic update check` 和 `gitpic update cask`。 **第一次用不需要开终端。** 打开设置窗口 → 图床页 → 「使用 GitHub 登录」,一次性码会显示在窗口里、 浏览器自动打开;授权完成后下面的下拉框会列出你可以上传的仓库,选一个,按右上角「保存」写进配置文件。 diff --git a/apps/GitPic/Sources/GitPicApp/AppModel.swift b/apps/GitPic/Sources/GitPicApp/AppModel.swift index 6770ada..92d04c3 100644 --- a/apps/GitPic/Sources/GitPicApp/AppModel.swift +++ b/apps/GitPic/Sources/GitPicApp/AppModel.swift @@ -975,11 +975,39 @@ final class AppModel { /// launch is not being quiet. Nothing else is suppressed — 设置 ▸ 通用 and the sheet still /// say so for as long as the update stands, which is where someone who wants to act on it /// later goes looking. + /// + /// **``forgetAnnouncement()`` exists because one situation can spend this record on a + /// moment the user could not act on.** The banner is posted when the check finds a release; + /// which upgrade is actually on offer is only worked out later, when the sheet opens. A + /// Homebrew user inside the tap's lag therefore gets their one banner for a version the + /// sheet then declines to install, and once `announcedVersion` equals that release no + /// further banner for it can ever fire — including after the tap lands and + /// `brew upgrade` would work. Before this policy the single notification was always + /// actionable, because the app installed for everyone. private(set) var announcedVersion: String? = AppModel.defaults .string(forKey: AppModel.announcedKey) { didSet { Self.defaults.set(announcedVersion, forKey: Self.announcedKey) } } + /// Drop the record of the banner for `version`, so a later check may announce it again. + /// + /// Called only for `homebrewUpToDate` — the one outcome that offers nothing at all. + /// `homebrewUnverified` hands over the command, so its banner was actionable and stays + /// spent. + /// + /// The cost is at most one banner per daily check for as long as the tap lags, and that is + /// the right trade rather than a nag: the tap normally follows a release by dispatch within + /// minutes and by cron within six hours, so a daily check almost never lands twice inside + /// the window. When it does lag for days, AGENTS.md records how that happens — an expired + /// dispatch token, which went unnoticed across three releases — and a daily reminder that + /// Homebrew has not caught up is precisely the signal that was missing. + func forgetAnnouncement(of version: String) { + guard announcedVersion == version else { return } + announcedVersion = nil + Diagnostics.log("update: \(version) was announced but Homebrew cannot install it yet" + + " — allowing it to be announced again") + } + fileprivate static let defaults = UserDefaults.standard fileprivate static let lastCheckKey = "update.lastCheck" fileprivate static let autoCheckKey = "update.autoCheck" @@ -1121,6 +1149,25 @@ final class AppModel { if upgradePathGeneration == updateGeneration { if case .unavailable(_, retryable: false) = upgradePath { return } if case .selfInstall = upgradePath { return } + // **No Homebrew case is listed here, and adding one would be a bug.** This is an + // allowlist, so they fall through and are recomputed — which is what they need. The + // report's generation is not a sufficient key for them: the *tap* can move without + // the report moving at all, since a release is published the moment it exists while + // the tap follows by dispatch with a six-hourly cron behind it. Cache + // `homebrewUpToDate` and reopening the sheet would keep repeating 「已是 Homebrew + // 提供的最新版本」 with no command even after `brew upgrade` had started working — + // the same shape as the bug described above, arriving from the other direction. + // + // **What that buys is a fresh answer per sheet opening, and no more than that.** + // `resolveUpgradePath` has one caller, `UpdateSheet`'s `.task(id:)`, so a sheet left + // open does not re-ask: the id only moves when a new check lands. Someone who leaves + // it open across the tap catching up still reads the old sentence until they close + // and reopen it. That is a real limit and is accepted here — the alternative is + // polling the tap behind an idle window — but it is narrower than "for the life of + // the process", which is what caching would cost. + // + // The recomputation is bounded: `GitpicRunner.tapCask` is off the spawn gate with a + // 10 s ceiling, and `resolvingUpgradePath` below stops two from stacking. } // The old guard also did not hold across the `await`, so two sheet appearances could // both spawn the probe. @@ -1140,36 +1187,78 @@ final class AppModel { // one that has to notice, and discard a route it computed from a report the user is no // longer looking at. It converges: `checkForUpdates` allows one check at a time, so each // extra pass is a real new report and not a spin. + // + // **This runs inside a task SwiftUI has already cancelled, and the second pass depends + // on `GitpicRunner.run` ignoring that.** Moving the generation is exactly what makes + // `.task(id:)` tear this task down, so by the time `continue` is reached + // `Task.isCancelled` is true. Measured: with a `withTaskCancellationHandler` in `run`, + // the first probe is killed mid-flight and the re-query is killed *before it starts*, + // because `onCancel` fires immediately on an already-cancelled task — and since + // `CaskOwnership.verdict` turns every failure into `Offer.unknown`, the new report + // resolved to 「暂时读不到 Homebrew 提供的版本」 instead of a real comparison. The + // prohibition is recorded on `run` itself; this is the caller it exists for. while true { guard let report = update else { return } let generation = updateGeneration - let route = await Updater.resolve(report: report) + let route = await Updater.resolve(report: report, runner: runner) guard generation == updateGeneration else { Diagnostics.log("update: a newer report landed mid-probe — resolving again") continue } upgradePath = route upgradePathGeneration = generation + // The banner for this release was spent on a version Homebrew cannot install yet, + // so let a later check announce it again — see `forgetAnnouncement(of:)`. + if case .homebrewUpToDate = route { forgetAnnouncement(of: report.latest) } return } } /// 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. + /// Still one arm that installs. The Homebrew cases are here to say so explicitly rather than + /// through a `default:` — nothing is installed over a cask-managed bundle, and the command + /// the user copies is `copyUpgradeCommand`'s business, not an upgrade this process performs. + /// That is the difference from the arm `bb07783` deleted, which 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 .selfInstall(let asset, let sha, let version): performSelfInstall(asset: asset, sha256: sha, version: version) - case .unavailable, .none: + case .unavailable, .homebrewManaged, .homebrewUpToDate, .homebrewUnverified, .none: return } } + /// Put the Homebrew upgrade command on the pasteboard. + /// + /// Reads the command off the route rather than taking it as a parameter, so what the user + /// copies is what the decision produced — the sheet cannot compose a command of its own, and + /// the cask token in it came from the Caskroom entry that actually owns this bundle. + /// + /// Returns whether the write happened, because `Clipboard.write` can fail and reporting + /// 「已复制」 anyway is worse than not copying: the user pastes something stale and never + /// learns why. The failure is also surfaced through `notify`, since a sheet that closes + /// takes any inline message with it. + @discardableResult + func copyUpgradeCommand() -> Bool { + let command: String + switch upgradePath { + case .homebrewManaged(let c, _, _), .homebrewUnverified(let c, _): + command = c + case .selfInstall, .unavailable, .homebrewUpToDate, .none: + return false + } + guard Clipboard.write(command) else { + notify(title: "写剪贴板失败", body: "升级命令没有复制,请手动输入 \(command)") + return false + } + return true + } + /// Download, verify, stage and hand off — reporting each stage into the sheet. /// /// Everything here can fail while the app is still on screen, which is the point: a failed diff --git a/apps/GitPic/Sources/GitPicApp/GeneralPane.swift b/apps/GitPic/Sources/GitPicApp/GeneralPane.swift index 71bf9b8..088b113 100644 --- a/apps/GitPic/Sources/GitPicApp/GeneralPane.swift +++ b/apps/GitPic/Sources/GitPicApp/GeneralPane.swift @@ -58,8 +58,11 @@ struct GeneralPane: View { // The label is short; the caption carries the two facts it dropped — that // this checks rather than installs, and that it does so daily. Nothing here // ever replaces the app on its own: a found update is reported, and the - // sheet's button is the only thing that installs anything — through brew when - // brew owns the bundle, and by downloading a verified image when it does not. + // sheet's button is the only thing that acts on it — by downloading the + // release's disk image, verifying it against the SHA-256 GitHub publishes and + // swapping the bundle, or, for a bundle a Homebrew cask owns, by handing over + // `brew upgrade --cask gitpic` and installing nothing at all. Which of the two + // is `SelfUpdate.route`'s first question; see `CaskOwnership`. CaptionedToggle( label: "自动更新", caption: "每天检查一次,发现新版本会告诉你,不会自动装。" diff --git a/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift b/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift index f1fa8be..de38e87 100644 --- a/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift +++ b/apps/GitPic/Sources/GitPicApp/UpdateSheet.swift @@ -8,15 +8,29 @@ import GitPicCore /// 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. +/// The prominent action depends on who installed the app, and only one of the two installs +/// anything. 「下载并更新」 downloads and swaps the bundle; 「复制升级命令」 puts +/// `brew upgrade --cask gitpic` on the pasteboard for a bundle a cask owns, and this sheet stays +/// open behind it because the user's next move is a terminal. A third outcome has neither: when +/// the tap has not caught up with the release yet, there is nothing to install and no command +/// worth running — see `Updater`'s header and `SelfUpdate.Route`. +/// +/// The button it replaced, 「立即更新」, quit the app and spawned brew. This one copies a line of +/// text. struct UpdateSheet: View { @Bindable var model: AppModel let report: UpdateReport @State private var confirmingInstall = false + /// Whether the Homebrew command has been copied, so the button can say so. + /// + /// Inline rather than a notification: the confirmation belongs next to the thing that was + /// copied, and this sheet stays open afterwards — there is nothing to install, so the user's + /// next move is a terminal. Reset with the report, since a new report means a new route and + /// possibly a different command. + @State private var copied = false + /// The release notes, parsed once per report rather than once per redraw. /// /// `report.summary` rewrites the body, `UpdateReport.displayMarkdown` rewrites its headings @@ -36,17 +50,23 @@ struct UpdateSheet: View { actions } .frame(width: 480, height: 420) - // Asked when the sheet appears rather than at launch: it spawns `brew list`, which - // is up to 20 s of somebody else's process, and nothing before this moment needs - // the answer. It also needs the completed report, because which route is available + // Asked when the sheet appears rather than at launch: for a Homebrew-managed bundle it + // goes to the network to find out what the cask offers, and nothing before this moment + // needs the answer. It also needs the completed report, because which route is available // depends on what the release published. // + // The old note here said this "spawns `brew list`, which is up to 20 s of somebody + // else's process". Nothing spawns brew any more — ownership is a directory scan — and + // what remains is one bounded `gitpic update cask`, off the spawn gate. See + // `CaskOwnership` and `GitpicRunner.tapCask`. + // // Keyed on the report generation, not on appearance alone: a check that lands while // this sheet is open replaces the report the route was derived from, and a route // computed from the previous one may name an asset this release does not have. See // `AppModel.updateGeneration`. .task(id: model.updateGeneration) { renderedNotes = Self.markdown(UpdateReport.displayMarkdown(report.summary)) + copied = false await model.resolveUpgradePath() } } @@ -122,10 +142,25 @@ struct UpdateSheet: View { .buttonStyle(.borderedProminent) Text(Self.size(asset.size)) .font(.caption).foregroundStyle(.secondary) - case .unavailable, .none: - // 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 reason printed below it. + case .homebrewManaged, .homebrewUnverified: + // Homebrew owns this bundle, so the prominent action is the command + // rather than an install. It sits exactly where the deleted 立即更新 + // button was, and does something narrower: that one quit the app and + // spawned brew, this one copies a line of text. + Button(copied ? "已复制" : "复制升级命令") { + copied = model.copyUpgradeCommand() + } + .buttonStyle(.borderedProminent) + // Not disabled once copied: the pasteboard is shared with everything + // else on the machine, so a second copy after something overwrote it is + // a reasonable thing to want. The label is the confirmation; the button + // stays a button. + case .unavailable, .homebrewUpToDate, .none: + // No button at all rather than a disabled one: there is nothing to + // offer here, and a greyed-out control with a tooltip is a worse answer + // than the sentence printed below it. `homebrewUpToDate` is in this arm + // deliberately — brew has nothing to install, so a command would be a + // command that does nothing. EmptyView() } Button("打开发布页") { @@ -147,12 +182,21 @@ struct UpdateSheet: View { // bundle brew manages at a path this app is not running from, and is wrong in // more ways now that "the directory cannot be written" and "the release has no // verifiable image" are also possible. + // + // **The `brew upgrade` sentence is gone from here**, and it was a live bug: it + // was appended to *every* refusal, so a copy running from `~/Downloads` on a + // machine with no cask was told to run a command that answers + // `Error: Cask 'gitpic' is not installed`. A cask-managed bundle no longer + // reaches this branch at all — it has its own, below — so the only readers left + // here are the ones for whom that command was always wrong. VStack(alignment: .leading, spacing: 4) { Text(reason).font(.caption).foregroundStyle(.secondary) - Text("可以到发布页手动下载,或在终端运行 `brew upgrade --cask gitpic`。") + Text("可以到发布页手动下载。") .font(.caption).foregroundStyle(.secondary) } .textSelection(.enabled) + } else { + homebrewExplanation } } .padding(16) @@ -164,10 +208,11 @@ struct UpdateSheet: View { // that can go wrong happens while the window is still here. // // 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. + // 安装更新」. That sentence explained a fork by *denying* one of its branches, and + // it was wrong for brew users when it was written. There is a fork again, but this + // alert is now only reachable from 下载并更新 — a bundle a cask owns is offered a + // command and never gets here — so provenance is settled before the reader arrives + // and does not need restating. What they want to know is what is about to happen. Text("会先下载并校验,全部通过之后才退出并替换,完成后自动重新打开——" + "下载或校验失败的话什么都不会改动。\n\n" + "替换那一步记录在 GitPic-update.log 里;万一失败,原来的版本仍然可用。\n\n" @@ -175,6 +220,47 @@ struct UpdateSheet: View { } } + /// What the three Homebrew outcomes say under the buttons. + /// + /// The command is shown as a selectable monospaced row, not folded into prose. Two reasons: + /// the house idiom for something the user has to retype is `.caption.monospaced()` plus + /// `.textSelection(.enabled)` (see `HostPane`'s one-time code), and a command wrapped into a + /// Chinese sentence is a command someone mistypes. The button copies it so most people never + /// retype it at all. + /// + /// `homebrewUpToDate` prints no command on purpose. Its whole point is that + /// `brew upgrade --cask gitpic` would answer "the latest version is already installed" and + /// exit 0 during the tap's lag, so offering it would be offering a command that does nothing. + /// It has **two** sentences because the case covers two different situations: the bundle and + /// the cask agreeing, which is the tap simply lagging, and the bundle being *ahead* of the + /// cask, which is what a user who self-installed before this version shipped looks like. One + /// sentence for both said 「已是 Homebrew 提供的最新版本(bundle 的版本号)」, which claims + /// Homebrew provides a version it does not and tells that user to wait for what they have. + @ViewBuilder private var homebrewExplanation: some View { + switch model.upgradePath { + case .homebrewManaged(let command, let installed, let available): + VStack(alignment: .leading, spacing: 4) { + Text("这份 GitPic 由 Homebrew 管理,请在终端里升级:" + + "\(installed) → \(available)") + .font(.caption).foregroundStyle(.secondary) + Text(command).font(.caption.monospaced()).textSelection(.enabled) + } + case .homebrewUnverified(let command, let reason): + VStack(alignment: .leading, spacing: 4) { + Text("这份 GitPic 由 Homebrew 管理。\(reason),所以先按下面这条命令升级:") + .font(.caption).foregroundStyle(.secondary) + Text(command).font(.caption.monospaced()).textSelection(.enabled) + } + case .homebrewUpToDate(let installed, let offered): + Text(installed == offered + ? "已是 Homebrew 提供的最新版本(\(installed))。新版本要等 Homebrew 跟上之后才能装。" + : "当前 \(installed) 比 Homebrew 提供的 \(offered) 新,所以没有可以装的更新。") + .font(.caption).foregroundStyle(.secondary).textSelection(.enabled) + case .selfInstall, .unavailable, .none: + EmptyView() + } + } + /// The download's own bar, plus the one action that makes sense while it runs. /// /// **取消 is live for the whole of this row**, and that is a fix rather than an oversight. diff --git a/apps/GitPic/Sources/GitPicApp/Updater.swift b/apps/GitPic/Sources/GitPicApp/Updater.swift index e76a72f..a0655b2 100644 --- a/apps/GitPic/Sources/GitPicApp/Updater.swift +++ b/apps/GitPic/Sources/GitPicApp/Updater.swift @@ -4,25 +4,31 @@ import GitPicCore /// Installing a newer GitPic: a disk image this process downloads and verifies, then a script /// that swaps the bundle once this process is gone. /// -/// **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 +/// **One path per owner, and only one of them installs.** `brew upgrade --cask gitpic` for a +/// bundle a cask owns; this download for everyone else. The split is back, but it is not the +/// split `bb07783` deleted, and the difference is the whole design: that one *ran* brew, and both +/// of its measured defects came from that. 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 +/// that wedged. And 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 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`. +/// Nothing is spawned now and nothing quits on that branch: the app prints the command, offers to +/// copy it, and stays where it is. Neither failure has anywhere left to happen. What replaces +/// them is a narrower cost, stated plainly on `SelfUpdate.Route.homebrewUpToDate`: inside the +/// tap's lag a brew user is told to wait rather than offered an install, because the command that +/// would run in that window does nothing. `CaskOwnership.verdict` is what avoids handing it over +/// blindly — it asks what the cask actually offers first, which is what Claude Code does in the +/// same spot. +/// +/// The stanza that makes the handed-over command safe is `uninstall quit: "dev.gitpic.app"`, in +/// `tarnish233/homebrew-tap`: `Cask::Upgrade` passes `quit: true`, so brew quits the app, +/// re-registers the new bundle with Launch Services and reopens it — and for an `.accessory` app +/// that reopen is the only thing that puts the menu-bar icon back. `SelfUpdate.route`'s header +/// carries the argument and what becomes of the cask's other stanza. /// /// **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 @@ -65,29 +71,54 @@ enum Updater { /// Which upgrade to offer for this install, if any. /// /// 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. + /// row of it is testable, and the Homebrew question is `CaskOwnership.verdict`, in + /// `GitPicCore` for the same reason — `swift test` cannot import `GitPicApp`, so anything + /// decided here is decided untested. What is left in this file is reading two facts off the + /// running bundle and handing the runner over as the thing that can reach the network. /// - /// **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 + /// **This used to be the expensive part of opening the sheet**, and the new version is why + /// the question could come back. It asked `brew` itself: up to an 8 s login-shell probe plus + /// a 20 s `brew list --cask` per prefix, serialised — up to 28 seconds of + /// 「正在确认升级方式…」 before a button could be drawn. Those questions were bought at that + /// price because `brew list --cask` answers about the *machine*: the cask being installed 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. + /// unchanged, still reporting the same update, forever. `CaskOwnership.detect` asks about the + /// bundle instead, with a directory scan and a `readlink`, and gets a better answer for + /// nothing. The one cost that remains is the tap lookup, and only for a bundle a cask really + /// owns — off the spawn gate and bounded at 10 s; see `GitpicRunner.tapCask`. /// - /// 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 { + /// `async` for a real reason now, where before it was kept only because `UpdateSheet`'s + /// `.task(id:)` awaited it. + static func resolve(report: UpdateReport, runner: GitpicRunner?) 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 cask = await CaskOwnership.verdict( + bundle: bundle, bundleVersion: mine, + askTap: { + // No runner means the CLI was never located, which is a state the app can be in + // (see `AppModel.attach`). Ownership is still known — it is a filesystem + // question — so the answer is "a cask owns this, and what it offers is unknown", + // which shows the command with a caveat rather than pretending nothing is wrong. + guard let runner else { throw RunFailure.spawnFailed("gitpic 还没准备好") } + return try await runner.tapCask() + }) + // Logged unconditionally, and worth its own line rather than being folded into the + // outcomes below: `check-self-update.sh` asserts on it. Its test copy lives in + // `~/Applications` and must stay on the self-install branch, and a change that flipped + // it would otherwise surface only as the script timing out with "never settled". + switch cask { + case .notHomebrews: + Diagnostics.log("update: not cask — no Caskroom entry points at this bundle") + case .homebrews(let token, .version(let offered)): + Diagnostics.log("update: cask \(token) — Homebrew offers \(offered)") + case .homebrews(let token, .unknown(let reason)): + Diagnostics.log("update: cask \(token) — what Homebrew offers is unknown (\(reason))") + } let route = SelfUpdate.route( + cask: cask, location: SelfUpdate.location(of: bundle), bundleVersion: mine, latest: report.latest, @@ -99,6 +130,12 @@ enum Updater { case .unavailable(let reason, let retryable): Diagnostics.log("update: no in-app upgrade — \(reason)" + (retryable ? " (will ask again)" : "")) + case .homebrewManaged(let command, let installed, let available): + Diagnostics.log("update: handing over `\(command)` — \(installed) → \(available)") + case .homebrewUpToDate(let installed, let offered): + Diagnostics.log("update: Homebrew offers \(offered), not newer than \(installed)") + case .homebrewUnverified(let command, let reason): + Diagnostics.log("update: offering `\(command)` unverified — \(reason)") } return route } diff --git a/apps/GitPic/Sources/GitPicCore/CaskOwnership.swift b/apps/GitPic/Sources/GitPicCore/CaskOwnership.swift new file mode 100644 index 0000000..319b18d --- /dev/null +++ b/apps/GitPic/Sources/GitPicCore/CaskOwnership.swift @@ -0,0 +1,307 @@ +import Foundation + +/// Whether Homebrew owns this bundle, and what its cask currently offers. +/// +/// **Why the cheap check is possible at all, and why Claude Code's one-liner does not port.** +/// Claude Code detects a package-managed install with `execPath().includes("/Caskroom/")`, which +/// works because its cask ships a `binary` artifact: the real executable stays in the Caskroom +/// and `HOMEBREW_PREFIX/bin/claude` is a link to it. GitPic's cask uses an `app` stanza, which +/// **moves** the bundle to an Applications directory and leaves a link pointing back at it — +/// measured on a real install: +/// +/// /Applications/GitPic.app (a real directory) +/// /opt/homebrew/Caskroom/gitpic/0.20.9/GitPic.app -> /Applications/GitPic.app +/// +/// So `Bundle.main.bundleURL` never contains `/Caskroom/`, and the evidence has to be read in +/// the other direction: a Caskroom link that resolves *to us*. That also makes the answer +/// correct at any `--appdir`, because the link follows wherever the bundle went. +/// +/// **What this deliberately is not.** The implementation `bb07783` deleted asked `brew` itself — +/// a login-shell probe for up to 8 s, then `brew list --cask gitpic` for up to 20 s, per prefix, +/// on a serial queue, every time the sheet opened. `SelfUpdateRoute`'s header records what that +/// cost. Nothing here spawns anything: it is a directory scan and a `readlink`, so the question +/// can be asked on the sheet-open path without the sheet paying for it. +/// +/// A side effect worth naming: `scripts/check-self-update.sh` installs its test copy at +/// `~/Applications/GitPic.app`, and a path comparison correctly calls that "not Homebrew's". A +/// `brew list --cask` probe would have answered about the *machine* rather than about that +/// bundle, flipped the test copy onto the Homebrew branch, and broken the script. +public enum CaskOwnership: Equatable, Sendable { + + /// Where a cask keeps its record of an installed bundle, and the prefixes to look in. + /// + /// An Intel and an Apple Silicon Homebrew are independent installations with independent + /// Caskrooms, so both are searched rather than one being derived from the other. This + /// mirrors `install_source.rs`'s `default_prefixes` on the Rust side; the two answer + /// different questions (that one is about a *binary*'s origin, this one about a *bundle*'s + /// owner) and share only this list. + /// + /// `HOMEBREW_PREFIX` is honoured when it is set and absolute, which is the only way a + /// Homebrew somewhere else can be found without spawning `brew --prefix`. It is worth + /// little to the app and a lot to the CLI: a Finder-launched bundle inherits an + /// environment that has never sourced `brew shellenv`, so in the app this fires only for a + /// copy launched from a terminal — including the one `check-self-update.sh` drives. + public static var defaultPrefixes: [URL] { + var prefixes = [URL(fileURLWithPath: "/opt/homebrew"), URL(fileURLWithPath: "/usr/local")] + if let declared = ProcessInfo.processInfo.environment["HOMEBREW_PREFIX"], + declared.hasPrefix("/") { + let extra = URL(fileURLWithPath: declared).standardizedFileURL + if !prefixes.contains(where: { $0.standardizedFileURL.path == extra.path }) { + prefixes.append(extra) + } + } + return prefixes + } + + /// The cask token, and the tap that defines it as Homebrew lays it out on disk. + /// + /// Spelled here as well as in `release.rs` because nothing can share a constant across the + /// two languages. They have to agree, and `theTapPathIsBuiltFromPinnedConstants` pins this + /// side the way `the_release_feed_is_a_compile_time_constant` pins that one, for the same + /// reason: a version read out of the wrong file would be shown next to a command the user + /// is being told to run. + public static let cask = "gitpic" + static let tapOwner = "tarnish233" + static let tapRepository = "homebrew-tap" + + /// A cask installation of a particular bundle: which cask, and which prefix recorded it. + /// + /// The prefix travels with the answer because the next question — what does the tap offer — + /// is asked of a file under that same prefix, and a machine with two Homebrews should not + /// have its cask found under one and its tap read under the other. + public struct Install: Equatable, Sendable { + public let cask: String + public let prefix: URL + } + + /// Whether any `Caskroom//*/GitPic.app` under `prefixes` resolves to `bundle`. + /// + /// There is no third "could not tell" state to propagate: a directory either holds such a + /// link or it does not, and nothing here can time out. That is what keeps + /// `SelfUpdate.Route.unavailable`'s `retryable` flag dead — the flag's one former source was + /// the probe this replaces, which could. + /// + /// **It is decisive, not omniscient**, and the difference is a false negative worth naming. + /// A cask installed under a prefix that is neither Homebrew default nor named by + /// `HOMEBREW_PREFIX` is not found, and its owner is then offered the in-app install — which + /// replaces the bundle behind brew's back and leaves the receipt describing a version that + /// is no longer on disk. What keeps that from being severe is that it is the same + /// self-healing shape as the migration AGENTS.md describes: the receipt is now unequal to + /// what is installed, so the next `brew upgrade` reinstalls over it once. Homebrew does not + /// support casks outside its own prefixes, which is why this is a documented edge and not a + /// probe. + public static func detect(bundle: URL, prefixes: [URL] = defaultPrefixes) -> Install? { + let bundle = bundle.resolvingSymlinksInPath().standardizedFileURL.path + for prefix in prefixes { + let versions = prefix.appendingPathComponent("Caskroom").appendingPathComponent(cask) + let entries = (try? FileManager.default.contentsOfDirectory( + at: versions, includingPropertiesForKeys: nil)) ?? [] + for entry in entries { + let link = entry.appendingPathComponent("GitPic.app") + guard FileManager.default.fileExists(atPath: link.path) else { continue } + // `.path`, not `URL ==`: that compares `absoluteString`, so the same directory + // can compare unequal purely from how the two URLs were built (a trailing + // slash from a directory hint is enough). `location(of:)` already compares + // paths for the same reason. + let target = link.resolvingSymlinksInPath().standardizedFileURL.path + if target == bundle { + return Install(cask: cask, prefix: prefix) + } + } + } + return nil + } + + /// The version the tap's cask declares, read off the clone Homebrew already keeps, or `nil`. + /// + /// **A lower bound on what `brew upgrade` would find, never an upper one.** Homebrew clones + /// a third-party tap rather than serving it from its API, so the file is right there and + /// costs nothing to read. But it is only as fresh as the last `brew update`, and + /// `brew upgrade` auto-updates before it resolves anything — so this file saying "nothing + /// newer" does not mean the command would do nothing. It is worth reading first precisely + /// because the *useful* direction is reliable: if this already names a version newer than + /// the installed bundle, then `brew upgrade` will certainly find at least that, and no + /// request has to be made at all. + /// + /// Returning `nil` therefore means "ask something authoritative", not "up to date". + /// + /// **Taps hang off `HOMEBREW_REPOSITORY`, which is not the prefix**, and getting that wrong + /// is why this reads two candidates instead of one. Read from Homebrew's own `bin/brew`: + /// the repository starts equal to the prefix and is then re-derived from the `bin/brew` + /// symlink target when there is one, after which an x86_64 install forces the prefix back + /// to `/usr/local`. On Apple Silicon `bin/brew` is a real file, so repository == prefix == + /// `/opt/homebrew`; on Intel `/usr/local/bin/brew` is a link into `/usr/local/Homebrew`, so + /// the Caskroom is at `/usr/local/Caskroom` while the taps are at + /// `/usr/local/Homebrew/Library/Taps`. Reading only `/Library/Taps` therefore found + /// nothing on any Intel Mac — `detect` still worked, so the failure was invisible: the + /// short-circuit simply never fired and every sheet paid for a request the clone on disk + /// could have answered. + public static func localTapVersion(prefix: URL) -> String? { + // The prefix itself first: that is the Apple Silicon layout and the common case. + for repository in [prefix, prefix.appendingPathComponent("Homebrew")] { + let file = repository + .appendingPathComponent("Library/Taps") + .appendingPathComponent(tapOwner) + .appendingPathComponent(tapRepository) + .appendingPathComponent("Casks") + .appendingPathComponent("\(cask).rb") + guard let text = try? String(contentsOf: file, encoding: .utf8) else { continue } + if let version = declaredVersion(in: text) { return version } + } + return nil + } + + /// The version a cask declares, or `nil` for anything this cannot compare. + /// + /// The same rules as `release.rs`'s `cask_version`, and the same reason for being strict + /// rather than lenient: it takes the first `version` stanza that is a plain quoted literal + /// parsing as three numbers, and refuses an interpolation, `version :latest`, and + /// Homebrew's comma-separated `version "1.2,345"` form (`Cask#version.csv`). A cask is Ruby + /// and this is not a Ruby parser. + /// + /// `nil` is the safe answer and a guess is not. It becomes "could not tell", which shows the + /// upgrade command with a caveat; a version invented out of an unparseable string could + /// instead show 「已是 Homebrew 提供的最新版本」 over a real update — the one outcome that + /// hides a pending upgrade behind a reassuring sentence. + /// + /// **Split on `isNewline`, not on `"\n"`, or a CRLF cask parses as nothing at all.** Swift + /// treats `"\r\n"` as a single grapheme cluster, so it is one `Character` that is not equal + /// to `"\n"` — measured, `split(separator: "\n")` returns the whole file as one piece for a + /// CRLF cask, which does not begin with `version ` and yields `nil`, while Rust's + /// `str::lines()` splits it correctly and returns the version. That made the two parsers + /// disagree on the same bytes, against the claim above, for any clone checked out with + /// `core.autocrlf` set or a `.gitattributes` asking for CRLF. `.whitespacesAndNewlines` for + /// the trim rather than `.whitespaces`, which excludes CR and would leave one behind. + static func declaredVersion(in cask: String) -> String? { + for line in cask.split(whereSeparator: \.isNewline) { + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.hasPrefix("version ") else { continue } + let rest = trimmed.dropFirst("version ".count) + .trimmingCharacters(in: .whitespacesAndNewlines) + guard rest.hasPrefix("\""), let literal = rest.dropFirst().split( + separator: "\"", omittingEmptySubsequences: false).first else { return nil } + let candidate = String(literal) + return SelfUpdate.Version(candidate) == nil ? nil : candidate + } + return nil + } +} + +/// What `gitpic update cask --json` reports. +/// +/// A `Decodable` mirror of `release.rs`'s `TapCask`, and its field spellings are a contract +/// between the two in the same way `UpdateReport`'s are. All three are single words, so unlike +/// `UpdateReport` there is nothing here for `CodingKeys` to translate. `theWireShapeIsAContract` +/// decodes a canned payload so that renaming a field on either side fails a test rather than +/// silently turning every Homebrew answer into a caveat. +/// +/// `version` is `nil` for a cask that was *read* and declares nothing comparable. A thrown +/// error is the other way the answer can be missing: the cask was not read at all. Those are +/// different facts that happen to have the same consequence, so nothing here merges them — +/// the caller decides once, in one place. +/// +/// `cask` echoes the token the CLI looked up. Nothing reads it today: ownership is established +/// by `detect`, which finds a `Caskroom//` directory and so already knows the token, +/// and taking the command's token from the *tap's* reply instead would name a cask this machine +/// may not have installed. It is decoded rather than dropped because it is what makes the +/// reply self-describing in a log, and `theWireShapeIsAContract` pins it. +public struct TapCask: Decodable, Equatable, Sendable { + public let ok: Bool + public let cask: String + public let version: String? +} + +extension CaskOwnership { + + /// What `SelfUpdate.route` is told about Homebrew — the whole answer, already computed. + /// + /// A value rather than a closure the route calls, which is the shape the deleted + /// `brew: @autoclosure () -> BrewOwnership` parameter had. That one existed so a bundle + /// outside the two Applications directories could refuse *without paying* for a 28-second + /// probe. Nothing here is expensive enough to defer, and making the route pure again is + /// worth more: every row of the decision table can be exercised by naming its inputs. + public enum Verdict: Equatable, Sendable { + /// No cask claims this bundle. The app installs its own updates, as it does for + /// everyone who did not use Homebrew. + case notHomebrews + /// A cask owns it, and this is what the cask has to offer. + case homebrews(cask: String, offers: Offer) + } + + /// What the tap declares, or why that could not be established. + public enum Offer: Equatable, Sendable { + case version(String) + /// User-facing and therefore **Chinese**, and deliberately not the underlying error: + /// a network message or a command line rendered in a caption at 480 pt is the bug + /// `refusalsAreWrittenForTheWindow` exists to catch. The real error is logged. + case unknown(reason: String) + } + + /// The whole Homebrew question, asked in the order that costs least. + /// + /// Three steps, and the second is the one worth explaining. Detection is free. Then the + /// tap's *local* clone is consulted, and if it already names something newer than the + /// installed bundle the answer is settled with no request at all — because that direction + /// is the reliable one: `brew upgrade` auto-updates before it resolves, so it will find at + /// least whatever the stale clone already knows about. Only when the clone cannot prove + /// that is `askTap` spent, since a clone saying "nothing newer" is indistinguishable from + /// a clone that has not been updated in a week. + /// + /// `askTap` is injected rather than reached for so that all three outcomes are testable + /// without a subprocess or a socket. In the app it is `GitpicRunner.tapCask`. + /// + /// `@Sendable` because this is `nonisolated` and the closure is awaited across an isolation + /// boundary — the app's caller is `@MainActor` and the runner it captures is an actor, so + /// there is nothing non-`Sendable` for it to close over. + /// + /// Every failure becomes `Offer.unknown`, never a refusal. A brew user whose network is + /// down still gets the command — that is Claude Code's behaviour too, and the alternative + /// is a dead end for someone whose upgrade path is fine. + public static func verdict( + bundle: URL, + prefixes: [URL] = defaultPrefixes, + bundleVersion: String?, + askTap: @Sendable () async throws -> TapCask + ) async -> Verdict { + guard let install = detect(bundle: bundle, prefixes: prefixes) else { + return .notHomebrews + } + let mine = bundleVersion.flatMap(SelfUpdate.Version.init) + if let local = localTapVersion(prefix: install.prefix), + let offered = SelfUpdate.Version(local), let mine, mine < offered { + return .homebrews(cask: install.cask, offers: .version(local)) + } + do { + let tap = try await askTap() + guard let version = tap.version else { + Diagnostics.log( + "tap: cask \(tap.cask) was read but declares no comparable version") + return .homebrews( + cask: install.cask, + offers: .unknown(reason: "Homebrew 的 cask 里没有可比较的版本号")) + } + return .homebrews(cask: install.cask, offers: .version(version)) + } catch { + // Logged here because the caption above deliberately says nothing specific, and + // that made six different failures — no runner, a 10 s timeout, a rate limit, a 404 + // on the cask path, undecodable output, a CLI too old to have the subcommand — + // produce byte-identical output with nothing left to diagnose from. The caption + // stays constant; the cause goes on the record. + Diagnostics.log("tap: could not read what Homebrew offers — " + + Self.describe(error)) + return .homebrews( + cask: install.cask, + offers: .unknown(reason: "暂时读不到 Homebrew 提供的版本")) + } + } + + /// The thrown error as one line for the log, preferring `RunFailure`'s own wording. + /// + /// `RunFailure.message` is written for a label in the window, which is exactly the level of + /// detail a maintainer reading the log wants too — and it is the only rendering that does + /// not print Swift syntax. Anything else falls back to `String(describing:)`, which is what + /// the rest of this app logs for an unknown error. + private static func describe(_ error: Error) -> String { + (error as? RunFailure)?.message ?? String(describing: error) + } +} diff --git a/apps/GitPic/Sources/GitPicCore/GitpicRunner.swift b/apps/GitPic/Sources/GitPicCore/GitpicRunner.swift index f65d94f..20d528a 100644 --- a/apps/GitPic/Sources/GitPicCore/GitpicRunner.swift +++ b/apps/GitPic/Sources/GitPicCore/GitpicRunner.swift @@ -21,6 +21,13 @@ public enum RunFailure: Error, Sendable, Equatable { /// Carries the raw text so the UI can show it verbatim instead of inventing an /// explanation. case undecodable(status: Int32, raw: String) + /// The child outlived the bound its caller set and was killed. + /// + /// Its own case because it is the one failure with *no output to quote*, and it used to + /// arrive as `.undecodable(status: 137, raw: "")` — a SIGKILL exit code and an empty + /// string, rendered as 「看不懂 gitpic 的回答(退出码 137,没有输出)。可能装的是旧版本。」, + /// which names the wrong cause entirely. Only a caller that passes `timeout:` can see it. + case timedOut(after: TimeInterval) } extension RunFailure { @@ -52,6 +59,8 @@ extension RunFailure { return "看不懂 gitpic 的回答(退出码 \(status),没有输出)。可能装的是旧版本。" } return "看不懂 gitpic 的回答(退出码 \(status)):\(said)" + case .timedOut(let after): + return "gitpic 超过 \(Int(after)) 秒没有回应,已经结束它。" } } } @@ -92,6 +101,21 @@ public actor GitpicRunner { /// UI, and the second would invalidate nothing but the user's attention. private nonisolated static let loginQueue = DispatchQueue(label: "dev.gitpic.app.login") + /// The tap lookup's own queue, off `gate` for the reason spelled out on `tapCask`. + /// Serial as well, so two sheet openings in a row cannot put two of them on the + /// machine — there is nothing to gain from the second and the answer would be the same. + private nonisolated static let tapQueue = DispatchQueue(label: "dev.gitpic.app.tap") + + /// Shorter than the CLI's own 20 s request ceiling on purpose, so this side is the + /// binding one. Coming off `gate` removed the accident that used to bound this. + /// + /// It bounds when the child is *asked* to stop, not when it is gone: `ChildProcess.run` + /// terminates, waits up to 2 s, `SIGKILL`s and waits up to 1 s more, all after the + /// deadline. So the worst case is nearer 13 s than 10 — stated because four doc comments + /// used to say "10 s" flatly, and a reader sizing the sheet's wait against it would be + /// three seconds short. + private nonisolated static let tapTimeout: TimeInterval = 10 + public init(tools: ToolPaths) { self.tools = tools } public var toolPaths: ToolPaths { tools } @@ -128,9 +152,18 @@ public actor GitpicRunner { private func runJSON( _ args: [String], - as: T.Type + as: T.Type, + on queue: DispatchQueue? = nil, + timeout: TimeInterval? = nil ) async throws -> T { - let out = try await run(args) + let out = try await run(args, on: queue, timeout: timeout) + // A killed child is not a decoding problem, and letting it fall through made it look + // like one: `ChildProcess.run` does not throw on timeout, it reports `timedOut` and an + // exit status of `128 + SIGKILL`, so the empty stdout failed to decode and arrived as + // `.undecodable(status: 137, raw: "")` — a failure with no text in it at all. + if out.timedOut, let timeout { + throw RunFailure.timedOut(after: timeout) + } guard let decoded = try? JSONDecoder().decode(T.self, from: out.stdout) else { throw Self.failure(out) } @@ -171,15 +204,44 @@ public actor GitpicRunner { /// invocations and `tools` is immutable. Hopping onto the actor would only /// add a suspension, and suspensions are precisely what does *not* serialise /// here (see the type comment). - nonisolated func run(_ args: [String]) async throws -> ProcessOutcome { + /// + /// `queue` and `timeout` both default to what every ordinary invocation wants — + /// the shared gate, and no bound. A caller overrides them together or not at + /// all: coming off the gate is what makes a bound necessary, since the gate is + /// the only thing that was keeping two spawns apart. + /// + /// **This deliberately does not honour task cancellation, and re-adding it is a bug.** + /// A `withCheckedThrowingContinuation` is not cancellable on its own, so cancelling the + /// awaiting task neither ends the `await` nor touches the child — and one caller *depends* + /// on that. `AppModel.resolveUpgradePath` runs inside `UpdateSheet`'s `.task(id:)`, which + /// SwiftUI cancels the moment a new report moves the generation; its loop then notices the + /// generation moved and asks again, and that second ask is made from a task that is already + /// cancelled. Its own comment says so: "the probe already running is the one that has to + /// notice." + /// + /// A `withTaskCancellationHandler` here was tried and reverted, having been measured: with + /// it, the first probe is killed mid-flight *and the re-query is killed before it starts*, + /// because `onCancel` fires immediately on an already-cancelled task. `CaskOwnership.verdict` + /// turns any failure into `Offer.unknown`, so the new report resolved to 「暂时读不到 + /// Homebrew 提供的版本」 instead of a real comparison — wrong information where the + /// alternative is an honest 「正在确认升级方式…」 for the length of the bound. What the + /// handler was meant to buy is not worth that: the only bounded caller is a read-only + /// lookup, capped by ``tapTimeout``, on its own queue, blocking nothing. + nonisolated func run( + _ args: [String], + on queue: DispatchQueue? = nil, + timeout: TimeInterval? = nil + ) async throws -> ProcessOutcome { let tools = self.tools + let queue = queue ?? gate return try await withCheckedThrowingContinuation { cont in - gate.async { + queue.async { var env = ProcessInfo.processInfo.environment env["PATH"] = ToolPaths.childPATH do { let out = try ChildProcess.run( - executable: tools.gitpic, args: args, environment: env) + executable: tools.gitpic, args: args, environment: env, + timeout: timeout) cont.resume(returning: out) } catch { cont.resume(throwing: error) @@ -398,10 +460,12 @@ extension GitpicRunner { /// Whether a newer gitpic has been released, and what changed in it. /// - /// Unlike its neighbours this one needs neither config nor credential — the releases - /// endpoint is public — so it is the one report that still works on a machine where - /// `config.toml` is unreadable. That matters here more than it sounds: the fix for - /// whatever broke it may be in the release this call is about to find. + /// Unlike its neighbours this one needs neither config nor credential to *work* — it + /// reads the image-host token when there is one, only to raise GitHub's rate limit, and + /// every way that can fail collapses to an anonymous request. So it is the one report + /// that still works on a machine where `config.toml` is unreadable. That matters here + /// more than it sounds: the fix for whatever broke it may be in the release this call is + /// about to find. /// /// A failure to reach GitHub throws, and the caller shows it rather than swallowing /// it: "已是最新" for a check that never completed is the one answer that hides a @@ -410,6 +474,30 @@ extension GitpicRunner { try await runJSON(["update", "check", "--json"], as: UpdateReport.self) } + /// What `brew upgrade --cask gitpic` would install, asked only when a cask owns us. + /// + /// **Deliberately not on `gate`**, for the reason `loginEvents` is not: the gate has no + /// timeout, and this one goes to the network. The CLI bounds a single attempt at 20 s + /// with a 10 s connect and retries once anonymously if GitHub refuses the credential, so + /// worst case is around forty seconds — and on `gate` that is forty seconds in front of + /// every upload, on the sheet-open path. Deleting twenty-eight seconds of exactly that + /// shape is what `bb07783` was for; putting forty back wearing a different hat would be + /// the worse regression. A read-only lookup races with nothing: it writes no file at all, + /// which is a weaker claim than the one that justifies `loginQueue`. + /// + /// Coming off the gate is why the bound is here rather than left to the CLI. Ten seconds + /// is shorter than the CLI's own ceiling on purpose, so this side is the real one — see + /// ``tapTimeout`` for why the wall-clock worst case is nearer thirteen. That bound, and not + /// task cancellation, is what stops a wedged child outliving the sheet: ``run`` deliberately + /// does not honour cancellation, for a reason spelled out there. A timeout is not a failure + /// to report: it means the tap could not be read, which is a state the caller has an answer + /// for — and it arrives as `RunFailure.timedOut` rather than as an empty decode failure, so + /// the log says so. + public func tapCask() async throws -> TapCask { + try await runJSON(["update", "cask", "--json"], as: TapCask.self, + on: Self.tapQueue, timeout: Self.tapTimeout) + } + /// Every branch on one repository. /// /// Takes the repository explicitly rather than reading the saved config, because the diff --git a/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift b/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift index 3b21b00..5b9e460 100644 --- a/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift +++ b/apps/GitPic/Sources/GitPicCore/SelfUpdateRoute.swift @@ -12,32 +12,31 @@ import Foundation /// 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. /// -/// **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. +/// **This is the install path for every copy nobody else manages.** A bundle a Homebrew cask +/// owns is not installed over at all: `route` hands its user `brew upgrade --cask gitpic` and +/// this file is not reached. `CaskOwnership` decides which of the two it is. /// -/// **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. +/// **Why that is not a return to what `bb07783` deleted.** The route it removed *ran* brew, and +/// both of its measured defects came from that and only from that. The app had to quit before +/// brew was spawned, so a tap refresh and a whole download happened with an `.accessory` app's +/// menu-bar icon already gone, with no progress, nothing to cancel, and a 900 s watchdog as the +/// only bound. And when the tap lagged the release, `brew upgrade` exited **0** saying "the +/// latest version is already installed", which the script logged as success before reopening +/// the same build. Nothing is spawned now and nothing quits: the app says what to run and stays +/// where it is, so neither failure has anywhere to happen. What it costs instead is stated on +/// ``Route/homebrewUpToDate(installed:)`` — during the tap's lag a brew user is told to wait +/// rather than offered an install. /// -/// **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. +/// **The stanza that makes the handed-over command safe is `uninstall quit: "dev.gitpic.app"`**, +/// and it is more load-bearing than before: `Cask::Upgrade` passes `quit: true`, so brew quits +/// the app, re-registers the new bundle with Launch Services and reopens it. For an `.accessory` +/// app that reopen is the only thing that puts the menu-bar icon back. Telling someone to run a +/// command that would leave them with a replaced bundle and a dead icon is not an option. +/// +/// `auto_updates true` is the other stanza the cask carries, and it is no longer what makes any +/// of this correct — it asserts that the artifact updates itself, which stops being true of a +/// cask-managed copy the moment this route defers to brew. AGENTS.md's Homebrew section records +/// what becomes of it and why the two repositories have to move in that order. extension SelfUpdate { /// Which upgrade this install can be offered, if any. @@ -60,13 +59,49 @@ extension SelfUpdate { /// 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. + /// **Nothing produces `true` any more**, and the reason is worth stating precisely + /// because it changed shape. The one source was a Homebrew probe that could time out, + /// so its "I could not get an answer" had to stay askable. Homebrew is asked about + /// again — but by the *caller*, which hands `route` a finished `CaskOwnership.Verdict`, + /// so `route` is still a pure function and every refusal it mints is still durable for + /// as long as the report is. A lookup that fails becomes `Offer.unknown`, which is one + /// of the Homebrew cases below and not a refusal at all. 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) + /// Homebrew owns this bundle and its cask has something newer: hand over the command. + /// + /// `installed` is the *bundle's* version and `available` is the **cask's**, not the + /// release's. Those differ whenever the tap lags a release, which is the whole reason + /// this case exists rather than reusing the release comparison — see ``route``. + /// + /// The command travels as its own value rather than inside a `reason` string, so that + /// `refusalsAreWrittenForTheWindow`'s ban on command lines in refusals stays exactly as + /// strict as it was: a refusal still may not read like a command, and this is not one. + case homebrewManaged(command: String, installed: String, available: String) + /// Homebrew owns this bundle and its cask has nothing newer. + /// + /// Reached even when a *release* newer than `installed` exists — the tap follows a + /// release by dispatch with a six-hourly cron behind it. No command is offered, because + /// `brew upgrade --cask gitpic` in this window prints "the latest version is already + /// installed" and exits 0, and handing someone a command that does nothing is worse + /// than saying so. This is the accepted cost of the policy; the app does not install + /// over a cask-managed bundle to fill the gap. + /// + /// **`offered` travels alongside `installed` because the two are not always equal**, and + /// the case is reached whenever the bundle is not *older*. It carried only `installed` + /// at first, which the sheet rendered as 「已是 Homebrew 提供的最新版本(X)」 — a + /// statement about what Homebrew provides, made from the bundle's own number. For a user + /// who self-installed 0.20.10 while the tap still declares 0.20.9 that sentence asserts + /// Homebrew provides 0.20.10 and tells them to wait for a version they already have. + /// Both numbers are here so the sheet can say which is which. + case homebrewUpToDate(installed: String, offered: String) + /// Homebrew owns this bundle and what its cask offers could not be established. + /// + /// The command is still offered, with the caveat, because a network that is down says + /// nothing about whether the upgrade path works — and it is what Claude Code does in + /// the same spot ("Could not check for updates" followed by the command). + case homebrewUnverified(command: String, reason: String) } /// Whether the running bundle sits somewhere an update may be installed. @@ -78,30 +113,72 @@ extension SelfUpdate { /// Decide whether to offer an upgrade, and for which asset. /// - /// **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. + /// **A pure function of four facts**, each supplied by the caller: who owns the bundle, + /// where it is, what version it is, and what the release has to install. Homebrew is a + /// question again — `bb07783` removed it and this puts it back — but nothing here asks it. + /// `CaskOwnership.verdict` does, and hands the finished answer in, which is why every row + /// of this table can still be exercised by naming its inputs. + /// + /// The old shape is worth remembering as the thing not to return to: `brew` arrived as an + /// `@autoclosure` producing a verdict from a login-shell probe of up to 8 s plus up to 20 s + /// per `brew list --cask`, per prefix, on a serial queue — up to 28 seconds of + /// 「正在确认升级方式…」 before a button could be drawn, and the laziness existed purely so a + /// bundle outside the two Applications directories could refuse without paying it. + /// `CaskOwnership` answers the same question with a directory scan and a `readlink`, so + /// there is nothing left to defer and the parameter is an ordinary value. + /// + /// **Ownership is asked first, ahead of the location.** That order is load-bearing, not + /// tidiness. `brew install --appdir` puts a cask anywhere, and `location(of:)` calls + /// anything outside `/Applications` and `~/Applications` `.elsewhere` — so asking location + /// first sends a perfectly ordinary cask install to a dead-end refusal when + /// `brew upgrade --cask gitpic` is exactly right for it. Claude Code is package-manager-first + /// for the same reason: whether *we* could install locally is irrelevant when somebody else + /// owns the install. /// - /// **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 Homebrew branch compares against the tap, not the release**, and must not reuse the + /// gate below. `latest` is the release's, and for a brew user the base is what the cask + /// offers: bundle 0.20.9 with release 0.20.10 and tap 0.20.9 is `homebrewUpToDate`, which + /// `mine < theirs` would wave straight through into an install. `latest` is not consulted on + /// that branch at all, and neither is `asset` — which is also why the branch sits above + /// both, since `installableAsset()` derives a filename from `latest` and would mint a + /// refusal about a missing DMG for someone who was never going to download one. /// - /// **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. + /// **The location rule survives on its own merits**, for the copies that are nobody's cask: + /// one running from `dist-app/` or a Downloads folder must not have its directory written + /// into, and the sheet sends it to the release page. public static func route( + cask: CaskOwnership.Verdict, location: BundleLocation, bundleVersion: String?, latest: String, asset: AssetChoice ) -> Route { + if case .homebrews(let token, let offers) = cask { + let command = "brew upgrade --cask \(token)" + switch offers { + case .unknown(let reason): + return .homebrewUnverified(command: command, reason: reason) + case .version(let offered): + // The bundle's own version, for the reason on the gate below. + guard let bundleVersion, let mine = Version(bundleVersion) else { + return .homebrewUnverified( + command: command, reason: "读不出当前 GitPic 的版本号") + } + // Both parsers already refuse what they cannot compare, so this is defensive + // rather than reachable — and a caveat is the right answer to an impossible + // string, where a comparison against a guess would not be. + guard let theirs = Version(offered) else { + return .homebrewUnverified( + command: command, reason: "读不懂 Homebrew 提供的版本号") + } + guard mine < theirs else { + return .homebrewUpToDate(installed: bundleVersion, offered: offered) + } + return .homebrewManaged( + command: command, installed: bundleVersion, available: offered) + } + } + if case .elsewhere(let path) = location { return .unavailable( reason: "这份 GitPic 在 \(path),不是 /Applications 或 ~/Applications," diff --git a/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift b/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift index 9d071db..7d73509 100644 --- a/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift +++ b/apps/GitPic/Sources/GitPicCore/ToolDiscovery.swift @@ -101,10 +101,11 @@ public enum ToolDiscovery { /// /// **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 + /// authorised replacing whatever was in `/Applications`. That caller is gone, and it did not + /// come back when the ownership question did — `CaskOwnership.detect` reads the Caskroom's own + /// symlinks instead of asking `brew` whether it exists, so no shell is involved and there is + /// no "could not tell" to fold. 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 diff --git a/apps/GitPic/Tests/GitPicCoreTests/CaskOwnershipTests.swift b/apps/GitPic/Tests/GitPicCoreTests/CaskOwnershipTests.swift new file mode 100644 index 0000000..da10da6 --- /dev/null +++ b/apps/GitPic/Tests/GitPicCoreTests/CaskOwnershipTests.swift @@ -0,0 +1,419 @@ +import Foundation +import Testing + +@testable import GitPicCore + +@Suite("Homebrew ownership") +struct CaskOwnershipTests { + + /// **The link is the evidence, and it has to resolve to *this* bundle.** + /// + /// The deleted implementation asked `brew list --cask gitpic`, which answers about the + /// machine: it is true whenever a cask is installed anywhere, including when the copy asking + /// is a different one at a different path. This asks about the bundle, so a machine that has + /// the cask *and* a second GitPic somewhere else gets the right answer for each. + @Test("a Caskroom link resolving to this bundle is what makes it Homebrew's") + func aCaskroomLinkIsTheEvidence() throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + + // Before the link exists, the same bundle at the same path is nobody's cask. + let prefix = f.root.appendingPathComponent("homebrew") + #expect(CaskOwnership.detect(bundle: f.bundle, prefixes: [prefix]) == nil) + + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.20.9") + let found = CaskOwnership.detect(bundle: f.bundle, prefixes: [layout.prefix]) + #expect(found == CaskOwnership.Install(cask: "gitpic", prefix: layout.prefix)) + } + + /// A cask installed elsewhere is not evidence about us. This is the case + /// `brew list --cask` could not distinguish, and getting it wrong would tell someone with a + /// hand-installed GitPic to run a command that upgrades a different copy. + @Test("a Caskroom link pointing at some other bundle is not evidence") + func anotherBundlesLinkIsNotOurs() throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + + let other = f.root.appendingPathComponent("Applications/Other.app") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + let layout = try HomebrewShape.install(bundle: other, under: f.root, version: "0.20.9") + + #expect(CaskOwnership.detect(bundle: f.bundle, prefixes: [layout.prefix]) == nil) + } + + /// A Caskroom entry left behind after the bundle was deleted by hand. `fileExists` follows + /// the link, so a dangling one is skipped rather than resolved to a path that is not there — + /// and *not* treated as ownership, because `brew upgrade` on it would be reinstalling rather + /// than upgrading anything this app is running from. + @Test("a dangling Caskroom link is not ownership") + func aDanglingLinkIsNotOwnership() throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.20.9") + try FileManager.default.removeItem(at: f.bundle) + + #expect(CaskOwnership.detect(bundle: f.bundle, prefixes: [layout.prefix]) == nil) + } + + /// Both prefixes are searched, and the one that answered travels back with the answer. + /// + /// An Intel and an Apple Silicon Homebrew are independent installations with independent + /// Caskrooms and independent tap clones — so a machine with both must not have its cask found + /// under one prefix and its tap version read from under the other. + @Test("either Homebrew prefix can be the one that owns it, and it says which") + func eitherPrefixCanOwnIt() throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + + let second = try HomebrewShape.install( + bundle: f.bundle, under: f.root, version: "0.20.9", prefixName: "usr-local") + let empty = f.root.appendingPathComponent("empty-prefix") + let found = CaskOwnership.detect(bundle: f.bundle, prefixes: [empty, second.prefix]) + #expect(found?.prefix == second.prefix) + } + + /// **Ownership does not depend on where the bundle lives**, which is the whole reason this + /// reads the link rather than the bundle's own path. `brew install --appdir` puts a cask + /// anywhere the user likes, and `SelfUpdate.location(of:)` calls anything outside the two + /// Applications directories `.elsewhere` — so a cask at a custom appdir is exactly the case + /// that used to reach a dead-end refusal when `brew upgrade --cask gitpic` was correct and + /// safe for it. + @Test("a cask at a custom appdir is still the cask's") + func aCustomAppdirIsStillTheCasks() throws { + for appDir in ["Applications", "Apps", "Users/x/Applications"] { + let f = try HomebrewShape.bundle(named: appDir) + defer { try? FileManager.default.removeItem(at: f.root) } + + let layout = try HomebrewShape.install( + bundle: f.bundle, under: f.root, version: "0.20.9") + #expect(CaskOwnership.detect(bundle: f.bundle, prefixes: [layout.prefix]) != nil, + "a cask installed at \(appDir) is still a cask") + } + } + + // MARK: - What the tap offers + + /// The clone Homebrew already keeps, read under the prefix that owned the bundle. + @Test("the tap's own clone is where the offered version comes from") + func theLocalCloneAnswers() throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.20.9") + // No clone yet: `nil` means "ask something authoritative", not "up to date". + #expect(CaskOwnership.localTapVersion(prefix: layout.prefix) == nil) + + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.20.10") + #expect(CaskOwnership.localTapVersion(prefix: layout.prefix) == "0.20.10") + } + + /// **The parse refuses more than it accepts, and the refusals are the point.** + /// + /// These rows mirror `release.rs`'s `a_cask_version_is_read_only_when_it_is_plainly_comparable` + /// one for one, because the two parsers have to agree: the app reads the local clone with + /// this one and the network copy with that one, and a version accepted by one and refused by + /// the other would make the answer depend on which path happened to be taken. + /// + /// `version "1.2,345"` is the row that matters most. It is a real Homebrew spelling + /// (`Cask#version.csv`) and reading it as a version would let the sheet claim + /// 「已是 Homebrew 提供的最新版本」 over a pending upgrade. + @Test("a cask version is read only when it is plainly comparable") + func onlyAComparableVersionIsRead() { + #expect(CaskOwnership.declaredVersion(in: "cask \"gitpic\" do\n version \"0.20.9\"\n") + == "0.20.9") + #expect(CaskOwnership.declaredVersion( + in: "# the version below is rewritten by the tap\n version \"1.2.3\"\nend") == "1.2.3") + for refused in [ + " version \"1.2,345\"\n", // csv — two fields, not a version + " version :latest\n", // a symbol, not a literal + " version \"#{ENV['V']}\"\n", // interpolated + " version \"0.20\"\n", // not three components + " version \"0.20.0-rc1\"\n", // prerelease, which `Version` refuses + "cask \"gitpic\" do\nend\n", // no stanza at all + "", + ] { + #expect(CaskOwnership.declaredVersion(in: refused) == nil, + "\(refused) is not something to compare a bundle against") + } + } + + // MARK: - The whole question, in the order that costs least + + /// Counts calls across an isolation boundary without pulling an actor into the test. + private final class Calls: @unchecked Sendable { + private let lock = NSLock() + private var n = 0 + func bump() { lock.lock(); n += 1; lock.unlock() } + var count: Int { lock.lock(); defer { lock.unlock() }; return n } + } + + private static func tap(_ version: String?) -> TapCask { + TapCask(ok: true, cask: "gitpic", version: version) + } + + /// A bundle no cask owns costs nothing at all — in particular it does **not** spend the + /// request. Almost every GitPic is this case, and it runs on the sheet-open path. + @Test("a bundle no cask owns never reaches the network") + func nothingIsSpentOnANonCask() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let calls = Calls() + + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [f.root.appendingPathComponent("homebrew")], + bundleVersion: "0.18.0", + askTap: { calls.bump(); return Self.tap("0.19.0") }) + + #expect(verdict == .notHomebrews) + #expect(calls.count == 0, "a bundle Homebrew does not own must not cost a request") + } + + /// **The local clone short-circuits, and only in the direction where it can be trusted.** + /// + /// The clone is a lower bound: `brew upgrade` auto-updates before it resolves, so if the + /// clone already names something newer than the bundle, brew will certainly find at least + /// that — the answer is settled and no request is needed. This is the common case on a + /// machine that runs `brew update` regularly, which is most of them. + @Test("a local clone that already proves an upgrade skips the request") + func aLocalCloneAheadSettlesItForFree() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.19.0") + let calls = Calls() + + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { calls.bump(); return Self.tap("0.20.0") }) + + #expect(verdict == .homebrews(cask: "gitpic", offers: .version("0.19.0"))) + #expect(calls.count == 0, "the clone already proved an upgrade exists") + } + + /// **And in the other direction it is not trusted at all**, which is the half that makes the + /// request worth keeping. A clone saying "nothing newer" is indistinguishable from a clone + /// nobody has updated in a week, so the authoritative answer is fetched — and it wins. + @Test("a local clone with nothing newer is not believed, it is checked") + func aStaleCloneIsCheckedRatherThanBelieved() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.18.0") + let calls = Calls() + + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { calls.bump(); return Self.tap("0.19.0") }) + + #expect(verdict == .homebrews(cask: "gitpic", offers: .version("0.19.0"))) + #expect(calls.count == 1, "a clone that cannot prove an upgrade has to be checked") + } + + /// A missing clone is the same "cannot prove it" as a stale one, not an error. + @Test("no local clone means ask, not fail") + func aMissingCloneAsks() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { Self.tap("0.19.0") }) + + #expect(verdict == .homebrews(cask: "gitpic", offers: .version("0.19.0"))) + } + + /// **A failure is never a refusal.** Both ways the answer can be missing — the lookup threw, + /// or it succeeded and the cask declares nothing comparable — become `Offer.unknown`, which + /// the route turns into the command plus a caveat. A brew user whose network is down still + /// gets something to run; their upgrade path is fine and the app has no business implying + /// otherwise. This is Claude Code's behaviour in the same spot. + @Test("a lookup that fails or says nothing still leaves the user a command") + func failureBecomesUnknownAndNotARefusal() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + + struct Boom: Error {} + let threw = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { throw Boom() }) + guard case .homebrews(_, .unknown(let thrownReason)) = threw else { + Issue.record("a failed lookup must still be a Homebrew answer") + return + } + #expect(!thrownReason.isEmpty) + + let saidNothing = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { Self.tap(nil) }) + guard case .homebrews(_, .unknown) = saidNothing else { + Issue.record("a cask with no comparable version must be `unknown`") + return + } + } + + /// An unreadable bundle version cannot short-circuit on the clone — there is nothing to + /// compare it against — so the lookup happens and the route decides what to do about it. + @Test("an unreadable bundle version does not skip the check") + func anUnreadableBundleVersionStillAsks() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.19.0") + let calls = Calls() + + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: nil, + askTap: { calls.bump(); return Self.tap("0.19.0") }) + + #expect(verdict == .homebrews(cask: "gitpic", offers: .version("0.19.0"))) + #expect(calls.count == 1, "with no bundle version the clone proves nothing") + } + + /// **Taps hang off `HOMEBREW_REPOSITORY`, which is not the prefix on an Intel install.** + /// + /// Read out of Homebrew's own `bin/brew`: the repository starts equal to the prefix, is + /// re-derived from the `bin/brew` symlink target when there is one, and an x86_64 install + /// then forces the prefix back to `/usr/local`. So on Apple Silicon everything is under + /// `/opt/homebrew`, while on Intel the Caskroom is `/usr/local/Caskroom` and the tap clone is + /// `/usr/local/Homebrew/Library/Taps`. + /// + /// Reading only `/Library/Taps` therefore found nothing on any Intel Mac, and the + /// failure was invisible: `detect` still worked, so ownership was right and only the free + /// short-circuit was dead — every sheet paid for a request the clone on disk could have + /// answered, and an Intel user whose network was down was told 「暂时读不到」 while the + /// answer sat in a file. The fixture could not have caught it either, because it wrote the + /// Apple Silicon layout by construction. + @Test("the tap clone is found under either Homebrew repository layout") + func theTapCloneIsFoundOnIntelToo() async throws { + for repositorySubpath in [nil, "Homebrew"] { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install( + bundle: f.bundle, under: f.root, version: "0.18.0") + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.19.0", + repositorySubpath: repositorySubpath) + + let where_ = repositorySubpath ?? "" + #expect(CaskOwnership.localTapVersion(prefix: layout.prefix) == "0.19.0", + "a clone under \(where_)/Library/Taps has to be read") + + // And the whole point of reading it: the request is not spent. + let calls = Calls() + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: { calls.bump(); return Self.tap("0.19.0") }) + #expect(verdict == .homebrews(cask: "gitpic", offers: .version("0.19.0"))) + #expect(calls.count == 0, "the clone already proved 0.19.0 is newer") + } + } + + /// A CRLF clone parses, which it did not. + /// + /// `"\r\n"` is a single Swift `Character` and is not equal to `"\n"`, so + /// `split(separator: "\n")` returned the entire file as one piece — measured, one piece + /// against `str::lines()`'s three on the same bytes. The line never began with `version `, + /// the parser returned nil, and the doc's claim to follow "the same rules as `release.rs`'s + /// `cask_version`" was false for any clone checked out with `core.autocrlf` set or a + /// `.gitattributes` asking for CRLF. + @Test("a cask with Windows line endings parses the same as one without") + func aCrlfCaskParses() throws { + for ending in ["\n", "\r\n", "\r"] { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install( + bundle: f.bundle, under: f.root, version: "0.18.0") + try HomebrewShape.tapClone(under: layout.prefix, declaring: "0.19.0", + lineEnding: ending) + #expect(CaskOwnership.localTapVersion(prefix: layout.prefix) == "0.19.0", + "line ending \(ending.debugDescription) must not change the answer") + } + } + + /// The captions **`verdict` itself writes**, as opposed to the ones a test hands it. + /// + /// Both are shown in a caption at 480 pt in a Chinese-only sheet, and neither may read like + /// a command — the command has its own monospaced row. `route`'s two are pinned by + /// `SelfUpdateRouteTests.theRoutesOwnCaptionsAreWrittenForTheWindow`; these are the other + /// two, and between them that is every user-facing Homebrew string in the codebase. + @Test("the captions the verdict writes are Chinese sentences, not command lines") + func everyCaptionIsWrittenForTheWindow() async throws { + let f = try HomebrewShape.bundle() + defer { try? FileManager.default.removeItem(at: f.root) } + let layout = try HomebrewShape.install(bundle: f.bundle, under: f.root, version: "0.18.0") + + func caption( + _ askTap: @escaping @Sendable () async throws -> TapCask + ) async -> String? { + let verdict = await CaskOwnership.verdict( + bundle: f.bundle, prefixes: [layout.prefix], bundleVersion: "0.18.0", + askTap: askTap) + guard case .homebrews(_, .unknown(let reason)) = verdict else { return nil } + return reason + } + + // The lookup failed outright, and the cask was read but declares nothing comparable. + let failed = await caption { throw RunFailure.spawnFailed("gitpic 还没准备好") } + let saidNothing = await caption { Self.tap(nil) } + guard let failed, let saidNothing else { + Issue.record("both cases have to reach `unknown`") + return + } + #expect(failed != saidNothing, + "a read that failed and a cask that says nothing are different facts") + for reason in [failed, saidNothing] { + #expect(!reason.isEmpty) + #expect(!reason.contains("--"), + "\(reason) reads like a command line, and the command has its own row") + #expect(!reason.contains("brew upgrade"), "\(reason) names the command inside prose") + #expect(reason.contains(where: { $0.unicodeScalars.first.map { + (0x4E00...0x9FFF).contains($0.value) + } == true }), "\(reason) is rendered in a Chinese-only sheet and has to be Chinese") + } + } + + /// The Swift/Rust wire shape, decoded from the bytes rather than built by hand. + /// + /// Every other row in this suite constructs `TapCask` through its memberwise initialiser, + /// which exercises none of the decoding — so renaming `ok`, `cask` or `version` on either + /// side, or adding `CodingKeys`, left both suites green while every Homebrew user silently + /// got the caveat instead of the real answer. `UpdateReport` has four decode tests over + /// canned JSON for exactly this reason; this is `TapCask`'s. + @Test("the wire shape is a contract") + func theWireShapeIsAContract() throws { + let full = Data(#"{"ok":true,"cask":"gitpic","version":"0.20.9"}"#.utf8) + let decoded = try JSONDecoder().decode(TapCask.self, from: full) + #expect(decoded == TapCask(ok: true, cask: "gitpic", version: "0.20.9")) + + // A cask that was read and declares nothing comparable: `version` is absent, not empty. + // `release.rs` skips the field entirely when it is `None`, so the absent form is the one + // that actually arrives. + let nothing = try JSONDecoder().decode( + TapCask.self, from: Data(#"{"ok":true,"cask":"gitpic"}"#.utf8)) + #expect(nothing.version == nil) + #expect(nothing.ok) + + // `ok` and `cask` are not optional, so a reply missing either is a contract break and + // has to fail loudly rather than decode into a default. + #expect(throws: (any Error).self) { + try JSONDecoder().decode(TapCask.self, from: Data(#"{"cask":"gitpic"}"#.utf8)) + } + } + + /// The path a user-facing version is read from is built from pinned constants. + /// + /// `CaskOwnership`'s doc claimed a counterpart to `release.rs`'s + /// `the_release_feed_is_a_compile_time_constant` already existed here. It did not — the three + /// constants that build the tap path were pinned only incidentally, by a raw string literal + /// inside the test fixture, so changing one of them here would have left the fixture agreeing + /// with the mistake. Same argument as the Rust side: a version read out of the wrong file + /// gets shown next to a command the user is told to run. + @Test("the tap path is built from pinned constants") + func theTapPathIsBuiltFromPinnedConstants() { + #expect(CaskOwnership.cask == "gitpic") + #expect(CaskOwnership.tapOwner == "tarnish233") + #expect(CaskOwnership.tapRepository == "homebrew-tap") + } +} diff --git a/apps/GitPic/Tests/GitPicCoreTests/HomebrewShape.swift b/apps/GitPic/Tests/GitPicCoreTests/HomebrewShape.swift new file mode 100644 index 0000000..638f479 --- /dev/null +++ b/apps/GitPic/Tests/GitPicCoreTests/HomebrewShape.swift @@ -0,0 +1,113 @@ +import Foundation + +/// A Homebrew-shaped install under a scratch root, built to what was measured off a real +/// machine rather than to what seemed likely: +/// +/// /opt/homebrew/bin/gitpic -> /Applications/GitPic.app/Contents/Resources/gitpic +/// /opt/homebrew/Caskroom/gitpic/0.20.9/GitPic.app -> /Applications/GitPic.app +/// +/// Shared by two suites that want the same shape for different reasons: `SelfUpdateInstallTests` +/// asserts a swap leaves both links resolving to the *new* bundle, and `CaskOwnershipTests` +/// asserts the Caskroom link is what makes detection answer "Homebrew's". +/// +/// Every destination is absolute and rooted at the caller's own fixture, so the layout is fully +/// relocatable — which is the property that lets detection be pointed at it instead of at the +/// machine's real `/opt/homebrew`. Without that seam the only way to test detection would be to +/// install a cask. +enum HomebrewShape { + + struct Layout { + /// Stands in for `HOMEBREW_PREFIX`. + let prefix: URL + /// `Caskroom/gitpic//GitPic.app` → the bundle. + let caskLink: URL + /// `bin/gitpic` → the CLI inside the bundle. + let binLink: URL + } + + /// Build the two links a cask leaves behind, pointing at `bundle`. + /// + /// The three shell completions the cask also installs are deliberately not here: they are + /// real files rather than links, which is exactly why they go stale after a self-update and + /// why there is nothing about them for either suite to assert. + @discardableResult + static func install( + bundle: URL, under root: URL, version: String, prefixName: String = "homebrew" + ) throws -> Layout { + let prefix = root.appendingPathComponent(prefixName) + let caskroom = prefix.appendingPathComponent("Caskroom/gitpic/\(version)") + 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: bundle.appendingPathComponent("Contents/Resources/gitpic")) + try FileManager.default.createSymbolicLink(at: caskLink, withDestinationURL: bundle) + return Layout(prefix: prefix, caskLink: caskLink, binLink: binLink) + } + + /// A tap clone where `brew update` would leave one, declaring `version`. + /// + /// Written as a whole cask rather than one line, so the parser is exercised against the + /// shape it will really meet — comments above the stanza included, since the tap's own + /// `Casks/gitpic.rb` opens with a long one. + /// + /// **`repositorySubpath` is what makes the Intel layout expressible**, and it exists because + /// this fixture used to hardcode `/Library/Taps` and so could not have caught the + /// bug it was covering. Taps hang off `HOMEBREW_REPOSITORY`, which equals the prefix only + /// when `bin/brew` is a real file: on Intel `/usr/local/bin/brew` links into + /// `/usr/local/Homebrew`, so the clone is at `/usr/local/Homebrew/Library/Taps` while the + /// Caskroom stays at `/usr/local/Caskroom`. Pass `"Homebrew"` for that shape. + /// + /// `lineEnding` is the other axis a single fixture hid. A clone checked out with + /// `core.autocrlf` set has CRLF line endings, and Swift treats `"\r\n"` as one `Character` + /// that does not equal `"\n"` — so a parser splitting on `"\n"` saw the whole file as a + /// single line and read no version at all, while the Rust parser on the same bytes read it + /// correctly. + static func tapClone( + under prefix: URL, + declaring version: String, + repositorySubpath: String? = nil, + lineEnding: String = "\n" + ) throws { + var repository = prefix + if let repositorySubpath { + repository = repository.appendingPathComponent(repositorySubpath) + } + let casks = repository + .appendingPathComponent("Library/Taps/tarnish233/homebrew-tap/Casks") + try FileManager.default.createDirectory(at: casks, withIntermediateDirectories: true) + let cask = """ + cask "gitpic" do + # The tap rewrites only the version, sha256 and url lines by targeted sub!. + version "\(version)" + sha256 "\(String(repeating: "ab", count: 32))" + + app "GitPic.app" + end + """ + let text = lineEnding == "\n" + ? cask + : cask.split(separator: "\n", omittingEmptySubsequences: false) + .joined(separator: lineEnding) + try text.write(to: casks.appendingPathComponent("gitpic.rb"), atomically: true, + encoding: .utf8) + } + + /// A scratch root with an empty `GitPic.app` directory in an Applications directory. + /// + /// `detect` compares paths and never opens the bundle, so a real signed app would be cost + /// without coverage — but the directory has to *exist*, because a dangling Caskroom link is + /// deliberately not treated as evidence. + static func bundle(named appDir: String = "Applications") throws -> (root: URL, bundle: URL) { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("gitpic-cask-test-\(UUID().uuidString)") + let bundle = root.appendingPathComponent(appDir).appendingPathComponent("GitPic.app") + try FileManager.default.createDirectory( + at: bundle.appendingPathComponent("Contents/Resources"), + withIntermediateDirectories: true) + return (root, bundle) + } +} diff --git a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift index 312bad6..4351924 100644 --- a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift +++ b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateInstallTests.swift @@ -823,19 +823,14 @@ struct SelfUpdateInstallTests { 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) + // Stand in for HOMEBREW_PREFIX. Built by `HomebrewShape`, which is shared with + // `CaskOwnershipTests` — the shape is measured off one real install and two suites want + // it for different reasons, so it is described in one place. 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 layout = try HomebrewShape.install(bundle: f.target, under: f.root, version: "0.18.0") + let binLink = layout.binLink + let caskLink = layout.caskLink // 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) diff --git a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift index 6291749..27e9060 100644 --- a/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift +++ b/apps/GitPic/Tests/GitPicCoreTests/SelfUpdateRouteTests.swift @@ -19,47 +19,74 @@ struct SelfUpdateRouteTests { } private static let sha = String(repeating: "ab", count: 32) - /// **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. + /// What every row that is not about Homebrew wants. Spelled out at each call rather than + /// defaulted in `route` itself: a default would let a new call site skip the question + /// silently, and this is a question whose wrong answer installs over somebody's cask. + private static let notBrews = CaskOwnership.Verdict.notHomebrews + /// A cask that owns this bundle and offers `version`. + private static func brews(_ version: String) -> CaskOwnership.Verdict { + .homebrews(cask: "gitpic", offers: .version(version)) + } + + /// **One install path, whoever installed the bundle — but only one of the two branches + /// installs.** This suite once opened with `brewWins`, went through a period with no brew + /// question at all, and now asks it again in a narrower form: a cask-managed bundle is handed + /// a command instead of being installed over, and nothing spawns. The rows that went with the + /// original fork protected things that no longer exist to protect — how two prefixes' verdicts + /// were folded, that an unanswered probe never became "not brew's" — because `CaskOwnership` + /// answers conclusively from the filesystem and its own suite covers it. @Test("an older bundle in an Applications directory gets the installer") func installsAnOlderBundle() { let route = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) #expect(route == .selfInstall(asset: Self.dmg, sha256: Self.sha, version: "0.19.0")) } - /// 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() { + /// The structural claim, one fact wider than it used to be: with ownership, the location, the + /// version and the asset all in order there is **no** remaining question that could send this + /// anywhere else — and ownership is the only input that was added, so nothing else about the + /// machine can change the answer either. + @Test("nothing but ownership, the location, the version and the asset decides the route") + func routeIsDecidedByFourFactsOnly() { let usable = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) guard case .selfInstall = usable else { - Issue.record("three facts in order must produce an install and nothing else") + Issue.record("four facts in order must produce an install and nothing else") return } - // Break exactly one at a time; each must refuse, and none may produce an install. + // Break exactly one at a time; none may produce an install. let broken: [SelfUpdate.Route] = [ - SelfUpdate.route(location: .elsewhere(path: "/Users/x/Downloads/GitPic.app"), + SelfUpdate.route(cask: Self.brews("0.19.0"), location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice), - SelfUpdate.route(location: .applicationsDir, bundleVersion: "not-a-version", + SelfUpdate.route(cask: Self.notBrews, + location: .elsewhere(path: "/Users/x/Downloads/GitPic.app"), + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice), + SelfUpdate.route(cask: Self.notBrews, location: .applicationsDir, + bundleVersion: "not-a-version", latest: "0.19.0", asset: Self.choice), - SelfUpdate.route(location: .applicationsDir, bundleVersion: "0.18.0", + SelfUpdate.route(cask: Self.notBrews, location: .applicationsDir, + bundleVersion: "0.18.0", latest: "0.19.0", asset: .none(reason: "GitHub 没有报校验和")), ] for route in broken { + if case .selfInstall = route { + Issue.record("a broken precondition must not install") + return + } + } + // And the ownership row specifically is a hand-over, not a refusal: a brew user must + // never be left with neither an install nor a command. + guard case .homebrewManaged = broken[0] else { + Issue.record("a cask-owned bundle must be handed the command") + return + } + for route in broken.dropFirst() { guard case .unavailable = route else { - Issue.record("a broken precondition must refuse, not install") + Issue.record("a broken precondition that is not about Homebrew must refuse") return } } @@ -69,14 +96,15 @@ struct SelfUpdateRouteTests { /// 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. + /// The row this used to absorb, `caskInACustomAppdirIsSentToTheReleasePage`, is now **inverted** + /// and lives in `casksOutrankTheLocationRule` below. It once proved the location rule was not + /// *looser* for a cask at a custom `--appdir`; the rule is now that ownership is asked first, + /// so such a bundle gets the command rather than this refusal. What is left here is the copy + /// that is nobody's cask. @Test("a bundle outside an Applications directory is refused, permanently") func elsewhereIsRefused() { let route = SelfUpdate.route( + cask: Self.notBrews, location: .elsewhere(path: "/Users/x/src/gitpic/dist-app/GitPic.app"), bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) guard case .unavailable(let reason, let retryable) = route else { @@ -88,6 +116,126 @@ struct SelfUpdateRouteTests { #expect(reason.contains("dist-app")) } + // MARK: - When Homebrew owns the bundle + + /// **Ownership is asked before the location, and this is the row that says why.** + /// + /// `brew install --cask gitpic --appdir ~/Apps` is an ordinary thing to do, and it produces a + /// bundle `location(of:)` calls `.elsewhere`. Asking location first sends that user to + /// 「这份 GitPic 在 …」 — a dead end — when `brew upgrade --cask gitpic` is exactly right for + /// them and safe, because the cask's own `uninstall quit:` handles the running app. + /// + /// This is the inversion of the deleted `caskInACustomAppdirIsSentToTheReleasePage`, which + /// pinned the opposite: that the location rule was not *looser* for a cask. The rule is now + /// that ownership outranks it, and the inversion is the load-bearing part. + @Test("a cask outranks the location rule, at any appdir") + func casksOutrankTheLocationRule() { + let route = SelfUpdate.route( + cask: Self.brews("0.19.0"), + location: .elsewhere(path: "/Users/x/Apps/GitPic.app"), + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) + #expect(route == .homebrewManaged(command: "brew upgrade --cask gitpic", + installed: "0.18.0", available: "0.19.0")) + } + + /// **The safety requirement, stated once over the whole space.** Nothing this app does may + /// install over a bundle Homebrew owns — that is the entire policy, and until now nothing + /// pinned it. Every other fact is varied underneath a cask verdict, including the + /// combinations that would otherwise be perfectly installable. + @Test("a cask-owned bundle is never installed over, whatever else is true") + func aCaskIsNeverInstalledOver() { + let locations: [SelfUpdate.BundleLocation] = + [.applicationsDir, .elsewhere(path: "/Users/x/Apps/GitPic.app")] + let versions: [String?] = ["0.18.0", "0.19.0", "not-a-version", nil] + let assets: [AssetChoice] = [Self.choice, .none(reason: "GitHub 没有报校验和")] + let offers: [CaskOwnership.Offer] = + [.version("0.19.0"), .version("0.18.0"), .unknown(reason: "暂时读不到")] + + for location in locations { + for mine in versions { + for asset in assets { + for offer in offers { + let route = SelfUpdate.route( + cask: .homebrews(cask: "gitpic", offers: offer), + location: location, bundleVersion: mine, latest: "0.19.0", + asset: asset) + if case .selfInstall = route { + Issue.record("a cask-owned bundle must never be installed over") + return + } + // Nor may it dead-end: a brew user with neither an install nor a command + // has nothing to do, which is the failure this whole route exists to + // avoid. `homebrewUpToDate` is the one case with no command, and it is + // an answer rather than a dead end. + if case .unavailable = route { + Issue.record("a cask-owned bundle must never reach a refusal") + return + } + } + } + } + } + } + + /// The three outcomes, which are Claude Code's three read out of its own binary: the cask has + /// something newer, the cask has nothing newer, or what the cask has could not be read. + /// + /// **The comparison is against the cask, never against the release.** The middle row is the + /// one that proves it: a release at 0.19.0 exists and the bundle is 0.18.0, so the ordinary + /// version gate would install — but the tap still says 0.18.0, so `brew upgrade` would print + /// "the latest version is already installed" and exit 0. That window is real; the tap follows + /// a release by dispatch with a six-hourly cron behind it, and AGENTS.md records the dispatch + /// token having expired for three releases. + @Test("the cask's own version decides, not the release's") + func theCasksVersionDecides() { + let ahead = SelfUpdate.route( + cask: Self.brews("0.19.0"), location: .applicationsDir, + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) + #expect(ahead == .homebrewManaged(command: "brew upgrade --cask gitpic", + installed: "0.18.0", available: "0.19.0")) + + // The tap lags the release: no command, because the command would do nothing. + let lagging = SelfUpdate.route( + cask: Self.brews("0.18.0"), location: .applicationsDir, + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) + #expect(lagging == .homebrewUpToDate(installed: "0.18.0", offered: "0.18.0")) + + // A bundle *ahead* of the tap — which a self-updated copy from before this change is — + // is also nothing for brew to do, and must not be offered a downgrade. + // + // Both numbers travel, and the asymmetry is the point: `installed` is 0.19.0 while + // `offered` is 0.18.0, so the sheet can say which is which. Carrying only `installed` + // let it print 「已是 Homebrew 提供的最新版本(0.19.0)」 — a claim about what Homebrew + // provides, made out of the bundle's number, telling this user to wait for a version + // they are already running. + let behindTap = SelfUpdate.route( + cask: Self.brews("0.18.0"), location: .applicationsDir, + bundleVersion: "0.19.0", latest: "0.19.0", asset: Self.choice) + #expect(behindTap == .homebrewUpToDate(installed: "0.19.0", offered: "0.18.0")) + + let unreadable = SelfUpdate.route( + cask: .homebrews(cask: "gitpic", offers: .unknown(reason: "暂时读不到 Homebrew 提供的版本")), + location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", + asset: Self.choice) + #expect(unreadable == .homebrewUnverified(command: "brew upgrade --cask gitpic", + reason: "暂时读不到 Homebrew 提供的版本")) + } + + /// The command names the cask that was actually found, not a hardcoded token — so a rename in + /// the tap, or a second cask, cannot make the app print a command for the wrong one. + @Test("the command is built from the cask that owns the bundle") + func theCommandNamesTheCaskThatWasFound() { + let route = SelfUpdate.route( + cask: .homebrews(cask: "gitpic-beta", offers: .version("0.19.0")), + location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", + asset: Self.choice) + guard case .homebrewManaged(let command, _, _) = route else { + Issue.record("expected the Homebrew hand-over") + return + } + #expect(command == "brew upgrade --cask gitpic-beta") + } + /// **No developer English reaches the window, and nothing reads like a command line.** /// /// Inherited from `unknownBrewIsRetryable`, which is deleted: that row's reason string used @@ -99,17 +247,25 @@ struct SelfUpdateRouteTests { /// 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. + /// + /// **Reintroducing the Homebrew branch did not weaken this.** The one deliberate command + /// string in the whole route is `homebrewManaged`/`homebrewUnverified`'s own `command` value, + /// which the sheet renders as a monospaced row rather than as prose — so the ban below still + /// applies to every `reason` unaltered, and `theHandOverCarriesTheCommandOutsideTheProse` + /// pins that the prose half stays clean too. @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"), + SelfUpdate.route(cask: Self.notBrews, + 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", + SelfUpdate.route(cask: Self.notBrews, location: .applicationsDir, + bundleVersion: nil, latest: "0.19.0", asset: Self.choice), + SelfUpdate.route(cask: Self.notBrews, location: .applicationsDir, + bundleVersion: "0.18.0", latest: "not-a-version", 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), + SelfUpdate.route(cask: Self.notBrews, location: .applicationsDir, + bundleVersion: "0.19.0", latest: "0.19.0", asset: Self.choice), ] for route in refusals { guard case .unavailable(let shown, _) = route else { @@ -124,12 +280,81 @@ struct SelfUpdateRouteTests { } } + /// **The one command string is carried, not narrated.** `refusalsAreWrittenForTheWindow` bans + /// a command line from any `reason`, and the Homebrew branch has to respect that rather than + /// be exempted from it: the flag lives in `command`, which the sheet draws as a monospaced + /// selectable row, and `homebrewUnverified`'s `reason` — the only prose the branch mints — + /// stays a Chinese sentence with no flag in it. + /// + /// `homebrewUpToDate` carries no command at all, which is the whole point of that case. + @Test("the hand-over carries the command outside the prose") + func theHandOverCarriesTheCommandOutsideTheProse() { + let unverified = SelfUpdate.route( + cask: .homebrews(cask: "gitpic", offers: .unknown(reason: "暂时读不到 Homebrew 提供的版本")), + location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", + asset: Self.choice) + guard case .homebrewUnverified(let command, let reason) = unverified else { + Issue.record("expected the unverified hand-over") + return + } + #expect(command.contains("--cask"), "the command is what the user has to run") + #expect(!reason.contains("--"), + "\(reason) is prose in a caption at 480 pt and may not read like a command") + #expect(reason.contains(where: { $0.unicodeScalars.first.map { + (0x4E00...0x9FFF).contains($0.value) + } == true }), "\(reason) is rendered in a Chinese-only sheet and has to be Chinese") + + // Nothing else in the route mints a command, and `homebrewUpToDate` deliberately has + // none: during the tap's lag `brew upgrade` would print "already installed" and exit 0. + let upToDate = SelfUpdate.route( + cask: Self.brews("0.18.0"), location: .applicationsDir, + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice) + #expect(upToDate == .homebrewUpToDate(installed: "0.18.0", offered: "0.18.0")) + } + + /// The reasons **`route` itself writes**, which the check above cannot see. + /// + /// The row above hands `route` a `reason` and then asserts that string is Chinese and + /// flag-free — which it is, because the test wrote it. That is a tautology, and it left the + /// two captions `route` actually mints covered by nothing. Both are reached only when a + /// version fails to parse, so neither has a natural call site to notice them. + /// + /// `verdict`'s own two are pinned in `CaskOwnershipTests.everyCaptionIsWrittenForTheWindow`; + /// between them the four user-facing Homebrew strings in the codebase are all exercised. + @Test("the captions the route writes are Chinese sentences, not command lines") + func theRoutesOwnCaptionsAreWrittenForTheWindow() { + let minted = [ + // The bundle's own version is unreadable. + SelfUpdate.route(cask: Self.brews("0.19.0"), location: .applicationsDir, + bundleVersion: nil, latest: "0.19.0", asset: Self.choice), + // The cask declares something that will not parse. Defensive rather than reachable + // — both parsers refuse what they cannot compare — and a caveat is still the right + // answer to an impossible string. + SelfUpdate.route(cask: Self.brews("not-a-version"), location: .applicationsDir, + bundleVersion: "0.18.0", latest: "0.19.0", asset: Self.choice), + ] + for route in minted { + guard case .homebrewUnverified(let command, let reason) = route else { + Issue.record("expected an unverified hand-over, got \(route)") + return + } + #expect(command == "brew upgrade --cask gitpic") + #expect(!reason.isEmpty) + #expect(!reason.contains("--"), + "\(reason) reads like a command line, and the command has its own row") + #expect(reason.contains(where: { $0.unicodeScalars.first.map { + (0x4E00...0x9FFF).contains($0.value) + } == true }), "\(reason) is rendered in a Chinese-only sheet and has to be Chinese") + } + } + /// The gate is the *bundle's* version, not the report's `current` — that one comes from /// the CLI, and this replaces the bundle. Equal or newer is not an update. @Test("the bundle's own version decides, and it must be older") func versionGate() { for mine in ["0.19.0", "0.20.0", "1.0.0"] { let route = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: mine, latest: "0.19.0", asset: Self.choice) guard case .unavailable(let reason, _) = route else { @@ -140,6 +365,7 @@ struct SelfUpdateRouteTests { } // And older is. guard case .selfInstall = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: "0.9.0", latest: "0.10.0", asset: Self.choice) else { // 0.9.0 < 0.10.0 is the comparison a string sort gets backwards, which is why @@ -153,6 +379,7 @@ struct SelfUpdateRouteTests { func unreadableVersion() { for mine in [nil, "", "0.18", "0.18.0.1", "0.18.0-rc1", "app-v0.1.2", "abc"] { let route = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: mine, latest: "0.19.0", asset: Self.choice) guard case .unavailable = route else { @@ -167,6 +394,7 @@ struct SelfUpdateRouteTests { @Test("an unverifiable asset stops the install and keeps its reason") func assetRefusalPropagates() { let route = SelfUpdate.route( + cask: Self.notBrews, location: .applicationsDir, bundleVersion: "0.18.0", latest: "0.19.0", asset: .none(reason: "GitHub 没有报校验和")) #expect(route == .unavailable(reason: "GitHub 没有报校验和", retryable: false)) diff --git a/apps/GitPic/Tests/GitPicCoreTests/TapProbeCancellationTests.swift b/apps/GitPic/Tests/GitPicCoreTests/TapProbeCancellationTests.swift new file mode 100644 index 0000000..917a554 --- /dev/null +++ b/apps/GitPic/Tests/GitPicCoreTests/TapProbeCancellationTests.swift @@ -0,0 +1,102 @@ +import Foundation +import Testing + +/// `GitpicRunner.run` must not honour task cancellation, and this is the tripwire for it. +/// +/// A source scan rather than a behavioural test, for the same reason `QuitPathContractTests` +/// is one: the interleaving cannot be reached from `swift test`. It needs `AppModel`, which +/// lives in `GitPicApp` and is not importable here (`Updater.swift` records why), driven by a +/// SwiftUI `.task(id:)` cancelling mid-probe. So this checks the property a grep *can* hold — +/// that the prohibition has not been quietly undone — and the argument for it lives on `run`. +/// +/// **What the prohibition is.** `AppModel.resolveUpgradePath` loops: when a check lands while +/// the tap probe is running, the generation moves, the in-flight call notices and asks again. +/// But moving the generation is exactly what makes `.task(id:)` tear that task down, so the +/// second ask is made from a task that is *already cancelled*. `withCheckedThrowingContinuation` +/// ignores cancellation, which is what lets the second ask succeed. +/// +/// **Measured, both ways.** With a `withTaskCancellationHandler` around it, the first probe is +/// killed mid-flight and the re-query is killed before it starts — `onCancel` fires immediately +/// on an already-cancelled task. Without it, both complete. And because `CaskOwnership.verdict` +/// turns every failure into `Offer.unknown`, the killed version resolved the new report to +/// 「暂时读不到 Homebrew 提供的版本」 with a caveat instead of a real version comparison: wrong +/// information, where the alternative is an honest 「正在确认升级方式…」 for the length of the +/// bound. The bound is what keeps a wedged child harmless — `tapTimeout`, on its own queue, +/// blocking nothing. +/// +/// **Being honest about what this cannot hold.** It cannot see whether the loop still depends on +/// the property, whether `verdict` still collapses failures into `Offer.unknown`, or whether some +/// *other* mechanism starts cancelling the probe. What it is genuinely good for is the one thing +/// that has already happened once: a plausible-looking cancellation handler being added to this +/// file by someone who had not traced the caller. +@Suite("Tap probe cancellation contract") +struct TapProbeCancellationTests { + + /// Every spelling that would make the continuation cancellable. + /// + /// `withTaskCancellationHandler` is the one that was tried and reverted. + /// `Task.checkCancellation` and a bare `isCancelled` are the other two ways the same effect + /// arrives — a throw or an early return on the second pass is just as fatal to the loop as a + /// terminated child. + static let forbidden = [ + "withTaskCancellationHandler", + "checkCancellation", + "Task.isCancelled", + ] + + /// Located from `#filePath` rather than the working directory, because `swift test` runs both + /// from the repository root and from inside the package — the argument is + /// `QuitPathContractTests.appSources`'s, and so is the failure it guards against: a path that + /// guessed wrong would leave this suite passing over a file it never opened. + static func runnerSource() throws -> (url: URL, text: String) { + var root = URL(fileURLWithPath: #filePath) + // 3 components: …/Tests/GitPicCoreTests/ → the `apps/GitPic` package root. + for _ in 0..<3 { root.deleteLastPathComponent() } + let url = root.appendingPathComponent("Sources/GitPicCore/GitpicRunner.swift") + let text = try String(contentsOf: url, encoding: .utf8) + return (url, text) + } + + /// The precondition, asserted where it matters rather than assumed: if the file moves or is + /// renamed, this fails first and says so, instead of the scan below reading nothing. + @Test("the runner source is where the scan expects it") + func sourceExists() throws { + let (url, text) = try Self.runnerSource() + #expect(text.contains("nonisolated func run("), "\(url.path) is not the runner any more") + #expect(text.contains("func tapCask()"), "\(url.path) no longer holds the tap probe") + } + + /// The tripwire. + @Test("the runner does not make its spawn cancellable") + func theSpawnIsNotCancellable() throws { + let (url, text) = try Self.runnerSource() + for (offset, line) in text.components(separatedBy: "\n").enumerated() { + // Comments may name it — `run`'s own doc comment explains the prohibition at length, + // and that explanation is the reason the property holds. Same rule and same reason as + // `QuitPathContractTests.isComment`: whole-line comments only, so a trailing comment + // cannot hide a real call. + guard !line.trimmingCharacters(in: .whitespaces).hasPrefix("//") else { continue } + for spelling in Self.forbidden where line.contains(spelling) { + Issue.record(""" + \(url.lastPathComponent):\(offset + 1) names \(spelling). \ + `AppModel.resolveUpgradePath` re-asks for the tap from a task SwiftUI has \ + already cancelled, so making this spawn cancellable turns a new report's \ + answer into 「暂时读不到 Homebrew 提供的版本」. The bound in `tapTimeout` is \ + what keeps a wedged child harmless. If this line is an explanation rather \ + than code, make it a whole-line comment. + """) + } + } + } + + /// The other half: the bound this relies on instead is still there and still shorter than the + /// CLI's own request ceiling, which is what makes the Swift side the binding one. + @Test("the tap probe is bounded rather than cancellable") + func theTapProbeIsBounded() throws { + let (_, text) = try Self.runnerSource() + #expect(text.contains("static let tapTimeout: TimeInterval = 10")) + // Off the shared gate, which is the other half of why an uncancelled child is harmless: + // it holds up nothing that an upload waits on. + #expect(text.contains("on: Self.tapQueue, timeout: Self.tapTimeout")) + } +} diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 2315c12..8feeab3 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -42,23 +42,36 @@ echo "==> resolving the gitpic binary to embed" TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" GITPIC_BIN="${GITPIC_BIN:-}" if [[ -z "$GITPIC_BIN" ]]; then - if [[ -x "$TARGET_DIR/release/gitpic" ]]; then - GITPIC_BIN="$TARGET_DIR/release/gitpic" - else - echo " no $TARGET_DIR/release/gitpic; building it" - ( cd "$ROOT" && cargo build --release --locked ) - GITPIC_BIN="$TARGET_DIR/release/gitpic" - fi + # Always build, rather than trusting a binary that happens to be there. + # + # This used to reuse `$TARGET_DIR/release/gitpic` whenever it existed, and the version + # check below was described as what made that safe. It is not: it compares *versions*, so + # it catches a binary left over from before a version bump and is blind to one left over + # from earlier the same day. Measured — a `target/release/gitpic` from the previous + # evening, still 0.20.9, was embedded into an 0.20.9 bundle and shipped without the + # `update cask` subcommand that had been added since. Nothing failed. The app degrades + # quietly in that state (a missing subcommand reads as "could not read the tap", so every + # Homebrew user gets the command with a caveat instead of the real answer), which makes it + # harder to notice rather than easier. + # + # `cargo build` is incremental, so this is a no-op when the binary is already current — + # the reuse saved nothing worth this failure mode. `release.yml` was never exposed because + # it builds the CLI in its own step first, and CI's checkout is clean; the machine this + # matters on is a developer's, which is also where `check-self-update.sh` builds the app it + # tests the real updater with. + echo " building $TARGET_DIR/release/gitpic" + ( cd "$ROOT" && cargo build --release --locked ) + GITPIC_BIN="$TARGET_DIR/release/gitpic" fi [[ -x "$GITPIC_BIN" ]] || { echo "error: gitpic binary not found at $GITPIC_BIN" >&2; exit 1; } CLI_VERSION="$("$GITPIC_BIN" --version | awk '{print $2}')" -# The one runtime check that the merged version is real rather than asserted. +# Still worth keeping, now for the case it can actually decide: an explicit `GITPIC_BIN` +# pointing at some other build. # # APP_VERSION comes from Cargo.toml; CLI_VERSION comes from asking the binary # that is about to be copied into the bundle. Those two agreeing is the whole -# claim of a unified release, and nothing else verifies it — a stale -# target/release/gitpic (or a GITPIC_BIN pointing somewhere else) would otherwise -# ship silently inside an app stamped with a version it does not contain. +# claim of a unified release. It is a necessary check and not a sufficient one — +# see the note above on what it cannot see. if [[ "$CLI_VERSION" != "$APP_VERSION" ]]; then echo "error: embedded gitpic is $CLI_VERSION but this build is $APP_VERSION" >&2 echo " $GITPIC_BIN is stale — rebuild it (cargo build --release) or set GITPIC_BIN" >&2 diff --git a/scripts/check-self-update.sh b/scripts/check-self-update.sh index abc028b..27d41f0 100755 --- a/scripts/check-self-update.sh +++ b/scripts/check-self-update.sh @@ -193,8 +193,16 @@ awk -v v="$OLD_VERSION" ' ' "$WORK/Cargo.toml.orig" > "$ROOT/Cargo.toml" [[ "$(cargo_version)" == "$OLD_VERSION" ]] || fail "could not rewrite Cargo.toml's version" -# The binary first, then the bundle: build-app.sh rejects a CARGO_TARGET_DIR/release/gitpic -# whose --version disagrees with Cargo.toml, which is exactly what a stale one is. +# The binary first, then the bundle — still required, but no longer for the reason it was added +# for. `build-app.sh` used to reuse whatever `CARGO_TARGET_DIR/release/gitpic` happened to exist +# and reject it only when its `--version` disagreed with Cargo.toml; it now always builds, so a +# stale binary is no longer a thing this step prevents. +# +# What it does prevent is a lockfile failure. The version rewrite above edits `Cargo.toml`, which +# leaves `Cargo.lock` describing the old version, and `build-app.sh` builds with `--locked` — which +# refuses to update the lock rather than doing it silently. This build carries no `--locked`, so it +# syncs the lock and the bundle build then succeeds. Remove this line and the run dies inside +# `build-app.sh` with cargo's lockfile error instead. ( cd "$ROOT" && cargo build --release ) OUT="$WORK/dist-app" "$ROOT/scripts/build-app.sh" >"$WORK/build.log" 2>&1 \ || { cat "$WORK/build.log"; fail "build-app.sh failed"; } @@ -295,12 +303,19 @@ 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. 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); +# The action row is 「正在确认升级方式…」 until the route is known. Ownership is a directory scan +# and a readlink, 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 稍后); # two means `.unavailable`, which is a different failure and worth saying so. +# +# **This test copy must land on the self-install branch, and that is now a real question.** A +# cask-managed bundle is handed `brew upgrade --cask gitpic` instead of being installed over, and +# button 1 is then 复制升级命令 — which this script would click, copy a string, and then wait +# forever for a process that was never going to be replaced. The copy lives in `~/Applications` +# and no Caskroom entry points at it, so `CaskOwnership.detect` answers "not cask" and the +# self-install branch is the right one. Asserted rather than assumed, because the failure mode +# without the assertion is a 60 s timeout reading "never settled", which says nothing about why. ROUTED="" BUTTONS="" for _ in $(seq 1 60); do @@ -313,6 +328,20 @@ if [[ -z "$ROUTED" ]]; then 稍后). The log line beginning 'update: no in-app upgrade' says which reason." fail "the sheet's action row never settled (found $BUTTONS button(s))" fi +# `Updater.resolve` logs the ownership verdict unconditionally, before the route. +# +# Scoped to this run's bytes with `LOG_MARK`, the way the wait at the top of the script is. The +# log is append-only and machine-wide (line 23), and the *installed* /Applications/GitPic.app +# writes to the same file — so a bare `grep` over the whole thing passes for ever after any +# earlier run, or any sheet ever opened on a non-cask copy, has written the line once. That is a +# guard that cannot fail, which is worse than no guard: the regression it exists for would sail +# past it into the click below, copy a string, and time out saying nothing was replaced — exactly +# the uninformative failure this was added to replace. +if ! tail -c "+$((LOG_MARK + 1))" "$APP_LOG" | grep -q 'update: not cask'; then + fail "this copy was taken for a Homebrew-managed bundle, so button 1 is 复制升级命令 and not + 下载并更新. The log line beginning 'update: cask' says which cask claimed it — a Caskroom + entry under /opt/homebrew or /usr/local resolving to $TEST_APP would do it." +fi step "下载并更新" # Positional, because the sheet's own buttons report their AXDescription as 「按钮」 and diff --git a/src/cli.rs b/src/cli.rs index f1554da..8638f38 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -289,15 +289,28 @@ pub enum Command { /// A subcommand rather than a bare `gitpic update`, and the shape is a promise. /// -/// `gitpic update` on its own would read as "install the update", which this does not do -/// and — see [`crate::commands::update`] — should not: the app is a Homebrew cask signed -/// ad-hoc, so there is no signature chain to verify a self-downloaded replacement against. -/// Requiring the verb keeps the door open for an `apply` later without today's spelling -/// having promised it. +/// `gitpic update` on its own would read as "install the update", which this does not do. The +/// reason is not the one recorded here before — "the app is a Homebrew cask signed ad-hoc, so +/// there is no signature chain to verify a self-downloaded replacement against" — which +/// `Updater`'s header retracts: the installer verifies the SHA-256 `api.github.com` reports for +/// the asset, which is the same trust root a cask's own `sha256` rests on, so ad-hoc signing +/// never separated the two. +/// +/// What holds is that for most installs the right actor is somebody else. A cask or a formula +/// is brew's to upgrade, and [`crate::install_source`] now says which — so the verb keeps the +/// door open for an `apply` that could only ever mean the installs nobody else manages, without +/// today's spelling having promised it. #[derive(Debug, Subcommand)] pub enum UpdateAction { /// Report the latest release and what changed in it Check, + /// Report which version the Homebrew cask offers, installing nothing + /// + /// A separate verb rather than part of `check`, because it costs a second request that + /// only a Homebrew-managed install has any use for. GitPic's update sheet asks this when + /// it finds a cask owns its bundle, so that it can say whether `brew upgrade` would + /// actually do something before telling anyone to run it. + Cask, } #[derive(Debug, Subcommand)] @@ -438,6 +451,7 @@ mod tests { vec!["branches"], vec!["paste"], vec!["update", "check"], + vec!["update", "cask"], ] { for global in [vec!["--json"], vec!["-q"], vec!["-vv"]] { let mut argv = vec!["gitpic"]; @@ -680,15 +694,24 @@ mod tests { )); } - /// The only subcommand that had no parse test, which is how it also ended up missing - /// from the global-flag table below. + /// `update`'s verbs, and the flag table below, kept in step by hand. + /// + /// `check` was once the only subcommand with no parse test, "which is how it also ended up + /// missing from the global-flag table below" — and `cask` then repeated the omission exactly, + /// arriving with neither. That is why both verbs are named here and both are rows in the + /// table: the note is only worth keeping if the next verb trips over it. /// /// `check` is required, and that is the part worth pinning: a bare `gitpic update` must /// not parse, because it reads as "install the update" — which this does not do and, /// per `commands::update`, should not. Requiring the verb keeps an `apply` possible later /// without today's spelling having promised it. + /// + /// `gitpic --json update cask` is the exact invocation `GitpicRunner.tapCask` makes, and the + /// app's whole Homebrew branch is downstream of it parsing. When it does not, the app shows + /// every cask user the upgrade command with a 「暂时读不到」 caveat and nothing fails, so a + /// green suite would have been the only signal. #[test] - fn update_check_parses_and_the_verb_is_required() { + fn update_verbs_parse_and_the_verb_is_required() { assert!(matches!( Cli::try_parse_from(["gitpic", "update", "check"]) .unwrap() @@ -697,6 +720,14 @@ mod tests { action: UpdateAction::Check }) )); + assert!(matches!( + Cli::try_parse_from(["gitpic", "update", "cask"]) + .unwrap() + .command, + Some(Command::Update { + action: UpdateAction::Cask + }) + )); assert!(Cli::try_parse_from(["gitpic", "update"]).is_err()); assert!(Cli::try_parse_from(["gitpic", "update", "apply"]).is_err()); } diff --git a/src/commands/update.rs b/src/commands/update.rs index d623030..2e4f465 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -2,23 +2,31 @@ //! //! The comparison and the request live in [`crate::release`]; this is the rendering. //! -//! **Config-free**, like `auth` and `list`: nothing here reads `config.toml` or the -//! credential, because "is there a new version" is a question worth answering on a machine -//! 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. +//! **Config-free, and that is not the same as credential-free.** Nothing here reads +//! `config.toml`, because "is there a new version" is a question worth answering on a machine +//! 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 does reach for `auth.toml`: +//! `release::best_effort_token` attaches a credential when one exists, because +//! `api.github.com` allows 60 anonymous requests an hour *per address* and behind a shared +//! egress that budget belongs to everyone behind it. Absent or rejected, the request goes +//! anonymously and still works — see `release`'s header for the measurement. The claim used +//! to read "nothing here reads `config.toml` or the credential", which the second half made +//! false. //! //! 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. +//! reason is the one about the CLI: a `gitpic` on `PATH` can have come from the cask (a +//! symlink into the app bundle, so it upgrades when the app upgrades), from a `GitPic.app` +//! installed by hand, from the `gitpic_cli` formula, from `cargo install --git`, or from an +//! unpacked tarball. Those want different upgrade commands and this process could perform at +//! most one of them, so it reports instead. How the *app* decides what to do is a separate +//! question with a separate answer; see `SelfUpdate.route` in `GitPicCore`. //! -//! 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. +//! What it no longer does is make the reader pick. The note used to print the cask's command +//! and the formula's command side by side, on the grounds that this process could not tell +//! them apart — which was true of the code and not of the machine. [`crate::install_source`] +//! tells them apart, so exactly one command is printed, and the reader for whom neither of +//! the old two was right (a hand-installed bundle, a cargo build, a tarball) gets an answer +//! instead of a wrong command that fails with "no available formula". use crate::error::Result; use crate::output::Mode; @@ -45,6 +53,51 @@ pub async fn run(mode: Mode) -> Result { Ok(0) } +/// `gitpic update cask` — what would `brew upgrade --cask gitpic` actually install? +/// +/// A command rather than something the app does for itself, because everything network-shaped +/// in this project goes through this binary: `GitPicCore` never talks to `api.github.com`, and +/// the origin has to stay a compile-time constant for the reason recorded on the tap constant +/// in [`crate::release`]. +/// +/// It answers about the *cask*, not the release, and that difference is the whole point. The +/// app learns a release exists the moment it is published, while the tap follows by dispatch +/// with a six-hourly cron behind it — so "there is a new version" and "brew can install it" +/// are different questions, and only this one decides whether telling someone to run +/// `brew upgrade` would do anything. +pub async fn cask(mode: Mode) -> Result { + let tap = crate::release::tap_cask().await?; + + if mode.is_json() { + crate::output::print_json(&tap); + return Ok(0); + } + if mode.is_quiet() { + // The version or nothing, the same rule `check` follows: "could not tell" must not be + // a string a script has to match on. + if let Some(version) = &tap.version { + crate::output::line(version); + } + return Ok(0); + } + match &tap.version { + Some(version) => { + crate::output::line(&format!("the {} cask offers {version}", tap.cask)); + crate::output::note(&format!( + "this is what `brew upgrade --cask {}` would install", + tap.cask + )); + } + // Not an error: the file was read. It just says something this cannot compare, and a + // guess here would be worse than admitting it. + None => crate::output::line(&format!( + "the {} cask declares no version this can compare", + tap.cask + )), + } + Ok(0) +} + fn human(report: &UpdateReport) { if report.update_available { crate::output::line(&format!( @@ -71,12 +124,10 @@ fn human(report: &UpdateReport) { } crate::output::line(""); crate::output::line(&report.url); - // Both paths, because the cask and the formula are different installs and - // `brew upgrade` on the wrong one reports "no available formula". - crate::output::note( - "upgrade with `brew upgrade --cask gitpic` (app) or \ - `brew upgrade gitpic_cli` (CLI only)", - ); + // One command, for the install this binary actually came from. Printing the cask's and + // the formula's side by side was wrong for whoever had neither, and `brew upgrade` on + // the wrong one of the two reports "no available formula". + crate::output::note(&crate::install_source::detect().upgrade_hint()); return; } if report.ahead { diff --git a/src/install_source.rs b/src/install_source.rs new file mode 100644 index 0000000..dbf757f --- /dev/null +++ b/src/install_source.rs @@ -0,0 +1,522 @@ +//! Where this `gitpic` came from, and therefore which one upgrade command to print. +//! +//! `gitpic update` reports and never installs, because a `gitpic` on `PATH` can have arrived +//! four different ways that want four different commands. It used to print two of them and +//! leave the reader to pick — including the reader for whom neither was right. This module +//! picks. +//! +//! **`current_exe()` on its own is not enough, and the way it fails is silent.** The cask +//! links `HOMEBREW_PREFIX/bin/gitpic` at the copy inside the app bundle, so the commonest +//! install of all is invoked *through a symlink*. On Apple platforms `current_exe()` is +//! `_NSGetExecutablePath` with no canonicalisation, and that returns the link rather than its +//! target — measured on macOS 26.6 against a binary invoked through a same-directory symlink, +//! which reported the symlink's own path and not the target's. `std::env::current_exe`'s own +//! documentation declines to promise either behaviour ("some platforms will return the path of +//! the symbolic link and other platforms will return the path of the symbolic link's target"), +//! so the answer is not to depend on which one you get: [`detect`] canonicalises. +//! +//! Without that step `/opt/homebrew/bin/gitpic` is neither inside a bundle nor under a Cellar, +//! and both answers it could fall to are wrong ones — [`InstallSource::Unknown`], which prints +//! the same unhelpful thing as before and buys nothing, or [`InstallSource::Formula`], which +//! prints `brew upgrade gitpic_cli` and fails with "no available formula". That second one is +//! the exact mistake the old two-command note existed to avoid. +//! +//! std's Security section warns against trusting `current_exe()` where it matters. What it +//! decides here is which sentence to print. Nothing is executed from it and no privilege turns +//! on it. +//! +//! **Why a cask check lives here as well as in the app.** `GitPicCore`'s `CaskOwnership` asks +//! "is *my bundle* cask-managed" so the update sheet knows whether to hand the user a command; +//! this asks "where did *this binary* come from" so the terminal prints the right one. They +//! are different questions with different answers — a hand-installed `GitPic.app` and a +//! cask-installed one are the same bundle shape and want different commands — and the shared +//! sub-question, whether a Caskroom entry points at a given bundle, is twenty lines in each +//! language. Sharing it would cost a subprocess on the app's sheet-open path, which is the +//! cost `bb07783` was written to delete. + +use std::path::{Path, PathBuf}; + +/// One spelling of each, shared with the tap lookup that echoes the cask token back to the +/// app — see [`crate::release::CASK`]. +use crate::release::{CASK, FORMULA}; + +/// The prefixes an Apple Silicon and an Intel Homebrew use, plus `HOMEBREW_PREFIX` when it is +/// set. The first two are independent installations with independent Caskrooms, so both are +/// searched rather than one being derived from the other. +/// +/// `HOMEBREW_PREFIX` matters much more here than it does to the app: `brew shellenv` exports it, +/// so a terminal that can run `brew` at a non-default prefix almost always has it, whereas a +/// Finder-launched bundle has never sourced anything. +fn default_prefixes() -> Vec { + let mut prefixes = vec![PathBuf::from("/opt/homebrew"), PathBuf::from("/usr/local")]; + if let Some(declared) = std::env::var_os("HOMEBREW_PREFIX") { + let declared = PathBuf::from(declared); + if declared.is_absolute() && !prefixes.contains(&declared) { + prefixes.push(declared); + } + } + prefixes +} + +/// Where `cargo install` puts a binary for the user running this one: `CARGO_HOME` if set, +/// otherwise the platform's home directory plus `.cargo`. +/// +/// Read at runtime and not baked in, because the question is where *this* file sits, and the +/// answer that matters is the one `cargo install --force` would write to now. +/// +/// `USERPROFILE` as well as `HOME`, because this CLI ships for Windows and `HOME` is usually +/// unset there. Getting it wrong is not a crash — `cargo_root` returns `None`, nothing matches, +/// and the answer degrades to [`InstallSource::Unknown`] and the release page — but `Cargo` is +/// the one source of the five that means anything on Windows at all, the other four being +/// Homebrew and macOS bundles, so it is the one worth resolving there. +fn cargo_root() -> Option { + if let Some(home) = std::env::var_os("CARGO_HOME") { + let home = PathBuf::from(home); + if home.is_absolute() { + return Some(home); + } + } + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(|h| PathBuf::from(h).join(".cargo")) +} + +/// How this copy of `gitpic` was installed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InstallSource { + /// Inside a `GitPic.app` that a Homebrew cask owns. The cask links its `bin/gitpic` into + /// the bundle, so upgrading the app upgrades this command — which is why the command to + /// print is the cask's and not something aimed at the CLI. + CaskApp, + /// Inside a `GitPic.app` that Homebrew does not manage: a DMG someone installed by hand. + /// The app updates itself, and this command comes along with it. + App, + /// Homebrew's `gitpic_cli` formula — a real file under a Cellar, no app involved. + Formula, + /// Built by `cargo install`. Not on crates.io, so the only spelling that works is the + /// `--git` one; a bare `cargo install gitpic` fails with "does not exist". + Cargo, + /// An unpacked tarball, a `cargo build` target directory, or anywhere else. This is what + /// this repository's own working copy reports, and it is the honest answer rather than a + /// guess: nothing about the path says how it got there. + Unknown, +} + +impl InstallSource { + /// The one line `gitpic update` prints under the release URL. + /// + /// [`InstallSource::Unknown`] deliberately points at the page rather than naming a + /// command: there is no command that is right for an arbitrary path, and inventing one is + /// how the reader ends up running something that fails. + pub fn upgrade_hint(self) -> String { + match self { + Self::CaskApp => format!("upgrade with `brew upgrade --cask {CASK}`"), + Self::App => { + "this command ships inside GitPic.app — update the app and it comes with it" + .to_string() + } + Self::Formula => format!("upgrade with `brew upgrade {FORMULA}`"), + Self::Cargo => format!( + "upgrade with `cargo install --force --git {} gitpic`", + env!("CARGO_PKG_REPOSITORY") + ), + Self::Unknown => "download the new build from the page above".to_string(), + } + } +} + +/// Classify the running binary, canonicalising first. Falls back to +/// [`InstallSource::Unknown`] rather than guessing when the path cannot be resolved at all. +pub fn detect() -> InstallSource { + match std::env::current_exe().and_then(|p| p.canonicalize()) { + Ok(exe) => classify(&exe, &default_prefixes(), cargo_root().as_deref()), + Err(_) => InstallSource::Unknown, + } +} + +/// An anchor in the same spelling `exe` arrives in. +/// +/// [`detect`] canonicalises the executable, so every comparison in [`classify`] is against a +/// *resolved* path — while the anchors are built straight out of the environment and are not. +/// Comparing the two spellings directly worked only while they happened to agree, and there are +/// two ways they do not: +/// +/// - **Windows, unconditionally.** `std::fs::canonicalize` returns an extended-length +/// `\\?\C:\…` path there, so `exe.parent()` can never equal a `C:\Users\x\.cargo\bin` built +/// from `CARGO_HOME` — every ordinary `cargo install` was classified +/// [`InstallSource::Unknown`] and sent to the release page. Documented behaviour rather than +/// something measured here; there is no Windows in this checkout to measure on. +/// - **Any platform, when a root is reached through a symlink.** Canonicalising the executable +/// resolves the link while the raw anchor still names it. Measured, on Unix, by +/// `anchors_are_compared_in_the_same_spelling_as_the_exe`. +/// +/// Falls back to the path as given when it cannot be resolved, which is the right answer rather +/// than a compromise: an anchor that does not exist cannot have `exe` underneath it, so the +/// comparison should fail — and it does, on the raw spelling, exactly as before. That fallback +/// is also what lets [`classify`]'s table be written against synthesized paths. +fn resolved(path: PathBuf) -> PathBuf { + path.canonicalize().unwrap_or(path) +} + +/// The pure half, so the table can be tested without installing anything. +/// +/// `exe` is expected to be canonical — [`detect`] guarantees it. The order of the tests is not +/// arbitrary: an app bundle is checked first because a cask's bundle sits in an Applications +/// directory with no Cellar above it, while a Cellar path never contains a bundle, so only the +/// bundle case needs the Caskroom lookup to refine it. +/// +/// **Both remaining tests are anchored to the exact directory an installer writes, and were +/// not.** They first asked whether `Cellar` or `.cargo` appeared *anywhere* in the canonicalised +/// path, which is true of `/Users/x/Cellar/gitpic` and of `~/backup/.cargo/bin/gitpic`. Anchoring +/// to the roots fixed those but was still one level too loose: `/Cellar` matches any +/// formula's keg, and the whole of `CARGO_HOME` includes `registry/src` and `git/checkouts` — +/// one buildable source tree per dependency ever fetched. A `target/release/gitpic` built in one +/// of those was reported as a `cargo install`, and `cargo install --force` would have rewritten +/// `CARGO_HOME/bin/gitpic`, a different file from the one running. Every one of those prints a +/// command that does not upgrade the binary that printed it, which is the whole thing this module +/// exists to avoid. A path under no directory an installer actually writes is +/// [`InstallSource::Unknown`], which points at the page. +fn classify(exe: &Path, prefixes: &[PathBuf], cargo_root: Option<&Path>) -> InstallSource { + if let Some(bundle) = app_bundle(exe) { + return if cask_owns(bundle, prefixes) { + InstallSource::CaskApp + } else { + InstallSource::App + }; + } + // `Cellar/gitpic_cli`, not `Cellar`: the question is whether *our* formula installed this + // file, and `brew upgrade gitpic_cli` is only the answer if it did. A `gitpic` sitting under + // some other formula's Cellar is not ours to upgrade. + if prefixes + .iter() + .any(|prefix| exe.starts_with(resolved(prefix.join("Cellar").join(FORMULA)))) + { + return InstallSource::Formula; + } + // The `bin` directory itself, not the whole of `CARGO_HOME`. `cargo install` writes exactly + // one place, and `CARGO_HOME` also holds sources that can be *built* — `registry/src` alone + // has one unpacked tree per dependency ever fetched, and `git/checkouts` holds clones. A + // `target/release/gitpic` inside one of those is not something `cargo install --force` + // replaces: that would rewrite `CARGO_HOME/bin/gitpic`, a different file from the one + // running. Comparing the parent directory also means the executable's name is not spelled + // here, so Windows' `gitpic.exe` needs no separate case. + if cargo_root.is_some_and(|root| exe.parent() == Some(resolved(root.join("bin")).as_path())) { + return InstallSource::Cargo; + } + InstallSource::Unknown +} + +/// The innermost `.app` ancestor of `exe`, which for this layout is the bundle root: +/// `…/GitPic.app/Contents/Resources/gitpic` has exactly one. +fn app_bundle(exe: &Path) -> Option<&Path> { + exe.ancestors() + .find(|p| p.extension().is_some_and(|e| e == "app")) +} + +/// Whether any `Caskroom/gitpic/*/GitPic.app` under `prefixes` resolves to `bundle`. +/// +/// This is the reverse of the test Claude Code can use on itself. Its binary really lives in +/// the Caskroom, so `execPath()` contains `/Caskroom/`; GitPic's cask uses an `app` stanza, +/// which *moves* the bundle to an Applications directory and leaves a symlink pointing back at +/// it. So the evidence is a link that resolves to us, and the check works at any `--appdir` +/// because the link follows wherever the bundle went. +fn cask_owns(bundle: &Path, prefixes: &[PathBuf]) -> bool { + prefixes.iter().any(|prefix| { + let versions = prefix.join("Caskroom").join(CASK); + let Ok(entries) = std::fs::read_dir(&versions) else { + return false; + }; + entries.flatten().any(|entry| { + entry + .path() + .join("GitPic.app") + .canonicalize() + .is_ok_and(|target| target == bundle) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The case the un-canonicalised version gets wrong, stated as a path table. Each row is a + /// real shape: the cask's symlink target, the formula's Cellar file, a cargo bin, a build + /// directory. + /// + /// **The bundle rows are scanned against a prefix that does not exist, and that is not + /// laziness.** `cask_owns` touches the filesystem, so handing these rows the real Homebrew + /// prefixes makes the answer depend on the machine: on a developer's Mac that has the cask + /// installed, `/Applications/GitPic.app` is genuinely `CaskApp` and the row asserting `App` + /// fails — measured, exactly that way round. Ownership is covered on a synthesized tree in + /// `a_caskroom_link_is_what_makes_a_bundle_the_casks` instead. The non-bundle rows use the + /// real prefixes freely, because `starts_with` is path arithmetic and reads no disk. + #[test] + fn paths_map_to_the_source_that_installed_them() { + let unowned = vec![PathBuf::from("/nonexistent-prefix")]; + let brews = vec![PathBuf::from("/opt/homebrew"), PathBuf::from("/usr/local")]; + let cargo = PathBuf::from("/Users/x/.cargo"); + for path in [ + "/Applications/GitPic.app/Contents/Resources/gitpic", + "/Users/x/Applications/GitPic.app/Contents/Resources/gitpic", + ] { + assert_eq!( + classify(Path::new(path), &unowned, Some(&cargo)), + InstallSource::App, + "{path}" + ); + } + for (path, want) in [ + ( + "/opt/homebrew/Cellar/gitpic_cli/0.20.9/bin/gitpic", + InstallSource::Formula, + ), + ( + "/usr/local/Cellar/gitpic_cli/0.20.9/bin/gitpic", + InstallSource::Formula, + ), + ("/Users/x/.cargo/bin/gitpic", InstallSource::Cargo), + ( + "/Users/x/src/gitpic/target/release/gitpic", + InstallSource::Unknown, + ), + ("/usr/local/bin/gitpic", InstallSource::Unknown), + ] { + assert_eq!( + classify(Path::new(path), &brews, Some(&cargo)), + want, + "{path}" + ); + } + } + + /// `Cellar` and `.cargo` are only meaningful at the exact directory an installer writes to, + /// and looser matches said otherwise. Every row here names one of those words while + /// belonging to a place no installer would replace, and each would otherwise be handed a + /// command that upgrades some *other* file — or none. + #[test] + fn a_familiar_word_in_the_path_is_not_evidence_of_an_installer() { + let brews = vec![PathBuf::from("/opt/homebrew")]; + let cargo = PathBuf::from("/Users/x/.cargo"); + for path in [ + // Not under any prefix's Cellar. + "/Users/x/Cellar/gitpic", + "/Users/x/Downloads/Cellar/gitpic_cli/0.20.9/bin/gitpic", + // A different Homebrew's Cellar, which this machine cannot upgrade from. + "/usr/local/Cellar/gitpic_cli/0.20.9/bin/gitpic", + // Under *a* Cellar, but not our formula's — `brew upgrade gitpic_cli` is not the + // command that put this here. + "/opt/homebrew/Cellar/some-other-tool/1.0.0/bin/gitpic", + // Copied out of a backup: `cargo install --force` would replace a *different* file. + "/Users/x/backup/.cargo/bin/gitpic", + "/Users/y/.cargo/bin/gitpic", + // Built inside CARGO_HOME, which holds one source tree per dependency ever fetched. + // `cargo install --force` writes `.cargo/bin/gitpic`, not this. + "/Users/x/.cargo/registry/src/index.crates.io-1949cf8/gitpic-0.20.9/target/release/gitpic", + "/Users/x/.cargo/git/checkouts/gitpic-abc123/9f8e7d6/target/release/gitpic", + ] { + assert_eq!( + classify(Path::new(path), &brews, Some(&cargo)), + InstallSource::Unknown, + "{path}" + ); + } + } + + /// **The anchors have to be compared in the same spelling as `exe`, and they were not.** + /// + /// [`detect`] canonicalises `exe` and then hands [`classify`] anchors built straight out of + /// the environment, so every comparison here assumes the two spellings agree. They do not + /// always agree, and where they diverge the answer is [`InstallSource::Unknown`] and the + /// release page instead of the command that would actually work. + /// + /// This row measures the case that can be measured on a Unix box: a `CARGO_HOME` or a + /// Homebrew prefix reached through a symlink, where canonicalising the executable resolves + /// the link and the raw anchor still names it. The motivating case is Windows, where it is + /// unconditional rather than a configuration — `std::fs::canonicalize` returns an + /// extended-length `\\?\C:\…` path there, so `exe.parent()` could never equal a + /// `C:\Users\x\.cargo\bin` built from the environment, and every ordinary + /// `cargo install` on Windows was classified `Unknown`. Not measured here — there is no + /// Windows to measure on — but it is the same comparison this row exercises. + #[cfg(unix)] + #[test] + fn anchors_are_compared_in_the_same_spelling_as_the_exe() { + let root = std::env::temp_dir().join(format!("gitpic-anchor-{}", std::process::id())); + std::fs::remove_dir_all(&root).ok(); + std::fs::create_dir_all(&root).unwrap(); + + // `CARGO_HOME=/cargo-link`, with the real tree at `/real/cargo`. + let cargo_real = root.join("real/cargo"); + std::fs::create_dir_all(cargo_real.join("bin")).unwrap(); + std::fs::write(cargo_real.join("bin/gitpic"), "").unwrap(); + let cargo_link = root.join("cargo-link"); + std::os::unix::fs::symlink(&cargo_real, &cargo_link).unwrap(); + let exe = cargo_link.join("bin/gitpic").canonicalize().unwrap(); + assert_eq!( + classify(&exe, &[], Some(&cargo_link)), + InstallSource::Cargo, + "a cargo bin reached through a symlinked CARGO_HOME is still a cargo install" + ); + + // The same for a Homebrew prefix behind a link. + let brew_real = root.join("real/brew"); + let keg = brew_real.join("Cellar/gitpic_cli/0.20.9/bin"); + std::fs::create_dir_all(&keg).unwrap(); + std::fs::write(keg.join("gitpic"), "").unwrap(); + let brew_link = root.join("brew-link"); + std::os::unix::fs::symlink(&brew_real, &brew_link).unwrap(); + let exe = brew_link + .join("Cellar/gitpic_cli/0.20.9/bin/gitpic") + .canonicalize() + .unwrap(); + assert_eq!( + classify(&exe, std::slice::from_ref(&brew_link), None), + InstallSource::Formula, + "a keg under a symlinked HOMEBREW_PREFIX is still the formula's" + ); + + std::fs::remove_dir_all(&root).ok(); + } + + /// The same property, on **every** platform including the one it matters most for. + /// + /// The symlink row above is `cfg(unix)`, so it never ran on the Windows runner — where the + /// divergence is unconditional and the whole `Cargo` case was broken. This needs no symlink + /// and no `cfg`, because `std::env::temp_dir()` is already spelled non-canonically on two of + /// the three platforms CI builds: measured, macOS returns `/var/folders/…` which canonicalises + /// to `/private/var/folders/…`, and Windows canonicalises to an extended-length `\\?\C:\…` + /// while the environment gives a plain `C:\…`. On Linux `/tmp` is usually already canonical, + /// so there it asserts the ordinary case still holds. + /// + /// Using `temp_dir()` *as the anchor without canonicalising it* is the point: that is exactly + /// how `cargo_root` and `default_prefixes` hand their values over — straight from the + /// environment, unresolved. + #[test] + fn an_anchor_from_the_environment_need_not_be_spelled_canonically() { + let root = std::env::temp_dir().join(format!("gitpic-spelling-{}", std::process::id())); + std::fs::remove_dir_all(&root).ok(); + let cargo = root.join("cargo"); + let cargo_bin = cargo.join("bin"); + std::fs::create_dir_all(&cargo_bin).unwrap(); + std::fs::write(cargo_bin.join("gitpic"), "").unwrap(); + + // What `detect` hands over: a canonical exe, and an anchor exactly as the environment + // spelled it. + let exe = cargo_bin.join("gitpic").canonicalize().unwrap(); + assert_eq!( + classify(&exe, &[], Some(&cargo)), + InstallSource::Cargo, + "exe {} vs anchor {}", + exe.display(), + cargo.display() + ); + + let prefix = root.join("brew"); + // Joined a component at a time: this test runs on the Windows runner too, and that is + // the platform it exists for. + let keg = prefix + .join("Cellar") + .join(FORMULA) + .join("0.20.9") + .join("bin"); + std::fs::create_dir_all(&keg).unwrap(); + std::fs::write(keg.join("gitpic"), "").unwrap(); + let exe = keg.join("gitpic").canonicalize().unwrap(); + assert_eq!( + classify(&exe, std::slice::from_ref(&prefix), None), + InstallSource::Formula, + "exe {} vs prefix {}", + exe.display(), + prefix.display() + ); + + std::fs::remove_dir_all(&root).ok(); + } + + /// A bundle in a user's own Applications directory, or at a custom `--appdir`, is still a + /// bundle. The cask supports both and the app's own installer accepts both. + #[test] + fn a_bundle_is_a_bundle_wherever_it_was_installed() { + let none = vec![PathBuf::from("/nonexistent-prefix")]; + for path in [ + "/Users/x/Applications/GitPic.app/Contents/Resources/gitpic", + "/Users/x/Apps/GitPic.app/Contents/Resources/gitpic", + ] { + assert_eq!( + classify(Path::new(path), &none, None), + InstallSource::App, + "{path}" + ); + } + } + + /// The distinction the hint turns on, built as the real two-part shape: a bundle, and a + /// `Caskroom/gitpic//GitPic.app` symlink resolving to it. Without the link the + /// same bundle is `App`, and printing a cask command for it would fail with + /// "Cask 'gitpic' is not installed". + /// + /// **Unix only, because it creates symlinks.** `std::os::unix::fs::symlink` does not exist + /// on Windows, so this did not compile there at all — and the CLI is built and tested for + /// Windows, which is where CI caught it. Gating rather than porting to + /// `std::os::windows::fs::symlink_dir`: the subject is a macOS cask installing a macOS app + /// bundle, so there is nothing for the Windows build to learn from it. Everything above is + /// pure path arithmetic and stays covered on every platform. + #[cfg(unix)] + #[test] + fn a_caskroom_link_is_what_makes_a_bundle_the_casks() { + let root = std::env::temp_dir().join(format!("gitpic-src-{}", std::process::id())); + // Cleared going in as well as coming out: the name reuses the pid, and the cleanup at + // the end is skipped when an assertion panics, so a failed run would otherwise leave a + // tree that makes the *next* run fail somewhere unrelated. + std::fs::remove_dir_all(&root).ok(); + let bundle = root.join("Applications/GitPic.app"); + let exe = bundle.join("Contents/Resources/gitpic"); + let caskroom = root.join("prefix/Caskroom/gitpic/0.20.9"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::create_dir_all(&caskroom).unwrap(); + std::fs::write(&exe, "").unwrap(); + let prefixes = vec![root.join("prefix")]; + + // `classify` needs a canonical path, which is what `detect` hands it. + let exe = exe.canonicalize().unwrap(); + let bundle = bundle.canonicalize().unwrap(); + assert_eq!(classify(&exe, &prefixes, None), InstallSource::App); + + std::os::unix::fs::symlink(&bundle, caskroom.join("GitPic.app")).unwrap(); + assert_eq!(classify(&exe, &prefixes, None), InstallSource::CaskApp); + + // A link that points somewhere else is not evidence about this bundle. + std::fs::remove_file(caskroom.join("GitPic.app")).unwrap(); + let other = root.join("Applications/Other.app"); + std::fs::create_dir_all(&other).unwrap(); + std::os::unix::fs::symlink(&other, caskroom.join("GitPic.app")).unwrap(); + assert_eq!(classify(&exe, &prefixes, None), InstallSource::App); + + std::fs::remove_dir_all(&root).ok(); + } + + /// Every source names something the reader can act on, and only the ones that have a + /// command name one. `Unknown` pointing at a command would be inventing it. + #[test] + fn every_hint_is_actionable_and_only_some_are_commands() { + for source in [ + InstallSource::CaskApp, + InstallSource::App, + InstallSource::Formula, + InstallSource::Cargo, + InstallSource::Unknown, + ] { + let hint = source.upgrade_hint(); + assert!(!hint.is_empty(), "{source:?}"); + assert!(!hint.contains(" "), "{source:?} is doubly spaced"); + } + assert!(InstallSource::CaskApp + .upgrade_hint() + .contains("--cask gitpic")); + assert!(InstallSource::Formula.upgrade_hint().contains("gitpic_cli")); + // Not on crates.io, so the bare spelling would fail: the hint has to carry `--git`. + assert!(InstallSource::Cargo.upgrade_hint().contains("--git")); + assert!(!InstallSource::Unknown.upgrade_hint().contains('`')); + assert!(!InstallSource::App.upgrade_hint().contains("brew")); + } +} diff --git a/src/main.rs b/src/main.rs index 40f8e8c..40f44d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ mod error; mod github; mod history; mod imageproc; +mod install_source; mod link; mod naming; mod oauth; @@ -92,9 +93,13 @@ async fn dispatch(cli: &Cli, mode: Mode) -> Result { Some(Command::Skill { action }) => commands::skill::run(action, mode), // Config-free too, and pointedly so: "is there a newer gitpic" is worth answering // on a machine whose config is broken — the fix may well be in the release the - // user does not have yet. It reads no credential either; the endpoint is public. + // user does not have yet. It does read the image-host credential when there is one, + // to raise GitHub's rate limit, but every way that can fail collapses to an + // anonymous request (`release::best_effort_token`), so a broken login cannot stop + // either of these answering. Some(Command::Update { action }) => match action { cli::UpdateAction::Check => commands::update::run(mode).await, + cli::UpdateAction::Cask => commands::update::cask(mode).await, }, Some(Command::Doctor { .. }) => { diff --git a/src/release.rs b/src/release.rs index a7d2c74..3e43f88 100644 --- a/src/release.rs +++ b/src/release.rs @@ -34,6 +34,7 @@ //! credential, only against the compile-time base, and never on a redirect. use crate::error::{AppError, ErrorCode, Result}; +use base64::Engine; use serde::{Deserialize, Serialize}; use std::time::Duration; @@ -281,14 +282,82 @@ fn best_effort_token() -> Option { } /// One attempt, and enough of its outcome for the caller to decide about a second. -enum Attempt { - Ok(LatestRelease), +/// +/// Generic over the decoded body because two endpoints share it: the release feed and the +/// tap's cask file. What is worth sharing is not the request — that part is three headers — +/// but the retry rule and its third branch; see [`get_json`]. +enum Attempt { + Ok(T), /// GitHub rejected the credential itself — the one outcome worth retrying anonymously, /// because a stale image-host token must not be able to break update checks. CredentialRejected, Failed(AppError), } +/// The client both lookups use: bounded, and structurally unable to carry a credential to +/// another host. +/// +/// Nothing either endpoint asks for redirects — `releases/latest` and a contents read both +/// answer 200 directly — so refusing to follow one costs nothing and makes "the credential +/// cannot travel" structural rather than a property of whichever reqwest release is linked. +/// reqwest does strip sensitive headers across hosts on its own; this does not depend on it. +fn client() -> Result { + reqwest::Client::builder() + .user_agent(UA) + .timeout(REQUEST_TIMEOUT) + .connect_timeout(CONNECT_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|e| AppError::network(format!("http client: {e}"))) +} + +/// One GET carrying the credential, and — only if GitHub refused *the credential* — one more +/// without it. +/// +/// Shared rather than written twice because the interesting part is the third branch. An +/// anonymous retry has no credential left to reject, so that arm is unreachable in practice; +/// it is still stated instead of `unreachable!()`, because a panic inside a background update +/// check would be a worse answer than a sentence. +/// What a request was for, carried far enough down to describe its own failures. +/// +/// Both fields used to be constants inside `status_error`, which was written when this module +/// had one endpoint. Generalising the client for the tap lookup left them behind, so a 404 on +/// `Casks/gitpic.rb` reported `tarnish233/gitpic has published no releases yet` — wrong +/// repository, wrong resource, wrong failure, from a command that never touched the release +/// feed. Every arm now names the endpoint it actually failed on, which is what makes one log +/// line enough to tell "the tap moved" from "GitHub is down". +#[derive(Clone, Copy)] +struct Endpoint<'a> { + /// What the caller was doing, in the imperative: "check for updates". + what: &'a str, + /// What a 404 means *here*, as a whole sentence. A missing release feed and a missing cask + /// file are different facts and neither is worth guessing from a status code alone. + missing: &'a str, +} + +async fn get_json( + client: &reqwest::Client, + url: &str, + token: Option<&str>, + endpoint: Endpoint<'_>, +) -> Result { + let what = endpoint.what; + match fetch(client, url, token, endpoint).await { + Attempt::Ok(value) => Ok(value), + // Anonymous retry, and only from here: the first attempt carried a credential that + // GitHub refused, which says nothing about whether the resource is readable. + Attempt::CredentialRejected => match fetch(client, url, None, endpoint).await { + Attempt::Ok(value) => Ok(value), + Attempt::Failed(e) => Err(e), + Attempt::CredentialRejected => Err(AppError::new( + ErrorCode::General, + format!("{what}: GitHub rejected an anonymous request as unauthorised"), + )), + }, + Attempt::Failed(e) => Err(e), + } +} + /// The same, against an explicit API base and with an explicit credential. /// /// Private, and unlike [`crate::github`]'s equivalent the reason is not only the credential @@ -302,45 +371,29 @@ enum Attempt { /// on CI and fail on any developer who had run `gitpic auth login` — a security assertion /// whose verdict depends on the machine is not one. async fn check_against(api: &str, token: Option<&str>) -> Result { - let client = reqwest::Client::builder() - .user_agent(UA) - .timeout(REQUEST_TIMEOUT) - .connect_timeout(CONNECT_TIMEOUT) - // Nothing here redirects — `releases/latest` answers 200 directly — so refusing to - // follow one costs nothing and makes "the credential cannot travel to another host" - // structural rather than a property of whichever reqwest release is linked. reqwest - // does strip sensitive headers across hosts on its own; this does not depend on it. - .redirect(reqwest::redirect::Policy::none()) - .build() - .map_err(|e| AppError::network(format!("http client: {e}")))?; - + let client = client()?; let url = format!("{api}/repos/{RELEASES_REPO}/releases/latest"); - - let latest = match fetch(&client, &url, token).await { - Attempt::Ok(latest) => latest, - // Anonymous retry, and only from here: the first attempt carried a credential that - // GitHub refused, which says nothing about whether the release feed is readable. - Attempt::CredentialRejected => match fetch(&client, &url, None).await { - Attempt::Ok(latest) => latest, - Attempt::Failed(e) => return Err(e), - // Unreachable in practice — there is no credential left to reject — but stated - // rather than `unreachable!()`, because a panic in a background update check - // would be a worse answer than an error message. - Attempt::CredentialRejected => { - return Err(AppError::new( - ErrorCode::General, - "check for updates: GitHub rejected an anonymous request as unauthorised", - )) - } + let latest: LatestRelease = get_json( + &client, + &url, + token, + Endpoint { + what: "check for updates", + missing: &format!("{RELEASES_REPO} has published no releases yet"), }, - Attempt::Failed(e) => return Err(e), - }; - + ) + .await?; report(CURRENT, latest) } /// One request, decoded, with the credential attached only if there is one. -async fn fetch(client: &reqwest::Client, url: &str, token: Option<&str>) -> Attempt { +async fn fetch( + client: &reqwest::Client, + url: &str, + token: Option<&str>, + endpoint: Endpoint<'_>, +) -> Attempt { + let what = endpoint.what; let mut req = client .get(url) .header("Accept", "application/vnd.github+json") @@ -350,7 +403,7 @@ async fn fetch(client: &reqwest::Client, url: &str, token: Option<&str>) -> Atte } let resp = match req.send().await { Ok(resp) => resp, - Err(e) => return Attempt::Failed(AppError::network(format!("check for updates: {e}"))), + Err(e) => return Attempt::Failed(AppError::network(format!("{what}: {e}"))), }; let status = resp.status(); @@ -364,14 +417,131 @@ async fn fetch(client: &reqwest::Client, url: &str, token: Option<&str>) -> Atte // `AppError::with_retry_hint` existed unused for want of a number. let headers = resp.headers().clone(); let body = resp.text().await.unwrap_or_default(); - return Attempt::Failed(status_error(status, &headers, &body)); + return Attempt::Failed(status_error(status, &headers, &body, endpoint)); + } + match resp.json::().await { + Ok(value) => Attempt::Ok(value), + Err(e) => Attempt::Failed(AppError::network(format!("{what}: unreadable reply: {e}"))), + } +} + +/// Where the Homebrew cask that installs GitPic is defined. +/// +/// A constant for the same reason [`RELEASES_REPO`] is one, and the reason bites harder here: +/// the version this reads is shown in GitPic's update sheet *next to a command the user is +/// being told to type into a terminal*. A settable origin would be a way to put an attacker's +/// version string — and with it an attacker's argument for running something — in front of the +/// user inside GitPic's own window. +const TAP_REPO: &str = "tarnish233/homebrew-tap"; +/// The cask, not the formula: this answers "what would `brew upgrade --cask gitpic` install". +const TAP_CASK_PATH: &str = "Casks/gitpic.rb"; + +/// The cask and the formula the tap defines. +/// +/// Here rather than beside the code that prints them, because they are one fact with two +/// readers — [`crate::install_source`] names them in an upgrade command and builds a Caskroom +/// path out of the cask token, and [`tap_cask`] echoes it back to the app so the app does not +/// spell it a third time. They are separate installs, and `brew upgrade` on the wrong one +/// reports "no available formula". +pub(crate) const CASK: &str = "gitpic"; +pub(crate) const FORMULA: &str = "gitpic_cli"; + +/// What the tap's cask currently declares. +/// +/// Separate from [`UpdateReport`] and from a separate request on purpose: this costs a round +/// trip that only a Homebrew-managed install has any use for, and folding it into +/// `update check` would spend it on every check for everybody. +#[derive(Debug, Serialize)] +pub struct TapCask { + pub ok: bool, + /// Echoed so the caller can build `brew upgrade --cask ` without hardcoding it. + pub cask: String, + /// `null` when the file was read but declares no version this can compare — see + /// [`cask_version`]. Distinct from an error, which means the file was not read at all; + /// both leave the app unable to tell, so both send it to the same outcome. + pub version: Option, +} + +/// The Contents API reply, narrowed to what this reads. +#[derive(Deserialize)] +struct ContentsFile { + content: String, + encoding: String, +} + +/// Ask the tap what version its cask declares. +pub async fn tap_cask() -> Result { + tap_cask_against(API, best_effort_token().as_deref()).await +} + +/// The same, against an explicit API base and credential — the seam every test uses, for the +/// reasons on [`check_against`]. +async fn tap_cask_against(api: &str, token: Option<&str>) -> Result { + let client = client()?; + let url = format!("{api}/repos/{TAP_REPO}/contents/{TAP_CASK_PATH}"); + let what = "read the Homebrew tap"; + let file: ContentsFile = get_json( + &client, + &url, + token, + Endpoint { + what, + // The likeliest 404 by far, and the one worth naming: Homebrew moved third-party + // casks into sharded directories (`Casks/g/gitpic.rb`), so a tap that follows suit + // makes this path vanish while the repository stays perfectly readable. + missing: &format!("{TAP_REPO} has no {TAP_CASK_PATH}"), + }, + ) + .await?; + + // GitHub sends `encoding: "none"` for a file too large to inline. A cask is a few + // kilobytes so this should not happen, and saying so beats decoding an empty string into + // "the tap declares nothing". + if file.encoding != "base64" { + return Err(AppError::general(format!( + "{what}: the cask came back {}-encoded, which this cannot read", + file.encoding + ))); } - match resp.json::().await { - Ok(latest) => Attempt::Ok(latest), - Err(e) => Attempt::Failed(AppError::network(format!( - "check for updates: unreadable reply: {e}" - ))), + // The Contents API wraps its base64 at column 60, and the decoder rejects the newlines. + let packed: String = file + .content + .chars() + .filter(|c| !c.is_whitespace()) + .collect(); + let bytes = base64::engine::general_purpose::STANDARD + .decode(&packed) + .map_err(|e| AppError::general(format!("{what}: the cask is not readable base64: {e}")))?; + let text = String::from_utf8(bytes) + .map_err(|e| AppError::general(format!("{what}: the cask is not UTF-8: {e}")))?; + + Ok(TapCask { + ok: true, + cask: CASK.to_string(), + version: cask_version(&text).map(str::to_string), + }) +} + +/// The version a cask declares, or `None`. +/// +/// Deliberately not a Ruby parser: it takes the first `version` stanza that is a plain quoted +/// literal parsing as three numbers, and answers `None` for everything else — an +/// interpolation, `version :latest`, or Homebrew's comma-separated `version "1.2,345"` form +/// (`Cask#version.csv`). +/// +/// `None` is the safe answer and a guess is not. It reaches the app as "could not tell", which +/// shows the upgrade command with a caveat; a version invented out of an unparseable string +/// could instead show 「已是 Homebrew 提供的最新版本」 over a real update, which is the one +/// outcome that hides a pending upgrade behind a reassuring sentence. +fn cask_version(cask: &str) -> Option<&str> { + for line in cask.lines() { + let Some(rest) = line.trim().strip_prefix("version ") else { + continue; + }; + let literal = rest.trim().strip_prefix('"')?.split('"').next()?; + return Version::parse(literal).map(|_| literal); } + None } /// Turn a fetched release into the report, or explain why it cannot be compared. @@ -489,26 +659,25 @@ fn status_error( status: reqwest::StatusCode, headers: &reqwest::header::HeaderMap, body: &str, + endpoint: Endpoint<'_>, ) -> AppError { + let Endpoint { what, missing } = endpoint; let code = status.as_u16(); match code { - 404 => AppError::new( - ErrorCode::RemoteNotFound, - format!("{RELEASES_REPO} has published no releases yet"), - ), + 404 => AppError::new(ErrorCode::RemoteNotFound, missing.to_string()), // Reachable only when the anonymous retry is itself refused as unauthorised, since a // rejected credential is retried without one before it gets here. Named honestly // rather than folded into `General`: 401 has exactly one meaning. 401 => AppError::new( ErrorCode::AuthFailed, - "check for updates: GitHub rejected the request as unauthorised".to_string(), + format!("{what}: GitHub rejected the request as unauthorised"), ), // Unauthenticated api.github.com allows 60 requests an hour per address. One // daily check cannot reach that alone, but it shares the quota with everything // else on the network, so this is a state real users will meet. _ if is_rate_limited(code, headers, body) => AppError::new( ErrorCode::RateLimited, - "GitHub rate-limited the update check; try again later".to_string(), + format!("GitHub rate-limited the request to {what}; try again later"), ) .with_retry_hint(retry_after_secs(headers)), // A 403 that is not a rate limit. Named as itself rather than dressed up as one: @@ -516,7 +685,7 @@ fn status_error( // "try again later" leaves nothing to act on. 403 => AppError::new( ErrorCode::General, - format!("check for updates: GitHub refused the request (403){}", { + format!("{what}: GitHub refused the request (403){}", { let detail = body.trim(); if detail.is_empty() { String::new() @@ -527,7 +696,7 @@ fn status_error( ), _ => AppError::new( ErrorCode::General, - format!("check for updates: GitHub returned {status}"), + format!("{what}: GitHub returned {status}"), ), } } @@ -661,21 +830,34 @@ mod tests { map } + /// The endpoint every `status_error` row below is asked about. + /// + /// One fixture rather than the real constants, so these rows assert the *mapping* from + /// status to `ErrorCode` and not the wording of either endpoint. What the wording has to do + /// is stay attached to its own endpoint, which is what + /// `a_tap_failure_does_not_describe_the_release_feed` pins. + fn probe() -> Endpoint<'static> { + Endpoint { + what: "do the thing", + missing: "the thing is not there", + } + } + #[test] fn statuses_map_to_the_codes_a_caller_can_act_on() { use reqwest::StatusCode; let none = headers(&[]); assert_eq!( - status_error(StatusCode::NOT_FOUND, &none, "").code, + status_error(StatusCode::NOT_FOUND, &none, "", probe()).code, ErrorCode::RemoteNotFound ); assert_eq!( - status_error(StatusCode::INTERNAL_SERVER_ERROR, &none, "").code, + status_error(StatusCode::INTERNAL_SERVER_ERROR, &none, "", probe()).code, ErrorCode::General ); // 429 is a rate limit whatever else it carries. assert_eq!( - status_error(StatusCode::TOO_MANY_REQUESTS, &none, "").code, + status_error(StatusCode::TOO_MANY_REQUESTS, &none, "", probe()).code, ErrorCode::RateLimited ); } @@ -693,6 +875,7 @@ mod tests { reqwest::StatusCode::FORBIDDEN, &headers(&[]), "Request forbidden by administrative rules", + probe(), ); assert_eq!(err.code, ErrorCode::General, "{}", err.message); assert!( @@ -731,7 +914,7 @@ mod tests { ), ]; for (what, hdrs, body) in cases { - let err = status_error(reqwest::StatusCode::FORBIDDEN, &hdrs, body); + let err = status_error(reqwest::StatusCode::FORBIDDEN, &hdrs, body, probe()); assert_eq!(err.code, ErrorCode::RateLimited, "{what}: {}", err.message); } } @@ -744,6 +927,7 @@ mod tests { reqwest::StatusCode::FORBIDDEN, &headers(&[("retry-after", "90")]), "", + probe(), ); assert!( err.message.contains("retry after 90s"), @@ -764,6 +948,7 @@ mod tests { ("x-ratelimit-reset", &soon.to_string()), ]), "", + probe(), ); assert_eq!(err.code, ErrorCode::RateLimited); let secs: u64 = err @@ -789,6 +974,7 @@ mod tests { ("x-ratelimit-reset", "1000000000"), ]), "", + probe(), ); assert_eq!(err.code, ErrorCode::RateLimited); assert!( @@ -804,15 +990,147 @@ mod tests { 595..=600 } - /// The update feed is fixed at compile time. A config key or an environment variable - /// here would let something else choose the repository whose release notes get - /// rendered inside GitPic's window. + /// Both origins are fixed at compile time. A config key or an environment variable here + /// would let something else choose the repository whose release notes get rendered inside + /// GitPic's window — and, for the tap, the version string shown beside a command the user + /// is being told to run. #[test] fn the_release_feed_is_a_compile_time_constant() { assert_eq!(RELEASES_REPO, "tarnish233/gitpic"); + assert_eq!(TAP_REPO, "tarnish233/homebrew-tap"); + assert_eq!(TAP_CASK_PATH, "Casks/gitpic.rb"); assert!(API.starts_with("https://")); } + /// Two endpoints share one client, so each has to describe its own failures. + /// + /// `status_error` was written when this module had a single endpoint and hardcoded the + /// release feed into three of its arms. Generalising the client for the tap lookup left them + /// alone, so a 404 on the cask reported that `tarnish233/gitpic has published no releases + /// yet` — the wrong repository and the wrong resource, from a command that never touched the + /// release feed — and a consumer branching on `RemoteNotFound` for the feed started + /// receiving it from the tap as well. + #[test] + fn a_tap_failure_does_not_describe_the_release_feed() { + let none = headers(&[]); + let tap = Endpoint { + what: "read the Homebrew tap", + missing: &format!("{TAP_REPO} has no {TAP_CASK_PATH}"), + }; + let missing = status_error(reqwest::StatusCode::NOT_FOUND, &none, "", tap); + assert_eq!(missing.code, ErrorCode::RemoteNotFound); + assert!( + missing.message.contains(TAP_REPO) && missing.message.contains(TAP_CASK_PATH), + "a 404 has to name the file that is missing: {}", + missing.message + ); + assert!( + !missing.message.contains(RELEASES_REPO), + "and must not name the release feed: {}", + missing.message + ); + // The same for every other arm: they all used to say "check for updates". + for status in [ + reqwest::StatusCode::UNAUTHORIZED, + reqwest::StatusCode::TOO_MANY_REQUESTS, + reqwest::StatusCode::FORBIDDEN, + reqwest::StatusCode::INTERNAL_SERVER_ERROR, + ] { + let err = status_error(status, &none, "", tap); + assert!( + !err.message.contains("check for updates"), + "{status} still blames the update check: {}", + err.message + ); + } + } + + /// Not a Ruby parser, and the rows that matter are the refusals. A csv version is a real + /// Homebrew spelling (`Cask#version.csv`) and comparing against `"1.2,345"` as though it + /// were a version would let the app claim 「已是最新」 over a pending upgrade. + #[test] + fn a_cask_version_is_read_only_when_it_is_plainly_comparable() { + assert_eq!( + cask_version("cask \"gitpic\" do\n version \"0.20.9\"\n"), + Some("0.20.9") + ); + // Whatever else is in the file, including a comment that mentions the word. + assert_eq!( + cask_version("# the version below is rewritten by the tap\n version \"1.2.3\"\nend"), + Some("1.2.3") + ); + for refused in [ + " version \"1.2,345\"\n", // csv — two fields, not a version + " version :latest\n", // a symbol, not a literal + " version \"#{ENV['V']}\"\n", // interpolated + " version \"0.20\"\n", // not three components + " version \"0.20.0-rc1\"\n", // prerelease, which `Version` refuses + "cask \"gitpic\" do\nend\n", // no stanza at all + "", + ] { + assert_eq!(cask_version(refused), None, "{refused:?}"); + } + } + + /// The happy path, against the wire shape GitHub actually sends: base64 **wrapped**, which + /// the decoder rejects until the whitespace is stripped. Encoding it unwrapped here would + /// have tested a reply this code never receives. + #[tokio::test] + async fn reads_the_version_the_tap_declares() { + let cask = "cask \"gitpic\" do\n version \"9.9.9\"\n sha256 \"ab\"\nend\n"; + let encoded = base64::engine::general_purpose::STANDARD.encode(cask); + let mid = encoded.len() / 2; + let wrapped = format!("{}\\n{}", &encoded[..mid], &encoded[mid..]); + let body = format!(r#"{{"content":"{wrapped}","encoding":"base64"}}"#); + let (addr, served) = crate::testutil::stub(vec![crate::testutil::http("200 OK", &body)]); + + let out = tap_cask_against(&addr, None).await.unwrap(); + assert!(out.ok); + assert_eq!(out.version.as_deref(), Some("9.9.9")); + assert_eq!(out.cask, CASK); + + let req = served.join().unwrap().remove(0); + assert!( + req.contains(&format!("GET /repos/{TAP_REPO}/contents/{TAP_CASK_PATH}")), + "unexpected request: {req}" + ); + assert!( + !req.to_lowercase().contains("authorization:"), + "no credential was given, so none may be sent: {req}" + ); + } + + /// A cask that parsed but says nothing comparable is `version: null` and **not** an error: + /// the file was read. The app treats both as "could not tell", but conflating them here + /// would report a network failure that did not happen. + #[tokio::test] + async fn an_uncomparable_cask_is_read_as_no_version_rather_than_an_error() { + let encoded = base64::engine::general_purpose::STANDARD.encode(" version \"1.2,345\"\n"); + let body = format!(r#"{{"content":"{encoded}","encoding":"base64"}}"#); + let (addr, served) = crate::testutil::stub(vec![crate::testutil::http("200 OK", &body)]); + + let out = tap_cask_against(&addr, None).await.unwrap(); + assert!(out.ok); + assert_eq!(out.version, None); + served.join().unwrap(); + } + + /// GitHub sends `encoding: "none"` for a file too large to inline. A cask is kilobytes so + /// this should not happen — and if it does, decoding an empty string into "the tap declares + /// nothing" would be a silent wrong answer where an error is the honest one. + #[tokio::test] + async fn an_unexpected_encoding_is_an_error_and_not_an_empty_version() { + let body = r#"{"content":"","encoding":"none"}"#; + let (addr, served) = crate::testutil::stub(vec![crate::testutil::http("200 OK", body)]); + + let err = tap_cask_against(&addr, None).await.unwrap_err(); + assert!( + err.to_string().contains("none-encoded"), + "should name the encoding it could not read: {err}" + ); + served.join().unwrap(); + } + /// The same rule as `UpdateCheck.summary` in `GitPicCore`, and the same two near-misses /// are pinned here: a heading needs a space after its hashes, and a fenced block is not /// scanned for one. Both sides render release notes to a person, so they have to agree.