This repository has been archived by the owner on Aug 9, 2020. It is now read-only.
/
main.go
836 lines (641 loc) · 16.9 KB
/
main.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
package main
import (
"fmt"
"golang.org/x/net/context"
"gopkg.in/urfave/cli.v1"
"os"
"path"
"strings"
)
var version string
type incorrectArgumentNumberError struct {
expected int
received int
}
type missingRequiredArgumentError struct {
argument string
}
type badArgumentError struct {
argument string
reason string
}
func main() {
app := cli.NewApp()
// Global flags
debugFlag := cli.BoolFlag{
Name: "debug, d",
Usage: "prints out verbose statements about what grease is doing",
EnvVar: "DEBUG",
}
dryRunFlag := cli.BoolFlag{
Name: "dry-run, n",
Usage: "prevents changes from being made; best used with --debug to see what changes would be made, if any",
}
// Common, non-global flags
assetsFlag := cli.StringFlag{
Name: "assets",
Usage: "uploads the assets at the given path (glob patterns enabled)",
}
gitHubTokenFlag := cli.StringFlag{
Name: "github-token",
Usage: "used to authenticate the request with the GitHub API",
EnvVar: "GITHUB_TOKEN",
}
draftFlag := cli.BoolFlag{
Name: "draft",
Usage: "marks the release as a draft (unpublished)",
}
prereleaseFlag := cli.BoolFlag{
Name: "pre-release, pre",
Usage: "marks the release as a pre-release",
}
nameFlag := cli.StringFlag{
Name: "name",
Usage: "sets the name of the release, for example \"v0.4.0 - 2017-08-22\"",
}
notesFlag := cli.StringFlag{
Name: "notes",
Usage: "sets the body of the release notes",
}
// Hidden flags
// These flags are hidden from the user and are used to hold positional
// arguments passed after flags
globPatternFlag := cli.StringFlag{
Name: "glob-pattern",
Usage: "Glob pattern to find files with",
Hidden: true,
}
repositoryFlag := cli.StringFlag{
Name: "repository",
Usage: "name of the GitHub repository to operate on (not including the owner portion)",
Hidden: true,
}
ownerFlag := cli.StringFlag{
Name: "owner",
Usage: "owner of the GitHub repository",
Hidden: true,
}
tagFlag := cli.StringFlag{
Name: "tag",
Usage: "tag to modify",
Hidden: true,
}
targetCommittishFlag := cli.StringFlag{
Name: "target-commitish",
Usage: "a commit-ish identifier to create the tag from",
Value: "master",
Hidden: true,
}
// Commands
// createReleaseCommand
createReleaseCommand := cli.Command{
Name: "create-release",
Usage: "creates a release on GitHub",
ArgsUsage: "REPO TAG COMMITISH",
Description: `
Creates a new GitHub release identified by TAG on the repository identified
by REPO using the COMMITTISH identifier.
`,
Action: cmdCreateRelease,
Before: beforeCreateRelease,
Flags: []cli.Flag{
repositoryFlag,
ownerFlag,
tagFlag,
targetCommittishFlag,
nameFlag,
notesFlag,
draftFlag,
prereleaseFlag,
assetsFlag,
gitHubTokenFlag,
},
}
// updateReleaseCommand
updateReleaseCommand := cli.Command{
Name: "update-release",
Usage: "updates a release on GitHub",
ArgsUsage: "REPO TAG",
Description: `
Updates the GitHub release identified by TAG on the repository identified by
REPO based on the flags passed on the command line.
`,
Action: cmdUpdateRelease,
Before: beforeUpdateRelease,
Flags: []cli.Flag{
repositoryFlag,
ownerFlag,
tagFlag,
nameFlag,
notesFlag,
draftFlag,
prereleaseFlag,
assetsFlag,
gitHubTokenFlag,
},
}
// uploadArtifactsCommand
uploadArtifactsCommand := cli.Command{
Name: "upload-assets",
Usage: "uploads assets to an existing release on GitHub",
ArgsUsage: "REPO TAG GLOB_PATTERN",
Description: `
Takes all files found using the glob pattern at GLOB_PATTERN and uploads them as
assets for the GitHub release identified by TAG on the repository identified
by REPO.
`,
Action: cmdUploadArtifacts,
Before: beforeUploadArtifacts,
Flags: []cli.Flag{
globPatternFlag,
repositoryFlag,
ownerFlag,
tagFlag,
gitHubTokenFlag,
},
}
// listFilesCommand
listFilesCommand := cli.Command{
Name: "list-files",
Usage: "print out list of files found using the glob pattern",
ArgsUsage: "GLOB_PATTERN",
Description: `
Takes a GLOB_PATTERN and prints out a list of the matching files.
This command is designed for trouble-shooting the use of a glob pattern when
using them to specify assets to upload.
`,
Action: cmdListFiles,
Before: beforeListFiles,
Flags: []cli.Flag{
globPatternFlag,
},
}
app.Usage = "creates and updates releases on GitHub with assets"
app.Version = version
app.Flags = []cli.Flag{
debugFlag,
dryRunFlag,
}
app.Commands = []cli.Command{
createReleaseCommand,
updateReleaseCommand,
uploadArtifactsCommand,
listFilesCommand,
}
app.Run(os.Args)
}
/*
Architectural pattern for the command interface
We use a package called `cli` for exposing the functionality of grease via
a command-line tool. The package defines the concept of an "application"; to
this application we add many "commands". The package is responsible for parsing
commands and arguments.
Each command has an action that it executes after parsing. The action is a function
of the form `func(*cli.Context) (error)`. We name these functions based on the
command name. The command "upload-assets", for example, uses the function
cmdUploadArtifacts as its function. Likewise, "create-release" uses the function
cmdCreateRelease.
*/
/*
before functions - func(*cli.Context)
The functions in this section are run prior to the command action but after
the context has been setup.
The intent of these before functions is to perform validation of command line
arguments and exit early if required parameters are not present or do not meet
constraints.
*/
func beforeCreateRelease(ctx *cli.Context) error {
debug := ctx.GlobalBool("debug")
// Expected positional arguments (3): REPO TAG COMMITTISH
err := validatePositionalArgumentCount(ctx, 3)
if err != nil {
return err
}
arguments := ctx.Args()
repo := arguments.Get(0)
repoOwner, repoName, err := splitRepositoryName(repo)
if err != nil {
return err
}
err = ctx.Set("owner", repoOwner)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository owner is: %s\n", repoOwner)
}
err = ctx.Set("repository", repoName)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository name is: %s\n", repo)
}
tag := arguments.Get(1)
err = ctx.Set("tag", tag)
if err != nil {
return err
}
if debug {
fmt.Printf("Git tag is: %s\n", tag)
}
commitish := arguments.Get(2)
err = ctx.Set("target-commitish", commitish)
if err != nil {
return err
}
if debug {
fmt.Printf("Git commitish is: %s\n", commitish)
}
return nil
}
func beforeUpdateRelease(ctx *cli.Context) error {
debug := ctx.GlobalBool("debug")
// Expected positional arguments (2): REPO TAG
err := validatePositionalArgumentCount(ctx, 2)
if err != nil {
return err
}
arguments := ctx.Args()
repo := arguments.Get(0)
repoOwner, repoName, err := splitRepositoryName(repo)
if err != nil {
return err
}
err = ctx.Set("owner", repoOwner)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository owner is: %s\n", repoOwner)
}
err = ctx.Set("repository", repoName)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository name is: %s\n", repo)
}
tag := arguments.Get(1)
err = ctx.Set("tag", tag)
if err != nil {
return err
}
if debug {
fmt.Printf("Git tag is: %s\n", tag)
}
return nil
}
func beforeUploadArtifacts(ctx *cli.Context) error {
debug := ctx.GlobalBool("debug")
// Expected positional arguments (3): REPO TAG GLOB_PATTERN
err := validatePositionalArgumentCount(ctx, 3)
if err != nil {
return err
}
arguments := ctx.Args()
repo := arguments.Get(0)
repoOwner, repoName, err := splitRepositoryName(repo)
if err != nil {
return err
}
err = ctx.Set("owner", repoOwner)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository owner is: %s\n", repoOwner)
}
err = ctx.Set("repository", repoName)
if err != nil {
return err
}
if debug {
fmt.Printf("GitHub repository name is: %s\n", repo)
}
tag := arguments.Get(1)
err = ctx.Set("tag", tag)
if err != nil {
return err
}
if debug {
fmt.Printf("Git tag is: %s\n", tag)
}
globPattern := arguments.Get(2)
err = ctx.Set("glob-pattern", globPattern)
if err != nil {
return err
}
if debug {
fmt.Printf("Glob pattern is: %s\n", globPattern)
}
return nil
}
func beforeListFiles(ctx *cli.Context) error {
debug := ctx.GlobalBool("debug")
// Expected positional arguments (1): GLOB_PATTERN
err := validatePositionalArgumentCount(ctx, 1)
if err != nil {
return err
}
arguments := ctx.Args()
globPattern := arguments.Get(0)
err = ctx.Set("glob-pattern", globPattern)
if err != nil {
return err
}
if debug {
fmt.Printf("Glob pattern is: %s\n", globPattern)
}
return nil
}
func cmdCreateRelease(ctx *cli.Context) error {
dry := ctx.GlobalBool("dry-run")
debug := ctx.GlobalBool("debug")
if debug {
fmt.Println("Preparing to create release")
}
repoName := ctx.String("repository")
repoOwner := ctx.String("owner")
tagName := ctx.String("tag")
targetCommitish := ctx.String("target-commitish")
releaseName := ctx.String("name")
releaseBody := ctx.String("notes")
draft := ctx.Bool("draft")
preRelease := ctx.Bool("pre-release")
assetGlobPattern := ctx.String("assets")
gitHubToken := ctx.String("github-token")
repo := &gitHubRepo{
Name: repoName,
Owner: repoOwner,
}
release := &gitHubRelease{
TagName: &tagName,
TargetCommitish: &targetCommitish,
Name: &releaseName,
Body: &releaseBody,
Draft: &draft,
PreRelease: &preRelease,
}
assets, err := findFiles(assetGlobPattern)
if err != nil {
return err
}
if debug {
fmt.Println("Release Creation Settings")
fmt.Println("=========================")
printRepoDebugStatements(repo)
printReleaseDebugStatements(release)
}
if dry {
fmt.Println("Dry run specified. Exiting.")
return nil
}
netCtx := context.Background()
releaseId, err := repo.CreateRelease(netCtx, release, gitHubToken)
if err != nil {
return err
}
if debug {
fmt.Printf("Created release (id: %d)!\n", *releaseId)
fmt.Println("Preparing to upload any assets")
}
for _, assetPath := range assets {
filename := path.Base(assetPath)
file, err := os.Open(assetPath)
if err != nil {
fmt.Printf("Failed to open %s. Skipping.\n", assetPath)
continue
}
if debug {
fmt.Printf("Uploading asset at %s as %s\n", assetPath, filename)
}
err = repo.UploadReleaseAsset(netCtx, *releaseId, file, filename, gitHubToken)
if err != nil {
fmt.Printf("Error while uploading asset at %s\n", filename)
fmt.Println(err)
}
}
return nil
}
func cmdUpdateRelease(ctx *cli.Context) error {
dry := ctx.GlobalBool("dry-run")
debug := ctx.GlobalBool("debug")
if debug {
fmt.Println("Preparing to update release")
}
repoName := ctx.String("repository")
repoOwner := ctx.String("owner")
tagName := ctx.String("tag")
releaseName := ctx.String("name")
releaseBody := ctx.String("notes")
draft := ctx.Bool("draft")
preRelease := ctx.Bool("pre-release")
assetGlobPattern := ctx.String("assets")
gitHubToken := ctx.String("github-token")
repo := &gitHubRepo{
Name: repoName,
Owner: repoOwner,
}
release := &gitHubRelease{
TagName: &tagName,
Name: &releaseName,
Body: &releaseBody,
Draft: &draft,
PreRelease: &preRelease,
}
assets, err := findFiles(assetGlobPattern)
if err != nil {
return err
}
if debug {
fmt.Println("Release Update Settings")
fmt.Println("=========================")
printRepoDebugStatements(repo)
printReleaseDebugStatements(release)
}
if dry {
fmt.Println("Dry run specified. Exiting.")
return nil
}
netCtx := context.Background()
releaseId, err := repo.GetReleaseIdByTag(netCtx, *release.TagName, gitHubToken)
if err != nil {
return err
}
_, err = repo.UpdateRelease(netCtx, *releaseId, release, gitHubToken)
if err != nil {
return err
}
if debug {
fmt.Printf("Updated release (id: %d)!\n", *releaseId)
fmt.Println("Preparing to upload any assets")
}
for _, assetPath := range assets {
filename := path.Base(assetPath)
file, err := os.Open(assetPath)
if err != nil {
fmt.Printf("Failed to open %s. Skipping.\n", assetPath)
continue
}
if debug {
fmt.Printf("Uploading asset at %s as %s\n", assetPath, filename)
}
err = repo.UploadReleaseAsset(netCtx, *releaseId, file, filename, gitHubToken)
if err != nil {
fmt.Printf("Error while uploading asset at %s\n", filename)
fmt.Println(err)
}
}
return nil
}
func cmdUploadArtifacts(ctx *cli.Context) error {
dry := ctx.GlobalBool("dry-run")
debug := ctx.GlobalBool("debug")
if debug {
fmt.Println("Preparing to upload assets")
}
repoName := ctx.String("repository")
repoOwner := ctx.String("owner")
tagName := ctx.String("tag")
assetGlobPattern := ctx.String("glob-pattern")
gitHubToken := ctx.String("github-token")
repo := &gitHubRepo{
Name: repoName,
Owner: repoOwner,
}
assets, err := findFiles(assetGlobPattern)
if err != nil {
return err
}
if debug {
fmt.Println("Asset Upload Settings")
fmt.Println("=====================")
printRepoDebugStatements(repo)
fmt.Printf("Tag:\t\t\t%s\n", tagName)
printAssetDebugStatements(assets)
}
if dry {
fmt.Println("Dry run specified. Exiting.")
return nil
}
netCtx := context.Background()
releaseId, err := repo.GetReleaseIdByTag(netCtx, tagName, gitHubToken)
if err != nil {
return err
}
for _, assetPath := range assets {
filename := path.Base(assetPath)
file, err := os.Open(assetPath)
if err != nil {
fmt.Printf("Failed to open %s. Skipping.\n", assetPath)
continue
}
if debug {
fmt.Printf("Uploading asset at %s as %s\n", assetPath, filename)
}
err = repo.UploadReleaseAsset(netCtx, *releaseId, file, filename, gitHubToken)
if err != nil {
fmt.Printf("Error while uploading asset at %s\n", filename)
fmt.Println(err)
}
}
return nil
}
func cmdListFiles(ctx *cli.Context) error {
globPattern := ctx.String("glob-pattern")
files, err := findFiles(globPattern)
if err != nil {
return err
}
if len(files) == 0 {
fmt.Println("No matches found")
}
for _, fileName := range files {
fmt.Printf("File match found: %s\n", fileName)
}
return nil
}
func printRepoDebugStatements(repo *gitHubRepo) {
fmt.Printf("Repo:\t\t\thttps://github.com/%s/%s\n", repo.Owner, repo.Name)
}
func printReleaseDebugStatements(release *gitHubRelease) {
fmt.Printf("Tag:\t\t\t%s\n", *release.TagName)
if release.TargetCommitish != nil {
fmt.Printf("Tag Commit:\t\t%s\n", *release.TargetCommitish)
}
fmt.Printf("Release Name/Title:\t%s\n", *release.Name)
fmt.Printf("Draft:\t\t\t%t\n", *release.Draft)
fmt.Printf("Pre-release:\t\t%t\n", *release.PreRelease)
fmt.Println("-----Begin Release Notes-----")
fmt.Printf("%s\n", *release.Body)
fmt.Println("------End Release Notes------")
}
func printAssetDebugStatements(assets []string) {
if len(assets) == 0 {
fmt.Println("No assets found to upload")
} else {
fmt.Println("The following assets will be uploaded:")
for _, assetPath := range assets {
filename := path.Base(assetPath)
fmt.Printf("\t- %s as %s\n", assetPath, filename)
}
}
}
func splitRepositoryName(name string) (owner string, repo string, e error) {
endOwnerIndex := strings.Index(name, "/")
if endOwnerIndex == -1 {
e = &badArgumentError{argument: "REPO", reason: "expected to be of the form owner/repo but found no /"}
return
}
if endOwnerIndex == 0 {
e = &badArgumentError{argument: "REPO", reason: "expected to be of the form owner/repo but owner portion was blank"}
return
}
repoStartIndex := endOwnerIndex + 1
repoEndIndex := len(name)
if repoStartIndex > repoEndIndex {
e = &badArgumentError{argument: "REPO", reason: "expected to be of the form owner/repo but repo portion was blank"}
return
}
owner = name[:endOwnerIndex]
repo = name[repoStartIndex:repoEndIndex]
return
}
func validatePositionalArgumentCount(ctx *cli.Context, expected int) error {
received := ctx.NArg()
if received != expected {
return &incorrectArgumentNumberError{expected: expected, received: received}
}
return nil
}
func validateGitHubToken(gitHubToken string) error {
if gitHubToken == "" {
return &missingRequiredArgumentError{argument: "--github-token"}
}
return nil
}
func (e *missingRequiredArgumentError) Error() string {
message := fmt.Sprintf("Required argument \"%s\" was not provided", e.argument)
return message
}
func (e *incorrectArgumentNumberError) Error() string {
message := fmt.Sprintf("Expected %d positional arguments but received %d", e.expected, e.received)
return message
}
func (e *badArgumentError) Error() string {
message := fmt.Sprintf("Bad argument %s: %s", e.argument, e.reason)
return message
}
func (e *missingRequiredArgumentError) ExitCode() int {
return 64
}
func (e *incorrectArgumentNumberError) ExitCode() int {
return 64
}
func (e *badArgumentError) ExitCode() int {
return 64
}
func (e *badGlobPatternError) ExitCode() int {
return 64
}