|
| 1 | +// Package update provides version update checking for the CNAP CLI. |
| 2 | +// It checks the GitHub Releases API in the background and caches results |
| 3 | +// for 24 hours to avoid excessive API calls. |
| 4 | +package update |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "os" |
| 13 | + "os/exec" |
| 14 | + "path/filepath" |
| 15 | + "strconv" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | + |
| 19 | + "github.com/cnap-tech/cli/internal/config" |
| 20 | + "golang.org/x/term" |
| 21 | + "gopkg.in/yaml.v3" |
| 22 | +) |
| 23 | + |
| 24 | +const ( |
| 25 | + repo = "cnap-tech/cli" |
| 26 | + stateFile = "state.yaml" |
| 27 | +) |
| 28 | + |
| 29 | +// ReleaseInfo stores information about a GitHub release. |
| 30 | +type ReleaseInfo struct { |
| 31 | + Version string `json:"tag_name"` |
| 32 | + URL string `json:"html_url"` |
| 33 | + PublishedAt time.Time `json:"published_at"` |
| 34 | +} |
| 35 | + |
| 36 | +type stateEntry struct { |
| 37 | + CheckedForUpdateAt time.Time `yaml:"checked_for_update_at"` |
| 38 | + LatestRelease ReleaseInfo `yaml:"latest_release"` |
| 39 | +} |
| 40 | + |
| 41 | +// ShouldCheckForUpdate returns true if the environment is suitable for update checks. |
| 42 | +func ShouldCheckForUpdate() bool { |
| 43 | + if os.Getenv("CNAP_NO_UPDATE_NOTIFIER") != "" { |
| 44 | + return false |
| 45 | + } |
| 46 | + if os.Getenv("CODESPACES") != "" { |
| 47 | + return false |
| 48 | + } |
| 49 | + if isCI() { |
| 50 | + return false |
| 51 | + } |
| 52 | + return term.IsTerminal(int(os.Stderr.Fd())) |
| 53 | +} |
| 54 | + |
| 55 | +// CheckForUpdate checks whether a newer version of the CLI is available. |
| 56 | +// Returns nil if the check was performed recently (within 24h) or if the |
| 57 | +// current version is up to date. |
| 58 | +func CheckForUpdate(ctx context.Context, currentVersion string) (*ReleaseInfo, error) { |
| 59 | + stateFilePath, err := statePath() |
| 60 | + if err != nil { |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + |
| 64 | + // Return early if checked recently |
| 65 | + state, _ := getState(stateFilePath) |
| 66 | + if state != nil && time.Since(state.CheckedForUpdateAt).Hours() < 24 { |
| 67 | + return nil, nil |
| 68 | + } |
| 69 | + |
| 70 | + // Fetch latest release from GitHub |
| 71 | + release, err := fetchLatestRelease(ctx) |
| 72 | + if err != nil { |
| 73 | + return nil, err |
| 74 | + } |
| 75 | + |
| 76 | + // Cache the result |
| 77 | + _ = setState(stateFilePath, time.Now(), *release) |
| 78 | + |
| 79 | + if versionGreaterThan(release.Version, currentVersion) { |
| 80 | + return release, nil |
| 81 | + } |
| 82 | + |
| 83 | + return nil, nil |
| 84 | +} |
| 85 | + |
| 86 | +// IsUnderHomebrew returns true if the CLI binary is managed by Homebrew. |
| 87 | +func IsUnderHomebrew() bool { |
| 88 | + exe, err := os.Executable() |
| 89 | + if err != nil { |
| 90 | + return false |
| 91 | + } |
| 92 | + |
| 93 | + brewExe, err := exec.LookPath("brew") |
| 94 | + if err != nil { |
| 95 | + return false |
| 96 | + } |
| 97 | + |
| 98 | + brewPrefixBytes, err := exec.Command(brewExe, "--prefix").Output() |
| 99 | + if err != nil { |
| 100 | + return false |
| 101 | + } |
| 102 | + |
| 103 | + brewBinPrefix := filepath.Join(strings.TrimSpace(string(brewPrefixBytes)), "bin") + string(filepath.Separator) |
| 104 | + return strings.HasPrefix(exe, brewBinPrefix) |
| 105 | +} |
| 106 | + |
| 107 | +// IsRecentRelease returns true if the release was published less than 24 hours ago. |
| 108 | +func IsRecentRelease(publishedAt time.Time) bool { |
| 109 | + return !publishedAt.IsZero() && time.Since(publishedAt) < 24*time.Hour |
| 110 | +} |
| 111 | + |
| 112 | +func statePath() (string, error) { |
| 113 | + dir, err := config.ConfigDir() |
| 114 | + if err != nil { |
| 115 | + return "", err |
| 116 | + } |
| 117 | + return filepath.Join(dir, stateFile), nil |
| 118 | +} |
| 119 | + |
| 120 | +func getState(path string) (*stateEntry, error) { |
| 121 | + data, err := os.ReadFile(path) |
| 122 | + if err != nil { |
| 123 | + return nil, err |
| 124 | + } |
| 125 | + var s stateEntry |
| 126 | + if err := yaml.Unmarshal(data, &s); err != nil { |
| 127 | + return nil, err |
| 128 | + } |
| 129 | + return &s, nil |
| 130 | +} |
| 131 | + |
| 132 | +func setState(path string, t time.Time, r ReleaseInfo) error { |
| 133 | + data, err := yaml.Marshal(stateEntry{CheckedForUpdateAt: t, LatestRelease: r}) |
| 134 | + if err != nil { |
| 135 | + return err |
| 136 | + } |
| 137 | + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| 138 | + return err |
| 139 | + } |
| 140 | + return os.WriteFile(path, data, 0o600) |
| 141 | +} |
| 142 | + |
| 143 | +func fetchLatestRelease(ctx context.Context) (*ReleaseInfo, error) { |
| 144 | + url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo) |
| 145 | + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 146 | + if err != nil { |
| 147 | + return nil, err |
| 148 | + } |
| 149 | + |
| 150 | + resp, err := http.DefaultClient.Do(req) |
| 151 | + if err != nil { |
| 152 | + return nil, err |
| 153 | + } |
| 154 | + defer func() { |
| 155 | + _, _ = io.Copy(io.Discard, resp.Body) |
| 156 | + resp.Body.Close() |
| 157 | + }() |
| 158 | + |
| 159 | + if resp.StatusCode != 200 { |
| 160 | + return nil, fmt.Errorf("unexpected HTTP %d", resp.StatusCode) |
| 161 | + } |
| 162 | + |
| 163 | + var release ReleaseInfo |
| 164 | + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { |
| 165 | + return nil, err |
| 166 | + } |
| 167 | + return &release, nil |
| 168 | +} |
| 169 | + |
| 170 | +// versionGreaterThan returns true if v is a newer version than w. |
| 171 | +// Versions are expected as semver strings with optional "v" prefix (e.g. "v0.5.1" or "0.5.1"). |
| 172 | +func versionGreaterThan(v, w string) bool { |
| 173 | + vParts := parseVersion(v) |
| 174 | + wParts := parseVersion(w) |
| 175 | + if vParts == nil || wParts == nil { |
| 176 | + return false |
| 177 | + } |
| 178 | + for i := 0; i < 3; i++ { |
| 179 | + if vParts[i] > wParts[i] { |
| 180 | + return true |
| 181 | + } |
| 182 | + if vParts[i] < wParts[i] { |
| 183 | + return false |
| 184 | + } |
| 185 | + } |
| 186 | + return false |
| 187 | +} |
| 188 | + |
| 189 | +func parseVersion(s string) []int { |
| 190 | + s = strings.TrimPrefix(s, "v") |
| 191 | + parts := strings.SplitN(s, ".", 3) |
| 192 | + if len(parts) != 3 { |
| 193 | + return nil |
| 194 | + } |
| 195 | + nums := make([]int, 3) |
| 196 | + for i, p := range parts { |
| 197 | + n, err := strconv.Atoi(p) |
| 198 | + if err != nil { |
| 199 | + return nil |
| 200 | + } |
| 201 | + nums[i] = n |
| 202 | + } |
| 203 | + return nums |
| 204 | +} |
| 205 | + |
| 206 | +// isCI returns true if running in a known CI environment. |
| 207 | +func isCI() bool { |
| 208 | + return os.Getenv("CI") != "" || |
| 209 | + os.Getenv("BUILD_NUMBER") != "" || |
| 210 | + os.Getenv("RUN_ID") != "" |
| 211 | +} |
0 commit comments