/
api_tree.go
319 lines (232 loc) · 7.08 KB
/
api_tree.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
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
package writer
import (
"context"
"errors"
"fmt"
"github.com/google/go-github/github"
wof_writer "github.com/whosonfirst/go-writer/v2"
"golang.org/x/oauth2"
"io"
"log"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
)
const GITHUBAPI_TREE_SCHEME string = "githubapi-tree"
type GitHubAPITreeWriter struct {
wof_writer.Writer
base_owner string
base_repo string
base_branch string
commit_owner string
commit_repo string
commit_branch string
commit_author string
commit_email string
commit_description string
commit_entries []github.TreeEntry
commit_ensure_repo bool
prefix string
client *github.Client
user *github.User
logger *log.Logger
mutex *sync.RWMutex
}
func init() {
ctx := context.Background()
wof_writer.RegisterWriter(ctx, GITHUBAPI_TREE_SCHEME, NewGitHubAPITreeWriter)
}
func NewGitHubAPITreeWriter(ctx context.Context, uri string) (wof_writer.Writer, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
base_owner := u.Host
path := strings.TrimLeft(u.Path, "/")
parts := strings.Split(path, "/")
if len(parts) != 1 {
return nil, errors.New("Invalid path")
}
base_repo := parts[0]
base_branch := DEFAULT_BRANCH
q := u.Query()
token := q.Get("access_token")
prefix := q.Get("prefix")
branch := q.Get("branch")
if token == "" {
return nil, errors.New("Missing access token")
}
if branch != "" {
base_branch = branch
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
users := client.Users
user, _, err := users.Get(ctx, "")
if err != nil {
return nil, fmt.Errorf("Unable to retrieve user for token, %w", err)
}
commit_owner := base_owner
commit_repo := base_repo
commit_branch := base_branch
to_branch := q.Get("to-branch")
if to_branch != "" {
commit_branch = to_branch
}
commit_description := q.Get("description")
commit_author := q.Get("author")
if commit_author == "" {
commit_author = user.GetName()
}
if commit_author == "" {
return nil, fmt.Errorf("Invalid author")
}
commit_email := q.Get("email")
if commit_email == "" {
commit_email = user.GetEmail()
}
if commit_email == "" {
return nil, fmt.Errorf("Invalid email address")
}
commit_entries := []github.TreeEntry{}
logger := log.Default()
mutex := new(sync.RWMutex)
wr := &GitHubAPITreeWriter{
client: client,
user: user,
base_owner: base_owner,
base_repo: base_repo,
base_branch: base_branch,
commit_owner: commit_owner,
commit_repo: commit_repo,
commit_branch: commit_branch,
commit_author: commit_author,
commit_email: commit_email,
commit_description: commit_description,
commit_entries: commit_entries,
prefix: prefix,
logger: logger,
mutex: mutex,
}
return wr, nil
}
func (wr *GitHubAPITreeWriter) Write(ctx context.Context, uri string, r io.ReadSeeker) (int64, error) {
// Something something something account for cases with a bazillion commits and not keeping
// everything in memory until we call Close(). One option would be to keep a local map of io.ReadSeeker
// instances but then we will just have filehandle exhaustion problems. Add option to write to
// disk or something like a SQLite database (allowing a custom DSN to determine whether to write to
// disk or memory) ?
body, err := io.ReadAll(r)
if err != nil {
return 0, err
}
wr_uri := wr.WriterURI(ctx, uri)
e := github.TreeEntry{
Path: github.String(wr_uri),
Type: github.String("blob"),
Content: github.String(string(body)),
Mode: github.String("100644"),
}
wr.mutex.Lock()
defer wr.mutex.Unlock()
wr.commit_entries = append(wr.commit_entries, e)
wr.logger.Printf("Add %s\n", wr_uri)
return 0, nil
}
func (wr *GitHubAPITreeWriter) Flush(ctx context.Context) error {
wr.mutex.Lock()
defer wr.mutex.Unlock()
if len(wr.commit_entries) == 0 {
return nil
}
ref, err := wr.getRef(ctx)
if err != nil {
if err != nil {
return fmt.Errorf("Failed to get ref, %w", err)
}
}
tree, _, err := wr.client.Git.CreateTree(ctx, wr.commit_owner, wr.commit_repo, *ref.Object.SHA, wr.commit_entries)
if err != nil {
return fmt.Errorf("Failed to create tree, %w", err)
}
err = wr.pushCommit(ctx, ref, tree)
if err != nil {
return fmt.Errorf("Failed to push commit, %w", err)
}
wr.commit_entries = []github.TreeEntry{}
return nil
}
func (wr *GitHubAPITreeWriter) Close(ctx context.Context) error {
return wr.Flush(ctx)
}
func (wr *GitHubAPITreeWriter) SetLogger(ctx context.Context, logger *log.Logger) error {
wr.logger = logger
return nil
}
func (wr *GitHubAPITreeWriter) WriterURI(ctx context.Context, key string) string {
uri := key
if wr.prefix != "" {
uri = filepath.Join(wr.prefix, key)
}
return uri
}
func (wr *GitHubAPITreeWriter) getRef(ctx context.Context) (*github.Reference, error) {
base_branch := fmt.Sprintf("refs/heads/%s", wr.base_branch)
commit_branch := fmt.Sprintf("refs/heads/%s", wr.commit_branch)
commit_ref, _, _ := wr.client.Git.GetRef(ctx, wr.commit_owner, wr.commit_repo, commit_branch)
if commit_ref != nil {
return commit_ref, nil
}
base_ref, _, err := wr.client.Git.GetRef(ctx, wr.commit_owner, wr.commit_repo, base_branch)
if err != nil {
return nil, fmt.Errorf("Failed to retrieve base branch '%s' for %s/%s, %w", base_branch, wr.commit_owner, wr.commit_repo, err)
}
new_ref := &github.Reference{Ref: github.String(commit_branch), Object: &github.GitObject{SHA: base_ref.Object.SHA}}
commit_ref, _, err = wr.client.Git.CreateRef(ctx, wr.commit_owner, wr.commit_repo, new_ref)
if err != nil {
return nil, fmt.Errorf("Failed to create new ref, %w", err)
}
return commit_ref, err
}
// pushCommit creates the commit in the given reference using the given tree.
func (wr *GitHubAPITreeWriter) pushCommit(ctx context.Context, ref *github.Reference, tree *github.Tree) error {
// Get the parent commit to attach the commit to.
parent, _, err := wr.client.Repositories.GetCommit(ctx, wr.commit_owner, wr.commit_repo, *ref.Object.SHA)
if err != nil {
return fmt.Errorf("Failed to determine parent commit, %w", err)
}
// This is not always populated, but is needed.
parent.Commit.SHA = parent.SHA
// Create the commit using the tree.
date := time.Now()
author := &github.CommitAuthor{
Date: &date,
Name: &wr.commit_author,
Email: &wr.commit_email,
}
parents := []github.Commit{
*parent.Commit,
}
commit := &github.Commit{
Author: author,
Message: &wr.commit_description,
Tree: tree,
Parents: parents,
}
newCommit, _, err := wr.client.Git.CreateCommit(ctx, wr.commit_owner, wr.commit_repo, commit)
if err != nil {
return fmt.Errorf("Failed to create commit, %w", err)
}
// Attach the commit to the main branch.
ref.Object.SHA = newCommit.SHA
_, _, err = wr.client.Git.UpdateRef(ctx, wr.commit_owner, wr.commit_repo, ref, false)
if err != nil {
return fmt.Errorf("Failed to update ref, %w", err)
}
return nil
}