forked from mistsys/github-release
/
cmd.go
455 lines (387 loc) · 10.3 KB
/
cmd.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
)
func infocmd(opt Options) error {
user := nvls(opt.Info.User, EnvUser)
repo := nvls(opt.Info.Repo, EnvRepo)
token := nvls(opt.Info.Token, EnvToken)
tag := opt.Info.Tag
latest := opt.Info.Latest
latestTag := opt.Info.LatestTag
if user == "" || repo == "" {
return fmt.Errorf("user and repo need to be passed as arguments")
}
if latest || latestTag {
var rel *Release
var err error
rel, err = LatestRelease(user, repo, token)
if err != nil {
return err
}
tag = rel.TagName
if latestTag {
fmt.Println(tag)
return nil
}
}
/* find regular git tags */
allTags, err := Tags(user, repo, token)
if err != nil {
return fmt.Errorf("could not fetch tags, %v", err)
}
if len(allTags) == 0 {
return fmt.Errorf("no tags available for %v/%v", user, repo)
}
/* list all tags */
tags := make([]Tag, 0, len(allTags))
for _, t := range allTags {
/* if the user only requested see one tag, skip the ones that
* don't match */
if tag != "" && t.Name != tag {
continue
}
tags = append(tags, t)
}
/* if no tags conformed to the users' request, exit */
if len(tags) == 0 {
return fmt.Errorf("no tag '%v' was found for %v/%v", tag, user, repo)
}
fmt.Println("git tags:")
for _, t := range tags {
fmt.Println("-", t.String())
}
/* list releases + assets */
var releases []Release
if tag == "" {
/* get all releases */
vprintf("%v/%v: getting information for all releases\n", user, repo)
releases, err = Releases(user, repo, token)
if err != nil {
return err
}
} else {
/* get only one release */
vprintf("%v/%v/%v: getting information for the release\n", user, repo, tag)
release, err := ReleaseOfTag(user, repo, tag, token)
if err != nil {
return err
}
releases = []Release{*release}
}
/* if no tags conformed to the users' request, exit */
if len(releases) == 0 {
return fmt.Errorf("no release(s) were found for %v/%v (%v)", user, repo, tag)
}
fmt.Println("releases:")
for _, release := range releases {
fmt.Println("-", release.String())
}
return nil
}
func uploadcmd(opt Options) error {
user := nvls(opt.Upload.User, EnvUser)
repo := nvls(opt.Upload.Repo, EnvRepo)
token := nvls(opt.Upload.Token, EnvToken)
tag := opt.Upload.Tag
name := opt.Upload.Name
label := opt.Upload.Label
file := opt.Upload.File
vprintln("uploading...")
if file == nil {
return fmt.Errorf("provided file was not valid")
}
defer file.Close()
if err := ValidateCredentials(user, repo, token, tag); err != nil {
return err
}
/* find the release corresponding to the entered tag, if any */
rel, err := ReleaseOfTag(user, repo, tag, token)
if err != nil {
return err
}
v := url.Values{}
v.Set("name", name)
if label != "" {
v.Set("label", label)
}
url := rel.CleanUploadUrl() + "?" + v.Encode()
resp, err := DoAuthRequest("POST", url, "application/octet-stream",
token, nil, file)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("can't create upload request to %v, %v", url, err)
}
vprintln("RESPONSE:", resp)
if resp.StatusCode != http.StatusCreated {
if msg, err := ToMessage(resp.Body); err == nil {
return fmt.Errorf("could not upload, status code (%v), %v",
resp.Status, msg)
} else {
return fmt.Errorf("could not upload, status code (%v)", resp.Status)
}
}
if VERBOSITY != 0 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error while reading response, %v", err)
}
vprintln("BODY:", string(body))
}
return nil
}
func downloadcmd(opt Options) error {
user := nvls(opt.Download.User, EnvUser)
repo := nvls(opt.Download.Repo, EnvRepo)
token := nvls(opt.Download.Token, EnvToken)
tag := opt.Download.Tag
name := opt.Download.Name
latest := opt.Download.Latest
regexed := opt.Download.Regexed
vprintln("downloading...")
if err := ValidateTarget(user, repo, tag, latest); err != nil {
return err
}
// Find the release corresponding to the entered tag, if any.
var rel *Release
var err error
if latest {
rel, err = LatestRelease(user, repo, token)
} else {
rel, err = ReleaseOfTag(user, repo, tag, token)
}
if err != nil {
return err
}
assetId := 0
var rx *regexp.Regexp
var theName string
if regexed {
rx = regexp.MustCompile(name)
}
for _, asset := range rel.Assets {
if regexed {
theName = rx.FindString(asset.Name)
} else {
theName = name
}
if asset.Name == theName {
assetId = asset.Id
}
}
if assetId == 0 {
return fmt.Errorf("coud not find asset named %s", theName)
}
var resp *http.Response
var url string
if token == "" {
url = GH_URL + fmt.Sprintf("/%s/%s/releases/download/%s/%s", user, repo, tag, theName)
resp, err = http.Get(url)
} else {
url = ApiURL() + fmt.Sprintf(ASSET_DOWNLOAD_URI, user, repo, assetId)
resp, err = DoAuthRequest("GET", url, "", token, map[string]string{
"Accept": "application/octet-stream",
}, nil)
}
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("could not fetch releases, %v", err)
}
vprintln("GET", url, "->", resp)
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("github did not respond with 200 OK but with %v", resp.Status)
}
out, err := os.Create(theName)
if err != nil {
return fmt.Errorf("could not create file %s", theName)
}
defer out.Close()
n, err := io.Copy(out, resp.Body)
if n != contentLength {
return fmt.Errorf("downloaded data did not match content length %d != %d", contentLength, n)
}
return err
}
func ValidateTarget(user, repo, tag string, latest bool) error {
if user == "" {
return fmt.Errorf("empty user")
}
if repo == "" {
return fmt.Errorf("empty repo")
}
if tag == "" && !latest {
return fmt.Errorf("empty tag")
}
return nil
}
func ValidateCredentials(user, repo, token, tag string) error {
if err := ValidateTarget(user, repo, tag, false); err != nil {
return err
}
if token == "" {
return fmt.Errorf("empty token")
}
return nil
}
func releasecmd(opt Options) error {
cmdopt := opt.Release
user := nvls(cmdopt.User, EnvUser)
repo := nvls(cmdopt.Repo, EnvRepo)
token := nvls(cmdopt.Token, EnvToken)
tag := cmdopt.Tag
name := nvls(cmdopt.Name, tag)
desc := nvls(cmdopt.Desc, tag)
target := nvls(cmdopt.Target)
draft := cmdopt.Draft
prerelease := cmdopt.Prerelease
vprintln("releasing...")
if err := ValidateCredentials(user, repo, token, tag); err != nil {
return err
}
params := ReleaseCreate{
TagName: tag,
TargetCommitish: target,
Name: name,
Body: desc,
Draft: draft,
Prerelease: prerelease,
}
/* encode params as json */
payload, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("can't encode release creation params, %v", err)
}
reader := bytes.NewReader(payload)
uri := fmt.Sprintf("/repos/%s/%s/releases", user, repo)
resp, err := DoAuthRequest("POST", ApiURL()+uri, "application/json",
token, nil, reader)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("while submitting %v, %v", string(payload), err)
}
vprintln("RESPONSE:", resp)
if resp.StatusCode != http.StatusCreated {
if resp.StatusCode == 422 {
return fmt.Errorf("github returned %v (this is probably because the release already exists)",
resp.Status)
}
return fmt.Errorf("github returned %v", resp.Status)
}
if VERBOSITY != 0 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error while reading response, %v", err)
}
vprintln("BODY:", string(body))
}
return nil
}
func editcmd(opt Options) error {
cmdopt := opt.Edit
user := nvls(cmdopt.User, EnvUser)
repo := nvls(cmdopt.Repo, EnvRepo)
token := nvls(cmdopt.Token, EnvToken)
tag := cmdopt.Tag
name := nvls(cmdopt.Name, tag)
desc := nvls(cmdopt.Desc, tag)
draft := cmdopt.Draft
prerelease := cmdopt.Prerelease
vprintln("editing...")
if err := ValidateCredentials(user, repo, token, tag); err != nil {
return err
}
id, err := IdOfTag(user, repo, tag, token)
if err != nil {
return err
}
vprintf("release %v has id %v\n", tag, id)
/* the release create struct works for editing releases as well */
params := ReleaseCreate{
TagName: tag,
Name: name,
Body: desc,
Draft: draft,
Prerelease: prerelease,
}
/* encode the parameters as JSON, as required by the github API */
payload, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("can't encode release creation params, %v", err)
}
uri := fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id)
resp, err := DoAuthRequest("PATCH", ApiURL()+uri, "application/json",
token, nil, bytes.NewReader(payload))
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("while submitting %v, %v", string(payload), err)
}
vprintln("RESPONSE:", resp)
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == 422 {
return fmt.Errorf("github returned %v (this is probably because the release already exists)",
resp.Status)
}
return fmt.Errorf("github returned unexpected status code %v", resp.Status)
}
if VERBOSITY != 0 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error while reading response, %v", err)
}
vprintln("BODY:", string(body))
}
return nil
}
func deletecmd(opt Options) error {
user, repo, token, tag := nvls(opt.Delete.User, EnvUser),
nvls(opt.Delete.Repo, EnvRepo),
nvls(opt.Delete.Token, EnvToken),
opt.Delete.Tag
vprintln("deleting...")
id, err := IdOfTag(user, repo, tag, token)
if err != nil {
return err
}
vprintf("release %v has id %v\n", tag, id)
resp, err := httpDelete(ApiURL()+fmt.Sprintf("/repos/%s/%s/releases/%d",
user, repo, id), token)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("release deletion unsuccesful, %v", err)
}
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("could not delete the release corresponding to tag %s on repo %s/%s",
tag, user, repo)
}
return nil
}
func httpDelete(url, token string) (*http.Response, error) {
resp, err := DoAuthRequest("DELETE", url, "application/json", token, nil, nil)
if err != nil {
return nil, err
}
return resp, nil
}