forked from zekroTJA/shinpuru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.go
84 lines (65 loc) · 1.67 KB
/
github.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
package versioncheck
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/valyala/fasthttp"
)
const endpoint = "https://api.github.com/repos/%s/%s/tags?per_page=1"
var (
ErrNoTags = errors.New("no tags available")
)
// GitHubProvider implements Provider using a GitHub
// repositories tag list as source for the current
// version.
type GitHubProvider struct {
owner, repo string
lastChecked time.Time
lastResult *Semver
}
var _ Provider = (*GitHubProvider)(nil)
// NewGitHubProvider returns a new instance of GitHubProvider
// with the passed repository owner and name as source.
func NewGitHubProvider(owner, repo string) *GitHubProvider {
return &GitHubProvider{
owner: owner,
repo: repo,
}
}
type tagsReponse []struct {
Name string `json:"name"`
}
func (gh *GitHubProvider) GetLatestVersion() (v Semver, err error) {
if gh.lastResult != nil && time.Since(gh.lastChecked) < 15*time.Minute {
v = *gh.lastResult
return
}
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(res)
req.Header.SetMethod("GET")
req.SetRequestURI(fmt.Sprintf(endpoint, gh.owner, gh.repo))
if err = fasthttp.Do(req, res); err != nil {
return
}
if res.StatusCode() != 200 {
err = fmt.Errorf("response error: %d", res.StatusCode())
return
}
var tags tagsReponse
if err = json.Unmarshal(res.Body(), &tags); err != nil {
return
}
if len(tags) == 0 {
err = ErrNoTags
return
}
if v, err = ParseSemver(tags[0].Name); err != nil {
return
}
gh.lastChecked = time.Now()
gh.lastResult = &v
return
}