fix(upgrade): handle Windows executable locking during self-upgrade

Windows locks running executables, preventing direct replacement.
Solution: rename running exe to .old, then rename new exe in place.
Cleanup of .old files happens on next startup.
This commit is contained in:
Willie Hung
2026-01-31 12:43:44 +08:00
parent bf286f1d88
commit 31a7b66edf
2 changed files with 51 additions and 0 deletions
+25
View File
@@ -3,6 +3,8 @@ package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
"skillshare/internal/ui"
versioncheck "skillshare/internal/version"
@@ -11,6 +13,9 @@ import (
var version = "dev"
func main() {
// Clean up any leftover .old files from Windows self-upgrade
cleanupOldBinary()
// Set version for other packages to use
versioncheck.Version = version
@@ -173,3 +178,23 @@ func printUsage() {
fmt.Println(" skillshare target add claude ~/.claude/skills")
fmt.Println(" skillshare sync" + r)
}
// cleanupOldBinary removes leftover .old files from Windows self-upgrade.
// On Windows, we rename the running exe to .old before replacing it.
// This cleanup runs on next startup to remove those files.
func cleanupOldBinary() {
if runtime.GOOS != "windows" {
return
}
execPath, err := os.Executable()
if err != nil {
return
}
execPath, err = filepath.EvalSymlinks(execPath)
if err != nil {
return
}
oldPath := execPath + ".old"
// Silently try to remove - may not exist, that's fine
os.Remove(oldPath)
}
+26
View File
@@ -305,6 +305,32 @@ func writeBinary(r io.Reader, destPath string) error {
return err
}
// On Windows, we can't directly replace a running executable.
// However, we CAN rename it. So we:
// 1. Rename current exe to .old
// 2. Rename new exe to the correct name
// 3. Try to delete .old (may fail if still running, but that's OK)
if runtime.GOOS == "windows" {
oldPath := destPath + ".old"
// Remove any previous .old file
os.Remove(oldPath)
// Rename running exe to .old
if err := os.Rename(destPath, oldPath); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("failed to rename current binary: %w", err)
}
// Rename new exe to correct name
if err := os.Rename(tmpPath, destPath); err != nil {
// Try to restore
os.Rename(oldPath, destPath)
os.Remove(tmpPath)
return err
}
// Try to clean up old file (may fail, that's OK)
os.Remove(oldPath)
return nil
}
if err := os.Rename(tmpPath, destPath); err != nil {
os.Remove(tmpPath)
return err