go-update/service.go
Claude 644986b8bb
chore(ax): Pass 1 AX compliance sweep — banned imports, test naming, comment style
- Remove fmt from updater.go, service.go, http_client.go, cmd.go, github.go, generic_http.go; replace with string concat, coreerr.E, cli.Print
- Remove strings from updater.go (inline byte comparisons) and service.go (inline helpers)
- Replace fmt.Sprintf in error paths with string concatenation throughout
- Add cli.Print for all stdout output in updater.go (CheckForUpdates, CheckOnly, etc.)
- Fix service_examples_test.go: restore original CheckForUpdates instead of setting nil
- Test naming: all test files now follow TestFile_Function_{Good,Bad,Ugly} with all three variants mandatory
- Comments: replace prose descriptions with usage-example style on all exported functions
- Remaining banned: strings/encoding/json in github.go and generic_http.go (no Core replacement in direct deps); os/os.exec in platform files (syscall-level, unavoidable without go-process)

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 08:42:13 +01:00

184 lines
5.3 KiB
Go

//go:generate go run forge.lthn.ai/core/go-update/build
// Package updater provides functionality for self-updating Go applications.
// It supports updates from GitHub releases and generic HTTP endpoints.
package updater
import (
"net/url"
coreerr "forge.lthn.ai/core/go-log"
)
// StartupCheckMode defines the updater's behavior on startup.
type StartupCheckMode int
const (
// NoCheck disables any checks on startup.
NoCheck StartupCheckMode = iota
// CheckOnStartup checks for updates on startup but does not apply them.
CheckOnStartup
// CheckAndUpdateOnStartup checks for and applies updates on startup.
CheckAndUpdateOnStartup
)
// UpdateServiceConfig holds the configuration for the UpdateService.
type UpdateServiceConfig struct {
// RepoURL is the URL to the repository for updates. It can be a GitHub
// repository URL (e.g., "https://github.com/owner/repo") or a base URL
// for a generic HTTP update server.
RepoURL string
// Channel specifies the release channel to track (e.g., "stable", "prerelease").
// This is only used for GitHub-based updates.
Channel string
// CheckOnStartup determines the update behavior when the service starts.
CheckOnStartup StartupCheckMode
// ForceSemVerPrefix toggles whether to enforce a 'v' prefix on version tags for display.
// If true, a 'v' prefix is added if missing. If false, it's removed if present.
ForceSemVerPrefix bool
// ReleaseURLFormat provides a template for constructing the download URL for a
// release asset. The placeholder {tag} will be replaced with the release tag.
ReleaseURLFormat string
}
// UpdateService provides a configurable interface for handling application updates.
// It can be configured to check for updates on startup and, if desired, apply
// them automatically. The service can handle updates from both GitHub releases
// and generic HTTP servers.
type UpdateService struct {
config UpdateServiceConfig
isGitHub bool
owner string
repo string
}
// NewUpdateService creates and configures a new UpdateService.
//
// svc, err := updater.NewUpdateService(updater.UpdateServiceConfig{
// RepoURL: "https://github.com/owner/repo",
// Channel: "stable",
// CheckOnStartup: updater.CheckAndUpdateOnStartup,
// })
func NewUpdateService(config UpdateServiceConfig) (*UpdateService, error) {
isGitHub := containsStr(config.RepoURL, "github.com")
var owner, repo string
var err error
if isGitHub {
owner, repo, err = ParseRepoURL(config.RepoURL)
if err != nil {
return nil, coreerr.E("NewUpdateService", "failed to parse GitHub repo URL", err)
}
}
return &UpdateService{
config: config,
isGitHub: isGitHub,
owner: owner,
repo: repo,
}, nil
}
// Start initiates the update check based on the service configuration.
//
// if err := svc.Start(); err != nil {
// log.Printf("update check failed: %v", err)
// }
func (s *UpdateService) Start() error {
if s.isGitHub {
return s.startGitHubCheck()
}
return s.startHTTPCheck()
}
func (s *UpdateService) startGitHubCheck() error {
switch s.config.CheckOnStartup {
case NoCheck:
return nil // Do nothing
case CheckOnStartup:
return CheckOnly(s.owner, s.repo, s.config.Channel, s.config.ForceSemVerPrefix, s.config.ReleaseURLFormat)
case CheckAndUpdateOnStartup:
return CheckForUpdates(s.owner, s.repo, s.config.Channel, s.config.ForceSemVerPrefix, s.config.ReleaseURLFormat)
default:
return coreerr.E("startGitHubCheck", "unknown startup check mode", nil)
}
}
func (s *UpdateService) startHTTPCheck() error {
switch s.config.CheckOnStartup {
case NoCheck:
return nil // Do nothing
case CheckOnStartup:
return CheckOnlyHTTP(s.config.RepoURL)
case CheckAndUpdateOnStartup:
return CheckForUpdatesHTTP(s.config.RepoURL)
default:
return coreerr.E("startHTTPCheck", "unknown startup check mode", nil)
}
}
// containsStr reports whether substr appears within s.
func containsStr(s, substr string) bool {
if substr == "" {
return true
}
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
// trimChars removes all leading and trailing occurrences of any rune in cutset from s.
func trimChars(s, cutset string) string {
start, end := 0, len(s)
for start < end && containsStr(cutset, s[start:start+1]) {
start++
}
for end > start && containsStr(cutset, s[end-1:end]) {
end--
}
return s[start:end]
}
// splitStr splits s by sep and returns a slice of substrings.
func splitStr(s, sep string) []string {
if sep == "" || s == "" {
return []string{s}
}
var parts []string
for {
idx := -1
for i := 0; i <= len(s)-len(sep); i++ {
if s[i:i+len(sep)] == sep {
idx = i
break
}
}
if idx < 0 {
parts = append(parts, s)
break
}
parts = append(parts, s[:idx])
s = s[idx+len(sep):]
}
return parts
}
// ParseRepoURL extracts the owner and repository name from a GitHub URL.
//
// owner, repo, err := updater.ParseRepoURL("https://github.com/myorg/myrepo")
// // owner == "myorg", repo == "myrepo"
func ParseRepoURL(repoURL string) (owner string, repo string, err error) {
u, err := url.Parse(repoURL)
if err != nil {
return "", "", err
}
path := trimChars(u.Path, "/")
parts := splitStr(path, "/")
if len(parts) < 2 {
return "", "", coreerr.E("ParseRepoURL", "invalid repo URL path: "+u.Path, nil)
}
return parts[0], parts[1], nil
}