internal/update.go
448 lines · 12040 bytes
1package internal
2
3import (
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
19const releaseStateFileName = "release_state.json"
20
21type githubRelease struct {
22 TagName string `json:"tag_name"`
23 HTMLURL string `json:"html_url"`
24}
25
26type releaseState struct {
27 LatestVersion string `json:"latest_version"`
28 ReleaseURL string `json:"release_url,omitempty"`
29 CheckedAt time.Time `json:"checked_at"`
30}
31
32func 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
46func 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
64func 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
77func 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
95func 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
127func 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
157func 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
202func 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
231func 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
234setlocal
235set "TARGET=%s"
236set "SOURCE=%s"
237set "OLD=%s.old"
238:wait_loop
239tasklist /FI "PID eq %d" 2>NUL | find "%d" >NUL
240if not errorlevel 1 (
241 timeout /T 1 /NOBREAK >NUL
242 goto wait_loop
243)
244if exist "%%OLD%%" del /F /Q "%%OLD%%" >NUL 2>NUL
245if exist "%%TARGET%%" move /Y "%%TARGET%%" "%%OLD%%" >NUL
246move /Y "%%SOURCE%%" "%%TARGET%%" >NUL
247if errorlevel 1 (
248 if exist "%%OLD%%" move /Y "%%OLD%%" "%%TARGET%%" >NUL 2>NUL
249 del /F /Q "%%~f0" >NUL 2>NUL
250 exit /B 1
251)
252if exist "%%OLD%%" del /F /Q "%%OLD%%" >NUL 2>NUL
253del /F /Q "%%~f0" >NUL 2>NUL
254`, executablePath, tmpPath, executablePath, os.Getpid(), os.Getpid())
255
256 if err := os.WriteFile(scriptPath, []byte(script), 0600); err != nil {
257 return fmt.Errorf("failed to create Windows update script: %w", err)
258 }
259
260 cmd := exec.Command("cmd", "/C", "start", "", "/B", scriptPath)
261 cmd.Dir = filepath.Dir(executablePath)
262 if err := cmd.Start(); err != nil {
263 _ = os.Remove(scriptPath)
264 return fmt.Errorf("failed to launch Windows updater: %w", err)
265 }
266
267 return nil
268}
269
270func saveReleaseState(storagePath string, state releaseState) error {
271 statePath, err := releaseStatePath(storagePath)
272 if err != nil {
273 return err
274 }
275
276 if err := os.MkdirAll(filepath.Dir(statePath), 0755); err != nil {
277 return fmt.Errorf("failed to create release cache directory: %w", err)
278 }
279
280 data, err := json.MarshalIndent(state, "", " ")
281 if err != nil {
282 return fmt.Errorf("failed to marshal release state: %w", err)
283 }
284
285 if err := os.WriteFile(statePath, data, 0644); err != nil {
286 return fmt.Errorf("failed to write release state: %w", err)
287 }
288
289 return nil
290}
291
292func loadReleaseState(storagePath string) (releaseState, error) {
293 statePath, err := releaseStatePath(storagePath)
294 if err != nil {
295 return releaseState{}, err
296 }
297
298 data, err := os.ReadFile(statePath)
299 if err != nil {
300 return releaseState{}, err
301 }
302
303 var state releaseState
304 if err := json.Unmarshal(data, &state); err != nil {
305 return releaseState{}, err
306 }
307
308 state.LatestVersion = normalizeVersion(state.LatestVersion)
309 return state, nil
310}
311
312func releaseStatePath(storagePath string) (string, error) {
313 expandedStorage := os.ExpandEnv(strings.TrimSpace(storagePath))
314 if expandedStorage == "" {
315 return "", fmt.Errorf("storage path is empty")
316 }
317
318 return filepath.Join(expandedStorage, releaseStateFileName), nil
319}
320
321func buildUpdatePrompt(currentVersion, latestVersion string) string {
322 switch runtime.GOOS {
323 case "windows":
324 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)
325 case "darwin":
326 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)
327 default:
328 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)
329 }
330}
331
332func compareVersions(leftVersion, rightVersion string) int {
333 leftParts := versionParts(leftVersion)
334 rightParts := versionParts(rightVersion)
335 maxParts := len(leftParts)
336 if len(rightParts) > maxParts {
337 maxParts = len(rightParts)
338 }
339
340 for i := 0; i < maxParts; i++ {
341 left := 0
342 right := 0
343 if i < len(leftParts) {
344 left = leftParts[i]
345 }
346 if i < len(rightParts) {
347 right = rightParts[i]
348 }
349 if left > right {
350 return 1
351 }
352 if left < right {
353 return -1
354 }
355 }
356
357 return 0
358}
359
360func versionParts(version string) []int {
361 cleanVersion := normalizeVersion(version)
362 if cleanVersion == "" {
363 return nil
364 }
365
366 segments := strings.FieldsFunc(cleanVersion, func(r rune) bool {
367 return r < '0' || r > '9'
368 })
369
370 parts := make([]int, 0, len(segments))
371 for _, segment := range segments {
372 if segment == "" {
373 continue
374 }
375
376 value, err := strconv.Atoi(segment)
377 if err != nil {
378 return nil
379 }
380 parts = append(parts, value)
381 }
382
383 return parts
384}
385
386func normalizeVersion(version string) string {
387 trimmed := strings.TrimSpace(version)
388 trimmed = strings.TrimPrefix(trimmed, "v")
389 if trimmed == "" || trimmed == "(devel)" {
390 return ""
391 }
392
393 if len(versionPartsWithoutNormalization(trimmed)) == 0 {
394 return ""
395 }
396
397 return trimmed
398}
399
400func versionPartsWithoutNormalization(version string) []int {
401 segments := strings.FieldsFunc(version, func(r rune) bool {
402 return r < '0' || r > '9'
403 })
404
405 parts := make([]int, 0, len(segments))
406 for _, segment := range segments {
407 if segment == "" {
408 continue
409 }
410
411 value, err := strconv.Atoi(segment)
412 if err != nil {
413 return nil
414 }
415 parts = append(parts, value)
416 }
417
418 return parts
419}
420
421func userAgentForVersion(currentVersion string) string {
422 currentVersion = normalizeVersion(currentVersion)
423 if currentVersion == "" {
424 return "curd"
425 }
426
427 return "curd/" + currentVersion
428}
429
430func wrapUpdateError(err error) error {
431 if err == nil {
432 return nil
433 }
434
435 message := strings.ToLower(err.Error())
436 if errors.Is(err, os.ErrPermission) || strings.Contains(message, "permission denied") || strings.Contains(message, "access is denied") {
437 switch runtime.GOOS {
438 case "windows":
439 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)
440 case "darwin":
441 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)
442 default:
443 return fmt.Errorf("%w. Try updating with your package manager or rerun the standalone updater with `sudo curd -u`", err)
444 }
445 }
446
447 return err
448}