forked from bettercap/bettercap
/
update.go
97 lines (76 loc) · 2.09 KB
/
update.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package update
import (
"context"
"math"
"strconv"
"strings"
"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/session"
"github.com/google/go-github/github"
"github.com/evilsocket/islazy/tui"
)
type UpdateModule struct {
session.SessionModule
client *github.Client
}
func NewUpdateModule(s *session.Session) *UpdateModule {
mod := &UpdateModule{
SessionModule: session.NewSessionModule("update", s),
client: github.NewClient(nil),
}
mod.AddHandler(session.NewModuleHandler("update.check on", "",
"Check latest available stable version and compare it with the one being used.",
func(args []string) error {
return mod.Start()
}))
return mod
}
func (mod *UpdateModule) Name() string {
return "update"
}
func (mod *UpdateModule) Description() string {
return "A module to check for bettercap's updates."
}
func (mod *UpdateModule) Author() string {
return "Simone Margaritelli <evilsocket@gmail.com>"
}
func (mod *UpdateModule) Configure() error {
return nil
}
func (mod *UpdateModule) Stop() error {
return nil
}
func (mod *UpdateModule) versionToNum(ver string) float64 {
if ver[0] == 'v' {
ver = ver[1:]
}
n := 0.0
parts := strings.Split(ver, ".")
nparts := len(parts)
// reverse
for i := nparts/2 - 1; i >= 0; i-- {
opp := nparts - 1 - i
parts[i], parts[opp] = parts[opp], parts[i]
}
for i, e := range parts {
ev, _ := strconv.Atoi(e)
n += float64(ev) * math.Pow10(i)
}
return n
}
func (mod *UpdateModule) Start() error {
return mod.SetRunning(true, func() {
defer mod.SetRunning(false, nil)
mod.Info("checking latest stable release ...")
if releases, _, err := mod.client.Repositories.ListReleases(context.Background(), "bettercap", "bettercap", nil); err == nil {
latest := releases[0]
if mod.versionToNum(core.Version) < mod.versionToNum(*latest.TagName) {
mod.Session.Events.Add("update.available", latest)
} else {
mod.Info("you are running %s which is the latest stable version.", tui.Bold(core.Version))
}
} else {
mod.Error("error while fetching latest release info from GitHub: %s", err)
}
})
}