-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider_gitlab.go
More file actions
335 lines (316 loc) · 9.68 KB
/
provider_gitlab.go
File metadata and controls
335 lines (316 loc) · 9.68 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//go:build !nogitlab
package gobookmarks
import (
"context"
"encoding/base64"
"encoding/gob"
"errors"
"fmt"
"log"
"net/http"
"strings"
gitlab "github.com/xanzy/go-gitlab"
"golang.org/x/oauth2"
)
// GitLabProvider implements Provider for GitLab.
//
// The GitLab server URL can be overridden using the GitlabServer variable
// defined in settings.go.
type GitLabProvider struct{}
func gitlabUnauthorized(err error) bool {
var respErr *gitlab.ErrorResponse
return errors.As(err, &respErr) && respErr.Response != nil && respErr.Response.StatusCode == http.StatusUnauthorized
}
func init() {
gob.Register(&gitlab.User{})
RegisterProvider(GitLabProvider{})
}
func (GitLabProvider) Name() string { return "gitlab" }
func (GitLabProvider) DefaultServer() string { return "https://gitlab.com" }
func (GitLabProvider) Config(clientID, clientSecret, redirectURL string) *oauth2.Config {
server := strings.TrimRight(Config.GitlabServer, "/")
if server == "" {
server = "https://gitlab.com"
}
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"api"},
Endpoint: oauth2.Endpoint{
AuthURL: server + "/oauth/authorize",
TokenURL: server + "/oauth/token",
},
}
}
func (GitLabProvider) client(token *oauth2.Token) (*gitlab.Client, error) {
server := Config.GitlabServer
if server == "" {
server = "https://gitlab.com"
}
return gitlab.NewOAuthClient(token.AccessToken, gitlab.WithBaseURL(server))
}
func (GitLabProvider) CurrentUser(ctx context.Context, token *oauth2.Token) (*User, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab CurrentUser client: %v", err)
return nil, err
}
u, _, err := c.Users.CurrentUser()
if err != nil {
log.Printf("gitlab CurrentUser lookup: %v", err)
return nil, err
}
return &User{Login: u.Username}, nil
}
func (GitLabProvider) GetTags(ctx context.Context, user string, token *oauth2.Token) ([]*Tag, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab GetTags client: %v", err)
return nil, err
}
tags, _, err := c.Tags.ListTags(user+"/"+Config.GetRepoName(), &gitlab.ListTagsOptions{})
if err != nil {
if gitlabUnauthorized(err) {
return nil, ErrSignedOut
}
log.Printf("gitlab GetTags: %v", err)
return nil, fmt.Errorf("ListTags: %w", err)
}
res := make([]*Tag, 0, len(tags))
for _, t := range tags {
res = append(res, &Tag{Name: t.Name})
}
return res, nil
}
func (GitLabProvider) GetBranches(ctx context.Context, user string, token *oauth2.Token) ([]*Branch, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab GetBranches client: %v", err)
return nil, err
}
bs, _, err := c.Branches.ListBranches(user+"/"+Config.GetRepoName(), &gitlab.ListBranchesOptions{})
if err != nil {
if gitlabUnauthorized(err) {
return nil, ErrSignedOut
}
log.Printf("gitlab GetBranches: %v", err)
return nil, fmt.Errorf("ListBranches: %w", err)
}
res := make([]*Branch, 0, len(bs))
for _, b := range bs {
res = append(res, &Branch{Name: b.Name})
}
return res, nil
}
func (GitLabProvider) GetCommits(ctx context.Context, user string, token *oauth2.Token, ref string, page, perPage int) ([]*Commit, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab GetCommits client: %v", err)
return nil, err
}
cs, _, err := c.Commits.ListCommits(user+"/"+Config.GetRepoName(), &gitlab.ListCommitsOptions{RefName: &ref, ListOptions: gitlab.ListOptions{Page: page, PerPage: perPage}})
if err != nil {
if gitlabUnauthorized(err) {
return nil, ErrSignedOut
}
log.Printf("gitlab GetCommits: %v", err)
return nil, fmt.Errorf("ListCommits: %w", err)
}
res := make([]*Commit, 0, len(cs))
for _, commit := range cs {
res = append(res, &Commit{
SHA: commit.ID,
Message: commit.Message,
CommitterName: commit.CommitterName,
CommitterEmail: commit.CommitterEmail,
CommitterDate: *commit.CommittedDate,
})
}
return res, nil
}
func (GitLabProvider) GetBookmarks(ctx context.Context, user, ref string, token *oauth2.Token) (string, string, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab GetBookmarks client: %v", err)
return "", "", err
}
if ref == "" {
ref = "HEAD"
}
f, _, err := c.RepositoryFiles.GetFile(user+"/"+Config.GetRepoName(), "bookmarks.txt", &gitlab.GetFileOptions{Ref: gitlab.Ptr(ref)})
if err != nil {
if errors.Is(err, gitlab.ErrNotFound) {
return "", "", nil
}
if respErr, ok := err.(*gitlab.ErrorResponse); ok {
if respErr.Response != nil && respErr.Response.StatusCode == http.StatusNotFound {
return "", "", nil
}
if gitlabUnauthorized(err) {
return "", "", ErrSignedOut
}
log.Printf("gitlab GetBookmarks get file: %v", err)
return "", "", nil
}
if gitlabUnauthorized(err) {
return "", "", ErrSignedOut
}
log.Printf("gitlab GetBookmarks: %v", err)
return "", "", err
}
data, err := base64.StdEncoding.DecodeString(f.Content)
if err != nil {
log.Printf("gitlab GetBookmarks decode: %v", err)
return "", "", err
}
return string(data), f.LastCommitID, nil
}
func (GitLabProvider) getDefaultBranch(ctx context.Context, user string, client *gitlab.Client, branch string) (string, error) {
p, _, err := client.Projects.GetProject(user+"/"+Config.GetRepoName(), nil)
if err != nil {
if respErr, ok := err.(*gitlab.ErrorResponse); ok {
if respErr.Response != nil && respErr.Response.StatusCode == http.StatusNotFound {
return "", ErrRepoNotFound
}
if gitlabUnauthorized(err) {
return "", ErrSignedOut
}
}
if gitlabUnauthorized(err) {
return "", ErrSignedOut
}
log.Printf("gitlab getDefaultBranch: %v", err)
return "", err
}
if p.DefaultBranch != "" {
branch = p.DefaultBranch
} else {
branch = "main"
}
return branch, nil
}
func (GitLabProvider) UpdateBookmarks(ctx context.Context, user string, token *oauth2.Token, sourceRef, branch, text, expectSHA string) error {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab UpdateBookmarks client: %v", err)
return err
}
if branch == "" {
branch, err = GitLabProvider{}.getDefaultBranch(ctx, user, c, branch)
if err != nil {
log.Printf("gitlab UpdateBookmarks default branch: %v", err)
return err
}
}
opt := &gitlab.UpdateFileOptions{
Branch: gitlab.Ptr(branch),
Content: gitlab.Ptr(text),
AuthorEmail: gitlab.Ptr("Gobookmarks@arran.net.au"),
AuthorName: gitlab.Ptr("Gobookmarks"),
LastCommitID: gitlab.Ptr(expectSHA),
CommitMessage: gitlab.Ptr("Auto change from web"),
}
_, _, err = c.RepositoryFiles.UpdateFile(user+"/"+Config.GetRepoName(), "bookmarks.txt", opt)
if err != nil {
var respErr *gitlab.ErrorResponse
if errors.As(err, &respErr) {
if respErr.Response != nil && respErr.Response.StatusCode == http.StatusNotFound {
return ErrRepoNotFound
}
if gitlabUnauthorized(err) {
return ErrSignedOut
}
log.Printf("gitlab UpdateBookmarks update file: %v", err)
return err
}
if gitlabUnauthorized(err) {
return ErrSignedOut
}
if err.Error() == "404 Not Found" {
return ErrRepoNotFound
}
log.Printf("gitlab UpdateBookmarks: %v", err)
return err
}
return nil
}
func (GitLabProvider) CreateBookmarks(ctx context.Context, user string, token *oauth2.Token, branch, text string) error {
c, err := GitLabProvider{}.client(token)
if err != nil {
log.Printf("gitlab CreateBookmarks client: %v", err)
return err
}
if branch == "" {
branch, err = GitLabProvider{}.getDefaultBranch(ctx, user, c, branch)
if err != nil {
log.Printf("gitlab CreateBookmarks default branch: %v", err)
return err
}
}
opt := &gitlab.CreateFileOptions{
Branch: gitlab.Ptr(branch),
Content: gitlab.Ptr(text),
AuthorEmail: gitlab.Ptr("Gobookmarks@arran.net.au"),
AuthorName: gitlab.Ptr("Gobookmarks"),
CommitMessage: gitlab.Ptr("Auto create from web"),
}
_, _, err = c.RepositoryFiles.CreateFile(user+"/"+Config.GetRepoName(), "bookmarks.txt", opt)
if err != nil {
if respErr, ok := err.(*gitlab.ErrorResponse); ok {
if respErr.Response != nil && respErr.Response.StatusCode == http.StatusNotFound {
return ErrRepoNotFound
}
if gitlabUnauthorized(err) {
return ErrSignedOut
}
log.Printf("gitlab CreateBookmarks create file: %v", err)
return err
}
if gitlabUnauthorized(err) {
return ErrSignedOut
}
log.Printf("gitlab CreateBookmarks: %v", err)
return err
}
return nil
}
func (p GitLabProvider) CreateRepo(ctx context.Context, user string, token *oauth2.Token, name string) error {
c, err := GitLabProvider{}.client(token)
if err != nil {
return err
}
_, _, err = c.Projects.CreateProject(&gitlab.CreateProjectOptions{
Name: gitlab.Ptr(name),
Description: gitlab.Ptr("Personal bookmarks"),
Visibility: gitlab.Ptr(gitlab.PrivateVisibility),
InitializeWithReadme: gitlab.Ptr(true),
})
if err != nil {
if respErr, ok := err.(*gitlab.ErrorResponse); ok && respErr.Response != nil &&
(respErr.Response.StatusCode == http.StatusBadRequest || respErr.Response.StatusCode == http.StatusConflict) {
// repository already exists
err = nil
} else if gitlabUnauthorized(err) {
return ErrSignedOut
}
}
return err
}
func (p GitLabProvider) RepoExists(ctx context.Context, user string, token *oauth2.Token, name string) (bool, error) {
c, err := GitLabProvider{}.client(token)
if err != nil {
return false, err
}
_, resp, err := c.Projects.GetProject(user+"/"+name, nil)
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
return false, nil
}
if gitlabUnauthorized(err) {
return false, ErrSignedOut
}
return false, err
}
return true, nil
}