Files
Reims-Go/internal/version/version.go
T
Nwflower 5c71ac8482
Release Reims-Go / release (push) Canceled after 0s
release: v0.2.8
2026-11-29 18:17:13 -07:00

285 lines
7.2 KiB
Go

package version
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/netproxy"
)
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.8"
var Version = "v0.2.8"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
DefaultAPIBase = "https://api.github.com"
DefaultWebBase = "https://github.com"
DefaultGitCodeRepo = "Nwflower/Reims-Go"
DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5"
DefaultGitCodeWebBase = "https://gitcode.com"
)
const fallbackProbeTimeout = 8 * time.Second
// Source configures where app releases are checked.
type Source struct {
APIBase string
WebBase string
Repo string
Client *http.Client
Fallbacks []Source
}
func githubSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{
APIBase: DefaultAPIBase,
WebBase: DefaultWebBase,
Repo: repo,
Client: client,
}
}
func gitcodeSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_GITCODE_REPO")
if repo == "" {
repo = DefaultGitCodeRepo
}
return Source{
APIBase: DefaultGitCodeAPIBase,
WebBase: DefaultGitCodeWebBase,
Repo: repo,
Client: client,
}
}
func DefaultSource() Source {
return DefaultSourceFor("")
}
func DefaultSourceFor(mode string) Source {
if strings.TrimSpace(mode) == "" {
mode = os.Getenv("REIMS_GO_SOURCE")
}
client := netproxy.NewClient()
switch strings.ToLower(strings.TrimSpace(mode)) {
case "github":
return githubSource(client)
case "gitcode":
return gitcodeSource(client)
default:
gh := githubSource(client)
gh.Fallbacks = []Source{gitcodeSource(client)}
return gh
}
}
// UpdateInfo describes the latest stable Reims-Go application release.
type UpdateInfo struct {
Current string `json:"current"`
Latest string `json:"latest"`
HasUpdate bool `json:"has_update"`
PageURL string `json:"page_url,omitempty"`
DownloadURL string `json:"download_url,omitempty"`
AssetName string `json:"asset_name,omitempty"`
AssetSize int64 `json:"asset_size,omitempty"`
// SumsURL is the release's SHA256SUMS.txt; an in-app update refuses to
// install without it.
SumsURL string `json:"sums_url,omitempty"`
PublishedAt string `json:"published_at,omitempty"`
}
type ghRelease struct {
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
CreatedAt string `json:"created_at"`
HTMLURL string `json:"html_url"`
Assets []ghAsset `json:"assets"`
}
type ghAsset struct {
Name string `json:"name"`
Size int64 `json:"size"`
URL string `json:"browser_download_url"`
}
// ParseSemver parses a tag like "v0.2.1" or "0.2.1-rc1" into major/minor/patch.
func ParseSemver(v string) (major, minor, patch int, ok bool) {
s := strings.TrimSpace(v)
s = strings.TrimPrefix(s, "v")
if idx := strings.IndexAny(s, "-+"); idx >= 0 {
s = s[:idx]
}
parts := strings.Split(s, ".")
if len(parts) < 2 || len(parts) > 3 {
return 0, 0, 0, false
}
maj, err1 := strconv.Atoi(parts[0])
min, err2 := strconv.Atoi(parts[1])
pat := 0
var err3 error
if len(parts) == 3 {
pat, err3 = strconv.Atoi(parts[2])
}
if err1 != nil || err2 != nil || err3 != nil || maj < 0 || min < 0 || pat < 0 {
return 0, 0, 0, false
}
return maj, min, pat, true
}
// Compare compares two semver strings: returns -1 if a < b, 0 if equal, +1 if a > b.
func Compare(a, b string) int {
aMaj, aMin, aPat, aOK := ParseSemver(a)
bMaj, bMin, bPat, bOK := ParseSemver(b)
if !aOK && !bOK {
return 0
}
if !aOK {
return -1
}
if !bOK {
return 1
}
if aMaj != bMaj {
if aMaj < bMaj {
return -1
}
return 1
}
if aMin != bMin {
if aMin < bMin {
return -1
}
return 1
}
if aPat != bPat {
if aPat < bPat {
return -1
}
return 1
}
return 0
}
// CheckUpdate queries GitHub/GitCode Releases for the newest stable (non-draft,
// non-prerelease) application release tagged "vX.Y.Z", failing over to
// Fallbacks when the primary source is unreachable.
func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) {
primaryCtx := ctx
var cancel context.CancelFunc
if len(s.Fallbacks) > 0 {
primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout)
defer cancel()
}
info, err := s.checkUpdateSingle(primaryCtx, current)
if err == nil {
return info, nil
}
if ctx.Err() != nil || len(s.Fallbacks) == 0 {
return info, err
}
for _, fb := range s.Fallbacks {
if fbInfo, fbErr := fb.checkUpdateSingle(ctx, current); fbErr == nil {
return fbInfo, nil
}
}
return info, err
}
func (s Source) checkUpdateSingle(ctx context.Context, current string) (UpdateInfo, error) {
if current == "" {
current = Version
}
info := UpdateInfo{Current: current}
client := s.Client
if client == nil {
client = http.DefaultClient
}
url := fmt.Sprintf("%s/repos/%s/releases?per_page=30", strings.TrimRight(s.APIBase, "/"), s.Repo)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return info, err
}
req.Header.Set("User-Agent", "reims-go")
req.Header.Set("Accept", "application/vnd.github+json")
if req.URL.Host == "api.github.com" {
if tok := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
} else if tok := strings.TrimSpace(os.Getenv("GH_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
resp, err := client.Do(req)
if err != nil {
return info, fmt.Errorf("check app updates: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return info, fmt.Errorf("GitHub API rate limit reached; try again later (HTTP %d)", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return info, fmt.Errorf("check app updates: HTTP %d", resp.StatusCode)
}
var rels []ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil {
return info, fmt.Errorf("read app releases: %w", err)
}
var best *ghRelease
for i := range rels {
r := &rels[i]
if r.Draft || r.Prerelease || !strings.HasPrefix(r.TagName, "v") {
continue
}
if _, _, _, ok := ParseSemver(r.TagName); !ok {
continue
}
if best == nil || Compare(r.TagName, best.TagName) > 0 {
best = r
}
}
if best == nil {
info.Latest = current
return info, nil
}
info.Latest = best.TagName
info.PageURL = best.HTMLURL
if info.PageURL == "" && s.WebBase != "" {
info.PageURL = fmt.Sprintf("%s/%s/releases/tag/%s", strings.TrimRight(s.WebBase, "/"), s.Repo, best.TagName)
}
info.PublishedAt = best.PublishedAt
if info.PublishedAt == "" {
info.PublishedAt = best.CreatedAt
}
for _, a := range best.Assets {
lower := strings.ToLower(a.Name)
switch {
case a.Name == "SHA256SUMS.txt":
info.SumsURL = a.URL
case info.DownloadURL == "" && strings.HasSuffix(lower, ".exe") && !strings.Contains(lower, "-cli-"):
info.AssetName = a.Name
info.AssetSize = a.Size
info.DownloadURL = a.URL
}
}
info.HasUpdate = Compare(current, best.TagName) < 0
return info, nil
}