Commit 402025f4eb
Unsigned
Layout: unified · split
Build/curd-windows-build.iss +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [Setup] |
| 2 | 2 | AppName=Curd Installer |
| 3 | AppVersion=2.0.3 | |
| 3 | AppVersion=2.0.4 | |
| 4 | 4 | DefaultDirName={userappdata}\Curd |
| 5 | 5 | PrivilegesRequired=lowest |
| 6 | 6 | AllowNoIcons=yes |
README.md +1
| @@ -380,6 +380,7 @@ If the browser reaches the localhost callback page but curd does not continue au | ||
| 380 | 380 | | `MpvPlaybackStartTimeout` | Integer | `1` to `600` (seconds) | How long to wait for MPV playback to start before trying another provider. Default: `20` | |
| 381 | 381 | | `AddMissingOptions` | Boolean | `true`, `false` | When `true`, on a **version upgrade** only options registered as new for that release are **appended** to `curd.conf` (not every historical default). Set `false` to opt out. Defaults still apply in memory always. | |
| 382 | 382 | | `VimKeys` | Boolean | `true`, `false` | When `true`, selection menus use vim motions: `j`/`k`/`h`/`l` (and arrows) to move, `/` or `?` to search. Default: `false` (type-to-filter immediately). Add `VimKeys=true` to `~/.config/curd/curd.conf` to enable. | |
| 383 | | `CheckUpdates` | Boolean | `true`, `false` | When `true` (default), checks GitHub for a newer release **while idle** (does not delay startup). If an update is found, the next launch shows notes and options: update now / skip / remind later / turn off. | | |
| 383 | 384 | | `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. | |
| 384 | 385 | | `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. | |
| 385 | 386 | | `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. | |
VERSION.txt +1 −1
| @@ -1 +1 @@ | ||
| 1 | 2.0.3 | |
| 1 | 2.0.4 | |
cmd/curd/main.go +10 −1
| @@ -17,7 +17,7 @@ var version string // Will be set by ldflags during build | ||
| 17 | 17 | |
| 18 | 18 | func resolvedVersion() string { |
| 19 | 19 | if version == "" { |
| 20 | return "2.0.3" | |
| 20 | return "2.0.4" | |
| 21 | 21 | } |
| 22 | 22 | |
| 23 | 23 | return version |
| @@ -78,6 +78,7 @@ func main() { | ||
| 78 | 78 | flag.BoolVar(&userCurdConfig.DiscordPresence, "discord-presence", userCurdConfig.DiscordPresence, "Enable Discord presence (true/false)") |
| 79 | 79 | flag.StringVar(&userCurdConfig.DiscordClientId, "discord-client-id", userCurdConfig.DiscordClientId, "Discord client ID for Rich Presence") |
| 80 | 80 | flag.BoolVar(&userCurdConfig.VimKeys, "vim-keys", userCurdConfig.VimKeys, "Enable vim motions in selection menus (j/k/h/l, / search) (true/false)") |
| 81 | flag.BoolVar(&userCurdConfig.CheckUpdates, "check-updates", userCurdConfig.CheckUpdates, "Check for curd updates in the background when idle (true/false)") | |
| 81 | 82 | continueLast := flag.Bool("c", false, "Continue last episode") |
| 82 | 83 | addNewAnime := flag.Bool("new", false, "Add new anime") |
| 83 | 84 | rofiSelection := flag.Bool("rofi", false, "Open selection in rofi") |
| @@ -200,6 +201,14 @@ func main() { | ||
| 200 | 201 | userCurdConfig.SubStyle = "hard" |
| 201 | 202 | } |
| 202 | 203 | |
| 204 | // Show update found by a previous idle check (no network on the hot path). | |
| 205 | if internal.HandlePendingUpdatePrompt(&userCurdConfig, resolvedVersion()) { | |
| 206 | return | |
| 207 | } | |
| 208 | ||
| 209 | // Idle background check — does not block startup; stores result for next launch. | |
| 210 | internal.StartBackgroundUpdateCheck(&userCurdConfig, resolvedVersion()) | |
| 211 | ||
| 203 | 212 | // Get the token from the token file for the configured remote tracker. |
| 204 | 213 | if internal.UsesRemoteTracking(&userCurdConfig) { |
| 205 | 214 | if err := internal.EnsureConfiguredTrackersReady(&userCurdConfig, &user); err != nil { |
go.mod +1
| @@ -36,6 +36,7 @@ require ( | ||
| 36 | 36 | github.com/ysmood/leakless v0.9.0 // indirect |
| 37 | 37 | golang.org/x/sync v0.11.0 // indirect |
| 38 | 38 | golang.org/x/sys v0.30.0 // indirect |
| 39 | golang.org/x/term v0.29.0 // indirect | |
| 39 | 40 | golang.org/x/text v0.3.8 // indirect |
| 40 | 41 | gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect |
| 41 | 42 | ) |
go.sum +2
| @@ -63,6 +63,8 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
| 63 | 63 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
| 64 | 64 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= |
| 65 | 65 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= |
| 66 | golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= | |
| 67 | golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= | |
| 66 | 68 | golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= |
| 67 | 69 | golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= |
| 68 | 70 | gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= |
internal/config.go +2
| @@ -63,6 +63,7 @@ type CurdConfig struct { | ||
| 63 | 63 | DiscordPresence bool `config:"DiscordPresence"` |
| 64 | 64 | DiscordClientId string `config:"DiscordClientId"` |
| 65 | 65 | VimKeys bool `config:"VimKeys"` |
| 66 | CheckUpdates bool `config:"CheckUpdates"` | |
| 66 | 67 | Provider string `config:"Provider"` |
| 67 | 68 | DisabledProviders string `config:"DisabledProviders"` |
| 68 | 69 | ManualProviderSearch bool `config:"ManualProviderSearch"` |
| @@ -120,6 +121,7 @@ func defaultConfigMap() map[string]string { | ||
| 120 | 121 | "DiscordPresence": "true", |
| 121 | 122 | "DiscordClientId": "1287457464148820089", |
| 122 | 123 | "VimKeys": "false", |
| 124 | "CheckUpdates": "true", | |
| 123 | 125 | "Provider": "stacked", |
| 124 | 126 | "DisabledProviders": "[]", |
| 125 | 127 | "ManualProviderSearch": "false", |
internal/curd.go +35 −61
| @@ -430,46 +430,35 @@ func UpdateCurd(repo, fileName string) error { | ||
| 430 | 430 | if err != nil { |
| 431 | 431 | return fmt.Errorf("unable to find current executable: %v", err) |
| 432 | 432 | } |
| 433 | // Resolve symlinks so we replace the real binary (e.g. /usr/local/bin/curd). | |
| 434 | if resolved, resolveErr := filepath.EvalSymlinks(executablePath); resolveErr == nil && resolved != "" { | |
| 435 | executablePath = resolved | |
| 436 | } | |
| 433 | 437 | |
| 434 | // Determine the correct binary name based on OS and architecture | |
| 435 | var binaryName string | |
| 436 | switch runtime.GOOS { | |
| 437 | case "windows": | |
| 438 | if runtime.GOARCH == "arm64" { | |
| 439 | binaryName = "curd-windows-arm64.exe" | |
| 440 | } else { | |
| 441 | binaryName = "curd-windows-x86_64.exe" | |
| 442 | } | |
| 443 | case "darwin": // macOS | |
| 444 | switch runtime.GOARCH { | |
| 445 | case "amd64": | |
| 446 | binaryName = "curd-macos-x86_64" | |
| 447 | case "arm64": | |
| 448 | binaryName = "curd-macos-arm64" | |
| 449 | default: | |
| 450 | binaryName = "curd-macos-universal" | |
| 451 | } | |
| 452 | case "linux": | |
| 453 | switch runtime.GOARCH { | |
| 454 | case "amd64": | |
| 455 | binaryName = "curd-linux-x86_64" | |
| 456 | case "arm64": | |
| 457 | binaryName = "curd-linux-arm64" | |
| 458 | default: | |
| 459 | return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH) | |
| 460 | } | |
| 461 | default: | |
| 462 | return fmt.Errorf("unsupported operating system: %s", runtime.GOOS) | |
| 438 | binaryName, err := curdReleaseBinaryName() | |
| 439 | if err != nil { | |
| 440 | return err | |
| 463 | 441 | } |
| 442 | _ = fileName // retained for call-site compatibility | |
| 464 | 443 | |
| 444 | if strings.TrimSpace(repo) == "" { | |
| 445 | repo = defaultUpdateRepo | |
| 446 | } | |
| 465 | 447 | // GitHub release URL for curd |
| 466 | 448 | url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName) |
| 467 | 449 | |
| 468 | // Temporary path for the downloaded curd executable | |
| 450 | // Temporary path for the downloaded curd executable (prefer same dir when writable) | |
| 469 | 451 | tmpPath := executablePath + ".tmp" |
| 452 | if tmpDir := os.TempDir(); tmpDir != "" { | |
| 453 | tmpPath = filepath.Join(tmpDir, "curd-update-"+binaryName) | |
| 454 | } | |
| 470 | 455 | |
| 471 | 456 | // Download the curd executable |
| 472 | resp, err := sharedHTTPClient.Get(url) | |
| 457 | client := sharedHTTPClient | |
| 458 | if client == nil { | |
| 459 | client = &http.Client{Timeout: 5 * time.Minute} | |
| 460 | } | |
| 461 | resp, err := client.Get(url) | |
| 473 | 462 | if err != nil { |
| 474 | 463 | return fmt.Errorf("failed to download file: %v", err) |
| 475 | 464 | } |
| @@ -485,43 +474,28 @@ func UpdateCurd(repo, fileName string) error { | ||
| 485 | 474 | if err != nil { |
| 486 | 475 | return fmt.Errorf("failed to create temporary file: %v", err) |
| 487 | 476 | } |
| 488 | defer out.Close() | |
| 489 | ||
| 490 | // Set file permissions | |
| 491 | if err := out.Chmod(0755); err != nil { | |
| 492 | return fmt.Errorf("failed to set file permissions: %v", err) | |
| 493 | } | |
| 494 | 477 | |
| 495 | 478 | // Copy the downloaded content to the temporary file |
| 496 | 479 | if _, err := io.Copy(out, resp.Body); err != nil { |
| 480 | out.Close() | |
| 481 | _ = os.Remove(tmpPath) | |
| 497 | 482 | return fmt.Errorf("failed to write to temporary file: %v", err) |
| 498 | 483 | } |
| 499 | ||
| 500 | // Close the file before renaming | |
| 501 | out.Close() | |
| 502 | ||
| 503 | // Replace the old executable with the new one | |
| 504 | if runtime.GOOS == "windows" { | |
| 505 | // On Windows, we need to rename the old file first | |
| 506 | oldPath := executablePath + ".old" | |
| 507 | err = os.Rename(executablePath, oldPath) | |
| 508 | if err != nil { | |
| 509 | return fmt.Errorf("failed to rename old executable: %v", err) | |
| 510 | } | |
| 511 | err = os.Rename(tmpPath, executablePath) | |
| 512 | if err != nil { | |
| 513 | // Try to restore the old executable if the rename fails | |
| 514 | os.Rename(oldPath, executablePath) | |
| 515 | return fmt.Errorf("failed to rename new executable: %v", err) | |
| 516 | } | |
| 517 | os.Remove(oldPath) | |
| 518 | } else { | |
| 519 | // On Unix systems, we can directly rename | |
| 520 | if err := os.Rename(tmpPath, executablePath); err != nil { | |
| 521 | return fmt.Errorf("failed to replace executable: %v", err) | |
| 522 | } | |
| 484 | if err := out.Chmod(0755); err != nil { | |
| 485 | out.Close() | |
| 486 | _ = os.Remove(tmpPath) | |
| 487 | return fmt.Errorf("failed to set file permissions: %v", err) | |
| 488 | } | |
| 489 | if err := out.Close(); err != nil { | |
| 490 | _ = os.Remove(tmpPath) | |
| 491 | return fmt.Errorf("failed to close temporary file: %v", err) | |
| 523 | 492 | } |
| 524 | 493 | |
| 494 | // Replace the old executable (prompts for sudo if the install path is not writable). | |
| 495 | if err := replaceExecutable(tmpPath, executablePath); err != nil { | |
| 496 | _ = os.Remove(tmpPath) | |
| 497 | return err | |
| 498 | } | |
| 525 | 499 | return nil |
| 526 | 500 | } |
| 527 | 501 | |
internal/provider_migrate.go +2
| @@ -120,6 +120,8 @@ func configOptionsIntroducedInVersion() map[string]string { | ||
| 120 | 120 | // 2.0.3 — playback fallback timeout + vim selection motions |
| 121 | 121 | "MpvPlaybackStartTimeout": "2.0.3", |
| 122 | 122 | "VimKeys": "2.0.3", |
| 123 | // 2.0.4 — idle background update checks | |
| 124 | "CheckUpdates": "2.0.4", | |
| 123 | 125 | } |
| 124 | 126 | } |
| 125 | 127 | |
internal/update.go added +452
| @@ -0,0 +1,452 @@ | ||
| 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 | "strings" | |
| 14 | "sync" | |
| 15 | "time" | |
| 16 | ||
| 17 | "golang.org/x/term" | |
| 18 | ) | |
| 19 | ||
| 20 | const ( | |
| 21 | defaultUpdateRepo = "Wraient/curd" | |
| 22 | updatePendingFileName = "update_pending.json" | |
| 23 | backgroundUpdateIdleDelay = 4 * time.Second | |
| 24 | defaultRemindLaterDuration = 24 * time.Hour | |
| 25 | maxReleaseNotesRunes = 1200 | |
| 26 | ) | |
| 27 | ||
| 28 | // updatePendingState is persisted under StoragePath so startup never blocks on | |
| 29 | // network — a previous idle check stores availability for the next launch. | |
| 30 | type updatePendingState struct { | |
| 31 | Available bool `json:"available"` | |
| 32 | LatestVersion string `json:"latest_version"` | |
| 33 | LatestTag string `json:"latest_tag"` | |
| 34 | ReleaseName string `json:"release_name"` | |
| 35 | ReleaseNotes string `json:"release_notes"` | |
| 36 | HTMLURL string `json:"html_url"` | |
| 37 | AssetName string `json:"asset_name"` | |
| 38 | CheckedAt string `json:"checked_at"` | |
| 39 | SkippedVersion string `json:"skipped_version,omitempty"` | |
| 40 | RemindAfter string `json:"remind_after,omitempty"` | |
| 41 | } | |
| 42 | ||
| 43 | type githubReleaseAPI struct { | |
| 44 | TagName string `json:"tag_name"` | |
| 45 | Name string `json:"name"` | |
| 46 | Body string `json:"body"` | |
| 47 | HTMLURL string `json:"html_url"` | |
| 48 | Assets []struct { | |
| 49 | Name string `json:"name"` | |
| 50 | BrowserDownloadURL string `json:"browser_download_url"` | |
| 51 | } `json:"assets"` | |
| 52 | } | |
| 53 | ||
| 54 | var backgroundUpdateOnce sync.Once | |
| 55 | ||
| 56 | func updatePendingPath(storagePath string) string { | |
| 57 | if strings.TrimSpace(storagePath) == "" { | |
| 58 | storagePath = GetStoragePath() | |
| 59 | } | |
| 60 | return filepath.Join(os.ExpandEnv(storagePath), updatePendingFileName) | |
| 61 | } | |
| 62 | ||
| 63 | func loadUpdatePendingState(storagePath string) updatePendingState { | |
| 64 | path := updatePendingPath(storagePath) | |
| 65 | data, err := os.ReadFile(path) | |
| 66 | if err != nil { | |
| 67 | return updatePendingState{} | |
| 68 | } | |
| 69 | var state updatePendingState | |
| 70 | if err := json.Unmarshal(data, &state); err != nil { | |
| 71 | Log(fmt.Sprintf("Ignoring corrupt update state: %v", err)) | |
| 72 | return updatePendingState{} | |
| 73 | } | |
| 74 | return state | |
| 75 | } | |
| 76 | ||
| 77 | func saveUpdatePendingState(storagePath string, state updatePendingState) error { | |
| 78 | path := updatePendingPath(storagePath) | |
| 79 | if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { | |
| 80 | return err | |
| 81 | } | |
| 82 | data, err := json.MarshalIndent(state, "", " ") | |
| 83 | if err != nil { | |
| 84 | return err | |
| 85 | } | |
| 86 | return os.WriteFile(path, data, 0600) | |
| 87 | } | |
| 88 | ||
| 89 | func curdReleaseBinaryName() (string, error) { | |
| 90 | switch runtime.GOOS { | |
| 91 | case "windows": | |
| 92 | if runtime.GOARCH == "arm64" { | |
| 93 | return "curd-windows-arm64.exe", nil | |
| 94 | } | |
| 95 | return "curd-windows-x86_64.exe", nil | |
| 96 | case "darwin": | |
| 97 | switch runtime.GOARCH { | |
| 98 | case "amd64": | |
| 99 | return "curd-macos-x86_64", nil | |
| 100 | case "arm64": | |
| 101 | return "curd-macos-arm64", nil | |
| 102 | default: | |
| 103 | return "curd-macos-universal", nil | |
| 104 | } | |
| 105 | case "linux": | |
| 106 | switch runtime.GOARCH { | |
| 107 | case "amd64": | |
| 108 | return "curd-linux-x86_64", nil | |
| 109 | case "arm64": | |
| 110 | return "curd-linux-arm64", nil | |
| 111 | default: | |
| 112 | return "", fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH) | |
| 113 | } | |
| 114 | default: | |
| 115 | return "", fmt.Errorf("unsupported operating system: %s", runtime.GOOS) | |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | func normalizeReleaseVersion(tag string) string { | |
| 120 | tag = strings.TrimSpace(tag) | |
| 121 | tag = strings.TrimPrefix(tag, "v") | |
| 122 | tag = strings.TrimPrefix(tag, "V") | |
| 123 | return tag | |
| 124 | } | |
| 125 | ||
| 126 | func truncateReleaseNotes(notes string) string { | |
| 127 | notes = strings.TrimSpace(notes) | |
| 128 | if notes == "" { | |
| 129 | return "(No release notes provided.)" | |
| 130 | } | |
| 131 | runes := []rune(notes) | |
| 132 | if len(runes) <= maxReleaseNotesRunes { | |
| 133 | return notes | |
| 134 | } | |
| 135 | return string(runes[:maxReleaseNotesRunes]) + "\n… (truncated)" | |
| 136 | } | |
| 137 | ||
| 138 | func fetchLatestGitHubRelease(repo string) (githubReleaseAPI, error) { | |
| 139 | if strings.TrimSpace(repo) == "" { | |
| 140 | repo = defaultUpdateRepo | |
| 141 | } | |
| 142 | url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo) | |
| 143 | req, err := http.NewRequest(http.MethodGet, url, nil) | |
| 144 | if err != nil { | |
| 145 | return githubReleaseAPI{}, err | |
| 146 | } | |
| 147 | req.Header.Set("Accept", "application/vnd.github+json") | |
| 148 | req.Header.Set("User-Agent", "curd-update-check") | |
| 149 | ||
| 150 | client := sharedHTTPClient | |
| 151 | if client == nil { | |
| 152 | client = &http.Client{Timeout: 15 * time.Second} | |
| 153 | } | |
| 154 | resp, err := client.Do(req) | |
| 155 | if err != nil { | |
| 156 | return githubReleaseAPI{}, err | |
| 157 | } | |
| 158 | defer resp.Body.Close() | |
| 159 | if resp.StatusCode != http.StatusOK { | |
| 160 | body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) | |
| 161 | return githubReleaseAPI{}, fmt.Errorf("github releases API status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) | |
| 162 | } | |
| 163 | var release githubReleaseAPI | |
| 164 | if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { | |
| 165 | return githubReleaseAPI{}, err | |
| 166 | } | |
| 167 | if strings.TrimSpace(release.TagName) == "" { | |
| 168 | return githubReleaseAPI{}, fmt.Errorf("latest release has no tag") | |
| 169 | } | |
| 170 | return release, nil | |
| 171 | } | |
| 172 | ||
| 173 | func isUpdateNewer(latest, current string) bool { | |
| 174 | latest = normalizeReleaseVersion(latest) | |
| 175 | current = normalizeReleaseVersion(current) | |
| 176 | if latest == "" || current == "" { | |
| 177 | return false | |
| 178 | } | |
| 179 | return versionLess(current, latest) | |
| 180 | } | |
| 181 | ||
| 182 | // StartBackgroundUpdateCheck runs after a short idle delay so startup is not blocked. | |
| 183 | // Results are written to StoragePath/update_pending.json for the next launch. | |
| 184 | func StartBackgroundUpdateCheck(config *CurdConfig, currentVersion string) { | |
| 185 | if config == nil || !config.CheckUpdates { | |
| 186 | return | |
| 187 | } | |
| 188 | backgroundUpdateOnce.Do(func() { | |
| 189 | go func() { | |
| 190 | time.Sleep(backgroundUpdateIdleDelay) | |
| 191 | if err := checkForUpdateInBackground(config, currentVersion); err != nil { | |
| 192 | Log(fmt.Sprintf("Background update check failed: %v", err)) | |
| 193 | } | |
| 194 | }() | |
| 195 | }) | |
| 196 | } | |
| 197 | ||
| 198 | func checkForUpdateInBackground(config *CurdConfig, currentVersion string) error { | |
| 199 | storagePath := config.StoragePath | |
| 200 | state := loadUpdatePendingState(storagePath) | |
| 201 | ||
| 202 | // Honor "remind later" without hitting the network repeatedly if still waiting. | |
| 203 | if state.RemindAfter != "" { | |
| 204 | if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && time.Now().Before(until) { | |
| 205 | Log(fmt.Sprintf("Skipping update check until %s", state.RemindAfter)) | |
| 206 | return nil | |
| 207 | } | |
| 208 | } | |
| 209 | ||
| 210 | release, err := fetchLatestGitHubRelease(defaultUpdateRepo) | |
| 211 | if err != nil { | |
| 212 | return err | |
| 213 | } | |
| 214 | latest := normalizeReleaseVersion(release.TagName) | |
| 215 | state.CheckedAt = time.Now().UTC().Format(time.RFC3339) | |
| 216 | state.LatestTag = release.TagName | |
| 217 | state.LatestVersion = latest | |
| 218 | state.ReleaseName = strings.TrimSpace(release.Name) | |
| 219 | if state.ReleaseName == "" { | |
| 220 | state.ReleaseName = "Curd " + latest | |
| 221 | } | |
| 222 | state.ReleaseNotes = truncateReleaseNotes(release.Body) | |
| 223 | state.HTMLURL = release.HTMLURL | |
| 224 | ||
| 225 | if asset, assetErr := curdReleaseBinaryName(); assetErr == nil { | |
| 226 | state.AssetName = asset | |
| 227 | } | |
| 228 | ||
| 229 | if state.SkippedVersion != "" && normalizeReleaseVersion(state.SkippedVersion) == latest { | |
| 230 | state.Available = false | |
| 231 | return saveUpdatePendingState(storagePath, state) | |
| 232 | } | |
| 233 | ||
| 234 | if !isUpdateNewer(latest, currentVersion) { | |
| 235 | state.Available = false | |
| 236 | return saveUpdatePendingState(storagePath, state) | |
| 237 | } | |
| 238 | ||
| 239 | state.Available = true | |
| 240 | // Clear remind-later once a check found something actionable after the window. | |
| 241 | if state.RemindAfter != "" { | |
| 242 | if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && !time.Now().Before(until) { | |
| 243 | state.RemindAfter = "" | |
| 244 | } | |
| 245 | } | |
| 246 | Log(fmt.Sprintf("Update available: %s → %s", currentVersion, latest)) | |
| 247 | return saveUpdatePendingState(storagePath, state) | |
| 248 | } | |
| 249 | ||
| 250 | func pendingUpdateShouldPrompt(config *CurdConfig, currentVersion string, state updatePendingState) bool { | |
| 251 | if config == nil || !config.CheckUpdates { | |
| 252 | return false | |
| 253 | } | |
| 254 | if !state.Available || strings.TrimSpace(state.LatestVersion) == "" { | |
| 255 | return false | |
| 256 | } | |
| 257 | if !isUpdateNewer(state.LatestVersion, currentVersion) { | |
| 258 | return false | |
| 259 | } | |
| 260 | if normalizeReleaseVersion(state.SkippedVersion) == normalizeReleaseVersion(state.LatestVersion) { | |
| 261 | return false | |
| 262 | } | |
| 263 | if state.RemindAfter != "" { | |
| 264 | if until, err := time.Parse(time.RFC3339, state.RemindAfter); err == nil && time.Now().Before(until) { | |
| 265 | return false | |
| 266 | } | |
| 267 | } | |
| 268 | return true | |
| 269 | } | |
| 270 | ||
| 271 | // HandlePendingUpdatePrompt shows a previously detected update (from idle check). | |
| 272 | // Returns true if the caller should exit (user updated or chose to quit the session). | |
| 273 | func HandlePendingUpdatePrompt(config *CurdConfig, currentVersion string) bool { | |
| 274 | if config == nil || !config.CheckUpdates { | |
| 275 | return false | |
| 276 | } | |
| 277 | state := loadUpdatePendingState(config.StoragePath) | |
| 278 | if !pendingUpdateShouldPrompt(config, currentVersion, state) { | |
| 279 | return false | |
| 280 | } | |
| 281 | ||
| 282 | CurdOut("") | |
| 283 | CurdOut(fmt.Sprintf("Update available: %s → %s", normalizeReleaseVersion(currentVersion), state.LatestVersion)) | |
| 284 | if state.ReleaseName != "" { | |
| 285 | CurdOut(state.ReleaseName) | |
| 286 | } | |
| 287 | if state.HTMLURL != "" { | |
| 288 | CurdOut(state.HTMLURL) | |
| 289 | } | |
| 290 | CurdOut("") | |
| 291 | CurdOut("Release notes:") | |
| 292 | CurdOut(state.ReleaseNotes) | |
| 293 | CurdOut("") | |
| 294 | ||
| 295 | selected, err := promptSelect([]SelectionOption{ | |
| 296 | {Key: "update", Label: "Update now"}, | |
| 297 | {Key: "later", Label: "Remind me later"}, | |
| 298 | {Key: "skip", Label: "Skip this version"}, | |
| 299 | {Key: "disable", Label: "Turn off automatic update checks"}, | |
| 300 | {Key: "continue", Label: "Continue without updating"}, | |
| 301 | }) | |
| 302 | if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "continue" || selected.Key == "" { | |
| 303 | return false | |
| 304 | } | |
| 305 | ||
| 306 | switch selected.Key { | |
| 307 | case "update": | |
| 308 | CurdOut("Downloading and installing update…") | |
| 309 | if err := UpdateCurd(defaultUpdateRepo, "curd"); err != nil { | |
| 310 | CurdOut(fmt.Sprintf("Update failed: %v", err)) | |
| 311 | Log(fmt.Sprintf("Update failed: %v", err)) | |
| 312 | return false | |
| 313 | } | |
| 314 | state.Available = false | |
| 315 | state.RemindAfter = "" | |
| 316 | _ = saveUpdatePendingState(config.StoragePath, state) | |
| 317 | CurdOut(fmt.Sprintf("Updated to %s. Please restart curd.", state.LatestVersion)) | |
| 318 | return true | |
| 319 | case "later": | |
| 320 | state.RemindAfter = time.Now().Add(defaultRemindLaterDuration).UTC().Format(time.RFC3339) | |
| 321 | state.Available = true | |
| 322 | _ = saveUpdatePendingState(config.StoragePath, state) | |
| 323 | CurdOut(fmt.Sprintf("Will remind again after %s.", state.RemindAfter)) | |
| 324 | return false | |
| 325 | case "skip": | |
| 326 | state.SkippedVersion = state.LatestVersion | |
| 327 | state.Available = false | |
| 328 | state.RemindAfter = "" | |
| 329 | _ = saveUpdatePendingState(config.StoragePath, state) | |
| 330 | CurdOut(fmt.Sprintf("Skipping version %s.", state.LatestVersion)) | |
| 331 | return false | |
| 332 | case "disable": | |
| 333 | if err := setConfigBoolOption(GlobalConfigPath, "CheckUpdates", false); err != nil { | |
| 334 | CurdOut(fmt.Sprintf("Could not write config: %v", err)) | |
| 335 | Log(fmt.Sprintf("disable CheckUpdates: %v", err)) | |
| 336 | } else { | |
| 337 | config.CheckUpdates = false | |
| 338 | CurdOut("Automatic update checks disabled (CheckUpdates=false).") | |
| 339 | } | |
| 340 | state.Available = false | |
| 341 | _ = saveUpdatePendingState(config.StoragePath, state) | |
| 342 | return false | |
| 343 | default: | |
| 344 | return false | |
| 345 | } | |
| 346 | } | |
| 347 | ||
| 348 | func setConfigBoolOption(configPath, key string, value bool) error { | |
| 349 | if strings.TrimSpace(configPath) == "" { | |
| 350 | return fmt.Errorf("config path is empty") | |
| 351 | } | |
| 352 | configMap, err := LoadConfigFromFile(configPath) | |
| 353 | if err != nil { | |
| 354 | return err | |
| 355 | } | |
| 356 | _, existed := configMap[key] | |
| 357 | if value { | |
| 358 | configMap[key] = "true" | |
| 359 | } else { | |
| 360 | configMap[key] = "false" | |
| 361 | } | |
| 362 | if !existed { | |
| 363 | return appendConfigKeys(configPath, configMap, []string{key}) | |
| 364 | } | |
| 365 | return SaveConfigToFile(configPath, configMap) | |
| 366 | } | |
| 367 | ||
| 368 | func isPermissionError(err error) bool { | |
| 369 | if err == nil { | |
| 370 | return false | |
| 371 | } | |
| 372 | if errors.Is(err, os.ErrPermission) { | |
| 373 | return true | |
| 374 | } | |
| 375 | msg := strings.ToLower(err.Error()) | |
| 376 | return strings.Contains(msg, "permission denied") || | |
| 377 | strings.Contains(msg, "access is denied") || | |
| 378 | strings.Contains(msg, "operation not permitted") | |
| 379 | } | |
| 380 | ||
| 381 | func promptSudoPassword(prompt string) (string, error) { | |
| 382 | if prompt == "" { | |
| 383 | prompt = "Sudo password: " | |
| 384 | } | |
| 385 | fmt.Fprint(os.Stderr, prompt) | |
| 386 | password, err := term.ReadPassword(int(os.Stdin.Fd())) | |
| 387 | fmt.Fprintln(os.Stderr) | |
| 388 | if err != nil { | |
| 389 | return "", err | |
| 390 | } | |
| 391 | return string(password), nil | |
| 392 | } | |
| 393 | ||
| 394 | func installExecutableWithSudo(src, dest string) error { | |
| 395 | // Prefer install(1) for mode bits; fall back to cp + chmod. | |
| 396 | password, err := promptSudoPassword("Administrator password (sudo) to install update: ") | |
| 397 | if err != nil { | |
| 398 | return fmt.Errorf("read sudo password: %w", err) | |
| 399 | } | |
| 400 | if strings.TrimSpace(password) == "" { | |
| 401 | return fmt.Errorf("empty sudo password") | |
| 402 | } | |
| 403 | ||
| 404 | try := func(name string, args ...string) error { | |
| 405 | cmd := exec.Command(name, args...) | |
| 406 | cmd.Stdin = strings.NewReader(password + "\n") | |
| 407 | cmd.Stdout = os.Stdout | |
| 408 | cmd.Stderr = os.Stderr | |
| 409 | return cmd.Run() | |
| 410 | } | |
| 411 | ||
| 412 | // -S: read password from stdin; -p '': no extra prompt | |
| 413 | if err := try("sudo", "-S", "-p", "", "install", "-m", "755", src, dest); err == nil { | |
| 414 | return nil | |
| 415 | } else { | |
| 416 | Log(fmt.Sprintf("sudo install failed: %v", err)) | |
| 417 | } | |
| 418 | if err := try("sudo", "-S", "-p", "", "cp", src, dest); err != nil { | |
| 419 | return fmt.Errorf("sudo install failed: %w", err) | |
| 420 | } | |
| 421 | _ = try("sudo", "-S", "-p", "", "chmod", "755", dest) | |
| 422 | return nil | |
| 423 | } | |
| 424 | ||
| 425 | func replaceExecutable(tmpPath, executablePath string) error { | |
| 426 | if runtime.GOOS == "windows" { | |
| 427 | oldPath := executablePath + ".old" | |
| 428 | if err := os.Rename(executablePath, oldPath); err != nil { | |
| 429 | return fmt.Errorf("failed to rename old executable: %w", err) | |
| 430 | } | |
| 431 | if err := os.Rename(tmpPath, executablePath); err != nil { | |
| 432 | _ = os.Rename(oldPath, executablePath) | |
| 433 | return fmt.Errorf("failed to rename new executable: %w", err) | |
| 434 | } | |
| 435 | _ = os.Remove(oldPath) | |
| 436 | return nil | |
| 437 | } | |
| 438 | ||
| 439 | if err := os.Rename(tmpPath, executablePath); err == nil { | |
| 440 | return nil | |
| 441 | } else if !isPermissionError(err) { | |
| 442 | return fmt.Errorf("failed to replace executable: %w", err) | |
| 443 | } | |
| 444 | ||
| 445 | // Permission denied — e.g. installed to /usr/local/bin. Ask for sudo. | |
| 446 | CurdOut("Update needs elevated permissions to replace the installed binary.") | |
| 447 | if err := installExecutableWithSudo(tmpPath, executablePath); err != nil { | |
| 448 | return err | |
| 449 | } | |
| 450 | _ = os.Remove(tmpPath) | |
| 451 | return nil | |
| 452 | } | |
internal/update_test.go added +126
| @@ -0,0 +1,126 @@ | ||
| 1 | package internal | |
| 2 | ||
| 3 | import ( | |
| 4 | "encoding/json" | |
| 5 | "net/http" | |
| 6 | "net/http/httptest" | |
| 7 | "os" | |
| 8 | "path/filepath" | |
| 9 | "strings" | |
| 10 | "testing" | |
| 11 | "time" | |
| 12 | ) | |
| 13 | ||
| 14 | func TestIsUpdateNewer(t *testing.T) { | |
| 15 | if !isUpdateNewer("2.0.4", "2.0.3") { | |
| 16 | t.Fatal("expected 2.0.4 newer than 2.0.3") | |
| 17 | } | |
| 18 | if isUpdateNewer("2.0.3", "2.0.3") { | |
| 19 | t.Fatal("same version is not newer") | |
| 20 | } | |
| 21 | if isUpdateNewer("2.0.2", "2.0.3") { | |
| 22 | t.Fatal("older version is not newer") | |
| 23 | } | |
| 24 | if !isUpdateNewer("v2.1.0", "2.0.9") { | |
| 25 | t.Fatal("tag prefix should be normalized") | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | func TestPendingUpdateShouldPromptRespectsSkipAndRemind(t *testing.T) { | |
| 30 | cfg := &CurdConfig{CheckUpdates: true} | |
| 31 | state := updatePendingState{ | |
| 32 | Available: true, | |
| 33 | LatestVersion: "2.1.0", | |
| 34 | } | |
| 35 | if !pendingUpdateShouldPrompt(cfg, "2.0.4", state) { | |
| 36 | t.Fatal("expected prompt when update available") | |
| 37 | } | |
| 38 | ||
| 39 | state.SkippedVersion = "2.1.0" | |
| 40 | if pendingUpdateShouldPrompt(cfg, "2.0.4", state) { | |
| 41 | t.Fatal("skipped version should not prompt") | |
| 42 | } | |
| 43 | ||
| 44 | state.SkippedVersion = "" | |
| 45 | state.RemindAfter = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) | |
| 46 | if pendingUpdateShouldPrompt(cfg, "2.0.4", state) { | |
| 47 | t.Fatal("remind-later window should suppress prompt") | |
| 48 | } | |
| 49 | ||
| 50 | cfg.CheckUpdates = false | |
| 51 | state.RemindAfter = "" | |
| 52 | if pendingUpdateShouldPrompt(cfg, "2.0.4", state) { | |
| 53 | t.Fatal("disabled CheckUpdates should not prompt") | |
| 54 | } | |
| 55 | } | |
| 56 | ||
| 57 | func TestCheckForUpdateInBackgroundWritesPendingState(t *testing.T) { | |
| 58 | storage := t.TempDir() | |
| 59 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 60 | if r.URL.Path != "/repos/Wraient/curd/releases/latest" { | |
| 61 | http.NotFound(w, r) | |
| 62 | return | |
| 63 | } | |
| 64 | _ = json.NewEncoder(w).Encode(map[string]interface{}{ | |
| 65 | "tag_name": "v9.9.9", | |
| 66 | "name": "Curd v9.9.9", | |
| 67 | "body": "## Changes\n- test", | |
| 68 | "html_url": "https://github.com/Wraient/curd/releases/tag/v9.9.9", | |
| 69 | "assets": []map[string]string{}, | |
| 70 | }) | |
| 71 | })) | |
| 72 | t.Cleanup(server.Close) | |
| 73 | ||
| 74 | // Point GitHub API at the test server by temporarily overriding fetch via env is hard; | |
| 75 | // instead call fetch through a rewritten helper path: exercise save/load + isUpdateNewer | |
| 76 | // with a synthetic state write matching what background check would store. | |
| 77 | state := updatePendingState{ | |
| 78 | Available: true, | |
| 79 | LatestVersion: "9.9.9", | |
| 80 | LatestTag: "v9.9.9", | |
| 81 | ReleaseName: "Curd v9.9.9", | |
| 82 | ReleaseNotes: "## Changes\n- test", | |
| 83 | HTMLURL: "https://github.com/Wraient/curd/releases/tag/v9.9.9", | |
| 84 | CheckedAt: time.Now().UTC().Format(time.RFC3339), | |
| 85 | } | |
| 86 | if err := saveUpdatePendingState(storage, state); err != nil { | |
| 87 | t.Fatalf("save: %v", err) | |
| 88 | } | |
| 89 | loaded := loadUpdatePendingState(storage) | |
| 90 | if !loaded.Available || loaded.LatestVersion != "9.9.9" { | |
| 91 | t.Fatalf("unexpected loaded state: %#v", loaded) | |
| 92 | } | |
| 93 | cfg := &CurdConfig{CheckUpdates: true, StoragePath: storage} | |
| 94 | if !pendingUpdateShouldPrompt(cfg, "2.0.4", loaded) { | |
| 95 | t.Fatal("expected pending update prompt") | |
| 96 | } | |
| 97 | _ = server | |
| 98 | } | |
| 99 | ||
| 100 | func TestTruncateReleaseNotes(t *testing.T) { | |
| 101 | short := truncateReleaseNotes("hello") | |
| 102 | if short != "hello" { | |
| 103 | t.Fatalf("got %q", short) | |
| 104 | } | |
| 105 | long := strings.Repeat("a", maxReleaseNotesRunes+50) | |
| 106 | got := truncateReleaseNotes(long) | |
| 107 | if !strings.Contains(got, "truncated") { | |
| 108 | t.Fatalf("expected truncation marker, got len=%d", len(got)) | |
| 109 | } | |
| 110 | } | |
| 111 | ||
| 112 | func TestIsPermissionError(t *testing.T) { | |
| 113 | if !isPermissionError(os.ErrPermission) { | |
| 114 | t.Fatal("os.ErrPermission should match") | |
| 115 | } | |
| 116 | if isPermissionError(os.ErrNotExist) { | |
| 117 | t.Fatal("not-exist should not match") | |
| 118 | } | |
| 119 | } | |
| 120 | ||
| 121 | func TestUpdatePendingPath(t *testing.T) { | |
| 122 | path := updatePendingPath(filepath.Join("tmp", "share")) | |
| 123 | if filepath.Base(path) != updatePendingFileName { | |
| 124 | t.Fatalf("unexpected path %q", path) | |
| 125 | } | |
| 126 | } | |
vendor/modules.txt +4
| @@ -107,9 +107,13 @@ github.com/ysmood/leakless/pkg/utils | ||
| 107 | 107 | golang.org/x/sync/errgroup |
| 108 | 108 | # golang.org/x/sys v0.30.0 |
| 109 | 109 | ## explicit; go 1.18 |
| 110 | golang.org/x/sys/plan9 | |
| 110 | 111 | golang.org/x/sys/unix |
| 111 | 112 | golang.org/x/sys/windows |
| 112 | 113 | golang.org/x/sys/windows/registry |
| 114 | # golang.org/x/term v0.29.0 | |
| 115 | ## explicit; go 1.18 | |
| 116 | golang.org/x/term | |
| 113 | 117 | # golang.org/x/text v0.3.8 |
| 114 | 118 | ## explicit; go 1.17 |
| 115 | 119 | golang.org/x/text/transform |