-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprovider_github.go
More file actions
267 lines (246 loc) · 8.1 KB
/
provider_github.go
File metadata and controls
267 lines (246 loc) · 8.1 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//go:build !nogithub
package gobookmarks
import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/google/go-github/v55/github"
"golang.org/x/oauth2"
)
// GitHubProvider implements Provider for GitHub.
type GitHubProvider struct{}
func init() { RegisterProvider(GitHubProvider{}) }
func (GitHubProvider) Name() string { return "github" }
func (GitHubProvider) DefaultServer() string { return "https://github.com" }
func (GitHubProvider) OAuth2Config(clientID, clientSecret, redirectURL string) *oauth2.Config {
server := strings.TrimRight(GitServer, "/")
if server == "" {
server = "https://github.com"
}
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"repo", "read:user", "user:email"},
Endpoint: oauth2.Endpoint{
AuthURL: server + "/login/oauth/authorize",
TokenURL: server + "/login/oauth/access_token",
},
}
}
func (GitHubProvider) client(ctx context.Context, token *oauth2.Token) *github.Client {
httpClient := oauth2.NewClient(ctx, oauth2.StaticTokenSource(token))
server := strings.TrimRight(GitServer, "/")
if server == "" || server == "https://github.com" {
return github.NewClient(httpClient)
}
c, err := github.NewEnterpriseClient(server+"/api/v3/", server+"/upload/v3/", httpClient)
if err != nil {
return github.NewClient(httpClient)
}
return c
}
func (p GitHubProvider) CurrentUser(ctx context.Context, token *oauth2.Token) (*User, error) {
u, _, err := p.client(ctx, token).Users.Get(ctx, "")
if err != nil {
return nil, err
}
user := &User{}
if u.Login != nil {
user.Login = *u.Login
}
return user, nil
}
func (p GitHubProvider) GetTags(ctx context.Context, user string, token *oauth2.Token) ([]*Tag, error) {
tags, _, err := p.client(ctx, token).Repositories.ListTags(ctx, user, RepoName, &github.ListOptions{})
if err != nil {
return nil, fmt.Errorf("ListTags: %w", err)
}
res := make([]*Tag, 0, len(tags))
for _, t := range tags {
res = append(res, &Tag{Name: t.GetName()})
}
return res, nil
}
func (p GitHubProvider) GetBranches(ctx context.Context, user string, token *oauth2.Token) ([]*Branch, error) {
bs, _, err := p.client(ctx, token).Repositories.ListBranches(ctx, user, RepoName, &github.BranchListOptions{})
if err != nil {
return nil, fmt.Errorf("ListBranches: %w", err)
}
res := make([]*Branch, 0, len(bs))
for _, b := range bs {
res = append(res, &Branch{Name: b.GetName()})
}
return res, nil
}
func (p GitHubProvider) GetCommits(ctx context.Context, user string, token *oauth2.Token) ([]*Commit, error) {
cs, _, err := p.client(ctx, token).Repositories.ListCommits(ctx, user, RepoName, &github.CommitsListOptions{})
if err != nil {
return nil, fmt.Errorf("ListCommits: %w", err)
}
res := make([]*Commit, 0, len(cs))
for _, c := range cs {
cm := c.GetCommit()
com := &Commit{SHA: c.GetSHA()}
if cm != nil {
com.Message = cm.GetMessage()
comm := cm.Committer
if comm != nil {
com.CommitterName = comm.GetName()
com.CommitterEmail = comm.GetEmail()
com.CommitterDate = comm.GetDate().Time
}
}
res = append(res, com)
}
return res, nil
}
func (p GitHubProvider) GetBookmarks(ctx context.Context, user, ref string, token *oauth2.Token) (string, string, error) {
contents, _, resp, err := p.client(ctx, token).Repositories.GetContents(ctx, user, RepoName, "bookmarks.txt", &github.RepositoryContentGetOptions{Ref: ref})
if resp != nil && resp.StatusCode == 404 {
return "", "", nil
}
if err != nil {
return "", "", fmt.Errorf("GetBookmarks: %w", err)
}
if contents.Content == nil {
return "", "", nil
}
b, err := base64.StdEncoding.DecodeString(*contents.Content)
if err != nil {
return "", "", fmt.Errorf("GetBookmarks: %w", err)
}
sha := ""
if contents.SHA != nil {
sha = *contents.SHA
}
return string(b), sha, nil
}
var commitAuthor = &github.CommitAuthor{Name: SP("Gobookmarks"), Email: SP("Gobookmarks@arran.net.au")}
func (p GitHubProvider) getDefaultBranch(ctx context.Context, user string, client *github.Client, branch string) (string, bool, error) {
rep, resp, err := client.Repositories.Get(ctx, user, RepoName)
created := false
if resp != nil && resp.StatusCode == 404 {
rep, err = p.createRepo(ctx, user, client)
if err != nil {
return "", created, err
}
created = true
}
if err != nil {
return "", created, fmt.Errorf("Repositories.Get: %w", err)
}
if rep.DefaultBranch != nil {
branch = *rep.DefaultBranch
} else {
branch = "main"
}
return branch, created, nil
}
func (p GitHubProvider) createRepo(ctx context.Context, user string, client *github.Client) (*github.Repository, error) {
rep := &github.Repository{Name: &RepoName, Description: SP("Personal bookmarks"), Private: BP(true)}
rep, _, err := client.Repositories.Create(ctx, "", rep)
if err != nil {
return nil, fmt.Errorf("Repositories.Create: %w", err)
}
_, _, err = client.Repositories.CreateFile(ctx, user, RepoName, "readme.md", &github.RepositoryContentFileOptions{
Message: SP("Auto create from web"),
Content: []byte(`# Your bookmarks
See . https://github.com/arran4/gobookmarks `),
Author: commitAuthor, Committer: commitAuthor,
})
if err != nil {
return nil, fmt.Errorf("CreateReadme: %w", err)
}
return rep, nil
}
func (p GitHubProvider) createRef(ctx context.Context, user string, client *github.Client, sourceRef, branchRef string) error {
gsref, resp, err := client.Git.GetRef(ctx, user, RepoName, sourceRef)
if resp != nil && resp.StatusCode == 404 {
err = nil
}
if err != nil {
return fmt.Errorf("GetRef: %w", err)
}
_, _, err = client.Git.CreateRef(ctx, user, RepoName, &github.Reference{Ref: &branchRef, Object: gsref.Object})
if err != nil {
return fmt.Errorf("CreateRef: %w", err)
}
return nil
}
func (p GitHubProvider) UpdateBookmarks(ctx context.Context, user string, token *oauth2.Token, sourceRef, branch, text, expectSHA string) error {
client := p.client(ctx, token)
defaultBranch, created, err := p.getDefaultBranch(ctx, user, client, branch)
if err != nil {
return err
}
if branch == "" {
branch = defaultBranch
}
branchRef := "refs/heads/" + branch
if sourceRef == "" {
sourceRef = branchRef
}
if created {
return p.CreateBookmarks(ctx, user, token, branch, text)
}
_, grefResp, err := client.Git.GetRef(ctx, user, RepoName, branchRef)
if err != nil && grefResp.StatusCode != 404 {
return fmt.Errorf("GetRef: %w", err)
}
if grefResp.StatusCode == 404 {
if err := p.createRef(ctx, user, client, sourceRef, branchRef); err != nil {
return fmt.Errorf("create ref: %w", err)
}
}
contents, _, resp, err := client.Repositories.GetContents(ctx, user, RepoName, "bookmarks.txt", &github.RepositoryContentGetOptions{Ref: branchRef})
if resp != nil && resp.StatusCode == 404 {
if _, err := p.createRepo(ctx, user, client); err != nil {
return fmt.Errorf("CreateRepo: %w", err)
}
return p.CreateBookmarks(ctx, user, token, branch, text)
}
if err != nil {
return fmt.Errorf("GetContents: %w", err)
}
if contents == nil || contents.Content == nil {
return nil
}
if expectSHA != "" && contents.SHA != nil && *contents.SHA != expectSHA {
return fmt.Errorf("bookmarks modified concurrently")
}
_, _, err = client.Repositories.UpdateFile(ctx, user, RepoName, "bookmarks.txt", &github.RepositoryContentFileOptions{
Message: SP("Auto change from web"),
Content: []byte(text),
Branch: &branch,
SHA: contents.SHA,
Author: commitAuthor,
Committer: commitAuthor,
})
if err != nil {
return fmt.Errorf("UpdateBookmarks: %w", err)
}
return nil
}
func (p GitHubProvider) CreateBookmarks(ctx context.Context, user string, token *oauth2.Token, branch, text string) error {
client := p.client(ctx, token)
if branch == "" {
var err error
branch, _, err = p.getDefaultBranch(ctx, user, client, branch)
if err != nil {
return err
}
}
_, _, err := client.Repositories.CreateFile(ctx, user, RepoName, "bookmarks.txt", &github.RepositoryContentFileOptions{
Message: SP("Auto create from web"),
Content: []byte(text),
Branch: &branch,
Author: commitAuthor,
Committer: commitAuthor,
})
if err != nil {
return fmt.Errorf("CreateBookmarks: %w", err)
}
return nil
}