Skip to content

Commit

Permalink
fix(update): move Windows binary via absolute path
Browse files Browse the repository at this point in the history
  • Loading branch information
Integralist committed Jun 21, 2023
1 parent aeceb5a commit 26109a4
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions pkg/commands/update/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,24 +130,31 @@ func (c *RootCommand) Exec(_ io.Reader, out io.Writer) error {
return fmt.Errorf("error determining absolute target path: %w", err)
}

// Windows does not permit removing a running executable, however it will
// permit renaming it! So we first rename the running executable and then we
// move the executable that we downloaded to the same location as the
// original executable (which is allowed since we first renamed the running
// executable).
// Windows does not permit replacing a running executable (see next condition),
// however it will permit it if you first move the original executable.
// So we first move the running executable to a new location, then we move the
// executable that we downloaded to the same location as the original.
//
// Reference:
// https://github.com/golang/go/issues/21997#issuecomment-331744930
if fstruntime.Windows {
if err := os.Rename(execPath, execPath+"~"); err != nil {
if err := os.Rename(currentPath, currentPath+".bak"); err != nil {
c.Globals.ErrLog.Add(err)
if err = os.Remove(execPath + "~"); err != nil {
if err = os.Remove(currentPath + ".bak"); err != nil {
c.Globals.ErrLog.Add(err)
}
}
}

// Move the downloaded binary to the same location as the current binary.
if err := os.Rename(tmpBin, currentPath); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Executable (source)": tmpBin,
"Executable (destination)": currentPath,
})
renameErr := err

// Failing that we'll try to io.Copy downloaded binary to the current binary.
if err := filesystem.CopyFile(tmpBin, currentPath); err != nil {
c.Globals.ErrLog.AddWithContext(err, map[string]any{
"Executable (source)": tmpBin,
Expand All @@ -160,7 +167,7 @@ func (c *RootCommand) Exec(_ io.Reader, out io.Writer) error {
return spinErr
}

return fmt.Errorf("error moving latest binary in place: %w", err)
return fmt.Errorf("error 'copying' latest binary in place: %w (following an error 'moving': %w)", err, renameErr)
}
}

Expand Down

0 comments on commit 26109a4

Please sign in to comment.