Commit 170016346f

170016346feef4bce2532f54756c744696d12483

parent: f28ee237f3

Unsigned

Wraient <wraient.911@gmail.com> · 2026-03-31 16:46 UTC

Add: Check Update Prompt

Layout: unified · split

Build/curd-windows-build.iss +1 −1
@@ -1,6 +1,6 @@
11[Setup]
22AppName=Curd Installer
3AppVersion=1.0.8
3AppVersion=1.2.0
44DefaultDirName={userappdata}\Curd
55PrivilegesRequired=lowest
66AllowNoIcons=yes
cmd/curd/main.go +15 −7
@@ -82,13 +82,19 @@ func main() {
8282
8383 flag.Parse()
8484
85 currentVersion := internal.ResolveCurrentVersion(version)
86
8587 // Check version before screen clearing
8688 if *versionFlag {
8789 internal.RestoreScreen()
88 if version == "" {
89 version = "1.2.0"
90 if currentVersion == "" {
91 if version == "" {
92 currentVersion = "1.2.0"
93 } else {
94 currentVersion = version
95 }
9096 }
91 fmt.Printf("Curd version: %s\n", version)
97 fmt.Printf("Curd version: %s\n", currentVersion)
9298 os.Exit(0)
9399 }
94100
@@ -96,13 +102,12 @@ func main() {
96102
97103 if *updateScript {
98104 repo := "wraient/curd"
99 fileName := "curd"
100
101 if err := internal.UpdateCurd(repo, fileName); err != nil {
105 updateMessage, err := internal.UpdateCurd(repo)
106 if err != nil {
102107 internal.CurdOut(fmt.Sprintf("Error updating executable: %v\n", err))
103108 internal.ExitCurd(err)
104109 } else {
105 internal.CurdOut("Program Updated!")
110 internal.CurdOut(updateMessage)
106111 internal.ExitCurd(nil)
107112 }
108113 }
@@ -141,6 +146,9 @@ func main() {
141146 return
142147 }
143148
149 internal.NotifyAboutCachedUpdate(currentVersion, userCurdConfig.StoragePath)
150 internal.StartBackgroundReleaseCheck(currentVersion, userCurdConfig.StoragePath)
151
144152 // Set SubOrDub based on the flags
145153 if *subFlag {
146154 userCurdConfig.SubOrDub = "sub"
internal/curd.go −101
@@ -508,107 +508,6 @@ updateOptionLoop:
508508 }
509509}
510510
511func UpdateCurd(repo, fileName string) error {
512 // Get the path of the currently running executable
513 executablePath, err := os.Executable()
514 if err != nil {
515 return fmt.Errorf("unable to find current executable: %v", err)
516 }
517
518 // Determine the correct binary name based on OS and architecture
519 var binaryName string
520 switch runtime.GOOS {
521 case "windows":
522 if runtime.GOARCH == "arm64" {
523 binaryName = "curd-windows-arm64.exe"
524 } else {
525 binaryName = "curd-windows-x86_64.exe"
526 }
527 case "darwin": // macOS
528 switch runtime.GOARCH {
529 case "amd64":
530 binaryName = "curd-macos-x86_64"
531 case "arm64":
532 binaryName = "curd-macos-arm64"
533 default:
534 binaryName = "curd-macos-universal"
535 }
536 case "linux":
537 switch runtime.GOARCH {
538 case "amd64":
539 binaryName = "curd-linux-x86_64"
540 case "arm64":
541 binaryName = "curd-linux-arm64"
542 default:
543 return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
544 }
545 default:
546 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
547 }
548
549 // GitHub release URL for curd
550 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
551
552 // Temporary path for the downloaded curd executable
553 tmpPath := executablePath + ".tmp"
554
555 // Download the curd executable
556 resp, err := http.Get(url)
557 if err != nil {
558 return fmt.Errorf("failed to download file: %v", err)
559 }
560 defer resp.Body.Close()
561
562 // Check if the download was successful
563 if resp.StatusCode != http.StatusOK {
564 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
565 }
566
567 // Create a new temporary file
568 out, err := os.Create(tmpPath)
569 if err != nil {
570 return fmt.Errorf("failed to create temporary file: %v", err)
571 }
572 defer out.Close()
573
574 // Set file permissions
575 if err := out.Chmod(0755); err != nil {
576 return fmt.Errorf("failed to set file permissions: %v", err)
577 }
578
579 // Copy the downloaded content to the temporary file
580 if _, err := io.Copy(out, resp.Body); err != nil {
581 return fmt.Errorf("failed to write to temporary file: %v", err)
582 }
583
584 // Close the file before renaming
585 out.Close()
586
587 // Replace the old executable with the new one
588 if runtime.GOOS == "windows" {
589 // On Windows, we need to rename the old file first
590 oldPath := executablePath + ".old"
591 err = os.Rename(executablePath, oldPath)
592 if err != nil {
593 return fmt.Errorf("failed to rename old executable: %v", err)
594 }
595 err = os.Rename(tmpPath, executablePath)
596 if err != nil {
597 // Try to restore the old executable if the rename fails
598 os.Rename(oldPath, executablePath)
599 return fmt.Errorf("failed to rename new executable: %v", err)
600 }
601 os.Remove(oldPath)
602 } else {
603 // On Unix systems, we can directly rename
604 if err := os.Rename(tmpPath, executablePath); err != nil {
605 return fmt.Errorf("failed to replace executable: %v", err)
606 }
607 }
608
609 return nil
610}
611
612511func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
613512 var query string
614513 // Remove the redeclared variable declaration since animeOptions is already declared above
internal/update.go added +443
@@ -0,0 +1,443 @@
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 exist "%%OLD%%" del /F /Q "%%OLD%%" >NUL 2>NUL
248del /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
265func 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
287func 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
307func 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
316func 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
327func 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
355func 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
381func 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
395func 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
416func userAgentForVersion(currentVersion string) string {
417 currentVersion = normalizeVersion(currentVersion)
418 if currentVersion == "" {
419 return "curd"
420 }
421
422 return "curd/" + currentVersion
423}
424
425func 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}
internal/update_test.go added +48
@@ -0,0 +1,48 @@
1package internal
2
3import "testing"
4
5func TestNormalizeVersion(t *testing.T) {
6 tests := []struct {
7 name string
8 input string
9 want string
10 }{
11 {name: "plain semver", input: "1.2.3", want: "1.2.3"},
12 {name: "trim leading v", input: "v1.2.3", want: "1.2.3"},
13 {name: "trim whitespace", input: " v2.0.1 ", want: "2.0.1"},
14 {name: "development build", input: "(devel)", want: ""},
15 {name: "invalid", input: "latest", want: ""},
16 }
17
18 for _, test := range tests {
19 t.Run(test.name, func(t *testing.T) {
20 if got := normalizeVersion(test.input); got != test.want {
21 t.Fatalf("normalizeVersion(%q) = %q, want %q", test.input, got, test.want)
22 }
23 })
24 }
25}
26
27func TestCompareVersions(t *testing.T) {
28 tests := []struct {
29 name string
30 left string
31 right string
32 want int
33 }{
34 {name: "equal", left: "1.2.3", right: "1.2.3", want: 0},
35 {name: "patch newer", left: "1.2.4", right: "1.2.3", want: 1},
36 {name: "minor older", left: "1.1.9", right: "1.2.0", want: -1},
37 {name: "prefix ignored", left: "v1.3.0", right: "1.2.9", want: 1},
38 {name: "missing patch treated as zero", left: "1.2", right: "1.2.0", want: 0},
39 }
40
41 for _, test := range tests {
42 t.Run(test.name, func(t *testing.T) {
43 if got := compareVersions(test.left, test.right); got != test.want {
44 t.Fatalf("compareVersions(%q, %q) = %d, want %d", test.left, test.right, got, test.want)
45 }
46 })
47 }
48}