/
version.go
80 lines (69 loc) · 2.01 KB
/
version.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cobracmds
import (
"context"
"fmt"
"html/template"
"io"
"github.com/cep21/cfmanage/internal/ctxfinder"
"github.com/cep21/cfmanage/internal/logger"
"github.com/google/go-github/v25/github"
"github.com/spf13/cobra"
)
type versionCommand struct {
Logger *logger.Logger
JSON *bool
ContextFinder *ctxfinder.ContextFinder
GithubClient *github.Client
}
func (s *versionCommand) Cobra() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Display the current version (and latest version if different) of cfmanage",
Example: "cfexecute version",
ValidArgs: []string{},
Args: cobra.NoArgs,
}
cmd.RunE = commonRunCommand(s.ContextFinder, s.model, s.JSON)
return cmd
}
type versionCommandModel struct {
CurrentVersion string
LatestVersion string
}
func (v *versionCommandModel) VersionMessage() string {
if v.CurrentVersion != v.LatestVersion {
return fmt.Sprintf("Your version is out of date. Download a newer one from https://github.com/%s/%s", githubOwner, githubRepo)
}
return ""
}
func tmpl() *template.Template {
return template.Must(template.New("version").Parse(`{{ .VersionMessage }}
Current Version: {{ .CurrentVersion }}
Latest Version: {{ .LatestVersion }}
`))
}
func (v *versionCommandModel) HumanReadable(out io.Writer) error {
return tmpl().Execute(out, v)
}
const githubOwner = "cep21"
const githubRepo = "cfmanage"
func (s *versionCommand) model(ctx context.Context, cmd *cobra.Command, args []string) (HumanPrintable, error) {
release, _, err := s.GithubClient.Repositories.GetLatestRelease(ctx, githubOwner, githubRepo)
if err != nil {
return nil, err
}
if release == nil || release.TagName == nil {
return &versionCommandModel{
CurrentVersion: currentVersion,
LatestVersion: "unknown",
}, nil
}
latestRelease := *release.TagName
if len(latestRelease) > 0 && latestRelease[0] == 'v' {
latestRelease = latestRelease[1:]
}
return &versionCommandModel{
CurrentVersion: currentVersion,
LatestVersion: latestRelease,
}, nil
}