github.com/creativeprojects/go-selfupdate@v1.2.0/updater.go (about) 1 package selfupdate 2 3 import ( 4 "fmt" 5 "regexp" 6 "runtime" 7 ) 8 9 // Updater is responsible for managing the context of self-update. 10 type Updater struct { 11 source Source 12 validator Validator 13 filters []*regexp.Regexp 14 os string 15 arch string 16 arm uint8 17 prerelease bool 18 draft bool 19 } 20 21 // keep the default updater instance in cache 22 var defaultUpdater *Updater 23 24 // NewUpdater creates a new updater instance. 25 // If you don't specify a source in the config object, GitHub will be used 26 func NewUpdater(config Config) (*Updater, error) { 27 source := config.Source 28 if source == nil { 29 // default source is GitHub 30 source, _ = NewGitHubSource(GitHubConfig{}) 31 } 32 33 filtersRe := make([]*regexp.Regexp, 0, len(config.Filters)) 34 for _, filter := range config.Filters { 35 re, err := regexp.Compile(filter) 36 if err != nil { 37 return nil, fmt.Errorf("could not compile regular expression %q for filtering releases: %w", filter, err) 38 } 39 filtersRe = append(filtersRe, re) 40 } 41 42 os := config.OS 43 arch := config.Arch 44 if os == "" { 45 os = runtime.GOOS 46 } 47 if arch == "" { 48 arch = runtime.GOARCH 49 } 50 arm := config.Arm 51 if arm == 0 && goarm > 0 { 52 arm = goarm 53 } 54 55 return &Updater{ 56 source: source, 57 validator: config.Validator, 58 filters: filtersRe, 59 os: os, 60 arch: arch, 61 arm: arm, 62 prerelease: config.Prerelease, 63 draft: config.Draft, 64 }, nil 65 } 66 67 // DefaultUpdater creates a new updater instance with default configuration. 68 // It initializes GitHub API client with default API base URL. 69 // If you set your API token to $GITHUB_TOKEN, the client will use it. 70 // Every call to this function will always return the same instance, it's only created once 71 func DefaultUpdater() *Updater { 72 // instantiate it only once 73 if defaultUpdater != nil { 74 return defaultUpdater 75 } 76 // an error can only be returned when using GitHub Enterprise URLs 77 // so we're safe here :) 78 source, _ := NewGitHubSource(GitHubConfig{}) 79 defaultUpdater = &Updater{ 80 source: source, 81 os: runtime.GOOS, 82 arch: runtime.GOARCH, 83 arm: goarm, 84 } 85 return defaultUpdater 86 }