Files
Reims-Go/internal/version/version.go
T
Nwflower 3ce0000215
Release Reims-Go / release (push) Canceled after 0s
release: v0.2.9
2026-11-30 01:16:40 -07:00

431 lines
11 KiB
Go

package version
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"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.9"
var Version = "v0.2.9"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
DefaultAPIBase = "https://api.github.com"
DefaultWebBase = "https://github.com"
ChannelStable = "stable"
ChannelAlpha = "alpha"
ChannelDev = "dev"
)
// NormalizeChannel canonicalizes an app update channel string into
// "stable", "alpha", or "dev" (defaulting to "stable").
func NormalizeChannel(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case ChannelAlpha:
return ChannelAlpha
case ChannelDev:
return ChannelDev
default:
return ChannelStable
}
}
// KeepsPreviousInstall reports whether the selected app update channel must
// preserve the previous executable (.old) and downloaded installers on startup
// so users can roll back from prerelease builds.
func KeepsPreviousInstall(channel string) bool {
ch := NormalizeChannel(channel)
return ch == ChannelAlpha || ch == ChannelDev
}
var (
reDevAssetVer = regexp.MustCompile(`(?i)^reims-go-(v\d+\.\d+\.\d+-dev-[0-9a-z.-]+)-windows-amd64\.exe$`)
reDevTitleVer = regexp.MustCompile(`(?i)\b(v\d+\.\d+\.\d+-dev-[0-9a-z.-]+)\b`)
)
// Source configures where app releases are checked.
type Source struct {
APIBase string
WebBase string
Repo string
Client *http.Client
}
func DefaultSource() Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{
APIBase: DefaultAPIBase,
WebBase: DefaultWebBase,
Repo: repo,
Client: netproxy.NewClient(),
}
}
// UpdateInfo describes the latest eligible Reims-Go application release.
type UpdateInfo struct {
Current string `json:"current"`
Latest string `json:"latest"`
Channel string `json:"channel,omitempty"`
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"`
Name string `json:"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) {
major, minor, patch, _, ok = parseSemverFull(v)
return major, minor, patch, ok
}
func parseSemverFull(v string) (major, minor, patch int, pre string, ok bool) {
s := strings.TrimSpace(v)
s = strings.TrimPrefix(s, "v")
if idx := strings.IndexByte(s, '+'); idx >= 0 {
s = s[:idx]
}
if idx := strings.IndexByte(s, '-'); idx >= 0 {
pre = s[idx+1:]
if pre == "" {
return 0, 0, 0, "", false
}
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, pre, true
}
func parseAllDigits(s string) (int, bool) {
if s == "" {
return 0, false
}
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return 0, false
}
}
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
return n, true
}
// comparePrerelease implements SemVer 2.0.0 §11.4 prerelease precedence.
func comparePrerelease(a, b string) int {
if a == b {
return 0
}
if a == "" {
return 1
}
if b == "" {
return -1
}
aParts := strings.Split(a, ".")
bParts := strings.Split(b, ".")
for i := 0; i < len(aParts) && i < len(bParts); i++ {
ap, bp := aParts[i], bParts[i]
if ap == bp {
continue
}
aNum, aIsNum := parseAllDigits(ap)
bNum, bIsNum := parseAllDigits(bp)
switch {
case aIsNum && bIsNum:
if aNum < bNum {
return -1
}
return 1
case aIsNum:
return -1
case bIsNum:
return 1
case ap < bp:
return -1
default:
return 1
}
}
if len(aParts) < len(bParts) {
return -1
}
if len(aParts) > len(bParts) {
return 1
}
return 0
}
// Compare compares two semver strings: returns -1 if a < b, 0 if equal, +1 if a > b.
// Prerelease versions (e.g. v0.2.9-alpha.1, v0.2.9-dev-66da194) rank lower than
// the matching stable release (v0.2.9) per SemVer 2.0.0.
func Compare(a, b string) int {
aMaj, aMin, aPat, aPre, aOK := parseSemverFull(a)
bMaj, bMin, bPat, bPre, bOK := parseSemverFull(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 comparePrerelease(aPre, bPre)
}
// CheckUpdate queries GitHub Releases for the newest stable (non-draft,
// non-prerelease) application release tagged "vX.Y.Z".
func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) {
return s.CheckUpdateChannel(ctx, current, ChannelStable)
}
type releaseCandidate struct {
rel *ghRelease
ver string
channel string
rolling bool
}
func classifyRelease(r *ghRelease) (releaseCandidate, bool) {
if r == nil || r.Draft {
return releaseCandidate{}, false
}
if strings.EqualFold(r.TagName, "dev") {
ver := ""
for _, a := range r.Assets {
if m := reDevAssetVer.FindStringSubmatch(a.Name); len(m) == 2 {
ver = m[1]
break
}
}
if ver == "" {
if m := reDevTitleVer.FindStringSubmatch(r.Name); len(m) == 2 {
ver = m[1]
}
}
if ver == "" {
return releaseCandidate{}, false
}
if _, _, _, pre, ok := parseSemverFull(ver); !ok || pre == "" {
return releaseCandidate{}, false
}
return releaseCandidate{rel: r, ver: ver, channel: ChannelDev, rolling: true}, true
}
if !strings.HasPrefix(r.TagName, "v") {
return releaseCandidate{}, false
}
_, _, _, pre, ok := parseSemverFull(r.TagName)
if !ok {
return releaseCandidate{}, false
}
if !r.Prerelease && pre == "" {
return releaseCandidate{rel: r, ver: r.TagName, channel: ChannelStable}, true
}
lowPre := strings.ToLower(pre)
if strings.HasPrefix(lowPre, "alpha") {
return releaseCandidate{rel: r, ver: r.TagName, channel: ChannelAlpha}, true
}
if strings.HasPrefix(lowPre, "dev") {
return releaseCandidate{rel: r, ver: r.TagName, channel: ChannelDev}, true
}
return releaseCandidate{}, false
}
func channelAccepts(selected, releaseChannel string) bool {
switch NormalizeChannel(selected) {
case ChannelDev:
return releaseChannel == ChannelStable || releaseChannel == ChannelAlpha || releaseChannel == ChannelDev
case ChannelAlpha:
return releaseChannel == ChannelStable || releaseChannel == ChannelAlpha
default:
return releaseChannel == ChannelStable
}
}
func isSameBaseDevBuild(a, b string) bool {
aMaj, aMin, aPat, aPre, aOK := parseSemverFull(a)
bMaj, bMin, bPat, bPre, bOK := parseSemverFull(b)
if !aOK || !bOK {
return false
}
return aMaj == bMaj && aMin == bMin && aPat == bPat &&
strings.HasPrefix(strings.ToLower(aPre), "dev-") &&
strings.HasPrefix(strings.ToLower(bPre), "dev-")
}
// CheckUpdateChannel queries GitHub Releases for the newest eligible Reims-Go
// release on the requested channel ("stable", "alpha", or "dev").
func (s Source) CheckUpdateChannel(ctx context.Context, current, channel string) (UpdateInfo, error) {
if current == "" {
current = Version
}
ch := NormalizeChannel(channel)
info := UpdateInfo{Current: current, Channel: ch}
client := s.Client
if client == nil {
client = http.DefaultClient
}
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", 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 *releaseCandidate
for i := range rels {
cand, ok := classifyRelease(&rels[i])
if !ok || !channelAccepts(ch, cand.channel) {
continue
}
if best == nil {
c := cand
best = &c
continue
}
if isSameBaseDevBuild(cand.ver, best.ver) {
// Prefer the rolling "dev" tag (or newer published_at) over hex hash order.
if cand.rolling && !best.rolling {
c := cand
best = &c
} else if cand.rolling == best.rolling && cand.rel.PublishedAt > best.rel.PublishedAt {
c := cand
best = &c
}
continue
}
if Compare(cand.ver, best.ver) > 0 {
c := cand
best = &c
}
}
if best == nil {
info.Latest = current
return info, nil
}
info.Latest = best.ver
info.Channel = best.channel
info.PageURL = best.rel.HTMLURL
if info.PageURL == "" && s.WebBase != "" {
info.PageURL = fmt.Sprintf("%s/%s/releases/tag/%s", strings.TrimRight(s.WebBase, "/"), s.Repo, best.rel.TagName)
}
info.PublishedAt = best.rel.PublishedAt
if info.PublishedAt == "" {
info.PublishedAt = best.rel.CreatedAt
}
for _, a := range best.rel.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
}
}
if best.rolling && isSameBaseDevBuild(current, best.ver) {
// Rolling dev builds carry non-monotonic short commit SHAs; any different SHA on the
// same base version is a newer rolling build.
info.HasUpdate = !strings.EqualFold(strings.TrimSpace(current), strings.TrimSpace(best.ver))
} else {
info.HasUpdate = Compare(current, best.ver) < 0
}
return info, nil
}