update: a magpie a package manager installed leaves updating to it (shuhai on Discord, AUR magpie-bin)

shuhai (Arch) installs magpie from the AUR's magpie-bin, which puts the
desktop build at /usr/bin/magpie. magpie's own updater saw a folder it
can't write and pkexec on the machine, so it downloaded the release and,
on restart, replaced the package's file as root. pacman's database then
no longer matched the file, and the next `yay` upgrade (magpie-bin lags
the releases, 0.1.2342 against 0.1.2357 today) put an older magpie back.
The two updaters fought each other.

Now magpie asks first who owns the binary it runs from
(update.PackagedBy): pacman's local database, dpkg's .list files, rpm
(`rpm -qf`, only where /var/lib/rpm exists), a Homebrew Cellar path or
/nix/store. Only a system path counts (/usr but not /usr/local, /bin,
/sbin, /opt), with merged-/usr aliases, and packages named magpie* are
looked at first. A packaged binary:

- GUI: the update is shown as available with "pacman installed magpie
  (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin"
  (apt, dnf, brew likewise; Nix with no command). Nothing is downloaded,
  there is no Download or Install, the Update pill isn't lit, and
  /api/update/install does nothing (state available, stuck "package").
- `magpie update` says the same and exits 1 before downloading. This
  takes the place of the Homebrew-only check it had.

An unpackaged magpie (~/.local/bin, /usr/local/bin, a file pacman doesn't
list in /opt) updates itself as before.

Run:
- mote: go test -tags nogui -run 'Packaged|Homebrew|NotWritable|InContainer'
  ./internal/update ./internal/gui ./internal/cli ok; full
  go test -tags nogui -count=1 -timeout 45m ./... at b1a1b950f: 81 ok, 3
  red. Two are on main and filed: TestNoCommandBypassesProc (claudetui,
  #4491) and TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll, #4514).
  The third, TestCoreScriptBudget, was this change: app.js is now 460
  bytes more (its comments cut to one line, one helper call per path),
  and both budgets are raised by exactly that, with no room added. After
  the rebase on bb5e68cea: TestCoreScriptBudget and the Packaged,
  NotWritable, InContainer and Homebrew tests ok on mote.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows.
- WSL magpie-desktop (Ubuntu 24.04), real package: built a 0.1.2300
  nogui magpie, packaged it as a .deb (magpie-aurpk-test) at
  /usr/bin/magpie, dpkg -i. `magpie update` as the user, through
  /bin/magpie, and as root each printed "magpie 0.1.2355 is out" and
  "this magpie was installed with apt (package magpie-aurpk-test), which
  updates it, not magpie: sudo apt install --only-upgrade
  magpie-aurpk-test", exit 1; the file's sha256 was unchanged and
  dpkg -V clean. Package removed after. An unpackaged copy in ~ still
  checked and offered the update.
- WSL GUI, both engines: every update-* file, i18n-keys, gui-de/ja/zh-tw,
  whats-new*, about-*: 390 pass. Reds: i18n-keys "Unmarked" (#4524, on
  main) and update-check's WebKit ResizeObserver notice (the previous
  commit). Rerun of every update-* file after it: 294 pass, 4 red, all
  timing reds filed as #4554 and #4555, none in update-stuck. After
  app.js was cut down, after the rebase: update-stuck, update-auto,
  update-hide and i18n-keys, both engines: 93 pass, 1 red (#4524).

Broken by hand:
- placeExe's and the CLI's package check turned off:
  TestUpdatePackagedLeavesItToTheManager red ("a packaged binary is to be
  replaced"), TestUpdatePackagedSaysTheManager red (it went on to the
  download).
- origin's app.js: the new update-stuck case times out (no text); only
  the pill condition reverted: red in WebKit.

Not tried:
- A real pacman/Arch install: the omarchy VM didn't answer ssh (banner
  exchange timed out twice), so pacman detection is from the database
  layout in tests only.
- rpm and Nix on a real system; Homebrew only through the existing path
  test.
- The whole GUI suite.
This commit is contained in:
yetone
2026-10-31 17:28:37 +08:00
parent bbb1250162
commit 0ac26fb52d
10 changed files with 629 additions and 20 deletions
+8 -2
View File
@@ -23,6 +23,7 @@ var (
updateExecutable = update.Executable
updateCanElevate = update.CanElevate
updateInContainer = gateway.InContainer
updatePackagedBy = update.PackagedBy
)
// updateEveries are the intervals magpie update auto takes, by their
@@ -247,8 +248,13 @@ func updateCmd(args []string) error {
if exe, err := updateExecutable(); err == nil && !update.Writable(filepath.Dir(exe)) && !updateCanElevate() && updateInContainer() {
return fmt.Errorf("this magpie runs in a container and can't replace itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container")
}
if exe, err := update.Executable(); err == nil && update.Homebrew(exe) {
return fmt.Errorf("this magpie was installed with Homebrew; update it with: brew upgrade magpie")
// a package manager's binary (Homebrew's, pacman's magpie-bin from
// the AUR, a .deb's): replaced under it, the manager's database names
// the old version and its next upgrade writes over this one
if exe, err := updateExecutable(); err == nil {
if p := updatePackagedBy(exe); p != nil {
return fmt.Errorf("%s", p.Say())
}
}
fmt.Println(muted.Render(" downloading " + update.BinaryAsset() + via(ctx) + " …"))
if err := update.ReplaceBinary(ctx, rel); err != nil {
+47
View File
@@ -0,0 +1,47 @@
package cli
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/update"
)
// `magpie update` from the AUR's magpie-bin (/usr/bin/magpie) asked for the
// password and replaced the package's file under pacman (shuhai on
// Discord). It now says the version is out and the command that updates
// the package, and replaces nothing.
func TestUpdatePackagedSaysTheManager(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/asset" {
t.Errorf("a packaged binary downloaded the release")
}
json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", URL: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.11",
Assets: map[string]update.Asset{update.BinaryAsset(): {URL: "http://" + r.Host + "/asset"}}})
}))
defer srv.Close()
t.Setenv("MAGPIE_UPDATE_FEED", srv.URL)
exe := filepath.Join(t.TempDir(), "magpie")
if err := os.WriteFile(exe, []byte("magpie"), 0o755); err != nil {
t.Fatal(err)
}
wasV, wasX, wasE, wasP := version, updateExecutable, updateCanElevate, updatePackagedBy
t.Cleanup(func() { version, updateExecutable, updateCanElevate, updatePackagedBy = wasV, wasX, wasE, wasP })
version = "0.1.10"
updateExecutable = func() (string, error) { return exe, nil }
updateCanElevate = func() bool { return true }
updatePackagedBy = func(string) *update.Packaged { return &update.Packaged{Manager: "pacman", Package: "magpie-bin"} }
err := updateCmd([]string{"update"})
if err == nil || !strings.Contains(err.Error(), "pacman") || !strings.Contains(err.Error(), "yay -S magpie-bin") {
t.Fatalf("%v", err)
}
if b, _ := os.ReadFile(exe); string(b) != "magpie" {
t.Fatalf("the package's file was changed: %q", b)
}
}
+5 -1
View File
@@ -4413,7 +4413,8 @@ async function renderUpdateBadge() {
delete b.dataset.pulling;
b.classList.remove("busy");
}
const on = pulling || (!!u && !updatePillOff(u.latest) && (u.state === "ready" || u.state === "available" || u.state === "found" || (u.state === "error" && u.retry)));
// a package manager's magpie: Settings names its command, no pill
const on = pulling || (!!u && !updatePillOff(u.latest) && (u.state === "ready" || (u.state === "available" && !u.packaged) || u.state === "found" || (u.state === "error" && u.retry)));
if (b.hidden !== !on) b.hidden = !on;
if (!on) return;
const hide = $("#updateHide");
@@ -4539,6 +4540,8 @@ async function backAsNew(was) {
// the Mac, a folder it may not write to, such as C:\ (#1277), or a
// container, whose image is what gets updated.
function updateStuck(u) {
const p = u.packaged;
if (p) return p.command ? t("{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}", { manager: p.manager, pkg: p.package, cmd: p.command }) : t("{manager} installed magpie, so {manager} updates it, not magpie.", { manager: p.manager });
if (u.stuck === "container") return t("magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.");
if (u.stuck === "not-writable") return t("magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.", { dir: u.stuckDir || "" });
return u.stuck === "translocated"
@@ -22642,6 +22645,7 @@ async function renderUpdate(r, u) {
case "available":
sub.textContent = t("{v} is out", { v: u.latest });
if (u.stuck) sub.textContent += " · " + updateStuck(u);
if (u.packaged) { sub.classList.add("wraps"); btn(t("Check"), check); break; }
btn(t("Download"), () => (web && u.url ? window.open(u.url, "_blank", "noopener") : api("update/install", {})));
if (!web) page();
break;
+8
View File
@@ -3274,6 +3274,8 @@ const I18N = {
"macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正从临时副本运行 magpie,无法自动更新;请将 magpie 移到「应用程序」文件夹后从那里打开。",
"magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie 正从磁盘映像运行,无法自动更新;请将它拖到「应用程序」文件夹后从那里打开。",
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 无法写入它所在的文件夹({dir}),所以无法自动更新;请把它移到你有写入权限的文件夹,再从那里打开。",
"{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} 安装了 magpie({pkg}),所以由 {manager} 更新它,而不是 magpie 自己:{cmd}",
"{manager} installed magpie, so {manager} updates it, not magpie.": "由 {manager} 安装的 magpie 由 {manager} 更新,而不是 magpie 自己。",
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 运行在容器里,无法自动更新;请拉取新镜像(docker pull ghcr.io/yetone/magpie:latest)并重新创建容器。",
"Config folder": "配置目录",
"Log": "日志",
@@ -7504,6 +7506,8 @@ const I18N = {
"macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正從臨時副本執行 magpie,無法自動更新;請將 magpie 移到「應用程式」資料夾後從那裡開啟。",
"magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie 正從磁碟映像執行,無法自動更新;請將它拖到「應用程式」資料夾後從那裡開啟。",
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 無法寫入它所在的資料夾({dir}),所以無法自動更新;請把它移到你有寫入權限的資料夾,再從那裡開啟。",
"{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} 安裝了 magpie({pkg}),所以由 {manager} 更新它,而不是 magpie 自己:{cmd}",
"{manager} installed magpie, so {manager} updates it, not magpie.": "由 {manager} 安裝的 magpie 由 {manager} 更新,而不是 magpie 自己。",
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 在容器中執行,無法自動更新;請拉取新映像(docker pull ghcr.io/yetone/magpie:latest)並重新建立容器。",
"Config folder": "設定目錄",
"Log": "日誌",
@@ -11745,6 +11749,8 @@ const I18N = {
"macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS が magpie を一時的なコピーから実行しているため、自動アップデートできません。magpie を「アプリケーション」フォルダに移動し、そこから開いてください。",
"magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie がディスクイメージから実行されているため、自動アップデートできません。「アプリケーション」フォルダにドラッグし、そこから開いてください。",
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie は実行中のフォルダ({dir})に書き込めないため、自動アップデートできません。書き込み可能なフォルダに移動し、そこから開いてください。",
"{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "magpie は {manager} でインストールされている({pkg})ため、magpie ではなく {manager} がアップデートします:{cmd}",
"{manager} installed magpie, so {manager} updates it, not magpie.": "magpie は {manager} でインストールされているため、magpie ではなく {manager} がアップデートします。",
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie はコンテナで実行されているため、自動アップデートできません。新しいイメージを取得し(docker pull ghcr.io/yetone/magpie:latest)、コンテナを作り直してください。",
"Config folder": "設定フォルダ",
"Log": "ログ",
@@ -15997,6 +16003,8 @@ const I18N = {
"macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS führt magpie aus einer temporären Kopie aus, daher kann es sich nicht selbst aktualisieren; verschieben Sie magpie in „Programme“ und öffnen Sie es von dort.",
"magpie is running from its disk image, so it can't update itself; drag it to Applications and open it from there.": "magpie läuft aus seinem Disk-Image und kann sich daher nicht selbst aktualisieren; ziehen Sie es in „Programme“ und öffnen Sie es von dort.",
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie kann nicht in den Ordner schreiben, aus dem es läuft ({dir}), und kann sich daher nicht selbst aktualisieren; verschieben Sie es in einen Ordner mit Schreibrechten und öffnen Sie es von dort.",
"{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}": "{manager} hat magpie installiert ({pkg}), daher aktualisiert {manager} es, nicht magpie: {cmd}",
"{manager} installed magpie, so {manager} updates it, not magpie.": "{manager} hat magpie installiert, daher aktualisiert {manager} es, nicht magpie.",
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie läuft in einem Container und kann sich daher nicht selbst aktualisieren; laden Sie das neue Image (docker pull ghcr.io/yetone/magpie:latest) und erstellen Sie den Container neu.",
"Config folder": "Konfigurationsordner",
"Log": "Protokoll",
File diff suppressed because one or more lines are too long
+51
View File
@@ -98,3 +98,54 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
});
}
// A magpie a package manager installed (the AUR's magpie-bin, shuhai on
// Discord) leaves its updates to the manager: the Version row says the
// version is out and the command that updates the package, with no
// Download (the release's binary isn't for this install) and no Update
// pill (the package can come days after the release).
const packaged = { state: "available", current: "0.1.400", latest: "0.1.401", url: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.401", stuck: "package", packaged: { manager: "pacman", package: "magpie-bin", command: "yay -S magpie-bin" } };
const byManager = {
en: "pacman installed magpie (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin",
zh: "pacman 安装了 magpie(magpie-bin),所以由 pacman 更新它,而不是 magpie 自己:yay -S magpie-bin",
"zh-TW": "pacman 安裝了 magpie(magpie-bin),所以由 pacman 更新它,而不是 magpie 自己:yay -S magpie-bin",
ja: "magpie は pacman でインストールされている(magpie-bin)ため、magpie ではなく pacman がアップデートします:yay -S magpie-bin",
de: "pacman hat magpie installiert (magpie-bin), daher aktualisiert pacman es, nicht magpie: yay -S magpie-bin",
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a packaged magpie names its package manager's command", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1000, 440]) {
await t.test(`${lang} at ${width}px`, async () => {
const ctl = { installs: 0 };
const errors = [];
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); });
await page.route("**/*", server(lang, ctl, packaged));
await page.goto("http://magpie.test/?view=settings&tab=about");
const want = byManager[lang];
const sub = await (await page.waitForFunction((w) => [...document.querySelectorAll("#about .row.pref .sub")].find((s) => s.textContent.includes(w))?.textContent, want)).jsonValue();
assert.ok(sub.includes("0.1.401"), sub);
const row = page.locator("#about .row.pref", { has: page.locator(".sub", { hasText: want }) });
const buttons = await row.locator("button").allTextContents();
const download = { en: "Download", zh: "下载", "zh-TW": "下載", ja: "ダウンロード", de: "Herunterladen" }[lang];
assert.ok(!buttons.some((b) => b.trim() === download), buttons.join("|"));
// no Update pill, once the pill has read the update too (a fetch
// of /api/update beside the row's)
await page.waitForFunction(() => performance.getEntriesByType("resource").filter((e) => new URL(e.name).pathname === "/api/update").length >= 2);
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
assert.equal(await page.locator("#update").isHidden(), true);
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert.ok(over <= 0, `the page scrolls sideways by ${over}px`);
assert.equal(ctl.installs, 0);
assert.deepEqual(errors, []);
await page.close();
});
}
}
});
}
+42 -15
View File
@@ -28,19 +28,22 @@ import (
// restart asks for the administrator's password; only an app that can't be
// replaced at all (run from its disk image, say) is sent to the release page.
type updater struct {
mu sync.Mutex
state string // checking | latest | found | downloading | ready | available | source | error | blocked
latest *update.Release
err string
bundle string // the .app to replace, "" when not in one or stuck
stuck string // why the .app or binary can't be replaced where it is (update.Stuck, exeStuck)
exe string // not in a .app: the binary to replace, "" when not writable
exeDir string // not in a .app: the binary's folder, named when it is stuck there
self os.FileInfo // exe (in a .app: bundleExe) as this process started from it
retry bool // error: the download failed, and may be tried again
mirror string // error: the mirror the failed download came through (#893)
network bool // error: the network broke the download off (update.Network)
staged string
mu sync.Mutex
state string // checking | latest | found | downloading | ready | available | source | error | blocked
latest *update.Release
err string
bundle string // the .app to replace, "" when not in one or stuck
stuck string // why the .app or binary can't be replaced where it is (update.Stuck, exeStuck)
exe string // not in a .app: the binary to replace, "" when not writable
exeDir string // not in a .app: the binary's folder, named when it is stuck there
// stuck "package": the package manager that installed the binary,
// which updates it instead (update.PackagedBy)
packaged *update.Packaged
self os.FileInfo // exe (in a .app: bundleExe) as this process started from it
retry bool // error: the download failed, and may be tried again
mirror string // error: the mirror the failed download came through (#893)
network bool // error: the network broke the download off (update.Network)
staged string
// stable: latest was found on Settings' Stable channel
stable bool
aside string // Windows: where install moved the running exe, to put back
@@ -92,7 +95,11 @@ type updateJSON struct {
Stuck string `json:"stuck,omitempty"` // available: why it can't update itself
// available, stuck "not-writable": the folder magpie may not write to
StuckDir string `json:"stuckDir,omitempty"`
Retry bool `json:"retry,omitempty"` // error: a click downloads it again
// available, stuck "package": the package manager that installed
// magpie and updates it (pacman's magpie-bin from the AUR, say), and
// the command that does
Packaged *packagedJSON `json:"packaged,omitempty"`
Retry bool `json:"retry,omitempty"` // error: a click downloads it again
// error: the download failed through this mirror (Settings' UpdateMirror),
// and GitHub itself may do (#893)
Mirror string `json:"mirror,omitempty"`
@@ -183,9 +190,16 @@ func (u *updater) place(goos string, gui bool) {
}
// placeExe takes exe as the binary an update replaces, or
// says why it can't be (stuck).
// says why it can't be (stuck). A binary a package manager installed is
// left to it ("package"), even where magpie may write or ask for the
// administrator's password: replacing it under the manager is what made
// the two fight (shuhai on Discord, the AUR's magpie-bin).
func (u *updater) placeExe(exe string) {
u.exeDir = filepath.Dir(exe)
if p := packagedBy(exe); p != nil {
u.stuck, u.packaged = "package", p
return
}
if u.stuck = exeStuck(u.exeDir); u.stuck != "" {
return
}
@@ -219,8 +233,15 @@ func exeStuck(dir string) string {
var (
canElevate = update.CanElevate
inContainer = gateway.InContainer
packagedBy = update.PackagedBy
)
type packagedJSON struct {
Manager string `json:"manager"` // as its users call it: pacman, apt, rpm, Homebrew, Nix
Package string `json:"package,omitempty"`
Command string `json:"command,omitempty"` // what updates it, "" when no one command does
}
// check asks the feed and, when it can, stages the new version.
func (u *updater) check() {
if u.begin() {
@@ -582,6 +603,9 @@ func (u *updater) jsonIn(lang string) updateJSON {
if u.stuck == "not-writable" {
j.StuckDir = u.exeDir
}
if u.stuck == "package" && u.packaged != nil {
j.Packaged = &packagedJSON{Manager: u.packaged.Name(), Package: u.packaged.Package, Command: u.packaged.Command()}
}
}
if u.state == "downloading" {
j.Done, j.Total = u.done, u.total
@@ -730,6 +754,9 @@ func updateRoutes(mux *http.ServeMux, w Windows) {
// a click: the download is asked for, whatever Settings'
// NoAutoDownload says (#2296)
updates.download()
case j.State == "available" && j.Stuck == "package":
// the package manager updates it: the release page's download
// isn't for this install
case j.State == "available" && j.URL != "":
// the newest's page, not the one the last check found: a check
// over a minute old is made again first (coeo91 on Discord)
+69
View File
@@ -0,0 +1,69 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/update"
)
// The AUR's magpie-bin installs /usr/bin/magpie, and with pkexec there
// magpie put its own download over the package's file on a restart, so
// pacman's database named one version and the disk had another, and the
// next yay upgrade wrote over it again (shuhai on Discord). A binary a
// package manager installed now says a version is out and the command
// that updates it, and never downloads or replaces anything, even where
// it may write or ask for the password.
func TestUpdatePackagedLeavesItToTheManager(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/asset" {
t.Errorf("a packaged binary downloaded the release")
}
json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", URL: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.11", Assets: map[string]update.Asset{
update.BinaryAsset(): {URL: "http://" + r.Host + "/asset"},
}})
}))
defer srv.Close()
t.Setenv("MAGPIE_UPDATE_FEED", srv.URL)
old := Version
Version = "0.1.10"
defer func() { Version = old }()
wasE, wasP := canElevate, packagedBy
defer func() { canElevate, packagedBy = wasE, wasP }()
canElevate = func() bool { return true }
dir := t.TempDir() // writable: ownership alone decides
exe := filepath.Join(dir, "magpie")
if err := os.WriteFile(exe, []byte("magpie"), 0o755); err != nil {
t.Fatal(err)
}
packagedBy = func(string) *update.Packaged { return &update.Packaged{Manager: "pacman", Package: "magpie-bin"} }
u := &updater{}
u.placeExe(exe)
if u.exe != "" {
t.Fatalf("a packaged binary is to be replaced: %q", u.exe)
}
u.check()
j := u.json()
if j.State != "available" || j.Stuck != "package" || j.Packaged == nil || j.Packaged.Manager != "pacman" || j.Packaged.Package != "magpie-bin" || j.Packaged.Command != "yay -S magpie-bin" || j.Latest != "0.1.11" {
t.Fatalf("%+v %+v", j, j.Packaged)
}
if u.install(true) {
t.Fatal("install put something in")
}
if b, _ := os.ReadFile(exe); string(b) != "magpie" {
t.Fatalf("the package's file was changed: %q", b)
}
// a binary no package owns updates itself as before
packagedBy = func(string) *update.Packaged { return nil }
u = &updater{}
u.placeExe(exe)
if u.exe != exe || u.stuck != "" {
t.Fatalf("not packaged: exe %q, stuck %q", u.exe, u.stuck)
}
}
+262
View File
@@ -0,0 +1,262 @@
package update
import (
"bufio"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"github.com/yetone/magpie/internal/proc"
)
// Packaged is the package manager that installed a magpie binary, which
// then has to be the one to update it. magpie replacing a file a package
// owns (pkexec over /usr/bin/magpie from the AUR's magpie-bin, shuhai on
// Discord) leaves the manager's database naming an older version and a
// file that no longer matches it, and the manager's next upgrade, which
// can be a version older than the one magpie put in, writes over it again.
type Packaged struct {
Manager string `json:"manager"` // pacman, dpkg, rpm, homebrew or nix
Package string `json:"package,omitempty"` // the package's name, when known
}
// Name is the manager as its users call it.
func (p *Packaged) Name() string {
switch p.Manager {
case "dpkg":
return "apt"
case "homebrew":
return "Homebrew"
case "nix":
return "Nix"
}
return p.Manager
}
// Command is what updates the package, "" when there is no one command
// (Nix: a profile or a system configuration). magpie is in no distribution's
// own repository, so a pacman package is the AUR's, which pacman alone
// doesn't upgrade: its AUR helper does.
func (p *Packaged) Command() string {
pkg := p.Package
if pkg == "" {
pkg = "magpie"
}
switch p.Manager {
case "pacman":
return "yay -S " + pkg
case "dpkg":
return "sudo apt install --only-upgrade " + pkg
case "rpm":
return "sudo dnf upgrade " + pkg
case "homebrew":
return "brew upgrade " + pkg
}
return ""
}
// Say is the sentence a terminal is told: who updates this magpie, and how.
func (p *Packaged) Say() string {
s := "this magpie was installed with " + p.Name()
if p.Package != "" {
s += " (package " + p.Package + ")"
}
s += ", which updates it, not magpie"
if c := p.Command(); c != "" {
s += ": " + c
if p.Manager == "pacman" {
s += " (or paru, or the AUR helper it came from)"
}
}
return s
}
// PackagedBy says which package manager installed exe (the running
// binary, symlinks resolved), nil when none did.
func PackagedBy(exe string) *Packaged {
return packagedIn("/", runtime.GOOS, exe)
}
// rpmOwner is the rpm package owning path, "" when none; a test stands in
// for it. rpm's database is SQLite (or Berkeley DB), read through rpm.
var rpmOwner = func(path string) string {
out, err := proc.Command("rpm", "-qf", "--queryformat", "%{NAME}", path).Output()
if err != nil {
return ""
}
s := strings.TrimSpace(string(out))
if s == "" || strings.Contains(s, " ") { // "file … is not owned by any package"
return ""
}
return s
}
// packagedIn is PackagedBy with the system's files under root.
func packagedIn(root, goos, exe string) *Packaged {
p := filepath.ToSlash(exe)
if _, rest, ok := strings.Cut(p, "/Cellar/"); ok {
name, _, _ := strings.Cut(rest, "/")
return &Packaged{Manager: "homebrew", Package: name}
}
if goos != "linux" {
return nil
}
if strings.HasPrefix(p, "/nix/store/") {
return &Packaged{Manager: "nix"}
}
if !systemPath(p) {
return nil
}
if name, ok := pacmanOwner(root, p); ok {
return &Packaged{Manager: "pacman", Package: name}
}
if name, ok := dpkgOwner(root, p); ok {
return &Packaged{Manager: "dpkg", Package: name}
}
if isDir(filepath.Join(root, "var/lib/rpm")) {
if name := rpmOwner(p); name != "" {
return &Packaged{Manager: "rpm", Package: name}
}
}
return nil
}
// systemPath is whether a package may own p: /usr (but not /usr/local,
// which packages leave to the machine's own), /bin, /sbin, /opt.
func systemPath(p string) bool {
if strings.HasPrefix(p, "/usr/local/") {
return false
}
for _, d := range []string{"/usr/", "/bin/", "/sbin/", "/opt/"} {
if strings.HasPrefix(p, d) {
return true
}
}
return false
}
// aliases are the names p has in a package's file list: on a merged /usr
// /bin is /usr/bin, and a package may list either.
func aliases(p string) []string {
out := []string{p}
for _, d := range []string{"/bin/", "/sbin/", "/lib/"} {
if strings.HasPrefix(p, "/usr"+d) {
out = append(out, strings.TrimPrefix(p, "/usr"))
} else if strings.HasPrefix(p, d) {
out = append(out, "/usr"+p)
}
}
return out
}
// magpieFirst orders names with those starting "magpie" first: the package
// owning magpie is all but always one of them (magpie-bin, magpie-cli-bin,
// magpie-git), so the rest are read only when none is.
func magpieFirst(names []string) []string {
slices.SortStableFunc(names, func(a, b string) int {
ma, mb := strings.HasPrefix(a, "magpie"), strings.HasPrefix(b, "magpie")
switch {
case ma && !mb:
return -1
case mb && !ma:
return 1
}
return 0
})
return names
}
// pacmanOwner reads pacman's local database, a folder per installed
// package (name-version-release) holding the list of its files, each
// without its leading slash.
func pacmanOwner(root, p string) (string, bool) {
dir := filepath.Join(root, "var/lib/pacman/local")
ents, err := os.ReadDir(dir)
if err != nil {
return "", false
}
var names []string
for _, e := range ents {
if e.IsDir() {
names = append(names, e.Name())
}
}
want := aliases(p)
for i := range want {
want[i] = strings.TrimPrefix(want[i], "/")
}
for _, n := range magpieFirst(names) {
if listed(filepath.Join(dir, n, "files"), want) {
return pacmanName(filepath.Join(dir, n), n), true
}
}
return "", false
}
// pacmanName is the package's name, from its desc (%NAME%), else its
// folder's name without its version and release.
func pacmanName(dir, folder string) string {
if b, err := os.ReadFile(filepath.Join(dir, "desc")); err == nil {
lines := strings.Split(string(b), "\n")
for i, l := range lines {
if strings.TrimSpace(l) == "%NAME%" && i+1 < len(lines) {
if n := strings.TrimSpace(lines[i+1]); n != "" {
return n
}
}
}
}
parts := strings.Split(folder, "-")
if len(parts) > 2 {
return strings.Join(parts[:len(parts)-2], "-")
}
return folder
}
// dpkgOwner reads dpkg's file lists, one name.list (or name:arch.list) per
// installed package, each line an absolute path.
func dpkgOwner(root, p string) (string, bool) {
dir := filepath.Join(root, "var/lib/dpkg/info")
ents, err := os.ReadDir(dir)
if err != nil {
return "", false
}
var names []string
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".list") {
names = append(names, e.Name())
}
}
want := aliases(p)
for _, n := range magpieFirst(names) {
if listed(filepath.Join(dir, n), want) {
name, _, _ := strings.Cut(strings.TrimSuffix(n, ".list"), ":")
return name, true
}
}
return "", false
}
// listed is whether the file list at path has a line equal to one of want.
func listed(path string, want []string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 64*1024), 1<<20)
for sc.Scan() {
if slices.Contains(want, strings.TrimSpace(sc.Text())) {
return true
}
}
return false
}
func isDir(path string) bool {
st, err := os.Stat(path)
return err == nil && st.IsDir()
}
+135
View File
@@ -0,0 +1,135 @@
package update
import (
"os"
"path/filepath"
"strings"
"testing"
)
func writeFile(t *testing.T, path, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
// pacman's local database as the AUR's magpie-bin 0.1.2342-1 leaves it
// (its PKGBUILD installs /usr/bin/magpie), beside a package that doesn't
// own magpie.
func pacmanRoot(t *testing.T) string {
root := t.TempDir()
local := filepath.Join(root, "var/lib/pacman/local")
writeFile(t, filepath.Join(local, "ALPM_DB_VERSION"), "9\n")
writeFile(t, filepath.Join(local, "bash-5.3.3-2/files"), "%FILES%\nusr/\nusr/bin/\nusr/bin/bash\nusr/bin/sh\n\n%BACKUP%\netc/bash.bashrc\t0b5ab6a3\n")
writeFile(t, filepath.Join(local, "bash-5.3.3-2/desc"), "%NAME%\nbash\n\n%VERSION%\n5.3.3-2\n")
writeFile(t, filepath.Join(local, "magpie-bin-0.1.2342-1/files"), "%FILES%\nusr/\nusr/bin/\nusr/bin/magpie\nusr/share/\nusr/share/applications/\nusr/share/applications/magpie.desktop\nusr/share/icons/hicolor/256x256/apps/magpie.png\nusr/share/licenses/magpie-bin/LICENSE\n\n")
writeFile(t, filepath.Join(local, "magpie-bin-0.1.2342-1/desc"), "%NAME%\nmagpie-bin\n\n%VERSION%\n0.1.2342-1\n\n%BASE%\nmagpie-bin\n")
return root
}
func TestPackagedByPacman(t *testing.T) {
root := pacmanRoot(t)
p := packagedIn(root, "linux", "/usr/bin/magpie")
if p == nil || p.Manager != "pacman" || p.Package != "magpie-bin" {
t.Fatalf("/usr/bin/magpie from magpie-bin: %+v", p)
}
if c := p.Command(); c != "yay -S magpie-bin" {
t.Fatalf("command %q", c)
}
if s := p.Say(); !strings.Contains(s, "pacman") || !strings.Contains(s, "yay -S magpie-bin") {
t.Fatalf("said %q", s)
}
// /bin is /usr/bin on Arch: the same file
if p := packagedIn(root, "linux", "/bin/magpie"); p == nil || p.Package != "magpie-bin" {
t.Fatalf("/bin/magpie: %+v", p)
}
// a copy in /usr/local, ~/.local/bin or /opt that no package lists is
// the user's own, and updates itself
for _, exe := range []string{"/usr/local/bin/magpie", "/home/u/.local/bin/magpie", "/opt/magpie/magpie", "/usr/lib/magpie/magpie"} {
if p := packagedIn(root, "linux", exe); p != nil {
t.Fatalf("%s: %+v", exe, p)
}
}
// not Linux: pacman's files aren't read
if p := packagedIn(root, "darwin", "/usr/bin/magpie"); p != nil {
t.Fatalf("darwin: %+v", p)
}
}
// A package named otherwise is found too, its name from the folder when
// its desc can't be read.
func TestPackagedByPacmanOtherName(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "var/lib/pacman/local/ai-tools-2.0-3/files"), "%FILES%\nopt/ai/bin/magpie\n")
p := packagedIn(root, "linux", "/opt/ai/bin/magpie")
if p == nil || p.Package != "ai-tools" {
t.Fatalf("%+v", p)
}
}
// dpkg lists absolute paths, and on a merged /usr may list /bin for the
// /usr/bin the binary resolves to.
func TestPackagedByDpkg(t *testing.T) {
root := t.TempDir()
info := filepath.Join(root, "var/lib/dpkg/info")
writeFile(t, filepath.Join(info, "coreutils.list"), "/.\n/bin\n/bin/ls\n")
writeFile(t, filepath.Join(info, "magpie:amd64.list"), "/.\n/usr\n/usr/bin\n/usr/bin/magpie\n")
p := packagedIn(root, "linux", "/usr/bin/magpie")
if p == nil || p.Manager != "dpkg" || p.Package != "magpie" || p.Name() != "apt" || p.Command() != "sudo apt install --only-upgrade magpie" {
t.Fatalf("%+v", p)
}
if p := packagedIn(root, "linux", "/usr/bin/ls"); p == nil || p.Package != "coreutils" {
t.Fatalf("merged /usr: %+v", p)
}
if p := packagedIn(root, "linux", "/usr/sbin/magpie"); p != nil {
t.Fatalf("not listed: %+v", p)
}
}
func TestPackagedByRpm(t *testing.T) {
root := t.TempDir()
was := rpmOwner
t.Cleanup(func() { rpmOwner = was })
asked := ""
rpmOwner = func(path string) string { asked = path; return "magpie" }
// no rpm database: rpm isn't asked
if p := packagedIn(root, "linux", "/usr/bin/magpie"); p != nil || asked != "" {
t.Fatalf("no rpm here: %+v, asked %q", p, asked)
}
if err := os.MkdirAll(filepath.Join(root, "var/lib/rpm"), 0o755); err != nil {
t.Fatal(err)
}
p := packagedIn(root, "linux", "/usr/bin/magpie")
if p == nil || p.Manager != "rpm" || asked != "/usr/bin/magpie" || p.Command() != "sudo dnf upgrade magpie" {
t.Fatalf("%+v, asked %q", p, asked)
}
rpmOwner = func(string) string { return "" }
if p := packagedIn(root, "linux", "/usr/bin/magpie"); p != nil {
t.Fatalf("not owned: %+v", p)
}
}
func TestPackagedByHomebrewAndNix(t *testing.T) {
root := t.TempDir()
for exe, want := range map[string]string{
"/opt/homebrew/Cellar/magpie/0.1.126/bin/magpie": "homebrew magpie brew upgrade magpie",
"/home/linuxbrew/.linuxbrew/Cellar/magpie/0.1.126/bin/magpie": "homebrew magpie brew upgrade magpie",
"/nix/store/abc123-magpie-0.1.2342/bin/magpie": "nix ",
} {
goos := "linux"
if strings.HasPrefix(exe, "/opt/homebrew") {
goos = "darwin"
}
p := packagedIn(root, goos, exe)
if p == nil || p.Manager+" "+p.Package+" "+p.Command() != want {
t.Fatalf("%s: %+v", exe, p)
}
}
if p := packagedIn(root, "darwin", "/Applications/magpie.app/Contents/MacOS/magpie"); p != nil {
t.Fatalf("the app: %+v", p)
}
}