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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<target>.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.
Expand Down
12 changes: 12 additions & 0 deletions archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,18 @@ func (a *ArchiveInstaller) Prepare(ctx context.Context, rel Release) (Staged, er
return staged, nil
}

// Sweep removes a <target>.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(
Expand Down
20 changes: 20 additions & 0 deletions archive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
// --- Contract assertions ---
var (
_ Installer = (*ArchiveInstaller)(nil)
_ Sweeper = (*ArchiveInstaller)(nil)
_ Staged = (*archiveStaged)(nil)
)

Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 10 additions & 0 deletions installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <target>.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.+-]*$`)
Expand Down
25 changes: 25 additions & 0 deletions replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -48,6 +51,28 @@ func replaceFile(target string, src io.Reader, mode os.FileMode) error {
return nil
}

// removeStaleNew deletes <target>.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.
Expand Down
62 changes: 62 additions & 0 deletions replace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,68 @@ func TestReplaceFile_NeverMovesTargetAside(t *testing.T) {
}
}

// writeStaleNew leaves a partial <target>.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 {
Expand Down
14 changes: 14 additions & 0 deletions selfupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
40 changes: 38 additions & 2 deletions selfupdate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
Loading