| @@ -0,0 +1,443 @@ |
| 1 | package internal |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "runtime/debug" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "time" |
| 17 | ) |
| 18 | |
| 19 | const releaseStateFileName = "release_state.json" |
| 20 | |
| 21 | type githubRelease struct { |
| 22 | TagName string `json:"tag_name"` |
| 23 | HTMLURL string `json:"html_url"` |
| 24 | } |
| 25 | |
| 26 | type releaseState struct { |
| 27 | LatestVersion string `json:"latest_version"` |
| 28 | ReleaseURL string `json:"release_url,omitempty"` |
| 29 | CheckedAt time.Time `json:"checked_at"` |
| 30 | } |
| 31 | |
| 32 | func ResolveCurrentVersion(rawVersion string) string { |
| 33 | version := normalizeVersion(rawVersion) |
| 34 | if version != "" { |
| 35 | return version |
| 36 | } |
| 37 | |
| 38 | buildInfo, ok := debug.ReadBuildInfo() |
| 39 | if !ok { |
| 40 | return "" |
| 41 | } |
| 42 | |
| 43 | return normalizeVersion(buildInfo.Main.Version) |
| 44 | } |
| 45 | |
| 46 | func NotifyAboutCachedUpdate(currentVersion, storagePath string) { |
| 47 | currentVersion = normalizeVersion(currentVersion) |
| 48 | if currentVersion == "" { |
| 49 | return |
| 50 | } |
| 51 | |
| 52 | state, err := loadReleaseState(storagePath) |
| 53 | if err != nil { |
| 54 | return |
| 55 | } |
| 56 | |
| 57 | if compareVersions(state.LatestVersion, currentVersion) <= 0 { |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | CurdOut(buildUpdatePrompt(currentVersion, state.LatestVersion)) |
| 62 | } |
| 63 | |
| 64 | func StartBackgroundReleaseCheck(currentVersion, storagePath string) { |
| 65 | currentVersion = normalizeVersion(currentVersion) |
| 66 | if currentVersion == "" { |
| 67 | return |
| 68 | } |
| 69 | |
| 70 | go func() { |
| 71 | if err := refreshReleaseState(currentVersion, storagePath); err != nil { |
| 72 | Log(fmt.Sprintf("Background release check failed: %v", err)) |
| 73 | } |
| 74 | }() |
| 75 | } |
| 76 | |
| 77 | func refreshReleaseState(currentVersion, storagePath string) error { |
| 78 | release, err := fetchLatestRelease("wraient/curd", currentVersion) |
| 79 | if err != nil { |
| 80 | return err |
| 81 | } |
| 82 | |
| 83 | state := releaseState{ |
| 84 | LatestVersion: normalizeVersion(release.TagName), |
| 85 | ReleaseURL: release.HTMLURL, |
| 86 | CheckedAt: time.Now().UTC(), |
| 87 | } |
| 88 | if state.LatestVersion == "" { |
| 89 | return fmt.Errorf("latest release did not include a version tag") |
| 90 | } |
| 91 | |
| 92 | return saveReleaseState(storagePath, state) |
| 93 | } |
| 94 | |
| 95 | func UpdateCurd(repo string) (string, error) { |
| 96 | executablePath, err := os.Executable() |
| 97 | if err != nil { |
| 98 | return "", fmt.Errorf("unable to find current executable: %w", err) |
| 99 | } |
| 100 | |
| 101 | binaryName, err := currentReleaseBinaryName() |
| 102 | if err != nil { |
| 103 | return "", err |
| 104 | } |
| 105 | |
| 106 | tmpPath := executablePath + ".tmp" |
| 107 | currentVersion := ResolveCurrentVersion("") |
| 108 | if err := downloadReleaseAsset(repo, binaryName, tmpPath, currentVersion); err != nil { |
| 109 | return "", err |
| 110 | } |
| 111 | |
| 112 | switch runtime.GOOS { |
| 113 | case "windows": |
| 114 | if err := scheduleWindowsBinarySwap(executablePath, tmpPath); err != nil { |
| 115 | return "", wrapUpdateError(err) |
| 116 | } |
| 117 | return "Update downloaded. It will be installed after Curd exits. Open Curd again after this window closes.", nil |
| 118 | default: |
| 119 | if err := os.Rename(tmpPath, executablePath); err != nil { |
| 120 | _ = os.Remove(tmpPath) |
| 121 | return "", wrapUpdateError(fmt.Errorf("failed to replace executable: %w", err)) |
| 122 | } |
| 123 | return "Program updated!", nil |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | func currentReleaseBinaryName() (string, error) { |
| 128 | switch runtime.GOOS { |
| 129 | case "windows": |
| 130 | if runtime.GOARCH == "arm64" { |
| 131 | return "curd-windows-arm64.exe", nil |
| 132 | } |
| 133 | return "curd-windows-x86_64.exe", nil |
| 134 | case "darwin": |
| 135 | switch runtime.GOARCH { |
| 136 | case "amd64": |
| 137 | return "curd-macos-x86_64", nil |
| 138 | case "arm64": |
| 139 | return "curd-macos-arm64", nil |
| 140 | default: |
| 141 | return "curd-macos-universal", nil |
| 142 | } |
| 143 | case "linux": |
| 144 | switch runtime.GOARCH { |
| 145 | case "amd64": |
| 146 | return "curd-linux-x86_64", nil |
| 147 | case "arm64": |
| 148 | return "curd-linux-arm64", nil |
| 149 | default: |
| 150 | return "", fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH) |
| 151 | } |
| 152 | default: |
| 153 | return "", fmt.Errorf("unsupported operating system: %s", runtime.GOOS) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func downloadReleaseAsset(repo, binaryName, destinationPath, currentVersion string) error { |
| 158 | url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName) |
| 159 | req, err := http.NewRequest("GET", url, nil) |
| 160 | if err != nil { |
| 161 | return fmt.Errorf("failed to create download request: %w", err) |
| 162 | } |
| 163 | |
| 164 | req.Header.Set("User-Agent", userAgentForVersion(currentVersion)) |
| 165 | |
| 166 | client := &http.Client{Timeout: 30 * time.Second} |
| 167 | resp, err := client.Do(req) |
| 168 | if err != nil { |
| 169 | return fmt.Errorf("failed to download file: %w", err) |
| 170 | } |
| 171 | defer resp.Body.Close() |
| 172 | |
| 173 | if resp.StatusCode != http.StatusOK { |
| 174 | return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode) |
| 175 | } |
| 176 | |
| 177 | out, err := os.Create(destinationPath) |
| 178 | if err != nil { |
| 179 | return fmt.Errorf("failed to create temporary file: %w", err) |
| 180 | } |
| 181 | |
| 182 | if err := out.Chmod(0755); err != nil { |
| 183 | out.Close() |
| 184 | _ = os.Remove(destinationPath) |
| 185 | return fmt.Errorf("failed to set file permissions: %w", err) |
| 186 | } |
| 187 | |
| 188 | if _, err := io.Copy(out, resp.Body); err != nil { |
| 189 | out.Close() |
| 190 | _ = os.Remove(destinationPath) |
| 191 | return fmt.Errorf("failed to write to temporary file: %w", err) |
| 192 | } |
| 193 | |
| 194 | if err := out.Close(); err != nil { |
| 195 | _ = os.Remove(destinationPath) |
| 196 | return fmt.Errorf("failed to close temporary file: %w", err) |
| 197 | } |
| 198 | |
| 199 | return nil |
| 200 | } |
| 201 | |
| 202 | func fetchLatestRelease(repo, currentVersion string) (githubRelease, error) { |
| 203 | req, err := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo), nil) |
| 204 | if err != nil { |
| 205 | return githubRelease{}, fmt.Errorf("failed to create release check request: %w", err) |
| 206 | } |
| 207 | |
| 208 | req.Header.Set("Accept", "application/vnd.github+json") |
| 209 | req.Header.Set("User-Agent", userAgentForVersion(currentVersion)) |
| 210 | |
| 211 | client := &http.Client{Timeout: 5 * time.Second} |
| 212 | resp, err := client.Do(req) |
| 213 | if err != nil { |
| 214 | return githubRelease{}, fmt.Errorf("failed to check latest release: %w", err) |
| 215 | } |
| 216 | defer resp.Body.Close() |
| 217 | |
| 218 | if resp.StatusCode != http.StatusOK { |
| 219 | body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) |
| 220 | return githubRelease{}, fmt.Errorf("release check failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) |
| 221 | } |
| 222 | |
| 223 | var release githubRelease |
| 224 | if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { |
| 225 | return githubRelease{}, fmt.Errorf("failed to decode latest release response: %w", err) |
| 226 | } |
| 227 | |
| 228 | return release, nil |
| 229 | } |
| 230 | |
| 231 | func scheduleWindowsBinarySwap(executablePath, tmpPath string) error { |
| 232 | scriptPath := filepath.Join(os.TempDir(), fmt.Sprintf("curd-update-%d.cmd", time.Now().UnixNano())) |
| 233 | script := fmt.Sprintf(`@echo off |
| 234 | setlocal |
| 235 | set "TARGET=%s" |
| 236 | set "SOURCE=%s" |
| 237 | set "OLD=%s.old" |
| 238 | :wait_loop |
| 239 | tasklist /FI "PID eq %d" 2>NUL | find "%d" >NUL |
| 240 | if not errorlevel 1 ( |
| 241 | timeout /T 1 /NOBREAK >NUL |
| 242 | goto wait_loop |
| 243 | ) |
| 244 | if exist "%%OLD%%" del /F /Q "%%OLD%%" >NUL 2>NUL |
| 245 | if exist "%%TARGET%%" move /Y "%%TARGET%%" "%%OLD%%" >NUL |
| 246 | move /Y "%%SOURCE%%" "%%TARGET%%" >NUL |
| 247 | if exist "%%OLD%%" del /F /Q "%%OLD%%" >NUL 2>NUL |
| 248 | del /F /Q "%%~f0" >NUL 2>NUL |
| 249 | `, executablePath, tmpPath, executablePath, os.Getpid(), os.Getpid()) |
| 250 | |
| 251 | if err := os.WriteFile(scriptPath, []byte(script), 0600); err != nil { |
| 252 | return fmt.Errorf("failed to create Windows update script: %w", err) |
| 253 | } |
| 254 | |
| 255 | cmd := exec.Command("cmd", "/C", "start", "", "/B", scriptPath) |
| 256 | cmd.Dir = filepath.Dir(executablePath) |
| 257 | if err := cmd.Start(); err != nil { |
| 258 | _ = os.Remove(scriptPath) |
| 259 | return fmt.Errorf("failed to launch Windows updater: %w", err) |
| 260 | } |
| 261 | |
| 262 | return nil |
| 263 | } |
| 264 | |
| 265 | func saveReleaseState(storagePath string, state releaseState) error { |
| 266 | statePath, err := releaseStatePath(storagePath) |
| 267 | if err != nil { |
| 268 | return err |
| 269 | } |
| 270 | |
| 271 | if err := os.MkdirAll(filepath.Dir(statePath), 0755); err != nil { |
| 272 | return fmt.Errorf("failed to create release cache directory: %w", err) |
| 273 | } |
| 274 | |
| 275 | data, err := json.MarshalIndent(state, "", " ") |
| 276 | if err != nil { |
| 277 | return fmt.Errorf("failed to marshal release state: %w", err) |
| 278 | } |
| 279 | |
| 280 | if err := os.WriteFile(statePath, data, 0644); err != nil { |
| 281 | return fmt.Errorf("failed to write release state: %w", err) |
| 282 | } |
| 283 | |
| 284 | return nil |
| 285 | } |
| 286 | |
| 287 | func loadReleaseState(storagePath string) (releaseState, error) { |
| 288 | statePath, err := releaseStatePath(storagePath) |
| 289 | if err != nil { |
| 290 | return releaseState{}, err |
| 291 | } |
| 292 | |
| 293 | data, err := os.ReadFile(statePath) |
| 294 | if err != nil { |
| 295 | return releaseState{}, err |
| 296 | } |
| 297 | |
| 298 | var state releaseState |
| 299 | if err := json.Unmarshal(data, &state); err != nil { |
| 300 | return releaseState{}, err |
| 301 | } |
| 302 | |
| 303 | state.LatestVersion = normalizeVersion(state.LatestVersion) |
| 304 | return state, nil |
| 305 | } |
| 306 | |
| 307 | func releaseStatePath(storagePath string) (string, error) { |
| 308 | expandedStorage := os.ExpandEnv(strings.TrimSpace(storagePath)) |
| 309 | if expandedStorage == "" { |
| 310 | return "", fmt.Errorf("storage path is empty") |
| 311 | } |
| 312 | |
| 313 | return filepath.Join(expandedStorage, releaseStateFileName), nil |
| 314 | } |
| 315 | |
| 316 | func buildUpdatePrompt(currentVersion, latestVersion string) string { |
| 317 | switch runtime.GOOS { |
| 318 | case "windows": |
| 319 | return fmt.Sprintf("A newer Curd release (%s) is available. You're on %s. Update it with the same package manager you used to install Curd, or run `curd -u` if you're using the standalone executable.", latestVersion, currentVersion) |
| 320 | case "darwin": |
| 321 | return fmt.Sprintf("A newer Curd release (%s) is available. You're on %s. Update it with the same package manager you used to install Curd, or run `sudo curd -u` if you installed the standalone binary in a protected location.", latestVersion, currentVersion) |
| 322 | default: |
| 323 | return fmt.Sprintf("A newer Curd release (%s) is available. You're on %s. Update it with the same package manager you used to install Curd, or run `sudo curd -u` for the standalone binary.", latestVersion, currentVersion) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | func compareVersions(leftVersion, rightVersion string) int { |
| 328 | leftParts := versionParts(leftVersion) |
| 329 | rightParts := versionParts(rightVersion) |
| 330 | maxParts := len(leftParts) |
| 331 | if len(rightParts) > maxParts { |
| 332 | maxParts = len(rightParts) |
| 333 | } |
| 334 | |
| 335 | for i := 0; i < maxParts; i++ { |
| 336 | left := 0 |
| 337 | right := 0 |
| 338 | if i < len(leftParts) { |
| 339 | left = leftParts[i] |
| 340 | } |
| 341 | if i < len(rightParts) { |
| 342 | right = rightParts[i] |
| 343 | } |
| 344 | if left > right { |
| 345 | return 1 |
| 346 | } |
| 347 | if left < right { |
| 348 | return -1 |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | return 0 |
| 353 | } |
| 354 | |
| 355 | func versionParts(version string) []int { |
| 356 | cleanVersion := normalizeVersion(version) |
| 357 | if cleanVersion == "" { |
| 358 | return nil |
| 359 | } |
| 360 | |
| 361 | segments := strings.FieldsFunc(cleanVersion, func(r rune) bool { |
| 362 | return r < '0' || r > '9' |
| 363 | }) |
| 364 | |
| 365 | parts := make([]int, 0, len(segments)) |
| 366 | for _, segment := range segments { |
| 367 | if segment == "" { |
| 368 | continue |
| 369 | } |
| 370 | |
| 371 | value, err := strconv.Atoi(segment) |
| 372 | if err != nil { |
| 373 | return nil |
| 374 | } |
| 375 | parts = append(parts, value) |
| 376 | } |
| 377 | |
| 378 | return parts |
| 379 | } |
| 380 | |
| 381 | func normalizeVersion(version string) string { |
| 382 | trimmed := strings.TrimSpace(version) |
| 383 | trimmed = strings.TrimPrefix(trimmed, "v") |
| 384 | if trimmed == "" || trimmed == "(devel)" { |
| 385 | return "" |
| 386 | } |
| 387 | |
| 388 | if len(versionPartsWithoutNormalization(trimmed)) == 0 { |
| 389 | return "" |
| 390 | } |
| 391 | |
| 392 | return trimmed |
| 393 | } |
| 394 | |
| 395 | func versionPartsWithoutNormalization(version string) []int { |
| 396 | segments := strings.FieldsFunc(version, func(r rune) bool { |
| 397 | return r < '0' || r > '9' |
| 398 | }) |
| 399 | |
| 400 | parts := make([]int, 0, len(segments)) |
| 401 | for _, segment := range segments { |
| 402 | if segment == "" { |
| 403 | continue |
| 404 | } |
| 405 | |
| 406 | value, err := strconv.Atoi(segment) |
| 407 | if err != nil { |
| 408 | return nil |
| 409 | } |
| 410 | parts = append(parts, value) |
| 411 | } |
| 412 | |
| 413 | return parts |
| 414 | } |
| 415 | |
| 416 | func userAgentForVersion(currentVersion string) string { |
| 417 | currentVersion = normalizeVersion(currentVersion) |
| 418 | if currentVersion == "" { |
| 419 | return "curd" |
| 420 | } |
| 421 | |
| 422 | return "curd/" + currentVersion |
| 423 | } |
| 424 | |
| 425 | func wrapUpdateError(err error) error { |
| 426 | if err == nil { |
| 427 | return nil |
| 428 | } |
| 429 | |
| 430 | message := strings.ToLower(err.Error()) |
| 431 | if errors.Is(err, os.ErrPermission) || strings.Contains(message, "permission denied") || strings.Contains(message, "access is denied") { |
| 432 | switch runtime.GOOS { |
| 433 | case "windows": |
| 434 | return fmt.Errorf("%w. Try running your terminal as Administrator, use the package manager you installed Curd with, or move the standalone executable somewhere writable before retrying `curd -u`", err) |
| 435 | case "darwin": |
| 436 | return fmt.Errorf("%w. Try updating with your package manager or rerun the standalone updater with `sudo curd -u` if Curd is installed in a protected location", err) |
| 437 | default: |
| 438 | return fmt.Errorf("%w. Try updating with your package manager or rerun the standalone updater with `sudo curd -u`", err) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | return err |
| 443 | } |