Skip to content

Commit fccabd8

Browse files
committed
Check for updates when printing version info
1 parent 01647f3 commit fccabd8

File tree

2 files changed

+62
-7
lines changed

2 files changed

+62
-7
lines changed

src/app/cli/cmd_version.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package cli
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"fmt"
7+
"io/ioutil"
8+
"klog/app"
9+
"net/http"
10+
"time"
11+
)
12+
13+
type Version struct {
14+
}
15+
16+
func (args *Version) Run(ctx *app.Context) error {
17+
fmt.Printf("Version: %s\n(Build %s)\n\n", ctx.MetaInfo().Version, ctx.MetaInfo().BuildHash)
18+
19+
fmt.Printf("Checking for newer version...\n")
20+
v := fetchVersionInfo("https://klog.jotaen.net/latest-stable-version.json")
21+
if v == nil {
22+
return errors.New("Failed to check for new version, please try again later")
23+
}
24+
if v.Latest.Version == ctx.MetaInfo().Version && v.Latest.BuildHash == ctx.MetaInfo().BuildHash {
25+
fmt.Printf("You already have the latest version!\n")
26+
} else {
27+
fmt.Printf("New version available: %s (%s)\n", v.Latest.Version, v.Latest.BuildHash)
28+
fmt.Printf("See: https://github.com/jotaen/klog\n")
29+
}
30+
return nil
31+
}
32+
33+
func fetchVersionInfo(url string) *versionInfo {
34+
req, _ := http.NewRequest(http.MethodGet, url, nil)
35+
res, err := (&http.Client{
36+
Timeout: time.Second * 5,
37+
}).Do(req)
38+
if err != nil {
39+
return nil
40+
}
41+
body, err := ioutil.ReadAll(res.Body)
42+
if err != nil {
43+
return nil
44+
}
45+
v := &versionInfo{}
46+
err = json.Unmarshal(body, &v)
47+
if err != nil {
48+
return nil
49+
}
50+
return v
51+
}
52+
53+
type versionInfo struct {
54+
Latest struct {
55+
Version string `json:"version"`
56+
BuildHash string `json:"buildHash"`
57+
} `json:"latest"`
58+
}

src/app/cli/exec.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ import (
1010
)
1111

1212
type cli struct {
13-
Print Print `cmd help:"Pretty-print records"`
14-
Eval Eval `cmd help:"Evaluate records"`
15-
Widget Widget `cmd help:"Start menu bar widget (MacOS only)"`
16-
Version kong.VersionFlag
13+
Print Print `cmd help:"Pretty-print records"`
14+
Eval Eval `cmd help:"Evaluate records"`
15+
Widget Widget `cmd help:"Start menu bar widget (MacOS only)"`
16+
Version Version `cmd help:"Print version info and check for updates"`
1717
}
1818

1919
func Execute() int {
@@ -32,9 +32,6 @@ func Execute() int {
3232
datePrototype, _ := klog.NewDate(1, 1, 1)
3333
return kong.TypeMapper(reflect.TypeOf(&datePrototype).Elem(), dateDecoder())
3434
}(),
35-
kong.Vars{
36-
"version": ctx.MetaInfo().Version + "\n(" + ctx.MetaInfo().BuildHash + ")",
37-
},
3835
)
3936
err = args.Run(ctx)
4037
if err != nil {

0 commit comments

Comments
 (0)