/
release.go
956 lines (760 loc) Β· 28.6 KB
/
release.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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
package release
import (
"bytes"
"context"
"flag"
"fmt"
"os"
"regexp"
"strings"
"text/template"
"time"
changelog "github.com/gardenbed/changelog/generate"
changelogspec "github.com/gardenbed/changelog/spec"
"github.com/gardenbed/charm/flagit"
"github.com/gardenbed/charm/shell"
"github.com/gardenbed/go-github"
"github.com/mitchellh/cli"
"golang.org/x/sync/errgroup"
"github.com/gardenbed/basil-cli/internal/command"
buildcmd "github.com/gardenbed/basil-cli/internal/command/project/build"
semvercmd "github.com/gardenbed/basil-cli/internal/command/project/semver"
"github.com/gardenbed/basil-cli/internal/config"
"github.com/gardenbed/basil-cli/internal/git"
"github.com/gardenbed/basil-cli/internal/semver"
"github.com/gardenbed/basil-cli/internal/spec"
"github.com/gardenbed/basil-cli/internal/ui"
)
const (
timeout = 10 * time.Minute
synopsis = `Create a release`
help = `
Use this command for creating a new release.
Currently, only GitHub repositories are supported.
It assumes the remote repository name is origin.
The initial semantic version is always 0.1.0.
DIRECT Release:
A new release commit will be created, tagged, and directly pushed to the default branch.
A new GitHub release will also be created and published.
INDIRECT Release:
A new release commit will be created and a pull request will be opened for it to be reviewed and merged.
A new draft GitHub release will also be created.
After the pull request is merged, you need to tag the release commit and publish the draft release.
The last step can be done manually or through a GitGub action.
Usage: basil project release [flags]
Flags:
-patch create a patch release (default: true)
-minor create a minor release (default: false)
-major create a major release (default: false)
-comment add a description for the release
-mode the release mode, either direct or indirect (default: {{.Project.Release.Mode}})
Examples:
basil project release
basil project release -patch
basil project release -minor
basil project release -major
basil project release -comment="Fixing Bugs!"
basil project release -minor -comment "New Features!"
basil project release -major -comment "Breaking Changes!"
`
)
const (
remoteName = "origin"
)
var (
h2Regex = regexp.MustCompile(`##[^\n]*\n`)
)
type (
gitService interface {
Remote(string) (string, string, error)
}
repoService interface {
Get(context.Context) (*github.Repository, *github.Response, error)
Permission(context.Context, string) (github.Permission, *github.Response, error)
BranchProtection(context.Context, string, bool) (*github.Response, error)
}
releaseService interface {
List(context.Context, int, int) ([]github.Release, *github.Response, error)
Create(context.Context, github.ReleaseParams) (*github.Release, *github.Response, error)
Update(context.Context, int, github.ReleaseParams) (*github.Release, *github.Response, error)
UploadAsset(context.Context, int, string, string) (*github.ReleaseAsset, *github.Response, error)
}
pullService interface {
Get(context.Context, int) (*github.Pull, *github.Response, error)
Create(context.Context, github.CreatePullParams) (*github.Pull, *github.Response, error)
Update(context.Context, int, github.UpdatePullParams) (*github.Pull, *github.Response, error)
}
userService interface {
User(context.Context) (*github.User, *github.Response, error)
}
searchService interface {
SearchIssues(context.Context, int, int, github.SearchResultSort, github.SearchResultOrder, github.SearchQuery) (*github.SearchIssuesResult, *github.Response, error)
}
changelogService interface {
Generate(context.Context, changelogspec.Spec) (string, error)
}
semverCommand interface {
Run([]string) int
SemVer() semver.SemVer
}
buildCommand interface {
Run([]string) int
Artifacts() []buildcmd.Artifact
}
)
// Command is the cli.Command implementation for release command.
type Command struct {
ui ui.UI
config config.Config
spec spec.Spec
flags struct {
patch, minor, major bool
comment string
}
data struct {
owner, repo string
changelogSpec changelogspec.Spec
}
funcs struct {
goList shell.RunnerFunc
gitStatus shell.RunnerFunc
gitRevBranch shell.RunnerFunc
gitBranch shell.RunnerFunc
gitCheckout shell.RunnerFunc
gitAdd shell.RunnerFunc
gitCommit shell.RunnerFunc
gitTag shell.RunnerFunc
gitPull shell.RunnerFunc
gitPush shell.RunnerFunc
gitPushTag shell.RunnerFunc
gitPushBranch shell.RunnerFunc
}
services struct {
git gitService
repo repoService
releases releaseService
pulls pullService
users userService
search searchService
changelog changelogService
}
commands struct {
semver semverCommand
build buildCommand
}
outputs struct {
version semver.SemVer
}
}
// New creates a new command.
func New(ui ui.UI, config config.Config, spec spec.Spec) *Command {
return &Command{
ui: ui,
config: config,
spec: spec,
}
}
// NewFactory returns a cli.CommandFactory for creating a new command.
func NewFactory(ui ui.UI, config config.Config, spec spec.Spec) cli.CommandFactory {
return func() (cli.Command, error) {
return New(ui, config, spec), nil
}
}
// Synopsis returns a short one-line synopsis for the command.
func (c *Command) Synopsis() string {
return synopsis
}
// Help returns a long help text including usage, description, and list of flags for the command.
func (c *Command) Help() string {
var buf bytes.Buffer
t := template.Must(template.New("help").Parse(help))
_ = t.Execute(&buf, c.spec)
return buf.String()
}
// Run runs the actual command with the given command-line arguments.
// This method is used as a proxy for creating dependencies and the actual command execution is delegated to the run method for testing purposes.
func (c *Command) Run(args []string) int {
if code := c.parseFlags(args); code != command.Success {
return code
}
git, err := git.Open(".")
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
domain, path, err := git.Remote(remoteName)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
if domain != "github.com" {
c.ui.Errorf(ui.Red, "unsupported git platform: %s", domain)
return command.GitHubError
}
parts := strings.Split(path, "/")
if len(parts) != 2 {
c.ui.Errorf(ui.Red, "Unexpected GitHub repository: cannot parse owner and repo.")
return command.GitHubError
}
ownerName, repoName := parts[0], parts[1]
if c.config.GitHub.AccessToken == "" {
c.ui.Errorf(ui.Red, "A GitHub access token is required.")
return command.GitHubError
}
client := github.NewClient(c.config.GitHub.AccessToken)
repo := client.Repo(ownerName, repoName)
changelogSpec, err := changelogspec.Default().FromFile()
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.ChangelogError
}
changelogSpec = changelogSpec.WithRepo(domain, path)
changelogSpec.Repo.AccessToken = c.config.GitHub.AccessToken
changelog, err := changelog.New(changelogSpec, &changelogUI{UI: c.ui})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.ChangelogError
}
c.data.owner = ownerName
c.data.repo = repoName
c.data.changelogSpec = changelogSpec
c.funcs.goList = shell.Runner("go", "list", "./...")
c.funcs.gitStatus = shell.Runner("git", "status", "--porcelain")
c.funcs.gitRevBranch = shell.Runner("git", "rev-parse", "--abbrev-ref", "HEAD")
c.funcs.gitBranch = shell.Runner("git", "branch")
c.funcs.gitCheckout = shell.Runner("git", "checkout")
c.funcs.gitAdd = shell.Runner("git", "add", c.data.changelogSpec.General.File)
c.funcs.gitCommit = shell.Runner("git", "commit", "-m")
c.funcs.gitTag = shell.Runner("git", "tag")
c.funcs.gitPull = shell.Runner("git", "pull")
c.funcs.gitPush = shell.Runner("git", "push")
c.funcs.gitPushTag = shell.Runner("git", "push", remoteName)
c.funcs.gitPushBranch = shell.Runner("git", "push", "-u", remoteName)
c.services.git = git
c.services.repo = repo
c.services.releases = repo.Releases
c.services.pulls = repo.Pulls
c.services.users = client.Users
c.services.search = client.Search
c.services.changelog = changelog
c.commands.semver = semvercmd.New(ui.NewNop())
c.commands.build = buildcmd.New(c.ui, c.spec)
return c.exec()
}
func (c *Command) parseFlags(args []string) int {
fs := flag.NewFlagSet("release", flag.ContinueOnError)
fs.BoolVar(&c.flags.patch, "patch", true, "")
fs.BoolVar(&c.flags.minor, "minor", false, "")
fs.BoolVar(&c.flags.major, "major", false, "")
fs.StringVar(&c.flags.comment, "comment", "", "")
fs.Usage = func() {
c.ui.Printf(c.Help())
}
if err := flagit.Register(fs, &c.spec.Project.Release, false); err != nil {
return command.GenericError
}
if err := fs.Parse(args); err != nil {
// In case of error, the error and help will be printed by the Parse method
return command.FlagError
}
return command.Success
}
// exec in an auxiliary method, so we can test the business logic with mock dependencies.
func (c *Command) exec() int {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// ==============================> RUN PREFLIGHT CHECKS <==============================
c.ui.Printf("Running preflight checks ...")
checklist := command.PreflightChecklist{
Git: true,
Go: true,
}
if _, err := command.RunPreflightChecks(ctx, checklist); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.PreflightError
}
// ==============================> VALIDATE REPO STATE <==============================
repo, _, err := c.services.repo.Get(ctx)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
_, gitBranch, err := c.funcs.gitRevBranch(ctx)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
if gitBranch != repo.DefaultBranch {
c.ui.Errorf(ui.Red, "The repository can only be released from the default branch.")
return command.GitError
}
_, gitStatus, err := c.funcs.gitStatus(ctx)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
if gitStatus != "" {
c.ui.Errorf(ui.Red, "Working directory is not clean and has uncommitted changes.")
return command.GitError
}
c.ui.Infof(ui.Green, "Pulling the latest changes on the %s branch ...", gitBranch)
if _, _, err := c.funcs.gitPull(ctx); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
// ==============================> RESOLVE SEMANTIC VERSION <==============================
c.ui.Printf("Releasing %s/%s in %s mode ...", c.data.owner, c.data.repo, c.spec.Project.Release.Mode)
// Run semver command
if code := c.commands.semver.Run(nil); code != command.Success {
return code
}
switch {
case c.flags.major:
c.outputs.version = c.commands.semver.SemVer().ReleaseMajor()
case c.flags.minor:
c.outputs.version = c.commands.semver.SemVer().ReleaseMinor()
case c.flags.patch:
fallthrough
default:
c.outputs.version = c.commands.semver.SemVer().ReleasePatch()
}
// ==============================> BRANCH BASED ON MODE <==============================
switch c.spec.Project.Release.Mode {
case spec.ReleaseModeDirect:
return c.directRelease(ctx, gitBranch)
case spec.ReleaseModeIndirect:
return c.indirectRelease(ctx, gitBranch)
default:
c.ui.Errorf(ui.Red, "Invalid release mode: %s", c.spec.Project.Release.Mode)
return command.SpecError
}
}
// For direct mode
func (c *Command) directRelease(ctx context.Context, defaultBranch string) int {
// ==============================> CHECK GITHUB PERMISSION <==============================
c.ui.Printf("Checking GitHub permission for direct mode ...")
user, _, err := c.services.users.User(ctx)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
perm, _, err := c.services.repo.Permission(ctx, user.Login)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
if perm != github.PermissionAdmin {
c.ui.Errorf(ui.Red, "The provided GitHub access token does not have admin permission for direct mode.")
return command.GitHubError
}
// ==============================> CREATE A DRAFT RELEASE <==============================
c.ui.Infof(ui.Green, "Creating the draft release %s ...", c.outputs.version)
release, _, err := c.services.releases.Create(ctx, github.ReleaseParams{
Name: c.outputs.version.String(),
TagName: c.outputs.version.TagName(),
Target: defaultBranch,
Draft: true,
Prerelease: false,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> GENERATE CHANGELOG <==============================
c.ui.Infof(ui.Green, "Creating/Updating the changelog ...")
c.data.changelogSpec.Tags.Future = c.outputs.version.TagName()
changelog, err := c.services.changelog.Generate(ctx, c.data.changelogSpec)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.ChangelogError
}
// Remove the H2 title
changelog = h2Regex.ReplaceAllString(changelog, "")
changelog = strings.TrimLeft(changelog, "\n")
// ==============================> CREATE RELEASE COMMIT & TAG <==============================
c.ui.Infof(ui.Green, "Creating the release commit %s ...", c.outputs.version)
if _, _, err := c.funcs.gitAdd(ctx); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
// We need to create the commit using the git command.
// So, all user configurations (author, committer, signing key, etc.) will be picked up correctly and automatically.
message := fmt.Sprintf("Release %s", c.outputs.version)
if _, _, err := c.funcs.gitCommit(ctx, message); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
c.ui.Infof(ui.Green, "Creating the release tag %s ...", c.outputs.version)
// We need to create the tag using the git command.
// So, all user configurations (author, committer, signing key, etc.) will be picked up correctly and automatically.
if _, _, err := c.funcs.gitTag(ctx, "-a", c.outputs.version.TagName(), "-m", message); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
// ==============================> BUILD AND UPLOAD ARTIFACTS <==============================
// Check if we can build any artifacts
if _, _, err := c.funcs.goList(ctx); err == nil {
c.ui.Printf("Building artifacts ...")
// Run build command
if code := c.commands.build.Run(nil); code != command.Success {
return code
}
if artifacts := c.commands.build.Artifacts(); len(artifacts) > 0 {
c.ui.Infof(ui.Green, "Uploading artifacts to release %s ...", release.Name)
group, groupCtx := errgroup.WithContext(ctx)
for _, artifact := range artifacts {
artifact := artifact // https://golang.org/doc/faq#closures_and_goroutines
group.Go(func() error {
_, _, err := c.services.releases.UploadAsset(groupCtx, release.ID, artifact.Path, artifact.Label)
return err
})
}
if err := group.Wait(); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
}
}
// ==============================> TEMPORARILY DISABLE DEFAULT BRANCH PROTECTION <==============================
c.ui.Warnf(ui.Yellow, "Temporarily enabling push to %s branch ...", defaultBranch)
if _, err := c.services.repo.BranchProtection(ctx, defaultBranch, false); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// Make sure we re-enable the branch protection
defer func() {
c.ui.Warnf(ui.Yellow, "π Re-disabling push to %s branch ...", defaultBranch)
if _, err := c.services.repo.BranchProtection(ctx, defaultBranch, true); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
os.Exit(command.GitHubError)
}
}()
// ==============================> PUSH RELEASE COMMIT & TAG <==============================
c.ui.Infof(ui.Green, "Pushing the release commit %s ...", c.outputs.version)
if _, _, err := c.funcs.gitPush(ctx); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
c.ui.Infof(ui.Green, "Pushing the release tag %s ...", c.outputs.version.TagName())
if _, _, err := c.funcs.gitPushTag(ctx, c.outputs.version.TagName()); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
// ==============================> PUBLISH THE RELEASE <==============================
c.ui.Infof(ui.Green, "Publishing the release %s ...", release.Name)
description := changelog
if c.flags.comment != "" {
description = fmt.Sprintf("%s\n\n%s", c.flags.comment, description)
}
release, _, err = c.services.releases.Update(ctx, release.ID, github.ReleaseParams{
Name: release.Name,
TagName: release.TagName,
Target: release.Target,
Draft: false,
Prerelease: false,
Body: description,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> DONE <==============================
return command.Success
}
// For indirect mode
func (c *Command) indirectRelease(ctx context.Context, defaultBranch string) int {
title := fmt.Sprintf("RELEASE %s", c.outputs.version)
releaseBranch := fmt.Sprintf("release-%s", c.outputs.version)
// ==============================> CHECK FOR A MERGED PULL REQUEST <==============================
c.ui.Printf("Checking for a merged pull request for release %s ...", c.outputs.version)
// Search for a merged pull request matching the release version
mergedQuery := github.SearchQuery{}
mergedQuery.IncludeKeywords(title)
mergedQuery.IncludeQualifiers(
github.QualifierIsPR,
github.QualifierIsMerged,
github.QualifierInTitle,
github.QualifierRepo(c.data.owner, c.data.repo),
)
mergedResult, _, err := c.services.search.SearchIssues(ctx, 1, 1, github.SortByDefault, github.DefaultOrder, mergedQuery)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> FINISH THE RELEASE <==============================
if len(mergedResult.Items) > 0 {
return c.tagAndPublishRelease(ctx, mergedResult.Items[0].Number, defaultBranch)
}
// ==============================> CHECK FOR AN OPEN PULL REQUEST <==============================
c.ui.Printf("Checking for an open pull request for release %s ...", c.outputs.version)
// Search for an open pull request matching the release version
openQuery := github.SearchQuery{}
openQuery.IncludeKeywords(title)
openQuery.IncludeQualifiers(
github.QualifierIsPR,
github.QualifierIsOpen,
github.QualifierInTitle,
github.QualifierRepo(c.data.owner, c.data.repo),
)
openResult, _, err := c.services.search.SearchIssues(ctx, 1, 1, github.SortByDefault, github.DefaultOrder, openQuery)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> CREATE/UPDATE PULL REQUEST <==============================
changelog, code := c.pushReleaseBranch(ctx, defaultBranch, releaseBranch)
if code != command.Success {
return code
}
description := changelog
if c.flags.comment != "" {
description = fmt.Sprintf("%s\n\n%s", c.flags.comment, description)
}
if len(openResult.Items) == 0 {
code := c.createPullAndRelease(ctx, defaultBranch, releaseBranch, title, description)
if code != command.Success {
return code
}
} else {
code := c.updatePullAndRelease(ctx, openResult.Items[0].Number, defaultBranch, title, description)
if code != command.Success {
return code
}
}
// ==============================> DONE <==============================
return command.Success
}
func (c *Command) tagAndPublishRelease(ctx context.Context, number int, defaultBranch string) int {
// ==============================> GET MERGED PULL REQUEST & DRAFT RELEASE <==============================
pull, _, err := c.services.pulls.Get(ctx, number)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
release, code := c.findDraftRelease(ctx, c.outputs.version.TagName())
if code != command.Success {
return code
}
// ==============================> CREATE & PUSH TAG <==============================
c.ui.Infof(ui.Green, "Pulling the latest changes on the %s branch ...", defaultBranch)
if _, _, err := c.funcs.gitPull(ctx); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
c.ui.Infof(ui.Green, "Creating the release tag %s ...", c.outputs.version)
// We need to create the tag using the git command.
// So, all user configurations (author, committer, signing key, etc.) will be picked up correctly and automatically.
message := fmt.Sprintf("Release %s", c.outputs.version)
if _, _, err := c.funcs.gitTag(ctx, "-a", c.outputs.version.TagName(), pull.MergeCommitSHA, "-m", message); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
c.ui.Infof(ui.Green, "Pushing the release tag %s ...", c.outputs.version.TagName())
if _, _, err := c.funcs.gitPushTag(ctx, c.outputs.version.TagName()); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitError
}
// ==============================> BUILD AND UPLOAD ARTIFACTS <==============================
// Check if we can build any artifacts
if _, _, err := c.funcs.goList(ctx); err == nil {
c.ui.Printf("Building artifacts ...")
// Run build command
if code := c.commands.build.Run(nil); code != command.Success {
return code
}
if artifacts := c.commands.build.Artifacts(); len(artifacts) > 0 {
c.ui.Infof(ui.Green, "Uploading artifacts to release %s ...", c.outputs.version)
group, groupCtx := errgroup.WithContext(ctx)
for _, artifact := range artifacts {
artifact := artifact // https://golang.org/doc/faq#closures_and_goroutines
group.Go(func() error {
_, _, err := c.services.releases.UploadAsset(groupCtx, release.ID, artifact.Path, artifact.Label)
return err
})
}
if err := group.Wait(); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
}
}
// ==============================> PUBLISH THE RELEASE <==============================
c.ui.Infof(ui.Green, "Publishing the release %s ...", release.Name)
release, _, err = c.services.releases.Update(ctx, release.ID, github.ReleaseParams{
Name: release.Name,
TagName: release.TagName,
Target: release.Target,
Draft: false,
Prerelease: false,
Body: release.Body,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> DONE <==============================
return command.Success
}
func (c *Command) pushReleaseBranch(ctx context.Context, defaultBranch, releaseBranch string) (string, int) {
// ==============================> GENERATE CHANGELOG <==============================
c.ui.Infof(ui.Green, "Creating/Updating the changelog ...")
c.data.changelogSpec.Tags.Future = c.outputs.version.TagName()
changelog, err := c.services.changelog.Generate(ctx, c.data.changelogSpec)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.ChangelogError
}
// Remove the H2 title
changelog = h2Regex.ReplaceAllString(changelog, "")
changelog = strings.TrimLeft(changelog, "\n")
// ==============================> CREATE RELEASE BRANCH & COMMIT <==============================
c.ui.Infof(ui.Green, "Creating the release branch %s ...", c.outputs.version)
// Create a new branch for the release
if _, _, err := c.funcs.gitCheckout(ctx, "-b", releaseBranch); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
c.ui.Infof(ui.Green, "Creating the release commit %s ...", c.outputs.version)
if _, _, err := c.funcs.gitAdd(ctx); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
// We need to create the commit using the git command.
// So, all user configurations (author, committer, signing key, etc.) will be picked up correctly and automatically.
message := fmt.Sprintf("Release %s", c.outputs.version)
if _, _, err := c.funcs.gitCommit(ctx, message); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
// ==============================> PUSH RELEASE BRANCH <==============================
c.ui.Infof(ui.Green, "Pushing the release branch %s ...", c.outputs.version)
// Push the release branch
if _, _, err := c.funcs.gitPushBranch(ctx, "-f", releaseBranch); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
// ==============================> DELETE RELEASE BRANCH <==============================
// Check out to default branch
if _, _, err := c.funcs.gitCheckout(ctx, defaultBranch); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
// Delete the release branch
if _, _, err := c.funcs.gitBranch(ctx, "-D", releaseBranch); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return changelog, command.GitError
}
return changelog, command.Success
}
func (c *Command) createPullAndRelease(ctx context.Context, defaultBranch, releaseBranch, title, description string) int {
// ==============================> CREATE PULL REQUEST <==============================
c.ui.Infof(ui.Green, "Creating pull request for release %s ...", c.outputs.version)
pull, _, err := c.services.pulls.Create(ctx, github.CreatePullParams{
Title: title,
Body: description,
Head: releaseBranch,
Base: defaultBranch,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> CREATE DRAFT RELEASE <==============================
c.ui.Infof(ui.Green, "Creating the draft release %s ...", c.outputs.version)
release, _, err := c.services.releases.Create(ctx, github.ReleaseParams{
Name: c.outputs.version.String(),
TagName: c.outputs.version.TagName(),
Target: defaultBranch,
Draft: true,
Prerelease: false,
Body: description,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> DONE <==============================
c.ui.Printf("Pull request created: %s", pull.HTMLURL)
c.ui.Printf("Draft release created: %s", release.HTMLURL)
c.ui.Warnf(ui.Yellow, "π Re-run this command to update the pull request.")
c.ui.Warnf(ui.Yellow, "π After merging the pull request, re-run this command to create the release.")
return command.Success
}
func (c *Command) updatePullAndRelease(ctx context.Context, number int, defaultBranch, title, description string) int {
// ==============================> UPDATE PULL REQUEST <==============================
c.ui.Infof(ui.Green, "Updating pull request for release %s ...", c.outputs.version)
pull, _, err := c.services.pulls.Update(ctx, number, github.UpdatePullParams{
Title: title,
Body: description,
Base: defaultBranch,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> UPDATE DRAFT RELEASE <==============================
c.ui.Infof(ui.Green, "Updating the draft release %s ...", c.outputs.version)
release, code := c.findDraftRelease(ctx, c.outputs.version.TagName())
if code != command.Success {
return code
}
release, _, err = c.services.releases.Update(ctx, release.ID, github.ReleaseParams{
Name: c.outputs.version.String(),
TagName: c.outputs.version.TagName(),
Target: defaultBranch,
Draft: true,
Prerelease: false,
Body: description,
})
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return command.GitHubError
}
// ==============================> DONE <==============================
c.ui.Printf("Pull request updated: %s", pull.HTMLURL)
c.ui.Printf("Draft release updated: %s", release.HTMLURL)
c.ui.Warnf(ui.Green, "π Re-run this command to update the pull request.")
c.ui.Warnf(ui.Green, "π After merging the pull request, re-run this command to create the release.")
return command.Success
}
func (c *Command) findDraftRelease(ctx context.Context, tag string) (*github.Release, int) {
releases, resp, err := c.services.releases.List(ctx, 100, 1)
if err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return nil, command.GitHubError
}
for _, release := range releases {
if release.Draft && release.TagName == tag {
return &release, command.Success
}
}
var release *github.Release
group, ctx := errgroup.WithContext(ctx)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
for page := 2; page <= resp.Pages.Last; page++ {
group.Go(func() error {
releases, _, err := c.services.releases.List(ctx, 100, 1)
if err != nil {
return err
}
for _, r := range releases {
if r.Draft && r.TagName == tag {
release = &r
cancel()
break
}
}
return nil
})
}
if err := group.Wait(); err != nil {
c.ui.Errorf(ui.Red, "%s", err)
return nil, command.GitHubError
}
if release == nil {
c.ui.Errorf(ui.Red, "Draft release not found for tag %s", tag)
return nil, command.GitHubError
}
return release, command.Success
}