From 084431513ad89578c3911f710411cf9a7c3aadda Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Tue, 8 Sep 2026 20:43:37 -0700 Subject: [PATCH] fix: remove a stale .new before every update An install interrupted between writing .new and renaming it left the file beside the binary, where it showed up in tab completion until the next release shipped. Update now asks an installer that implements the new Sweeper interface to remove it before the release check, so the cleanup runs even when nothing is available. Only a regular file by that name is removed. --- README.md | 6 +++++ archive.go | 12 +++++++++ archive_test.go | 20 +++++++++++++++ installer.go | 10 ++++++++ replace.go | 25 +++++++++++++++++++ replace_test.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++ selfupdate.go | 14 +++++++++++ selfupdate_test.go | 40 ++++++++++++++++++++++++++++-- 8 files changed, 187 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cf07b53..40590d2 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,12 @@ archive into a temp directory. Nothing is downloaded when a check fails. it ad hoc. On a terminal the download line shows a progress bar. Elsewhere it is a single line. +Every `Update` call first removes a stale `.new` left by an install +that was interrupted between writing the file and renaming it into place. +The cleanup runs before the release check, so the file disappears the next +time the user runs the command even when nothing new is available or the +network is down. Only a regular file by that name is removed. + Linux and macOS with `.tar.gz` assets are supported. Windows is not. Verification proves the download matches what the release page lists. It does not prove who published it. Signature checking is out of scope. diff --git a/archive.go b/archive.go index 85f2555..48d195b 100644 --- a/archive.go +++ b/archive.go @@ -88,6 +88,18 @@ func (a *ArchiveInstaller) Prepare(ctx context.Context, rel Release) (Staged, er return staged, nil } +// Sweep removes a .new left behind when an earlier install was +// interrupted between writing the file and renaming it into place. The +// name sits beside the binary in tab completion otherwise. Only a regular +// file is removed; a missing file is not an error. +func (a *ArchiveInstaller) Sweep() error { + target, err := a.target() + if err != nil { + return err + } + return removeStaleNew(target) +} + // stage downloads asset into staged.dir, verifies it unless SkipChecksum, // and extracts name beside it. func (a *ArchiveInstaller) stage( diff --git a/archive_test.go b/archive_test.go index 36dd5c5..473bf86 100644 --- a/archive_test.go +++ b/archive_test.go @@ -24,6 +24,7 @@ import ( // --- Contract assertions --- var ( _ Installer = (*ArchiveInstaller)(nil) + _ Sweeper = (*ArchiveInstaller)(nil) _ Staged = (*archiveStaged)(nil) ) @@ -326,6 +327,25 @@ func TestArchiveInstaller_DefaultClientHeaderTimeout(t *testing.T) { } } +func TestArchiveInstaller_SweepRemovesStaleNew(t *testing.T) { + target := writeTarget(t, contentOld) + writeStaleNew(t, target) + if err := newTestInstaller(target, io.Discard).Sweep(); err != nil { + t.Fatal(err) + } + assertNoLeftovers(t, target) + if got := readTarget(t, target); got != contentOld { + t.Fatalf("Sweep must not touch the target: %q", got) + } +} + +func TestArchiveInstaller_SweepMissingTargetIsError(t *testing.T) { + missing := filepath.Join(t.TempDir(), "gone") + if err := newTestInstaller(missing, io.Discard).Sweep(); err == nil { + t.Fatal("a target that cannot be resolved must be reported") + } +} + // TestArchiveInstaller_ClientIsConcurrencySafe runs under -race: a shared // installer must not be mutated by client(). func TestArchiveInstaller_ClientIsConcurrencySafe(t *testing.T) { diff --git a/installer.go b/installer.go index 415160d..97a6ca3 100644 --- a/installer.go +++ b/installer.go @@ -27,6 +27,16 @@ type Staged interface { Close() error } +// Sweeper is implemented by installers that can remove leftovers of an +// interrupted install without a release in hand. Updater.Update calls it +// on every run, so a stale .new left by a crash disappears the +// next time the user runs the update command, even when nothing new is +// available. A Sweep failure is reported as a warning and never blocks +// the update. +type Sweeper interface { + Sweep() error +} + // safeTag is the only shape of tag ScriptInstaller will place on a command // line: a release tag with no shell metacharacters. var safeTag = regexp.MustCompile(`^v?[0-9A-Za-z][0-9A-Za-z.+-]*$`) diff --git a/replace.go b/replace.go index 28241c9..0f50834 100644 --- a/replace.go +++ b/replace.go @@ -38,6 +38,9 @@ func preflightWritable(dir string) error { // process keeps its unlinked inode and is unaffected. func replaceFile(target string, src io.Reader, mode os.FileMode) error { newPath := target + ".new" + if err := removeStaleNew(target); err != nil { + return err + } if err := writeFile(newPath, src, mode); err != nil { return err } @@ -48,6 +51,28 @@ func replaceFile(target string, src io.Reader, mode os.FileMode) error { return nil } +// removeStaleNew deletes .new when it is a regular file. An +// interrupted install can leave one behind. The .new suffix is ours only +// by convention, so a directory or symlink by that name is left alone and +// writeFile reports it. +func removeStaleNew(target string) error { + newPath := target + ".new" + info, err := os.Lstat(newPath) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("selfupdate: inspect %s: %w", newPath, err) + } + if !info.Mode().IsRegular() { + return nil + } + if err := os.Remove(newPath); err != nil { + return fmt.Errorf("selfupdate: remove stale %s: %w", newPath, err) + } + return nil +} + // writeFile streams src into path with mode, removing the file on failure. // The mode is applied with Chmod after creation so the process umask cannot // narrow it. diff --git a/replace_test.go b/replace_test.go index e714e4a..f699c53 100644 --- a/replace_test.go +++ b/replace_test.go @@ -101,6 +101,68 @@ func TestReplaceFile_NeverMovesTargetAside(t *testing.T) { } } +// writeStaleNew leaves a partial .new beside target, as an install +// interrupted before its rename would. +func writeStaleNew(t *testing.T, target string) { + t.Helper() + if err := os.WriteFile(target+".new", []byte("partial"), 0o755); err != nil { //nolint:gosec // fixture + t.Fatal(err) + } +} + +func TestRemoveStaleNew_RemovesRegularFile(t *testing.T) { + target := writeTarget(t, contentOld) + writeStaleNew(t, target) + if err := removeStaleNew(target); err != nil { + t.Fatal(err) + } + assertNoLeftovers(t, target) + if err := removeStaleNew(target); err != nil { + t.Fatalf("a missing .new is not an error: %v", err) + } +} + +func TestRemoveStaleNew_LeavesDirectoryAlone(t *testing.T) { + target := writeTarget(t, contentOld) + if err := os.Mkdir(target+".new", 0o755); err != nil { + t.Fatal(err) + } + if err := removeStaleNew(target); err != nil { + t.Fatal(err) + } + if info, err := os.Stat(target + ".new"); err != nil || !info.IsDir() { + t.Fatalf("directory must survive: %v, %v", info, err) + } +} + +func TestRemoveStaleNew_LeavesSymlinkAlone(t *testing.T) { + target := writeTarget(t, contentOld) + if err := os.Symlink(target, target+".new"); err != nil { + t.Fatal(err) + } + if err := removeStaleNew(target); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(target + ".new"); err != nil { + t.Fatalf("symlink must survive: %v", err) + } + if got := readTarget(t, target); got != contentOld { + t.Fatalf("link target changed: %q", got) + } +} + +func TestReplaceFile_RemovesStaleNewFirst(t *testing.T) { + target := writeTarget(t, contentOld) + writeStaleNew(t, target) + if err := replaceFile(target, strings.NewReader(contentNew), 0o755); err != nil { + t.Fatal(err) + } + if got := readTarget(t, target); got != contentNew { + t.Fatalf("content %q", got) + } + assertNoLeftovers(t, target) +} + func TestPreflightWritable_LeavesNoProbe(t *testing.T) { dir := t.TempDir() if err := preflightWritable(dir); err != nil { diff --git a/selfupdate.go b/selfupdate.go index 40188f8..821ba50 100644 --- a/selfupdate.go +++ b/selfupdate.go @@ -118,6 +118,7 @@ func (u *Updater) Check(ctx context.Context) (CheckResult, error) { // //nolint:revive // CLI output writes always succeed func (u *Updater) Update(ctx context.Context, opts UpdateOptions) error { + u.sweep() res, err := u.Check(ctx) if err != nil { return fmt.Errorf("check for updates: %w", err) @@ -157,6 +158,19 @@ func (u *Updater) Update(ctx context.Context, opts UpdateOptions) error { return u.install(ctx, res) } +// sweep asks an Installer that implements Sweeper to remove leftovers of an +// interrupted install. It runs before the release check so the cleanup +// happens even when the network is down. A failure is a warning only. +func (u *Updater) sweep() { + s, ok := u.Installer.(Sweeper) + if !ok { + return + } + if err := s.Sweep(); err != nil { + _, _ = fmt.Fprintf(u.errOut(), "Warning: %v\n", err) + } +} + // install runs Prepare, PreInstall, Commit and PostInstall in that order. // Each step runs only when every earlier step succeeded. func (u *Updater) install(ctx context.Context, res CheckResult) error { diff --git a/selfupdate_test.go b/selfupdate_test.go index 2f3645c..43dfa5f 100644 --- a/selfupdate_test.go +++ b/selfupdate_test.go @@ -102,16 +102,23 @@ func TestDefaultPatterns(t *testing.T) { // already cover "v1.0.0" and "v0.10.0". const tagV200 = "v2.0.0" -// recordingInstaller records Prepare and Commit calls. prepareErr fails -// Prepare; commitErr fails Commit. +// recordingInstaller records Sweep, Prepare and Commit calls. prepareErr +// fails Prepare; commitErr fails Commit; sweepErr fails Sweep. type recordingInstaller struct { + swept int prepared []string committed []string closed int + sweepErr error prepareErr error commitErr error } +func (r *recordingInstaller) Sweep() error { + r.swept++ + return r.sweepErr +} + func (r *recordingInstaller) Prepare(_ context.Context, rel Release) (Staged, error) { r.prepared = append(r.prepared, rel.Tag) if r.prepareErr != nil { @@ -239,6 +246,35 @@ func TestUpdater_UpdateUpToDateInstallsNothing(t *testing.T) { if !strings.Contains(out.String(), "tool v1.0.0 (stable) is up to date") || len(inst.committed) != 0 { t.Fatalf("output: %s, installs: %v", out.String(), inst.committed) } + if inst.swept != 1 { + t.Fatalf("Sweep must run once even when nothing is installed, ran %d times", inst.swept) + } +} + +func TestUpdater_UpdateSweepErrorIsWarningOnly(t *testing.T) { + src := &fakeSource{latest: Release{Tag: tagV200}} + u, _, errOut, inst := newTestUpdater(tagV100, src, nil, "") + inst.sweepErr = errors.New("simulated sweep failure") + if err := u.Update(context.Background(), UpdateOptions{Yes: true}); err != nil { + t.Fatal(err) + } + if !strings.Contains(errOut.String(), "Warning: simulated sweep failure") { + t.Fatalf("warning missing: %q", errOut.String()) + } + if len(inst.committed) != 1 { + t.Fatalf("the update must proceed past a sweep failure, installs: %v", inst.committed) + } +} + +func TestUpdater_UpdateSweepRunsBeforeCheck(t *testing.T) { + src := &fakeSource{latestErr: errors.New("offline")} + u, _, _, inst := newTestUpdater(tagV100, src, nil, "") + if err := u.Update(context.Background(), UpdateOptions{}); err == nil { + t.Fatal("the check failure must still be returned") + } + if inst.swept != 1 { + t.Fatalf("Sweep must run even when the release check fails, ran %d times", inst.swept) + } } func TestUpdater_UpdateCurrentNewerInstallsNothing(t *testing.T) {