Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: a standalone Windows rtk gets rtk's own upgrade action (#2006, Edward4226; LoKi)
Edward4226b91bcf2606bd
diff --git a/internal/library/rtk.go b/internal/library/rtk.goindex 2dd47310c..bc45fe123 100644--- a/internal/library/rtk.go+++ b/internal/library/rtk.go@@ -859,6 +859,11 @@ func shown(c []string) string {if c[0] == "sh" {return c[2]}+ if c[0] == rtkWindowsRelease {+ // magpie's own action, not a command line: name what it does+ // rather than the action and the path the user's rtk is at (#2006)+ return "rtk's own Windows release"+ }return strings.Join(c, " ")}diff --git a/internal/library/rtk_upgrade.go b/internal/library/rtk_upgrade.goindex 6a894d7df..51f236d55 100644--- a/internal/library/rtk_upgrade.go+++ b/internal/library/rtk_upgrade.go@@ -1,7 +1,11 @@package libraryimport (+ "archive/zip"+ "bytes""context"+ "crypto/sha256"+ "encoding/hex""encoding/json""errors""fmt"@@ -12,12 +16,14 @@ import ("path/filepath""regexp""runtime"+ "strconv""strings""sync""time""github.com/yetone/magpie/internal/proc""github.com/yetone/magpie/internal/source"+ "github.com/yetone/magpie/internal/steady")// rtk's version is kept up to date the way it was installed: Homebrew's@@ -362,12 +368,194 @@ func rtkUpgrader(bin string) []string {}// installed with winget --location into a folder of the user's own// (D:\codes\tools\rtk): winget's records say so, not the folder's name- case have("winget") && wingetOwnsRTK(bin, real):+ case have("winget") && wingetOwns(bin, real):return wingetUp+ // a standalone rtk.exe somewhere else on Windows, put there by hand+ // from rtk's own Windows release (%USERPROFILE%\.local\bin, #2006): no+ // package manager installed it, so magpie replaces it itself. winget's+ // and cargo's folders were taken above, and an rtk winget's records or+ // winget list say is winget's went to winget; when winget couldn't say+ // (it timed out), magpie still can't tell rather than take it over.+ // rtk's Windows release has no arm64 build, so on one it can't either+ case rtkOnWindows && rtkArch == "amd64" &&+ strings.EqualFold(filepath.Base(bin), "rtk.exe") &&+ wingetDisowns(bin, real):+ return []string{rtkWindowsRelease, bin}}return nil}+// rtkWindowsRelease is the upgrader rtkUpgrader gives a Windows rtk no+// package manager installed (#2006): magpie replaces it with rtk.exe out of+// rtk's own Windows release. The action names only the binary to replace:+// the release is RTKLatest's when the upgrade runs, since naming it here+// would have ReadRTK (a page draw) wait on RTKLatest's lock while it asks+// GitHub.+const rtkWindowsRelease = "rtk-windows-release"++// rtkDownloadBase is where rtk's releases are downloaded from; a var so+// tests can point it at a fake release.+var rtkDownloadBase = "https://github.com/rtk-ai/rtk/releases/download"++// rtkDownloadMax is the largest file magpie reads from a release: rtk's+// Windows zip is a few MB.+const rtkDownloadMax = 200 << 20++// rtkArch is the architecture rtk's Windows release is chosen for: magpie's+// own, which Windows on arm64 runs emulated when it is amd64. A var so a+// test runs the amd64 branch on any machine.+var rtkArch = runtime.GOARCH++// installRTKWindowsRelease replaces bin with rtk.exe out of rtk's Windows+// release v version (#2006). The zip and the checksums.txt it is checked+// against both come from rtk's own release (source.DoOfficial), so a+// download that doesn't match is a real failure and nothing is replaced.+func installRTKWindowsRelease(version, bin string) error {+ const asset = "rtk-x86_64-pc-windows-msvc.zip"+ base := rtkDownloadBase + "/v" + version + "/"+ sums, err := rtkFetch(base + "checksums.txt")+ if err != nil {+ return fmt.Errorf("couldn't read RTK %s's checksums: %w", version, err)+ }+ want := rtkChecksum(string(sums), asset)+ if want == "" {+ return fmt.Errorf("RTK %s's checksums don't list %s", version, asset)+ }+ z, err := rtkFetch(base + asset)+ if err != nil {+ return fmt.Errorf("couldn't download RTK %s: %w", version, err)+ }+ if got := sha256.Sum256(z); hex.EncodeToString(got[:]) != want {+ return fmt.Errorf("the RTK %s download doesn't match its checksum from rtk-ai/rtk; %s left as it was", version, filepath.Base(bin))+ }+ exe, err := rtkExeFromZip(z)+ if err != nil {+ return fmt.Errorf("couldn't read %s from RTK %s: %w", asset, version, err)+ }+ return replaceRTKBinary(bin, exe)+}++// rtkFetch is a release file from its official address (source.DoOfficial:+// the file's checksum must come from the same trusted place as the file).+func rtkFetch(url string) ([]byte, error) {+ req, err := http.NewRequest("GET", url, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("User-Agent", "magpie")+ c := &http.Client{Timeout: 5 * time.Minute}+ resp, err := source.DoOfficial(c, req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != 200 {+ return nil, fmt.Errorf("%s: %s", url, resp.Status)+ }+ b, err := io.ReadAll(io.LimitReader(resp.Body, rtkDownloadMax+1))+ if err != nil {+ return nil, err+ }+ if int64(len(b)) > rtkDownloadMax {+ return nil, fmt.Errorf("%s: too large", url)+ }+ return b, nil+}++// rtkChecksum is the SHA-256 checksums.txt gives for name, "" when it+// doesn't name it. The lines are "sha256 name", as sha256sum writes them.+func rtkChecksum(sums, name string) string {+ for _, l := range strings.FieldsFunc(sums, func(r rune) bool { return r == '\n' || r == '\r' }) {+ if f := strings.Fields(l); len(f) == 2 && strings.TrimPrefix(f[1], "*") == name {+ return strings.ToLower(f[0])+ }+ }+ return ""+}++// rtkExeFromZip is rtk.exe out of rtk's Windows release zip (beside it,+// LICENSE and LICENSE-ENGINE in v1.0.1). Only a member named rtk.exe is+// taken: another exe in it is not rtk.+func rtkExeFromZip(z []byte) ([]byte, error) {+ zr, err := zip.NewReader(bytes.NewReader(z), int64(len(z)))+ if err != nil {+ return nil, err+ }+ var pick *zip.File+ for _, f := range zr.File {+ if f.FileInfo().IsDir() {+ continue+ }+ if strings.EqualFold(filepath.Base(f.Name), "rtk.exe") {+ pick = f+ break+ }+ }+ if pick == nil {+ return nil, errors.New("it has no rtk.exe")+ }+ if pick.UncompressedSize64 > rtkDownloadMax {+ return nil, errors.New("its rtk.exe is too large")+ }+ rc, err := pick.Open()+ if err != nil {+ return nil, err+ }+ defer rc.Close()+ return io.ReadAll(io.LimitReader(rc, rtkDownloadMax))+}++// replaceRTKBinary puts b in bin's place, written beside it first and with+// the old one moved aside rather than removed: on Windows an rtk.exe an+// agent is running refuses to be replaced outright (steady.Rename waits it+// out), and a replacement that fails puts the user's rtk back, so it is+// never lost (#2006).+func replaceRTKBinary(bin string, b []byte) error {+ tmp, err := os.CreateTemp(filepath.Dir(bin), "."+filepath.Base(bin)+".*")+ if err != nil {+ return fmt.Errorf("couldn't write the new rtk beside %s: %w", bin, err)+ }+ tmpName := tmp.Name()+ if _, err := tmp.Write(b); err != nil {+ tmp.Close()+ os.Remove(tmpName)+ return fmt.Errorf("couldn't write the new rtk beside %s: %w", bin, err)+ }+ if err := tmp.Chmod(0o755); err != nil {+ tmp.Close()+ os.Remove(tmpName)+ return fmt.Errorf("couldn't write the new rtk beside %s: %w", bin, err)+ }+ if err := tmp.Close(); err != nil {+ os.Remove(tmpName)+ return fmt.Errorf("couldn't write the new rtk beside %s: %w", bin, err)+ }+ // the old binary renamed, not removed: a rename that fails leaves it.+ // One an agent was running when it was moved aside can't be removed+ // until it exits, so the ones earlier upgrades left are removed now+ if ents, err := os.ReadDir(filepath.Dir(bin)); err == nil {+ for _, e := range ents {+ if strings.HasPrefix(e.Name(), filepath.Base(bin)+".old-") {+ os.Remove(filepath.Join(filepath.Dir(bin), e.Name()))+ }+ }+ }+ aside := bin + ".old-" + strconv.Itoa(os.Getpid())+ if err := steady.Rename(bin, aside); err != nil {+ os.Remove(tmpName)+ return fmt.Errorf("couldn't move the rtk at %s aside to replace it: %w", bin, err)+ }+ if err := steady.Rename(tmpName, bin); err != nil {+ os.Remove(tmpName)+ if rerr := steady.Rename(aside, bin); rerr != nil {+ return fmt.Errorf("couldn't put the new rtk in %s (%v), and couldn't put the old one back from %s: %w", bin, err, aside, rerr)+ }+ return fmt.Errorf("couldn't put the new rtk in %s: %w", bin, err)+ }+ os.Remove(aside)+ return nil+}+// rtkOnWindows is whether rtk is upgraded as Windows has it; a var so a// test can ask a fake winget on any platform.var rtkOnWindows = runtime.GOOS == "windows"@@ -388,37 +576,56 @@ var rtkWingetOwned = struct {}{m: map[string]rtkOwned{}}type rtkOwned struct {- yes bool- next time.Time+ yes, known bool+ next time.Time+}++// wingetOwns says whether winget installed the rtk at bin (real, with links+// followed); no when winget couldn't say.+func wingetOwns(bin, real string) bool {+ yes, _ := wingetOwnsRTK(bin, real)+ return yes+}++// wingetDisowns says whether winget said it didn't install the rtk at bin:+// winget couldn't say (it timed out, failed or couldn't run) is no answer, and an+// rtk that may be winget's isn't taken over (#2006).+func wingetDisowns(bin, real string) bool {+ yes, known := wingetOwnsRTK(bin, real)+ return known && !yes}// wingetOwnsRTK says whether winget installed the rtk at bin (real, with-// links followed), remembered for ten minutes.-func wingetOwnsRTK(bin, real string) bool {+// links followed), and whether that is known, remembered for ten minutes.+func wingetOwnsRTK(bin, real string) (yes, known bool) {key := strings.ToLower(real)rtkWingetOwned.Lock()defer rtkWingetOwned.Unlock()if o, ok := rtkWingetOwned.m[key]; ok && time.Now().Before(o.next) {- return o.yes+ return o.yes, o.known}- yes := askWingetOwns(bin, real)- rtkWingetOwned.m[key] = rtkOwned{yes: yes, next: time.Now().Add(10 * time.Minute)}- return yes+ yes, known = askWingetOwns(bin, real)+ rtkWingetOwned.m[key] = rtkOwned{yes: yes, known: known, next: time.Now().Add(10 * time.Minute)}+ return yes, known}// askWingetOwns asks winget's records whether the rtk at bin is the one it// installed: the folder its record names holds it, so an rtk.exe put// somewhere else by hand isn't taken for winget's. When there is no record// to read, winget list --id rtk-ai.rtk is asked, briefly, whether winget-// has rtk installed at all.-func askWingetOwns(bin, real string) bool {+// has rtk installed at all. known is false when neither could say: winget+// is there but timed out or couldn't be run.+func askWingetOwns(bin, real string) (yes, known bool) {if locs, ok := wingetRecords(); ok && len(locs) > 0 {for _, l := range locs {if inFolder(real, l) || inFolder(bin, l) {- return true+ return true, true}}- return false+ return false, true+ }+ if _, err := exec.LookPath("winget"); err != nil {+ return false, true // no winget, so not winget's}ctx, cancel := context.WithTimeout(context.Background(), wingetListTimeout)defer cancel()@@ -426,8 +633,16 @@ func askWingetOwns(bin, real string) bool {cmd.Stdin = nilout, err := cmd.Output()// it lists the package by its id in any language, and says it has none- // with exit code 0x8A150014- return err == nil && strings.Contains(string(out), "rtk-ai.rtk")+ // with exit code 0x8A150014; any other failure (out of time, its+ // sources unreachable) said nothing+ if err == nil {+ return strings.Contains(string(out), "rtk-ai.rtk"), true+ }+ var ee *exec.ExitError+ if ctx.Err() == nil && errors.As(err, &ee) && uint32(ee.ExitCode()) == wingetNotFound {+ return false, true+ }+ return false, false}// wingetListTimeout is how long winget list is given; a var for tests.@@ -456,26 +671,39 @@ func UpgradeRTK() (*RTKView, error) {return nil, fmt.Errorf("magpie can't tell how the rtk at %s was installed — update it the way you installed it", bin)}before := rtkVersion()- var env []string- if c[0] == "sh" {- env = []string{"RTK_INSTALL_DIR=" + c[3]}- c = c[:3]- }- timeout := 10 * time.Minute- if c[0] == "cargo" {- timeout = 30 * time.Minute // it builds rtk- }- // brew upgrade updates Homebrew first, for its newest rtk- // winget having no newer rtk than this one yet is no failurenone := false- if _, err := runRTKInstaller(c, timeout, rtkAdminFolder(c, bin), env...); err != nil {- var ie *installError- if none = errors.As(err, &ie) && c[0] == "winget" && uint32(ie.code) == wingetNoUpgrade; !none {+ if c[0] == rtkWindowsRelease {+ // no package manager and no installer to run: magpie downloads+ // rtk's own Windows release and replaces the binary itself (#2006)+ version := RTKLatest()+ if version == "" {+ return nil, fmt.Errorf("magpie can't tell which RTK release to install for %s — check the network and try again", bin)+ }+ if err := installRTKWindowsRelease(version, bin); err != nil {return nil, err}+ } else {+ var env []string+ if c[0] == "sh" {+ env = []string{"RTK_INSTALL_DIR=" + c[3]}+ c = c[:3]+ }+ timeout := 10 * time.Minute+ if c[0] == "cargo" {+ timeout = 30 * time.Minute // it builds rtk+ }+ // brew upgrade updates Homebrew first, for its newest rtk+ // winget having no newer rtk than this one yet is no failure+ if _, err := runRTKInstaller(c, timeout, rtkAdminFolder(c, bin), env...); err != nil {+ var ie *installError+ if none = errors.As(err, &ie) && c[0] == "winget" && uint32(ie.code) == wingetNoUpgrade; !none {+ return nil, err+ }+ }}v := ReadRTK()- // the package manager just installed the newest it has+ // an upgrade through a package manager leaves it with the newest it+ // has; the release path above has no package manager to record forrtkChannelHas(c, v.Version)v.CheckLatest()if v.Latest != "" && newer(v.Latest, v.Version) {@@ -532,11 +760,14 @@ func (e *installError) Error() string { return e.msg }// winget's exit codes are HRESULTs (AppInstallerErrors.h); the ones an// upgrade or install of rtk-ai.rtk meets, said plainly.-const wingetNoUpgrade uint32 = 0x8A15002B // APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE+const (+ wingetNoUpgrade uint32 = 0x8A15002B // APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE+ wingetNotFound uint32 = 0x8A150014 // APPINSTALLER_CLI_ERROR_NO_APPLICATIONS_FOUND+)var wingetSays = map[uint32]string{wingetNoUpgrade: "winget has no newer RTK than this one yet",- 0x8A150014: "winget finds no rtk-ai.rtk package",+ wingetNotFound: "winget finds no rtk-ai.rtk package",wingetNeedsAdmin: "winget needs an administrator for this RTK, installed for every user of this computer",0x8A150050: "winget can't tell which version of RTK is installed, so it won't upgrade it",0x8A150101: "RTK is in use — close the agents running it and try again",diff --git a/internal/library/rtk_windows_release_test.go b/internal/library/rtk_windows_release_test.gonew file mode 100644index 000000000..46d21395b--- /dev/null+++ b/internal/library/rtk_windows_release_test.go@@ -0,0 +1,288 @@+package library++import (+ "archive/zip"+ "bytes"+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/testenv"+)++// fakeRTKRelease serves a fake rtk Windows release at the URL rtkDownloadBase+// is set to: the zip holds exe as rtk.exe, and checksums.txt gives its+// SHA-256 — a wrong one when bad, so the check can be made to fail (#2006).+func fakeRTKRelease(t *testing.T, exe string, bad bool) string {+ t.Helper()+ var zb bytes.Buffer+ zw := zip.NewWriter(&zb)+ w, err := zw.Create("rtk.exe")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := w.Write([]byte(exe)); err != nil {+ t.Fatal(err)+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }+ sum := sha256.Sum256(zb.Bytes())+ line := hex.EncodeToString(sum[:])+ if bad {+ line = strings.Repeat("0", 64)+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.HasSuffix(r.URL.Path, "/checksums.txt") {+ fmt.Fprintf(w, "%s rtk-x86_64-pc-windows-msvc.zip\n", line)+ return+ }+ w.Write(zb.Bytes())+ }))+ t.Cleanup(srv.Close)+ return srv.URL+}++// #2006: a standalone rtk.exe on Windows — rtk's own release put in+// %USERPROFILE%\.local\bin, not winget's and not cargo's — had no upgrade+// command, so the Upgrade button was disabled. It now gets one; an rtk+// winget's records say winget installed is still not taken over.+func TestRTKWindowsStandaloneUpgrader(t *testing.T) {+ h := sandbox(t)+ arch := rtkArch+ rtkArch = "amd64"+ t.Cleanup(func() { rtkArch = arch })+ bin := filepath.Join(h, ".local", "bin", "rtk.exe")+ write(t, bin, "rtk")+ win, rec := rtkOnWindows, wingetRecords+ rtkOnWindows = true+ wingetRecords = func() ([]string, bool) { return []string{filepath.Join(h, "winget")}, true }+ forgetWingetOwned()+ t.Cleanup(func() {+ rtkOnWindows, wingetRecords = win, rec+ forgetWingetOwned()+ })++ if c := rtkUpgrader(bin); len(c) != 2 || c[0] != rtkWindowsRelease || c[1] != bin {+ t.Fatalf("standalone: upgrader %q; want %s … %s", c, rtkWindowsRelease, bin)+ }++ // winget's records say it is winget's: magpie doesn't take it over+ forgetWingetOwned()+ wingetRecords = func() ([]string, bool) { return []string{filepath.Dir(bin)}, true }+ if c := rtkUpgrader(bin); c != nil {+ t.Fatalf("winget's own: upgrader %q; want none", c)+ }++ // magpie on arm64: rtk's Windows release has no build for it+ forgetWingetOwned()+ wingetRecords = func() ([]string, bool) { return []string{filepath.Join(h, "winget")}, true }+ rtkArch = "arm64"+ if c := rtkUpgrader(bin); c != nil {+ t.Fatalf("arm64: upgrader %q; want none", c)+ }+}++// #2006: with no record of winget's to read, the standalone action needs+// winget to say it has no rtk-ai.rtk, or no winget at all. A winget that+// couldn't say (it timed out) is no answer: the rtk may be winget's, and+// magpie doesn't take it over.+func TestRTKWindowsStandaloneAsksWinget(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fakes are shell scripts")+ }+ h := sandbox(t)+ bin := filepath.Join(h, ".local", "bin", "rtk.exe")+ write(t, bin, "rtk")+ arch := rtkArch+ rtkArch = "amd64"+ t.Cleanup(func() { rtkArch = arch })+ none := func() ([]string, bool) { return nil, false }+ t.Setenv("PATH", filepath.Join(h, "empty"))++ // no winget on the PATH: nothing of winget's to take over+ win, rec := rtkOnWindows, wingetRecords+ rtkOnWindows, wingetRecords = true, none+ forgetWingetOwned()+ t.Cleanup(func() {+ rtkOnWindows, wingetRecords = win, rec+ forgetWingetOwned()+ })+ if c := rtkUpgrader(bin); len(c) != 2 || c[0] != rtkWindowsRelease {+ t.Fatalf("no winget: upgrader %q; want %s", c, rtkWindowsRelease)+ }++ // winget answers, and lists no rtk-ai.rtk+ wingetOn(t, h, wingetUnlisted, 0, none)+ if c := rtkUpgrader(bin); len(c) != 2 || c[0] != rtkWindowsRelease {+ t.Fatalf("unlisted: upgrader %q; want %s", c, rtkWindowsRelease)+ }++ // winget lists it: winget upgrades it+ wingetOn(t, h, wingetListed, 0, none)+ if c := rtkUpgrader(bin); len(c) == 0 || c[0] != "winget" {+ t.Fatalf("listed: upgrader %q; want winget upgrade", c)+ }++ // winget fails some other way (its sources unreachable): no answer+ wingetOn(t, h, "", 1, none)+ if c := rtkUpgrader(bin); c != nil {+ t.Fatalf("winget failed: upgrader %q; want none", c)+ }++ // winget runs out of time: no answer either+ testenv.Program(t, filepath.Join(h, "tools", "winget"), "#!/bin/sh\nexec sleep 5\n")+ old := wingetListTimeout+ wingetListTimeout = 200 * time.Millisecond+ t.Cleanup(func() { wingetListTimeout = old })+ forgetWingetOwned()+ if c := rtkUpgrader(bin); c != nil {+ t.Fatalf("hung winget: upgrader %q; want none", c)+ }+}++// #2006: only a member named rtk.exe is taken out of the release zip;+// another exe in it (rtk-proxy's) is not rtk.+func TestRTKWindowsReleaseZipNeedsRTKExe(t *testing.T) {+ var zb bytes.Buffer+ zw := zip.NewWriter(&zb)+ for _, n := range []string{"LICENSE", "rtk-proxy.exe"} {+ w, err := zw.Create(n)+ if err != nil {+ t.Fatal(err)+ }+ w.Write([]byte(n))+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }+ if b, err := rtkExeFromZip(zb.Bytes()); err == nil {+ t.Fatalf("took %q from a zip with no rtk.exe", b)+ }+}++// #2006: UpgradeRTK replaces a standalone Windows rtk with rtk.exe out of+// rtk's own Windows release, and what it then reads is the new version.+func TestRTKWindowsReleaseReplacesBinary(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the fake rtk is a shell script")+ }+ h := sandbox(t)+ latestServer(t, "v1.0.1")+ dir := filepath.Join(h, ".local", "bin")+ bin := filepath.Join(dir, "rtk")+ write(t, filepath.Join(dir, "VERSION"), "0.9.0")+ testenv.Program(t, bin, strings.ReplaceAll(versionedRTK, "VERSION", filepath.Join(dir, "VERSION")))+ t.Setenv("PATH", dir)+ // the action rtkUpgrader gives the standalone rtk.exe: this runnable rtk+ // stands in for one, since a fake here is a shell script (rtkUpgrader's+ // own branch is judged above)+ up := upgraderOf+ upgraderOf = func(string) []string { return []string{rtkWindowsRelease, bin} }+ t.Cleanup(func() { upgraderOf = up })++ const newRTK = "#!/bin/sh\ncase \"$1\" in\n--version) echo 'rtk 1.0.1'; exit 0 ;;\ngain) echo '{\"summary\":{\"total_commands\":0}}' ;;\nesac\nexit 2\n"+ old := rtkDownloadBase+ rtkDownloadBase = fakeRTKRelease(t, newRTK, false)+ t.Cleanup(func() { rtkDownloadBase = old })++ v, err := UpgradeRTK()+ if err != nil {+ t.Fatal(err)+ }+ if v.Version != "1.0.1" {+ t.Fatalf("version %q; want 1.0.1", v.Version)+ }+ if got := read(t, bin); got != newRTK {+ t.Fatalf("binary not replaced:\n got %q\nwant %q", got, newRTK)+ }+ // the rtk and the fake's VERSION file, nothing written beside them+ if ents, _ := os.ReadDir(dir); len(ents) != 2 {+ t.Fatalf("left files behind in %s: %v", dir, ents)+ }+}++// #2006: a download that doesn't match rtk's own checksums is refused, and+// the rtk that was there is left untouched — no half-written file either.+func TestRTKWindowsReleaseChecksumMismatch(t *testing.T) {+ h := sandbox(t)+ dir := filepath.Join(h, ".local", "bin")+ bin := filepath.Join(dir, "rtk.exe")+ write(t, bin, "the rtk that was here")+ old := rtkDownloadBase+ rtkDownloadBase = fakeRTKRelease(t, "the new rtk", true)+ t.Cleanup(func() { rtkDownloadBase = old })++ err := installRTKWindowsRelease("1.0.1", bin)+ if err == nil || !strings.Contains(err.Error(), "checksum") {+ t.Fatalf("mismatch: %v; want a checksum error", err)+ }+ if got := read(t, bin); got != "the rtk that was here" {+ t.Fatalf("binary changed to %q", got)+ }+ if ents, _ := os.ReadDir(dir); len(ents) != 1 {+ t.Fatalf("left files behind in %s: %v", dir, ents)+ }+}++// #2006: the Upgrade button shows this string, so it must read as what the+// upgrade does — not the internal action name and the user's binary path.+func TestRTKWindowsReleaseShown(t *testing.T) {+ bin := `C:\x\rtk.exe`+ got := shown([]string{rtkWindowsRelease, bin})+ if got != "rtk's own Windows release" {+ t.Fatalf("shown %q; want %q", got, "rtk's own Windows release")+ }+ if strings.Contains(got, rtkWindowsRelease) || strings.Contains(got, bin) {+ t.Fatalf("shown %q leaks the action or the path", got)+ }+}++// #2006: UpgradeRTK hands this channel to magpie's own download-and-replace+// instead of running the action as a command (it is not one). This is the+// wiring the two tests above leave untested on Windows: the successful one+// skips there. A download that doesn't match rtk's checksums is enough —+// its error is the install's, not the installer's.+func TestRTKWindowsReleaseUpgradeRunsTheInstall(t *testing.T) {+ h := sandbox(t)+ latestServer(t, "v1.0.1")+ // rtk is found on the PATH first (rtkPath), which is how a hand-placed+ // .local\bin\rtk.exe on it is found on the machine of the report+ const script = "#!/bin/sh\nexit 2\n"+ testenv.Program(t, filepath.Join(h, "bin", "rtk"), script)+ write(t, filepath.Join(h, "bin", "rtk.exe"), "rtk")+ bin := rtkPath()+ if bin == "" {+ t.Fatal("no rtk on the sandbox's PATH")+ }+ up := upgraderOf+ upgraderOf = func(string) []string { return []string{rtkWindowsRelease, bin} }+ old := rtkDownloadBase+ rtkDownloadBase = fakeRTKRelease(t, "the new rtk", true)+ ver := rtkVersion+ rtkVersion = func() string { return "0.9.0" }+ t.Cleanup(func() {+ upgraderOf, rtkDownloadBase, rtkVersion = up, old, ver+ })++ _, err := UpgradeRTK()+ if err == nil || !strings.Contains(err.Error(), "checksum") {+ t.Fatalf("upgrade through the release channel: %v; want the checksum error", err)+ }+ // rtkPath finds the runnable rtk here, rtk.exe on Windows+ want := script+ if filepath.Base(bin) == "rtk.exe" {+ want = "rtk"+ }+ if got := read(t, bin); got != want {+ t.Fatalf("the rtk changed to %q", got)+ }+}diff --git a/internal/library/rtk_windows_replace_test.go b/internal/library/rtk_windows_replace_test.gonew file mode 100644index 000000000..8d5683ffe--- /dev/null+++ b/internal/library/rtk_windows_replace_test.go@@ -0,0 +1,31 @@+package library++import (+ "os"+ "path/filepath"+ "testing"+)++// #2006: the replacement itself is what the bug was about — the standalone+// rtk.exe had no upgrade at all — and the tests above skip the successful+// one on Windows, where the fake rtk is a shell script. This one needs no+// runnable rtk: it is the swap, on whatever platform it runs, including+// the one the issue is about, where the old file is renamed aside rather+// than removed.+func TestRTKWindowsReleaseSwapsTheFile(t *testing.T) {+ dir := t.TempDir()+ bin := filepath.Join(dir, "rtk.exe")+ write(t, bin, "the rtk that was here")+ // what an earlier upgrade left when the rtk it moved aside was running+ write(t, bin+".old-123", "an older rtk")++ if err := replaceRTKBinary(bin, []byte("the new rtk")); err != nil {+ t.Fatal(err)+ }+ if got := read(t, bin); got != "the new rtk" {+ t.Fatalf("binary %q; want %q", got, "the new rtk")+ }+ if ents, _ := os.ReadDir(dir); len(ents) != 1 {+ t.Fatalf("left files behind in %s: %v", dir, ents)+ }+}