Skip to content

Commit 96baa6c

Browse files
committed
feat: implement automatic update check
1 parent 5f8f8ee commit 96baa6c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

internal/update/update.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,82 @@
11
package update
22

33
import (
4+
"encoding/json"
5+
"fmt"
6+
"io"
7+
"net/http"
48
"os"
59
"os/exec"
10+
"strings"
11+
12+
"github.com/yplog/memotty/internal/ui"
613
)
714

15+
type GitHubRelease struct {
16+
TagName string `json:"tag_name"`
17+
}
18+
19+
func getLatestVersion() (string, error) {
20+
resp, err := http.Get("https://api.github.com/repos/yplog/memotty/releases/latest")
21+
if err != nil {
22+
return "", fmt.Errorf("failed to fetch latest release: %w", err)
23+
}
24+
defer resp.Body.Close()
25+
26+
if resp.StatusCode != http.StatusOK {
27+
return "", fmt.Errorf("GitHub API returned status: %d", resp.StatusCode)
28+
}
29+
30+
body, err := io.ReadAll(resp.Body)
31+
if err != nil {
32+
return "", fmt.Errorf("failed to read response: %w", err)
33+
}
34+
35+
var release GitHubRelease
36+
if err := json.Unmarshal(body, &release); err != nil {
37+
return "", fmt.Errorf("failed to parse JSON: %w", err)
38+
}
39+
40+
return release.TagName, nil
41+
}
42+
43+
func normalizeVersion(version string) string {
44+
return strings.TrimPrefix(version, "v")
45+
}
46+
847
func Run() error {
48+
fmt.Println("🔍 Checking for updates...")
49+
50+
currentVersion := ui.GetVersionInfo()
51+
currentVersionClean := normalizeVersion(strings.TrimPrefix(currentVersion, "memotty "))
52+
53+
if currentVersionClean == "dev" {
54+
fmt.Println("Development version detected, proceeding with update...")
55+
return runInstallScript()
56+
}
57+
58+
latestVersion, err := getLatestVersion()
59+
if err != nil {
60+
fmt.Printf("Could not check latest version: %v\n", err)
61+
fmt.Println("Proceeding with update anyway...")
62+
return runInstallScript()
63+
}
64+
65+
latestVersionClean := normalizeVersion(latestVersion)
66+
67+
fmt.Printf("Current version: %s\n", currentVersionClean)
68+
fmt.Printf("Latest version: %s\n", latestVersionClean)
69+
70+
if currentVersionClean >= latestVersionClean {
71+
fmt.Println("Already up to date! No update needed.")
72+
return nil
73+
}
74+
75+
fmt.Printf("Updating from %s to %s...\n", currentVersionClean, latestVersionClean)
76+
return runInstallScript()
77+
}
78+
79+
func runInstallScript() error {
980
cmd := exec.Command("bash", "-c", "curl -fsSL https://raw.githubusercontent.com/yplog/memotty/main/scripts/install.sh | bash")
1081
cmd.Stdout = os.Stdout
1182
cmd.Stderr = os.Stderr

0 commit comments

Comments
 (0)