Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions cmd/mprp/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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) + `}}`)
Expand Down Expand Up @@ -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
Expand Down
41 changes: 34 additions & 7 deletions cmd/mprp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
149 changes: 149 additions & 0 deletions cmd/mprp/selfrename.go
Original file line number Diff line number Diff line change
@@ -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 (<former>.old, <former>.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)
}
21 changes: 21 additions & 0 deletions cmd/mprp/selfrename_other.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading