|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/hashicorp/errwrap" |
| 8 | + |
| 9 | + "github.com/hellofresh/github-cli/pkg/log" |
| 10 | + "github.com/italolelis/goupdater" |
| 11 | + "github.com/spf13/cobra" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + githubOwner = "hellofresh" |
| 16 | + githubRepo = "github-cli" |
| 17 | +) |
| 18 | + |
| 19 | +// UpdateOptions are the command flags |
| 20 | +type UpdateOptions struct{} |
| 21 | + |
| 22 | +// NewUpdateCmd creates a new update command |
| 23 | +func NewUpdateCmd(ctx context.Context) *cobra.Command { |
| 24 | + opts := &UpdateOptions{} |
| 25 | + |
| 26 | + cmd := &cobra.Command{ |
| 27 | + Use: "update", |
| 28 | + Aliases: []string{"self-update"}, |
| 29 | + Short: fmt.Sprintf("Check for new versions of %s", githubRepo), |
| 30 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 31 | + return RunUpdate(ctx, opts) |
| 32 | + }, |
| 33 | + } |
| 34 | + |
| 35 | + return cmd |
| 36 | +} |
| 37 | + |
| 38 | +// RunUpdate runs the update command |
| 39 | +func RunUpdate(ctx context.Context, opts *UpdateOptions) error { |
| 40 | + logger := log.WithContext(ctx) |
| 41 | + logger.Info("Checking if any new version is available...") |
| 42 | + |
| 43 | + resolver, err := goupdater.NewGithubWithContext(ctx, goupdater.GithubOpts{ |
| 44 | + Owner: githubOwner, |
| 45 | + Repo: githubRepo, |
| 46 | + }) |
| 47 | + if err != nil { |
| 48 | + return errwrap.Wrapf("could not create the updater client: {{err}}", err) |
| 49 | + } |
| 50 | + |
| 51 | + updated, err := goupdater.UpdateWithContext(ctx, resolver, version) |
| 52 | + if err != nil { |
| 53 | + return errwrap.Wrapf("could not update the binary: {{err}}", err) |
| 54 | + } |
| 55 | + |
| 56 | + if updated { |
| 57 | + logger.Infof("You are now using the latest version of %s", githubRepo) |
| 58 | + } else { |
| 59 | + logger.Infof("You already have the latest version of %s", githubRepo) |
| 60 | + } |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
0 commit comments