diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bce8fc3..a83290d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -146,6 +146,7 @@ jobs: echo "no release for $TAG yet" fi - uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 + id: draft with: # the program files with their checksums, under the current and the former names (verify-release.ps1 # checks that exactly these are there) @@ -163,6 +164,24 @@ jobs: body_path: ${{ runner.temp }}/release-notes.md fail_on_unmatched_files: true draft: true # made public by the verify job, once the files check out + # The release page shows a file's label in place of its name: each copy under a former name (and its .sha256) says + # what it is. The program finds its file by name, never by label, and verify-release.ps1 checks the labels. + - name: Label the copies under the former names + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RELEASE_ID: ${{ steps.draft.outputs.id }} + run: | + assets="$(gh api "repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID/assets?per_page=100" --jq '.[] | "\(.id) \(.name)"')" + while read -r kind current former; do + [ "$kind" = file ] || continue + for suffix in "" .sha256; do + id="$(awk -v n="$former$suffix" '$2 == n { print $1 }' <<< "$assets")" + [ -n "$id" ] || { echo "::error title=release::$former$suffix is not in the draft"; exit 1; } + gh api -X PATCH "repos/$GITHUB_REPOSITORY/releases/assets/$id" -f label="Former name, for copies installed before the rename: the same file as $current$suffix" > /dev/null + echo "labelled $former$suffix" + done + done < <(tr -d '\r' < tools/ci/former-names.txt) # Every program file again, built on another runner from the tag, at the same time as the release job (it needs nothing # from it). Its files' SHA-256 go to the verify job, which compares them with the release's before it publishes the diff --git a/cmd/mprp/api.go b/cmd/mprp/api.go index e777549..2bca164 100644 --- a/cmd/mprp/api.go +++ b/cmd/mprp/api.go @@ -103,7 +103,7 @@ func (a *app) fullState() map[string]any { } return map[string]any{ "version": version, "schema": store.SectionsFor(runtime.GOOS), "os": runtime.GOOS, "values": a.st.Values(), "app": a.st.App(), - "status": a.eng.Status(), "autoStart": winsys.GetAutoStart(a.exe), "dataDir": a.st.Dir, "update": upd, + "status": a.eng.Status(), "autoStart": winsys.GetAutoStart(a.exePath()), "dataDir": a.st.Dir, "update": upd, "changelog": json.RawMessage(assets.Changelog), "stats": a.eng.Stats(), "tray": a.getTray() != nil, // macOS: whether the menu bar icon is there (a build without it runs in the background) } @@ -130,7 +130,7 @@ func (a *app) save(body *jsonx.Obj) (any, error) { applySettings(a.st, a.eng) after := a.st.App() if pa, ok := body.M["app"].(*jsonx.Obj); ok { - if _, has := pa.M["autoStart"]; has && !winsys.SetAutoStart(after.AutoStart, a.exe) { + if _, has := pa.M["autoStart"]; has && !winsys.SetAutoStart(after.AutoStart, a.exePath()) { // the switch would only flip back at the next redraw, with "Saved." shown: say so, and keep the saved value // matching the system undo, _ := jsonx.Parse(`{"app":{"autoStart":` + strconv.FormatBool(!after.AutoStart) + `}}`) @@ -166,7 +166,7 @@ func (a *app) reset() (any, error) { return nil, err } applySettings(a.st, a.eng) - winsys.SetAutoStart(a.st.App().AutoStart, a.exe) + winsys.SetAutoStart(a.st.App().AutoStart, a.exePath()) a.upd.set(nil) a.log("INFO", "Settings restored to their defaults.") return a.fullState(), nil diff --git a/cmd/mprp/app.go b/cmd/mprp/app.go index 99bed06..acbaa1b 100644 --- a/cmd/mprp/app.go +++ b/cmd/mprp/app.go @@ -28,7 +28,7 @@ type app struct { eng *engine.Engine lg *logger log func(level, msg string) - exe string // this program, where the autostart entry and updates point + exe string // this program file, where the autostart entry and updates point (read with exePath) ipcFile string ipcFormer string // during an update, ipc.json also goes here (formerIPC; "": nowhere else) browserProfile string // the profile of the browser that shows the settings window @@ -48,7 +48,7 @@ type app struct { winSys *windowSys // nil: the system's window functions (tests stand in for a window) busyUntil atomic.Int64 // until then (Unix nanoseconds) no update installs itself: see settle - mu sync.Mutex + mu sync.Mutex // guards tray, notifier and exe tray *winsys.Tray notifier *notify.Notifier // Linux: the desktop notification service (made at the first notification) @@ -130,15 +130,20 @@ func run() error { a.log("WARN", "The update to "+failedUpdate+" did not start, so "+version+" is back. That version is not installed by itself again; a newer one will be.") } } - if afterUpdate { + switch whenToRename(afterUpdate, updateFailed) { + case renameAfterHandOver: // The copy that started this one keeps the old program file until this one has shown that it runs, to put it - // back otherwise. So the leftovers go a little later, once that copy is gone. + // back otherwise. So the leftovers go a little later, once that copy is gone, and only then may the program + // file get the program's name. engine.Go(a.log, "The clean-up after the update", func() { time.Sleep(proofWait + 30*time.Second) - updater.CleanupOld(exe) - _ = os.Remove(filepath.Join(st.Dir, failedMarker)) + a.afterHandOver() }) - } else { + case renameAtStart: + a.followName() + exe = a.exePath() + updater.CleanupOld(exe) + default: updater.CleanupOld(exe) } winsys.CloseWindowBrowser(a.browserProfile) // a window browser left behind by a crash @@ -214,6 +219,28 @@ func run() error { return nil } +// afterHandOver is the clean-up once an update's hand-over is over: the old copy has left, or can no longer put its +// own file back. The update's leftovers go, then the program file gets the program's name if it still has the former +// one (followName). +func (a *app) afterHandOver() { + updater.CleanupOld(a.exePath()) + _ = os.Remove(filepath.Join(a.st.Dir, failedMarker)) + a.followName() +} + +// exePath is the program file (exe). +func (a *app) exePath() string { + a.mu.Lock() + defer a.mu.Unlock() + return a.exe +} + +func (a *app) setExe(p string) { + a.mu.Lock() + a.exe = p + a.mu.Unlock() +} + func (a *app) getTray() *winsys.Tray { a.mu.Lock() defer a.mu.Unlock() diff --git a/cmd/mprp/selfrename.go b/cmd/mprp/selfrename.go new file mode 100644 index 0000000..93edb15 --- /dev/null +++ b/cmd/mprp/selfrename.go @@ -0,0 +1,149 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/CptPakundo/MPRP/internal/core" + "github.com/CptPakundo/MPRP/internal/updater" + "github.com/CptPakundo/MPRP/internal/winsys" +) + +// An install made before the program was renamed updates itself in place, so its program file keeps the former +// release name (MPCvibedRPC.exe, MPCvibedRPC-linux-amd64, ...). The program gives such a file the current name +// (MPRP.exe, ...) itself: a file with any other name (a user's own, a development build) is never touched, nor is the +// macOS app (it does not update itself, and its file is inside the app bundle). + +// renameMoment is when the program renames its own file. +type renameMoment int + +const ( + renameNever renameMoment = iota // the old version, back after an update that did not start + renameAtStart // a normal start + renameAfterHandOver // after an update, once the copy that started this one can no longer put itself back +) + +// whenToRename: never during an update's hand-over (the old copy puts its own file back under the former name if this +// copy does not come up) and never in the copy that came back that way. +func whenToRename(afterUpdate, updateFailed bool) renameMoment { + switch { + case updateFailed: + return renameNever + case afterUpdate: + return renameAfterHandOver + } + return renameAtStart +} + +// formerFileName is this system's former release file name and the current one ("" for both where there is none). +func formerFileName(goos, goarch string) (former, current string) { + current = updater.AssetFor(goos, goarch) + if current == "" { + return "", "" + } + return strings.Replace(current, core.Name, core.FormerName, 1), current +} + +// renameTarget is the path exe gets: the current name in its folder when exe's file name is exactly the former release +// name (any case on Windows), else "". +func renameTarget(goos, goarch, exe string) string { + former, current := formerFileName(goos, goarch) + if former == "" { + return "" + } + base := filepath.Base(exe) + if base == former || (goos == "windows" && strings.EqualFold(base, former)) { + return filepath.Join(filepath.Dir(exe), current) + } + return "" +} + +// renameProgramFile gives exe the current name (renameTarget) and returns the program file's path afterwards (exe when +// it was not renamed) with a line for the log ("": nothing to say). The rule when a file of the current name is there +// already: +// - the same bytes: exe is a second copy of the same program. It is moved aside as exe + ".old" (deleted now where +// the system allows it, else at the next start: removeFormerLeftovers) and the program goes on as the other file. +// - other bytes: both stay as they are, and the start says so in the log. +// +// A folder that cannot be written to (Program Files without the rights) leaves the file as it is, with a warning. +func renameProgramFile(goos, goarch, exe string) (now, level, msg string) { + to := renameTarget(goos, goarch, exe) + if to == "" { + return exe, "", "" + } + name := filepath.Base(to) + if _, err := os.Lstat(to); err == nil { + if !sameContent(exe, to) { + return exe, "INFO", "The program file keeps its former name " + filepath.Base(exe) + ": a different " + name + " is already in its folder." + } + old := exe + ".old" + _ = os.Remove(old) + if err := os.Rename(exe, old); err != nil { + return exe, "WARN", "The program file " + filepath.Base(exe) + " is a second copy of " + name + " next to it but could not be moved aside: " + err.Error() + } + _ = os.Remove(old) // Linux lets a running program's file go; on Windows it goes at the next start + return to, "INFO", "The program file " + filepath.Base(exe) + " was a second copy of " + name + " next to it, so the program now runs as " + name + "; shortcuts made to the old name need making again." + } + if err := renameNoReplace(exe, to); err != nil { + return exe, "WARN", "Could not rename the program file to " + name + " (" + err.Error() + "); it keeps working under its former name." + } + return to, "INFO", "The program file was renamed to " + name + " (the program's new name); shortcuts made to the old name need making again." +} + +// sameContent says whether the files a and b hold the same bytes (a program file is a few MB). +func sameContent(a, b string) bool { + x, err := os.ReadFile(a) + if err != nil { + return false + } + y, err := os.ReadFile(b) + return err == nil && bytes.Equal(x, y) +} + +// removeFormerLeftovers deletes what an update or renameProgramFile left next to the program file exe under the +// former name (.old, .new), once the program runs under the current name and no file of the former +// name is there any more (one that is there may be another copy, whose update they belong to). +func removeFormerLeftovers(goos, goarch, exe string) { + former, current := formerFileName(goos, goarch) + if former == "" || !strings.EqualFold(filepath.Base(exe), current) { + return + } + f := filepath.Join(filepath.Dir(exe), former) + if _, err := os.Lstat(f); err == nil { + return + } + _ = os.Remove(f + ".old") + _ = os.Remove(f + ".new") +} + +// followRunEntry points the run-at-login entry at the renamed file (a variable: tests never touch the real one). +var followRunEntry = winsys.FollowRename + +// setProgramFile tells the window code the new path (a variable: tests leave the package alone). +var setProgramFile = winsys.SetProgramFile + +// followName renames the program file when it still has the former name (renameProgramFile), and makes everything +// that names it follow: the path updates and the window use, and the run-at-login entry. It deletes the former name's +// leftovers. It holds off while an update is being installed (the next start does it). +func (a *app) followName() { + if !a.upd.installing.CompareAndSwap(false, true) { + return + } + defer a.upd.installing.Store(false) + old := a.exePath() + now, level, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, old) + if msg != "" { + a.log(level, msg) + } + if now != old { + a.setExe(now) + setProgramFile(now) + if note := followRunEntry(old, now); note != "" { + a.log("INFO", note) + } + } + removeFormerLeftovers(runtime.GOOS, runtime.GOARCH, now) +} diff --git a/cmd/mprp/selfrename_other.go b/cmd/mprp/selfrename_other.go new file mode 100644 index 0000000..9d50160 --- /dev/null +++ b/cmd/mprp/selfrename_other.go @@ -0,0 +1,21 @@ +//go:build !windows + +package main + +import "os" + +// renameNoReplace renames from to to, failing when to exists (os.Rename would replace it). A hard link fails when to +// exists; a file system without hard links gets a plain rename after a look. +func renameNoReplace(from, to string) error { + if err := os.Link(from, to); err == nil { + if err := os.Remove(from); err != nil { + _ = os.Remove(to) + return err + } + return nil + } + if _, err := os.Lstat(to); err == nil { + return os.ErrExist + } + return os.Rename(from, to) +} diff --git a/cmd/mprp/selfrename_test.go b/cmd/mprp/selfrename_test.go new file mode 100644 index 0000000..f883f18 --- /dev/null +++ b/cmd/mprp/selfrename_test.go @@ -0,0 +1,258 @@ +package main + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// The program file is renamed only at a normal start, or after an update once its hand-over is over; never in the +// old version that came back after an update that did not start. +func TestWhenToRename(t *testing.T) { + for _, c := range []struct { + after, failed bool + want renameMoment + }{ + {false, false, renameAtStart}, + {true, false, renameAfterHandOver}, + {false, true, renameNever}, + {true, true, renameNever}, + } { + if got := whenToRename(c.after, c.failed); got != c.want { + t.Errorf("after update %v, update failed %v: %v, want %v", c.after, c.failed, got, c.want) + } + } +} + +// Only the exact former release names are renamed (any case on Windows), each to its current twin; any other name, +// and the macOS app, never. +func TestRenameTarget(t *testing.T) { + dir := filepath.Join("some", "folder") + for _, c := range []struct{ goos, goarch, name, want string }{ + {"windows", "amd64", "MPCvibedRPC.exe", "MPRP.exe"}, + {"windows", "arm64", "mpcvibedrpc.EXE", "MPRP.exe"}, + {"windows", "amd64", "MPRP.exe", ""}, + {"windows", "amd64", "MPCvibedRPC (1).exe", ""}, + {"windows", "amd64", "MyPresence.exe", ""}, + {"windows", "amd64", "MPCvibedRPC-linux-amd64", ""}, + {"linux", "amd64", "MPCvibedRPC-linux-amd64", "MPRP-linux-amd64"}, + {"linux", "arm64", "MPCvibedRPC-linux-arm64", "MPRP-linux-arm64"}, + {"linux", "amd64", "mpcvibedrpc-linux-amd64", ""}, // case counts on Linux + {"linux", "amd64", "MPCvibedRPC-linux-arm64", ""}, // another system's file + {"linux", "amd64", "mprp", ""}, + {"darwin", "arm64", "MPCvibedRPC", ""}, + {"darwin", "arm64", "MPRP", ""}, + } { + want := "" + if c.want != "" { + want = filepath.Join(dir, c.want) + } + if got := renameTarget(c.goos, c.goarch, filepath.Join(dir, c.name)); got != want { + t.Errorf("%s/%s %s: %q, want %q", c.goos, c.goarch, c.name, got, want) + } + } +} + +// Each pair is a file line of tools/ci/former-names.txt, the list of former-name files every release publishes. +func TestFormerFileNamesAreInTheList(t *testing.T) { + b, err := os.ReadFile(filepath.Join("..", "..", "tools", "ci", "former-names.txt")) + if err != nil { + t.Fatal(err) + } + list := strings.ReplaceAll(string(b), "\r", "") + for _, s := range [][2]string{{"windows", "amd64"}, {"linux", "amd64"}, {"linux", "arm64"}} { + former, current := formerFileName(s[0], s[1]) + if !strings.Contains(list, "\nfile "+current+" "+former+"\n") { + t.Errorf("former-names.txt has no line \"file %s %s\"", current, former) + } + } +} + +// thisSystem skips where the program does not rename itself (macOS), and gives this system's former and current +// file names. +func thisSystem(t *testing.T) (former, current string) { + t.Helper() + former, current = formerFileName(runtime.GOOS, runtime.GOARCH) + if former == "" { + t.Skip("the program file is not renamed on " + runtime.GOOS) + } + return former, current +} + +func TestRenameProgramFile(t *testing.T) { + former, current := thisSystem(t) + setup := func(t *testing.T, files map[string]string) (dir string) { + dir = t.TempDir() + for n, c := range files { + os.WriteFile(filepath.Join(dir, n), []byte(c), 0o755) + } + return dir + } + exists := func(p string) bool { _, err := os.Lstat(p); return err == nil } + + t.Run("renamed", func(t *testing.T) { + dir := setup(t, map[string]string{former: "program"}) + now, level, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, filepath.Join(dir, former)) + if now != filepath.Join(dir, current) || level != "INFO" || !strings.Contains(msg, "renamed to "+current) { + t.Fatalf("now %q, %s %q", now, level, msg) + } + if fileText(now) != "program" || exists(filepath.Join(dir, former)) { + t.Error("the file was not renamed") + } + }) + t.Run("any other name is left alone", func(t *testing.T) { + dir := setup(t, map[string]string{"dev-build": "program"}) + exe := filepath.Join(dir, "dev-build") + if now, _, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, exe); now != exe || msg != "" || !exists(exe) { + t.Errorf("now %q, msg %q", now, msg) + } + }) + t.Run("a second copy of the same file is moved aside", func(t *testing.T) { + dir := setup(t, map[string]string{former: "program", current: "program"}) + now, level, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, filepath.Join(dir, former)) + if now != filepath.Join(dir, current) || level != "INFO" || !strings.Contains(msg, "second copy") { + t.Fatalf("now %q, %s %q", now, level, msg) + } + if exists(filepath.Join(dir, former)) || fileText(now) != "program" { + t.Error("the second copy is still there, or the other file changed") + } + // the file moved aside (still there where the system keeps a running program's file) goes at the next start + removeFormerLeftovers(runtime.GOOS, runtime.GOARCH, now) + if exists(filepath.Join(dir, former+".old")) { + t.Error("the file moved aside is still there") + } + }) + t.Run("a different file of the new name: both stay", func(t *testing.T) { + dir := setup(t, map[string]string{former: "program", current: "another program"}) + exe := filepath.Join(dir, former) + now, level, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, exe) + if now != exe || level != "INFO" || !strings.Contains(msg, "keeps its former name") { + t.Fatalf("now %q, %s %q", now, level, msg) + } + if fileText(exe) != "program" || fileText(filepath.Join(dir, current)) != "another program" { + t.Error("a file was changed") + } + }) + t.Run("a folder that cannot be written to", func(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a read-only folder still allows renames on Windows") + } + dir := setup(t, map[string]string{former: "program"}) + os.Chmod(dir, 0o555) + defer os.Chmod(dir, 0o755) + exe := filepath.Join(dir, former) + if f, err := os.Create(filepath.Join(dir, "probe")); err == nil { // running as root + f.Close() + t.Skip("the folder is writable all the same") + } + now, level, msg := renameProgramFile(runtime.GOOS, runtime.GOARCH, exe) + if now != exe || level != "WARN" || !strings.Contains(msg, "keeps working") || !exists(exe) { + t.Errorf("now %q, %s %q", now, level, msg) + } + }) +} + +// Leftovers of the former name go once the program runs under its current name, and only when no file of the former +// name is there (its own update may need them). +func TestRemoveFormerLeftovers(t *testing.T) { + former, current := thisSystem(t) + dir := t.TempDir() + for _, n := range []string{former + ".old", former + ".new", former} { + os.WriteFile(filepath.Join(dir, n), []byte("x"), 0o755) + } + removeFormerLeftovers(runtime.GOOS, runtime.GOARCH, filepath.Join(dir, current)) + if _, err := os.Stat(filepath.Join(dir, former+".old")); err != nil { + t.Error("removed with a file of the former name there") + } + os.Remove(filepath.Join(dir, former)) + removeFormerLeftovers(runtime.GOOS, runtime.GOARCH, filepath.Join(dir, former)) // not under the current name yet + if _, err := os.Stat(filepath.Join(dir, former+".old")); err != nil { + t.Error("removed while the program still has the former name") + } + removeFormerLeftovers(runtime.GOOS, runtime.GOARCH, filepath.Join(dir, current)) + for _, n := range []string{former + ".old", former + ".new"} { + if _, err := os.Stat(filepath.Join(dir, n)); err == nil { + t.Errorf("%s is still there", n) + } + } +} + +// renameApp is an app whose program file is a stand-in of the former name in a temporary folder; the run-at-login +// entry and the window code are fakes. +func renameApp(t *testing.T) (a *app, logs func() string, entry *string) { + t.Helper() + former, _ := thisSystem(t) + a, logs = autoApp(t) + a.exe = filepath.Join(t.TempDir(), former) + os.WriteFile(a.exe, []byte("program"), 0o755) + cmd := `"` + a.exe + `" --background` // the fake Run value + entry = &cmd + f, s := followRunEntry, setProgramFile + t.Cleanup(func() { followRunEntry, setProgramFile = f, s }) + followRunEntry = func(old, now string) string { + if !strings.Contains(*entry, old) { + return "" + } + *entry = `"` + now + `" --background` + return "The run-at-login entry now starts " + now + "." + } + setProgramFile = func(string) {} + return a, logs, entry +} + +// After a rename everything follows the new path: the updates, the run-at-login entry; the log says so once. +func TestFollowName(t *testing.T) { + _, current := thisSystem(t) + a, logs, entry := renameApp(t) + old := a.exe + a.followName() + want := filepath.Join(filepath.Dir(old), current) + if a.exePath() != want || fileText(want) != "program" { + t.Fatalf("exe %q\n%s", a.exePath(), logs()) + } + if *entry != `"`+want+`" --background` { + t.Errorf("run entry %q", *entry) + } + if n := strings.Count(logs(), "renamed to "+current); n != 1 { + t.Errorf("%d log lines of the rename\n%s", n, logs()) + } + if a.upd.installing.Load() { + t.Error("an update stays blocked") + } + a.followName() // the next time there is nothing to do + if strings.Count(logs(), "renamed") != 1 { + t.Errorf("renamed twice\n%s", logs()) + } +} + +// An update being installed holds the rename off: the update's own files are next to the program file. +func TestFollowNameWaitsForAnInstall(t *testing.T) { + a, _, _ := renameApp(t) + old := a.exe + a.upd.installing.Store(true) + a.followName() + if a.exePath() != old || fileText(old) != "program" { + t.Error("renamed during an install") + } +} + +// After an update the rename waits for the end of the hand-over (afterHandOver): until then the copy that started +// this one may still put its own program file back under the former name. +func TestAfterHandOverRenames(t *testing.T) { + _, current := thisSystem(t) + a, logs, _ := renameApp(t) + old := a.exe + os.WriteFile(old+".old", []byte("the version before"), 0o755) + os.WriteFile(filepath.Join(a.st.Dir, failedMarker), []byte("9.9.9"), 0o644) + a.afterHandOver() + if a.exePath() != filepath.Join(filepath.Dir(old), current) { + t.Fatalf("exe %q\n%s", a.exePath(), logs()) + } + for _, f := range []string{old + ".old", filepath.Join(a.st.Dir, failedMarker)} { + if _, err := os.Stat(f); err == nil { + t.Errorf("%s is still there", f) + } + } +} diff --git a/cmd/mprp/selfrename_windows.go b/cmd/mprp/selfrename_windows.go new file mode 100644 index 0000000..4c5fc00 --- /dev/null +++ b/cmd/mprp/selfrename_windows.go @@ -0,0 +1,28 @@ +package main + +import ( + "syscall" + "unsafe" +) + +var pMoveFileEx = syscall.NewLazyDLL("kernel32.dll").NewProc("MoveFileExW") + +// renameNoReplace renames from to to, failing when to exists (os.Rename would replace it). Windows lets a running +// program's file be renamed. +func renameNoReplace(from, to string) error { + f, err := syscall.UTF16PtrFromString(from) + if err != nil { + return err + } + t, err := syscall.UTF16PtrFromString(to) + if err != nil { + return err + } + if err := pMoveFileEx.Find(); err != nil { + return err + } + if r, _, e := pMoveFileEx.Call(uintptr(unsafe.Pointer(f)), uintptr(unsafe.Pointer(t)), 0); r == 0 { + return e + } + return nil +} diff --git a/cmd/mprp/update.go b/cmd/mprp/update.go index bd45263..99189f3 100644 --- a/cmd/mprp/update.go +++ b/cmd/mprp/update.go @@ -258,7 +258,7 @@ func (a *app) installUpdate(quiet func() bool) error { return errors.New("You already have the latest version.") } a.log("INFO", fmt.Sprintf("Downloading %s...", info.Latest)) - next, err := updater.Download(nil, info, a.exe) + next, err := updater.Download(nil, info, a.exePath()) if err != nil { return err } @@ -279,14 +279,14 @@ func (a *app) installUpdate(quiet func() bool) error { } } } - if err := updater.Swap(a.exe, next); err != nil { + if err := updater.Swap(a.exePath(), next); err != nil { a.log("ERROR", "Update failed: "+err.Error()) goOn() return err } - child, err := startCopy(a.exe, "--after-update") + child, err := startCopy(a.exePath(), "--after-update") if err != nil { - if rerr := updater.Restore(a.exe); rerr != nil { + if rerr := updater.Restore(a.exePath()); rerr != nil { a.log("ERROR", "The old version could not be put back: "+rerr.Error()) } err = fmt.Errorf("The new version could not be started: %v", err) @@ -364,7 +364,7 @@ func (a *app) handOverTo(child *os.Process, latest string, auto bool) { case <-gone: case <-time.After(5 * time.Second): } - if err := updater.Restore(a.exe); err != nil { + if err := updater.Restore(a.exePath()); err != nil { a.log("ERROR", "The old version could not be put back: "+err.Error()) leave(1) return @@ -375,7 +375,7 @@ func (a *app) handOverTo(child *os.Process, latest string, auto bool) { if auto { args = append(args, "--background") // it updated itself in the background, so it comes back there } - if _, err := startCopy(a.exe, args...); err != nil { + if _, err := startCopy(a.exePath(), args...); err != nil { a.log("ERROR", "The old version is back in place but could not be started: "+err.Error()) leave(1) return diff --git a/docs/decisions.md b/docs/decisions.md index 2b67fe6..2cc06bc 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -144,7 +144,10 @@ roadmap; open questions are its [Open decisions](roadmap.md#open-decisions-the-m over by itself at its first normal start: its data folder and run-at-login entry are moved to the new name (a start switched off in Task Manager stays off; after an in-app update from the former version the folder moves at the next start), and every release also publishes its program files under the former names, so copies that update - themselves find them, until the maintainer drops those names (`tools/ci/former-names.txt`). Going back to a version + themselves find them, until the maintainer drops those names (`tools/ci/former-names.txt`; the release page labels + them). Such a copy then renames its own program file to the new release name (`MPCvibedRPC.exe` to `MPRP.exe`, the + Linux files alike; never a file with any other name, never the macOS app) and points its run-at-login entry at it; + shortcuts made to the old name need making again. Going back to a version from before the rename starts it with default settings and signed out: the data stays in the new folder, and the next update to a current version uses it again. The upstream credit and MPC-HC's own names are unchanged. *Why:* the program long since serves many players and services, not only the MPC family; the new name says what it is, and the maintainer wanted it to apply to everything. diff --git a/docs/development.md b/docs/development.md index 22a3b12..de1dfd7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -168,7 +168,7 @@ on every system. | `macapp_darwin.go` | macOS (cgo only): the menu bar icon, the settings window (WebKit) and the notifications (`UNUserNotificationCenter`, only as an app bundle) | | `window.go`, `browser*.go` | the window's browser, opening a URL or folder | | `taskbar_windows.go` | the browser window's taskbar button gets the program's name, icon and start command (set from outside: from the first window on, a hook thread gives every taskbar window of a browser process that uses the window profile the identity and the built-in icon whenever it appears, and keeps the icon on it, through the shell hook and WinEvents, which it listens to only while a settings window is there or coming; it logs when the window first has the icon and what failed) | -| `autostart*.go` | start at login: the registry's Run key, a LaunchAgent, XDG autostart (`autostart_unix.go`), and carrying an entry of the former name over (`MigrateAutoStart`) | +| `autostart*.go` | start at login: the registry's Run key, a LaunchAgent, XDG autostart (`autostart_unix.go`), carrying an entry of the former name over (`MigrateAutoStart`), and following the program file's rename (`FollowRename`) | | `single_*.go` | single instance (mutex, file lock) | | `playersetup.go` (`SetUpPlayers`), `setup_unix.go`, `mpvconf.go`, `vlcconf.go` | **Set up the player connection** | @@ -391,6 +391,15 @@ Playing form while Discord shares the screen ([users' view](how-it-works.md#on-y single-instance lock and waits for the new copy's `ipc.json`. If it does not come, it puts the old program file back, writes `update-failed` (the version, which is not installed by itself again) and starts itself again with `--update-failed`. +- **The program file's former name** (`selfrename.go`): an install from before the rename keeps its file name across + in-app updates (`MPCvibedRPC.exe`, `MPCvibedRPC-linux-amd64`, ...). `followName` gives such a file (exact name; any + case on Windows) the current release name, at a normal start, or after an update once the hand-over is over + (`afterHandOver`, with the clean-up of the update's leftovers, `proofWait` + 30 s after the start: the old copy can + put its own file back until then); never with `--update-failed`, never while an update installs. A different file of + the new name in the folder leaves both; the same bytes move the former one aside (`.old`, deleted at the next + start). Then the program's path (`a.exe`, `winsys.SetProgramFile` for the window's relaunch command, since Windows' + `os.Executable` keeps the old path) and the run-at-login entry that named the old file (`winsys.FollowRename`) + follow. - **Red dot:** while an update waits, the tray and menu bar icon show a dot (`assets.IconUpdate`, made by `tools/mkico -dot`; macOS: `winsys.menuBarIcon`). @@ -554,7 +563,8 @@ Everything below has only run against fakes, or not at all. Anyone with the setu - **Start with Windows** after it was switched off in Task Manager's Startup list. - **An install from before the rename** on a real system: its data folder moved (or copied while a file is held), its run-at-login entry carried over (the Windows registry with a start switched off in Task Manager, a macOS - LaunchAgent, a Linux autostart file), and a second start while a copy of the former version still runs. + LaunchAgent, a Linux autostart file), and a second start while a copy of the former version still runs. The program + file's own rename on a real Linux desktop (its autostart file following it). - **Set up the player connection** end to end (it writes MPC-HC's registry values). - **MPC-QT's multi-window mode** with a portable build and the live engine test. - **mpv on a real Linux desktop.** diff --git a/docs/maintaining.md b/docs/maintaining.md index 10d7a70..c192731 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -65,14 +65,16 @@ version and the maintainer's go-ahead. fake server; macOS and Linux: the API, login item, player setup, a second start, and on macOS opening the app like the Finder does). It writes the `.sha256` files, adds a byte-identical copy of each program file under the former name for copies installed before the rename (`tools/ci/former-names.txt`, which says when they go), - attests the builds and publishes a **draft**. + attests the builds and publishes a **draft**, then labels each former-name copy on the release page (GitHub + shows the label in place of the file name; the program finds its file by name). 6. **`reproduce`** rebuilds the exe and both Linux programs from the tag on another runner at the same time (`tools/ci/reproduce.sh`); only `verify` waits for it. 7. **`verify`** checks that the rebuilt files' checksums equal the release's (byte for byte), then runs `tools/ci/verify-release.ps1` on the draft: the eighteen assets (the copies under the former name the same files - byte for byte), every checksum and build record, the exe's version. Only if these pass is the release made - public (and latest). Then come the checks that need it public: that it is the latest release, and a real - self-update from the previous release. + byte for byte, with their labels), every checksum and build record, the exe's version. Only if these pass is + the release made public (and latest). Then come the checks that need it public: that it is the latest release, + and a real self-update from the previous release (from one of the former name: that the updated copy renames its + file to `MPRP.exe`, about a minute after it started). 8. **A draft that fails** stays a draft (nobody's updater sees it): fix, then delete the draft and the tag, or publish it by hand once checked. 4. **Read the `verify` job's log** (`gh run view --log`) and report. Nothing needs re-running locally after a release. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8474320..ca95437 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -179,6 +179,11 @@ To uninstall: That version is not installed by itself a second time (a newer one is). On Windows 11, Smart App Control (below) can be why a new version does not start. - **macOS:** the window links to the download. +- **Installed before the rename to MPRP?** The program file renames itself from `MPCvibedRPC.exe` to `MPRP.exe` (Linux: + `MPCvibedRPC-linux-amd64` to `MPRP-linux-amd64`, and the same for arm64), at the next start, or about a minute after + the update to this version. Start with Windows follows by itself; a shortcut or a pin you made to the old file needs + making again. A file you named yourself keeps its name. If a different `MPRP.exe` is already in that folder, or the + folder cannot be written to (Program Files without the rights), the file keeps the old name and still works. - After an update the window shows what's new once; the version number at the bottom of the window shows every version. ## Is the download safe? diff --git a/internal/assets/changelog.json b/internal/assets/changelog.json index 892a48d..504717e 100644 --- a/internal/assets/changelog.json +++ b/internal/assets/changelog.json @@ -1,6 +1,7 @@ [ {"version": "0.9.60", "date": "2026-11-25", "items": [ "✨ MPCvibedRPC is now MPRP, Media Player Rich Presence, with a new logo. Your settings and start-up entry move over by themselves.", + "📁 An install from before the rename renames its program file to MPRP.exe too; shortcuts to the old name need making again.", "🎮 The status comes from the project's own Discord app: it reads \"Watching MPRP\" when the title is not the name.", "🎯 Fix a match is new: search the catalogs as you type, then pick the title, cover and episode offset, for one file or all.", "✏️ Text lines on the Look tab: Standard, Short, Detailed, or lines of your own for the status.", diff --git a/internal/core/name.go b/internal/core/name.go index 1687e4e..5505652 100644 --- a/internal/core/name.go +++ b/internal/core/name.go @@ -7,7 +7,8 @@ import "os" const Name = "MPRP" // FormerName is the name the program had before it was renamed. Only the steps that carry an existing install over -// use it: the data folder, the run-at-login entry and the check for a copy of the former version that still runs. +// use it: the data folder, the run-at-login entry, the program file's name and the check for a copy of the former +// version that still runs. const FormerName = "MPCvibedRPC" // FormerEnv pairs each environment variable the program reads with the one the former version read for the same diff --git a/internal/winsys/autostart.go b/internal/winsys/autostart.go index 9402779..e11a68e 100644 --- a/internal/winsys/autostart.go +++ b/internal/winsys/autostart.go @@ -197,3 +197,28 @@ func migrateRunValue(r runRegistry, from, to, command string) string { } return note + "." } + +// FollowRename points the run-at-login entry (Windows: the Run value; macOS, Linux: the login item) of this copy at +// newExe after the program renamed its own file from oldExe (see the program's renameProgramFile). Only an entry that +// names oldExe is rewritten, so one switched off stays off and one of another copy is left alone; on Windows the +// Task Manager switch is not touched. It gives a sentence for the log ("" when no entry named oldExe). +func FollowRename(oldExe, newExe string) string { + home := os.Getenv("MPRP_HOME") + if !IsWindows { + return followLoginItem(runtime.GOOS, userLoginItem(), oldExe, newExe, home) + } + return followRunValue(systemRegistry, runName(), oldExe, newExe, home) +} + +// followRunValue rewrites the Run value name to start newExe when its command line names oldExe (case does not +// matter: Windows paths). +func followRunValue(r runRegistry, name, oldExe, newExe, home string) string { + cur, ok := r.run(name) + if !ok || oldExe == "" || !strings.Contains(strings.ToLower(cur), strings.ToLower(oldExe)) { + return "" + } + if !r.setRun(name, runCommand(newExe, home)) { + return "Could not point the run-at-login entry " + name + " at " + newExe + "; it still names " + oldExe + "." + } + return "The run-at-login entry " + name + " now starts " + newExe + "." +} diff --git a/internal/winsys/autostart_test.go b/internal/winsys/autostart_test.go index d17b39b..a91d67b 100644 --- a/internal/winsys/autostart_test.go +++ b/internal/winsys/autostart_test.go @@ -195,3 +195,56 @@ func TestMigrateLoginItem(t *testing.T) { } } } + +// After the program renamed its file, the Run value that named the old path starts the new one; any other value, and +// the Task Manager switch, stay as they are. +func TestFollowRunValue(t *testing.T) { + oldExe, newExe := `C:\Apps\MPCvibedRPC.exe`, `C:\Apps\MPRP.exe` + f := &fakeRegistry{runs: map[string]string{"MPRP": `"C:\Apps\mpcvibedrpc.exe" --background`, "Other": `"C:\Other\MPCvibedRPC.exe"`}, + approvals: map[string][]byte{"MPRP": {3, 0}}} + note := followRunValue(f.registry(), "MPRP", oldExe, newExe, "") + if f.runs["MPRP"] != `"C:\Apps\MPRP.exe" --background` || !strings.Contains(note, "now starts") { + t.Errorf("run %q, note %q", f.runs["MPRP"], note) + } + if f.runs["Other"] != `"C:\Other\MPCvibedRPC.exe"` || f.approvals["MPRP"][0] != 3 { + t.Error("another value or the Task Manager switch was changed") + } + // a copy with a data folder of its own keeps --home + f.runs["MPRP-1"] = `"C:\Apps\MPCvibedRPC.exe" --background --home "D:\Data"` + followRunValue(f.registry(), "MPRP-1", oldExe, newExe, `D:\Data`) + if f.runs["MPRP-1"] != `"C:\Apps\MPRP.exe" --background --home "D:\Data"` { + t.Errorf("with a data folder: %q", f.runs["MPRP-1"]) + } + // a value naming another file, or none at all: nothing to do + if note := followRunValue(f.registry(), "Other", `C:\Apps\MPCvibedRPC.exe`, newExe, ""); note != "" || f.runs["Other"] != `"C:\Other\MPCvibedRPC.exe"` { + t.Errorf("another file's value: %q", note) + } + if note := followRunValue(f.registry(), "None", oldExe, newExe, ""); note != "" { + t.Errorf("no value: %q", note) + } + f.runs["MPRP"] = `"C:\Apps\MPCvibedRPC.exe" --background` + f.refuse = true + if note := followRunValue(f.registry(), "MPRP", oldExe, newExe, ""); !strings.Contains(note, "Could not") { + t.Errorf("a write that fails: %q", note) + } +} + +func TestFollowLoginItem(t *testing.T) { + for _, goos := range []string{"linux", "darwin"} { + dir := t.TempDir() + p := filepath.Join(dir, "item") + oldExe, newExe := "/opt/x/MPCvibedRPC-linux-amd64", "/opt/x/MPRP-linux-amd64" + if note := followLoginItem(goos, p, oldExe, newExe, ""); note != "" { + t.Errorf("%s: no login item, but %q", goos, note) + } + os.WriteFile(p, []byte(loginItem(goos, "/opt/y/other", "")), 0o644) + if note := followLoginItem(goos, p, oldExe, newExe, ""); note != "" { + t.Errorf("%s: another program's login item, but %q", goos, note) + } + os.WriteFile(p, []byte(loginItem(goos, oldExe, "/data")), 0o644) + note := followLoginItem(goos, p, oldExe, newExe, "/data") + if b, _ := os.ReadFile(p); string(b) != loginItem(goos, newExe, "/data") || !strings.Contains(note, "now starts") { + t.Errorf("%s: login item %q, note %q", goos, b, note) + } + } +} diff --git a/internal/winsys/autostart_unix.go b/internal/winsys/autostart_unix.go index 3f966b7..4168f4c 100644 --- a/internal/winsys/autostart_unix.go +++ b/internal/winsys/autostart_unix.go @@ -106,8 +106,11 @@ func getLoginItem(exe string) bool { } // loginItemExe is how exe appears inside the login item. -func loginItemExe(exe string) string { - if runtime.GOOS == "darwin" { +func loginItemExe(exe string) string { return loginItemExeFor(runtime.GOOS, exe) } + +// loginItemExeFor is how exe appears inside the login item on goos. +func loginItemExeFor(goos, exe string) string { + if goos == "darwin" { return html.EscapeString(exe) } return execQuote(exe) @@ -160,3 +163,18 @@ func migrateLoginItem(goos, home, xdgConfig, exe, mprpHome string) string { } return "Moved the login item " + from + " to " + to + " (the program's new name)." } + +// followLoginItem rewrites the login item at path to start newExe when it starts oldExe (FollowRename). +func followLoginItem(goos, path, oldExe, newExe, home string) string { + if path == "" || oldExe == "" { + return "" + } + b, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(b), strings.Trim(loginItemExeFor(goos, oldExe), `"`)) { + return "" + } + if os.WriteFile(path, []byte(loginItem(goos, newExe, home)), 0o644) != nil { + return "Could not point the login item " + path + " at " + newExe + "; it still names " + oldExe + "." + } + return "The login item " + path + " now starts " + newExe + "." +} diff --git a/internal/winsys/taskbar_windows.go b/internal/winsys/taskbar_windows.go index 0357daf..664ce06 100644 --- a/internal/winsys/taskbar_windows.go +++ b/internal/winsys/taskbar_windows.go @@ -106,7 +106,7 @@ func windowIdentity(exe, home string) (id, name, command, icon string) { // its own back now and then), until StopWindowIcon. log gets a line when the window first has the program's icon, // when something fails, and when the keeping ends. It reports whether the keeping runs. func NameWindow(profileDir string, log func(level, msg string)) bool { - exe, err := os.Executable() + exe, err := executable() if err != nil || profileDir == "" { return false } @@ -122,6 +122,14 @@ func NameWindow(profileDir string, log func(level, msg string)) bool { return r != 0 } +// executable is the program file: the path SetProgramFile gave, else os.Executable. +func executable() (string, error) { + if p := programFile.Load(); p != nil { + return *p, nil + } + return os.Executable() +} + // nameWindow gives one window the program's identity and icons; false when the identity was not taken. func nameWindow(hwnd uintptr, strs []windowString) bool { applyWindowIcons(hwnd) @@ -651,15 +659,21 @@ func keepWindowIcons(profileDir, exe string, log func(level, msg string), gen in var m msg pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmNoRemove) // makes the thread's message queue tid, _, _ := pGetCurrentThread.Call() - id, name, command, icon := windowIdentity(exe, os.Getenv("MPRP_HOME")) - strs := []windowString{{propAppID, id}, {propRelaunchCommand, command}, {propRelaunchDisplayName, name}, {propRelaunchIcon, icon}} + // the identity is made for each window it names: the program may have renamed its file meanwhile (SetProgramFile) + identity := func() []windowString { + if p, err := executable(); err == nil { + exe = p + } + id, name, command, icon := windowIdentity(exe, os.Getenv("MPRP_HOME")) + return []windowString{{propAppID, id}, {propRelaunchCommand, command}, {propRelaunchDisplayName, name}, {propRelaunchIcon, icon}} + } k := &iconKeeper{profile: profileDir, tid: tid, self: uint32(os.Getpid()), log: log, visible: func(h uintptr) bool { v, _, _ := pIsWindowVisible.Call(h); return v != 0 }, inspect: describeWindow, ours: func(pid uint32) bool { return processUsesProfile(pid, profileDir) }, name: func(h uintptr) bool { loadWindowIcons(exe) // icons that could not be had before are tried again - return nameWindow(h, strs) + return nameWindow(h, identity()) }, check: checkWindowIcons, iconsLoaded: haveWindowIcons, diff --git a/internal/winsys/winsys.go b/internal/winsys/winsys.go index b7407a0..1532ce7 100644 --- a/internal/winsys/winsys.go +++ b/internal/winsys/winsys.go @@ -4,7 +4,18 @@ // default browser) and do without the rest (no registry; no tray icon on Linux). package winsys -import "runtime" +import ( + "runtime" + "sync/atomic" +) // IsWindows is true on Windows. const IsWindows = runtime.GOOS == "windows" + +// programFile is the program file's path once the program has renamed it (SetProgramFile; nil: os.Executable). +var programFile atomic.Pointer[string] + +// SetProgramFile tells this package the program file's new path after the program renamed its own file: on Windows +// os.Executable goes on naming the file the program was started from, and a pinned settings window must start the +// file that is there. +func SetProgramFile(path string) { programFile.Store(&path) } diff --git a/tools/ci/allowed-skips.sh b/tools/ci/allowed-skips.sh index dd28bf7..203674f 100755 --- a/tools/ci/allowed-skips.sh +++ b/tools/ci/allowed-skips.sh @@ -2,10 +2,10 @@ # Prints the tests that may skip on this runner's system, for test-noskip.sh (ci.yml and release.yml share it). # The live tests are opt-in everywhere; on Windows the Unix-socket fakes and the end-to-end run are Linux/macOS-only # (the smoke test covers them there); the update rollback run is Linux-only (the Windows smoke test has its own, and -# the macOS program does not install updates itself); the data-folder copy for a held file is Windows-only (only Windows refuses that rename); the registry tests are opt-in. A new test that skips on some system belongs here. +# the macOS program does not install updates itself); the data-folder copy for a held file is Windows-only (only Windows refuses that rename); the registry tests are opt-in; the program file's rename is Windows and Linux only (the macOS app does not update itself), and its read-only folder case Linux only. A new test that skips on some system belongs here. live='TestLivePlayer|TestLiveJellyfin|TestLivePotPlayer|TestLiveCatalogs' case "${RUNNER_OS:-$(uname -s)}" in - Windows|MINGW*|MSYS*) echo "$live|TestEndToEnd|TestEndToEndUpdateRollback|TestLoginAndActivity|TestErrorReply|TestHandshakeTimeout|TestServerCloseFailsPending|TestCloseFrameSaysWhy|TestAutostartRegistryRoundTrip|TestAutostartMigrationRegistry" ;; - macOS|Darwin*) echo "$live|TestEndToEndUpdateRollback|TestMoveFormerDataCopiesWhenAFileIsHeld" ;; + Windows|MINGW*|MSYS*) echo "$live|TestEndToEnd|TestEndToEndUpdateRollback|TestLoginAndActivity|TestErrorReply|TestHandshakeTimeout|TestServerCloseFailsPending|TestCloseFrameSaysWhy|TestAutostartRegistryRoundTrip|TestAutostartMigrationRegistry|TestRenameProgramFile/a_folder_that_cannot_be_written_to" ;; + macOS|Darwin*) echo "$live|TestEndToEndUpdateRollback|TestMoveFormerDataCopiesWhenAFileIsHeld|TestRenameProgramFile|TestRemoveFormerLeftovers|TestFollowName|TestFollowNameWaitsForAnInstall|TestAfterHandOverRenames" ;; *) echo "$live|TestMoveFormerDataCopiesWhenAFileIsHeld" ;; esac diff --git a/tools/ci/verify-release.ps1 b/tools/ci/verify-release.ps1 index cd09fed..70614f9 100644 --- a/tools/ci/verify-release.ps1 +++ b/tools/ci/verify-release.ps1 @@ -30,7 +30,8 @@ foreach ($line in Get-Content (Join-Path $PSScriptRoot 'former-names.txt')) { if ($w[0] -eq 'file') { $formerFile[$w[1]] = $w[2] } elseif ($w[0] -eq 'env') { $formerEnv[$w[1]] = $w[2] } } $formerPrograms = @($programs | Where-Object { $formerFile.ContainsKey($_) } | ForEach-Object { $formerFile[$_] }) -# the process names of the copies this check starts (a copy updated from the former version keeps its file name) +# the process names of the copies this check starts (a copy updated from the former version keeps its process name +# after it renamed its file) $procNames = @('MPRP') + @($formerFile.Values | Where-Object { $_ -like '*.exe' } | ForEach-Object { $_ -replace '\.exe$', '' }) $rel = Join-Path $work 'release' # every download of a release file is recorded in the download ledger, so the download counter leaves it out @@ -51,6 +52,13 @@ try { $same = (Get-FileHash (Join-Path $rel $f)).Hash -eq (Get-FileHash (Join-Path $rel $formerFile[$f])).Hash Check $same "$($formerFile[$f]) is the same file as $f" } + # each copy under a former name carries a label that says what it is (release.yml sets it; the release page shows + # it in place of the name) + $draft = (gh api "repos/$repo/releases?per_page=30") -join "`n" | ConvertFrom-Json | Where-Object { $_.tag_name -eq $tag } | Select-Object -First 1 + foreach ($n in @($formerPrograms + ($formerPrograms | ForEach-Object { "$_.sha256" }))) { + $label = [string](@($draft.assets) | Where-Object { $_.name -eq $n } | Select-Object -First 1).label + Check ($label -like 'Former name*') "$n has its label ($label)" + } foreach ($f in $all) { $path = Join-Path $rel $f $line = (Get-Content "$path.sha256" -Raw).Trim() @@ -107,6 +115,14 @@ try { if ($exited) { bash $ledger record "release check $tag self-update" "$tag/$exeName" "$tag/$exeName.sha256" } Check $exited "$prev exits to update" Check (WaitFor { (Ping) -eq $Version } 60 'new version up') "$Version runs after the update" + # a copy of the former file name renames its file to MPRP.exe once the hand-over is over (about a minute after it + # started: the old copy can put its own file back until then) + if ($exeName -ne 'MPRP.exe') { + $renamed = Join-Path $dir 'MPRP.exe' + Check (WaitFor { (Test-Path $renamed) -and -not (Test-Path $app) } 150 'rename') "the updated copy renamed $exeName to MPRP.exe" + if (Test-Path $renamed) { $app = $renamed } + Check ((Ping) -eq $Version) "$Version still runs after the rename" + } Check ((Get-FileHash $app).Hash -eq (Get-FileHash (Join-Path $rel 'MPRP.exe')).Hash) 'the updated file is the released exe' try { Api 'quit' | Out-Null } catch {} Check (WaitFor { -not (Ours) } 20 'quit') 'the updated program quits' diff --git a/tools/relnotes/main.go b/tools/relnotes/main.go index d9bd2c4..ca1f3bc 100644 --- a/tools/relnotes/main.go +++ b/tools/relnotes/main.go @@ -1,9 +1,10 @@ // relnotes writes the text of a GitHub release from the in-app changelog (internal/assets/changelog.json), so a // release is described once: the newest entry's lines, an optional hand-written block (.github/release-advisory.md, // for a security note or anything the one-liners cannot say; delete it after the release that needs it), and the -// same "Get it" footer every release has. +// same "Get it" footer every release has (with a line on the copies under the program's former name while +// tools/ci/former-names.txt has file lines). // -// go run ./tools/relnotes -version X.Y.Z -out notes.md [-changelog path] [-advisory path] +// go run ./tools/relnotes -version X.Y.Z -out notes.md [-changelog path] [-advisory path] [-former-names path] package main import ( @@ -26,8 +27,9 @@ func main() { out := flag.String("out", "", "where to write the release text (stdout when empty)") changelog := flag.String("changelog", "internal/assets/changelog.json", "the in-app changelog") advisory := flag.String("advisory", ".github/release-advisory.md", "an optional hand-written block (used when the file exists)") + formerNames := flag.String("former-names", "tools/ci/former-names.txt", "the list of former-name files (used when the file exists)") flag.Parse() - text, err := build(*version, *changelog, *advisory) + text, err := build(*version, *changelog, *advisory, *formerNames) if err != nil { fmt.Fprintln(os.Stderr, "relnotes:", err) os.Exit(1) @@ -42,8 +44,9 @@ func main() { } } -// build makes the release text for version from the changelog file and the advisory file (which may be missing). -func build(version, changelogPath, advisoryPath string) (string, error) { +// build makes the release text for version from the changelog file, the advisory file and the list of former-name +// files (both may be missing). +func build(version, changelogPath, advisoryPath, formerPath string) (string, error) { if version == "" { return "", errors.New("-version is required") } @@ -64,11 +67,22 @@ func build(version, changelogPath, advisoryPath string) (string, error) { } else if !errors.Is(err, os.ErrNotExist) { return "", err } - return render(log[0], extra), nil + former := false + if b, err := os.ReadFile(formerPath); err == nil { + for _, l := range strings.Split(string(b), "\n") { + if f := strings.Fields(l); len(f) > 0 && f[0] == "file" { + former = true + } + } + } else if !errors.Is(err, os.ErrNotExist) { + return "", err + } + return render(log[0], extra, former), nil } -// render lays the text out: heading, the changelog's lines as a list, the hand-written block, the footer. -func render(e entry, extra string) string { +// render lays the text out: heading, the changelog's lines as a list, the hand-written block, the footer (with the +// line on the copies under the former name when former). +func render(e entry, extra string, former bool) string { var b strings.Builder fmt.Fprintf(&b, "## MPRP %s\n\n", e.Version) b.WriteString("### What's new\n") @@ -78,14 +92,26 @@ func render(e entry, extra string) string { if extra != "" { b.WriteString("\n" + extra + "\n") } + b.WriteString(footerTop) + if former { + b.WriteString(formerLine) + } b.WriteString(footer) return b.String() } -const footer = ` +const footerTop = ` Nothing to do: the update installs itself (Windows and Linux, unless you switched that off), and your settings and sign-ins are kept. +` + +// formerLine explains the release files under the program's former name (tools/ci/former-names.txt). +const formerLine = ` +The ` + "`MPCvibedRPC`" + ` files are the same program under its former name, so that copies installed before the rename +can update themselves; download the ` + "`MPRP`" + ` files. +` +const footer = ` ### Get it - **Windows:** download **` + "`MPRP.exe`" + `** and run it, or install it from the Updates section of the version you have. Your settings are kept. diff --git a/tools/relnotes/main_test.go b/tools/relnotes/main_test.go index f050e23..f459594 100644 --- a/tools/relnotes/main_test.go +++ b/tools/relnotes/main_test.go @@ -17,8 +17,9 @@ func TestBuild(t *testing.T) { {"version": "9.9.8", "date": "2026-01-01", "items": ["Older."]} ]`), 0o644) advisory := filepath.Join(dir, "advisory.md") + former := filepath.Join(dir, "former-names.txt") - text, err := build("9.9.9", changelog, advisory) + text, err := build("9.9.9", changelog, advisory, former) if err != nil { t.Fatal(err) } @@ -30,17 +31,33 @@ func TestBuild(t *testing.T) { if strings.Contains(text, "Older") { t.Error("an older entry leaked in") } + if strings.Contains(text, "former name") { + t.Error("the line on the former-name files without a list of them") + } + + // the line on the copies under the former name comes with file lines in the list, just before "Get it" + os.WriteFile(former, []byte("# comment: file\r\nenv MPRP_HOME MPCRPC_HOME\r\n"), 0o644) + if text, _ = build("9.9.9", changelog, advisory, former); strings.Contains(text, "former name") { + t.Error("the line on the former-name files with no file lines") + } + os.WriteFile(former, []byte("# comment\r\nfile MPRP.exe MPCvibedRPC.exe\r\n"), 0o644) + text, err = build("9.9.9", changelog, advisory, former) + if err != nil || !strings.Contains(text, "sign-ins are kept.\n\nThe `MPCvibedRPC` files are the same program under its former name") || + !strings.Contains(text, "download the `MPRP` files.\n\n### Get it\n") { + t.Fatalf("the line on the former-name files is missing or misplaced: %v\n%s", err, text) + } + os.Remove(former) os.WriteFile(advisory, []byte("> **If you run a sample server:** do the sample thing.\r\n"), 0o644) - text, err = build("9.9.9", changelog, advisory) + text, err = build("9.9.9", changelog, advisory, former) if err != nil || !strings.Contains(text, "- 🔒 Sample line two.\n\n> **If you run a sample server:** do the sample thing.\n") { t.Fatalf("advisory not placed after the lines: %v\n%s", err, text) } - if _, err := build("9.9.8", changelog, advisory); err == nil { + if _, err := build("9.9.8", changelog, advisory, former); err == nil { t.Fatal("an older version must be refused") } - if _, err := build("", changelog, advisory); err == nil { + if _, err := build("", changelog, advisory, former); err == nil { t.Fatal("no version must be refused") } } @@ -58,7 +75,7 @@ func TestRealChangelogRenders(t *testing.T) { } v := string(raw[i+len(`"version": "`):]) v = v[:strings.Index(v, `"`)] - text, err := build(v, path, filepath.Join(t.TempDir(), "none.md")) + text, err := build(v, path, filepath.Join(t.TempDir(), "none.md"), filepath.Join("..", "ci", "former-names.txt")) if err != nil || !strings.HasPrefix(text, "## MPRP "+v+"\n") { t.Fatalf("%v\n%s", err, text) }