-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
81 lines (71 loc) · 2.04 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
package main
import (
"fmt"
)
type GitHubAsset struct {
Name string `json:"name"`
URL string `json:"url"`
BrowserDownloadURL string `json:"browser_download_url"`
}
type GitHubRelease struct {
Name string `json:"name"`
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
Assets []GitHubAsset `json:"assets"`
}
type GitHub struct {
token string
repo string
authHeaders map[string]string
}
func NewGitHub(token, repo string) *GitHub {
authHeaders := make(map[string]string)
if token != "" {
authHeaders["Authorization"] = "Bearer " + token
}
return &GitHub{
token: token,
repo: repo,
authHeaders: authHeaders,
}
}
func (g *GitHub) GetLatestRelease() (Release, error) {
// https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-the-latest-release
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", g.repo)
return g.getRelease(url)
}
func (g *GitHub) GetTaggedRelease(tag string) (Release, error) {
// https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-a-release-by-tag-name
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/tags/%s", g.repo, tag)
return g.getRelease(url)
}
func (g *GitHub) getRelease(url string) (Release, error) {
var gr GitHubRelease
if err := GetRelease(url, g.authHeaders, &gr); err != nil {
return Release{}, err
}
return g.convertRelease(gr), nil
}
func (g *GitHub) convertRelease(gr GitHubRelease) Release {
// https://docs.github.com/en/rest/releases/assets?apiVersion=2022-11-28#get-a-release-asset
headers := g.authHeaders
if g.token != "" {
headers["Accept"] = "application/octet-stream"
}
r := Release{
Name: gr.Name,
TagName: gr.TagName,
AuthHeaders: headers,
}
for _, ga := range gr.Assets {
var url string
if g.token == "" {
url = ga.BrowserDownloadURL
} else {
url = ga.URL
}
r.Assets = append(r.Assets, *NewAsset(ga.Name, url))
}
return r
}