-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
github.go
82 lines (68 loc) · 1.68 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
package badgestorer
import (
"context"
"fmt"
"net/http"
"github.com/google/go-github/v56/github"
)
type Git struct {
Token string
Owner string
Repository string
Branch string
FileName string
}
func GitPublicURL(cfg Git) string {
return fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/%s",
cfg.Owner, cfg.Repository, cfg.Branch, cfg.FileName,
)
}
type githubStorer struct {
cfg Git
}
func NewGithub(cfg Git) Storer {
return &githubStorer{cfg: cfg}
}
func (s *githubStorer) Store(data []byte) (bool, error) {
git := s.cfg
client := github.NewClient(nil).WithAuthToken(git.Token)
updateBadge := func(sha *string) (bool, error) {
_, _, err := client.Repositories.UpdateFile(
context.Background(),
git.Owner,
git.Repository,
git.FileName,
&github.RepositoryContentFileOptions{
Message: github.String("update badge " + git.FileName),
Content: data,
Branch: &git.Branch,
SHA: sha,
},
)
if err != nil {
return false, fmt.Errorf("update badge contents: %w", err)
}
return true, nil // has changed
}
fc, _, httpResp, err := client.Repositories.GetContents(
context.Background(),
git.Owner,
git.Repository,
git.FileName,
&github.RepositoryContentGetOptions{Ref: git.Branch},
)
if httpResp.StatusCode == http.StatusNotFound { // when badge is not found create it
return updateBadge(nil)
}
if err != nil {
return false, fmt.Errorf("get badge content: %w", err)
}
content, err := fc.GetContent()
if err != nil {
return false, fmt.Errorf("decode badge content: %w", err)
}
if content == string(data) { // same badge already exists... do nothing
return false, nil
}
return updateBadge(fc.SHA)
}