diff --git a/internal/update/update.go b/internal/update/update.go index 6decefc..7459c60 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -16,21 +16,21 @@ func NewCommand() *cobra.Command { Use: "update", Short: "Update to the latest version.", RunE: func(cmd *cobra.Command, _ []string) error { - current, err := semver.Parse(cmd.Root().Version) + isUpdated, err := IsUpdated(cmd) if err != nil { return err } + if isUpdated { + return errors.New(internal.AlreadyUpToDateErr) + } - latest, found, err := selfupdate.DetectLatest(repo) + current, err := semver.Parse(cmd.Root().Version) if err != nil { return err } - if !found || current.Equals(latest.Version) { - return errors.New(internal.AlreadyUpToDateErr) - } - - if _, err := selfupdate.UpdateSelf(current, repo); err != nil { + latest, err := selfupdate.UpdateSelf(current, repo) + if err != nil { return err } @@ -39,3 +39,18 @@ func NewCommand() *cobra.Command { }, } } + +func IsUpdated(cmd *cobra.Command) (bool, error) { + current, err := semver.Parse(cmd.Root().Version) + if err != nil { + return true, err + } + + latest, found, err := selfupdate.DetectLatest(repo) + if err != nil { + return true, err + } + + isUpdated := !found || current.Equals(latest.Version) + return isUpdated, nil +} diff --git a/main.go b/main.go index 1400371..934e042 100644 --- a/main.go +++ b/main.go @@ -15,6 +15,7 @@ import ( "spotify/internal/status" "spotify/internal/unsave" "spotify/internal/update" + "time" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -32,9 +33,10 @@ func main() { } root := &cobra.Command{ - Use: "spotify", - Short: "Spotify for the terminal 🎵", - Version: "1.5.1", + Use: "spotify", + Short: "Spotify for the terminal 🎵", + Version: "1.5.1", + PersistentPreRunE: promptUpdate, } root.AddCommand(back.NewCommand()) @@ -60,3 +62,23 @@ func main() { root.Execute() } + +func promptUpdate(cmd *cobra.Command, _ []string) error { + if time.Now().Unix() < viper.GetInt64("prompt_update_timer") { + return nil + } + + isUpdated, err := update.IsUpdated(cmd) + if err != nil { + return err + } + if !isUpdated { + cmd.Println("Use 'spotify update' to get the latest version.") + } + + // Wait one day before the next prompt + const day int64 = 24 * 60 * 60 + viper.Set("prompt_update_timer", time.Now().Unix()+day) + + return viper.WriteConfig() +}