Make the "check update" interface a little cleaner

This commit is contained in:
Corey Johnson 2019-12-02 10:28:00 -08:00
parent 78a9599e2a
commit de98dbd378
2 changed files with 31 additions and 28 deletions

25
main.go
View file

@ -10,20 +10,15 @@ import (
)
func main() {
printUpdateMessage := make(chan func())
go update.CheckForUpdate(printUpdateMessage)
if cmd, err := command.RootCmd.ExecuteC(); err != nil {
fmt.Fprintln(os.Stderr, err)
_, isFlagError := err.(command.FlagError)
if isFlagError || strings.HasPrefix(err.Error(), "unknown command ") {
fmt.Fprintln(os.Stderr, cmd.UsageString())
isProduction := os.Getenv("APP_ENV") != "production"
update.RunWhileCheckingForUpdate(isProduction, func() {
if cmd, err := command.RootCmd.ExecuteC(); err != nil {
fmt.Fprintln(os.Stderr, err)
_, isFlagError := err.(command.FlagError)
if isFlagError || strings.HasPrefix(err.Error(), "unknown command ") {
fmt.Fprintln(os.Stderr, cmd.UsageString())
}
os.Exit(1)
}
os.Exit(1)
}
printFunc := <-printUpdateMessage
if printFunc != nil {
printFunc()
}
})
}

View file

@ -19,36 +19,44 @@ type releaseInfo struct {
URL string `json:"html_url"`
}
func CheckForUpdate(handleUpdate chan func()) {
// Only check for updates in production
if os.Getenv("APP_ENV") != "production" {
handleUpdate <- nil
func RunWhileCheckingForUpdate(isProduction bool, f func()) {
if isProduction {
f()
return
}
newReleaseChan := make(chan *releaseInfo)
go checkForUpdate(newReleaseChan)
f()
newRelease := <-newReleaseChan
if newRelease != nil {
fmt.Printf(utils.Cyan(`
A new version of gh is available! %s %s
Changelog: %s
Run 'brew upgrade gh' to update!`)+"\n\n", command.Version, newRelease.Version, newRelease.URL)
}
}
func checkForUpdate(newReleaseChan chan *releaseInfo) {
// Ignore if this stdout is not a tty
if !terminal.IsTerminal(int(os.Stdout.Fd())) {
handleUpdate <- nil
newReleaseChan <- nil
return
}
latestRelease, err := getLatestRelease()
if err != nil {
handleUpdate <- nil
newReleaseChan <- nil
return
}
updateAvailable := latestRelease.Version != command.Version
if updateAvailable {
handleUpdate <- func() {
fmt.Printf(utils.Cyan(`
A new version of gh is available! %s %s
Changelog: %s
Run 'brew upgrade gh' to update!`)+"\n\n", command.Version, latestRelease.Version, latestRelease.URL)
}
newReleaseChan <- latestRelease
} else {
handleUpdate <- nil
newReleaseChan <- nil
}
}