-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate.go
More file actions
258 lines (216 loc) · 6.25 KB
/
update.go
File metadata and controls
258 lines (216 loc) · 6.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const githubRepo = "erkantaylan/livemd"
type githubRelease struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
Body string `json:"body"`
PublishedAt string `json:"published_at"`
HTMLURL string `json:"html_url"`
Assets []githubAsset `json:"assets"`
}
// VersionInfo represents the current and latest version for the API
type VersionInfo struct {
Current string `json:"current"`
Latest string `json:"latest"`
UpdateAvail bool `json:"updateAvailable"`
LatestURL string `json:"latestUrl,omitempty"`
CheckedAt string `json:"checkedAt"`
}
type githubAsset struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
}
// cmdUpdate checks GitHub for a newer release and self-updates the binary.
func cmdUpdate() {
if Version == "dev" {
fmt.Fprintln(os.Stderr, "Cannot update a dev build. Install a release version first.")
os.Exit(1)
}
fmt.Println("Checking for updates...")
release, err := fetchLatestRelease()
if err != nil {
fmt.Fprintf(os.Stderr, "Error checking for updates: %v\n", err)
os.Exit(1)
}
if !isNewer(Version, release.TagName) {
fmt.Printf("Already up to date (%s)\n", Version)
return
}
fmt.Printf("New version available: %s (current: %s)\n", release.TagName, Version)
assetName := fmt.Sprintf("livemd-%s-%s", runtime.GOOS, runtime.GOARCH)
if runtime.GOOS == "windows" {
assetName += ".exe"
}
var downloadURL string
for _, asset := range release.Assets {
if asset.Name == assetName {
downloadURL = asset.BrowserDownloadURL
break
}
}
if downloadURL == "" {
fmt.Fprintf(os.Stderr, "No release binary found for %s/%s\n", runtime.GOOS, runtime.GOARCH)
os.Exit(1)
}
fmt.Printf("Downloading %s...\n", assetName)
binary, err := downloadAsset(downloadURL)
if err != nil {
fmt.Fprintf(os.Stderr, "Error downloading update: %v\n", err)
os.Exit(1)
}
if err := replaceBinary(binary); err != nil {
fmt.Fprintf(os.Stderr, "Error installing update: %v\n", err)
os.Exit(1)
}
fmt.Printf("Updated to %s\n", release.TagName)
}
func fetchLatestRelease() (*githubRelease, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", githubRepo)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GitHub API returned %d", resp.StatusCode)
}
var release githubRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return nil, err
}
return &release, nil
}
// isNewer returns true if remote version is newer than local.
// Both are expected to be semver tags like "v1.2.3".
func isNewer(local, remote string) bool {
local = strings.TrimPrefix(local, "v")
remote = strings.TrimPrefix(remote, "v")
return remote != local && compareSemver(remote, local) > 0
}
// compareSemver compares two semver strings (without "v" prefix).
// Returns >0 if a > b, <0 if a < b, 0 if equal.
func compareSemver(a, b string) int {
aParts := strings.SplitN(a, ".", 3)
bParts := strings.SplitN(b, ".", 3)
for i := 0; i < 3; i++ {
var av, bv int
if i < len(aParts) {
fmt.Sscanf(aParts[i], "%d", &av)
}
if i < len(bParts) {
fmt.Sscanf(bParts[i], "%d", &bv)
}
if av != bv {
return av - bv
}
}
return 0
}
func downloadAsset(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("download returned %d", resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
// replaceBinary replaces the currently running binary with new content.
func replaceBinary(newBinary []byte) error {
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("cannot determine executable path: %w", err)
}
execPath, err = filepath.EvalSymlinks(execPath)
if err != nil {
return fmt.Errorf("cannot resolve symlinks: %w", err)
}
if runtime.GOOS == "windows" {
return replaceWindows(execPath, newBinary)
}
return replaceUnix(execPath, newBinary)
}
// replaceUnix writes to a temp file in the same dir then renames atomically.
func replaceUnix(execPath string, newBinary []byte) error {
dir := filepath.Dir(execPath)
tmp, err := os.CreateTemp(dir, "livemd-update-*")
if err != nil {
return err
}
tmpPath := tmp.Name()
if _, err := tmp.Write(newBinary); err != nil {
tmp.Close()
os.Remove(tmpPath)
return err
}
tmp.Close()
if err := os.Chmod(tmpPath, 0755); err != nil {
os.Remove(tmpPath)
return err
}
if err := os.Rename(tmpPath, execPath); err != nil {
os.Remove(tmpPath)
return err
}
return nil
}
// fetchAllReleases returns all GitHub releases (for changelog display).
func fetchAllReleases() ([]githubRelease, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/releases", githubRepo)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GitHub API returned %d", resp.StatusCode)
}
var releases []githubRelease
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
return nil, err
}
return releases, nil
}
// CheckForUpdate checks if a newer version is available and returns version info.
func CheckForUpdate() VersionInfo {
info := VersionInfo{
Current: Version,
CheckedAt: time.Now().UTC().Format(time.RFC3339),
}
release, err := fetchLatestRelease()
if err != nil {
info.Latest = Version
return info
}
info.Latest = release.TagName
info.LatestURL = release.HTMLURL
info.UpdateAvail = isNewer(Version, release.TagName)
return info
}
// replaceWindows renames the current exe to .bak, writes the new one in place.
func replaceWindows(execPath string, newBinary []byte) error {
bakPath := execPath + ".bak"
os.Remove(bakPath) // clean up previous backup
if err := os.Rename(execPath, bakPath); err != nil {
return fmt.Errorf("cannot rename old binary: %w", err)
}
if err := os.WriteFile(execPath, newBinary, 0755); err != nil {
// Try to restore backup
os.Rename(bakPath, execPath)
return fmt.Errorf("cannot write new binary: %w", err)
}
return nil
}