-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
2685 lines (2356 loc) · 62.8 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
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main // import "github.com/MYOB-OSS/hubr"
import (
"archive/zip"
"bufio"
"context"
"debug/elf"
"debug/macho"
"debug/pe"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/awserr"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/format/config"
"gopkg.in/src-d/go-git.v4/plumbing/format/diff"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
const (
// the default tag if not supplied
defaultTag = "latest"
// the number of parallel uploads or downloads
workers = 3
)
var (
// the default org/owner if not supplied
defaultOrg = ""
// default auth chain (key:value,key:value)
defaultChain = "env:GITHUB_API_TOKEN,env:TOKEN"
// context used for github calls
ctxbg = context.Background()
// hubr version, set at build time
// -ldflags="-X main.hubr=$(head -n 1 VERSION)"
hubr = "unknown"
// COMMIT the commit sha
COMMIT = "none"
// BRANCH the branch name
BRANCH = "unknown"
)
func init() {
if org, ok := os.LookupEnv("HUBR_DEFAULT_ORG"); ok {
defaultOrg = org
}
}
// asset is a GitHub release asset and a pointer to the release
type asset struct {
github.ReleaseAsset
Release *github.RepositoryRelease
id ident
}
// client is a wrapper over the github client.
type client struct {
*github.Client
}
// NewClient creates a new client. It attempts to acquire a GitHub token from
// the auth chain defined by the global defaultChain.
// The chain takes the form of a string "k:v,k:v,k:v".
// - key "env" calls os.Getenv(v)
// - key "ssm" calls ssmGet(v)
// The first result which is not missing is used for GitHub authentication.
// If no result is found hubr will attempt to invoke a git credential helper.
func newClient() (*client, error) {
var err error
var token string
for _, p := range strings.Split(defaultChain, ",") {
kv := strings.Split(p, ":")
if len(kv) != 2 {
return nil, fmt.Errorf("invalid auth chain value: %v", p)
}
switch kv[0] {
case "env":
token = os.Getenv(kv[1])
case "ssm":
token, err = ssmGet(kv[1])
default:
return nil, fmt.Errorf("invalid auth chain value: %v", p)
}
if token != "" {
break
}
}
if token == "" {
token = credHelper()
}
if token == "" {
if err != nil {
return nil, fmt.Errorf("auth chain failed: %v", err)
}
return nil, fmt.Errorf("auth chain failed: " + defaultChain)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctxbg, ts)
return &client{Client: github.NewClient(tc)}, nil
}
// CreateRelease creates a GitHub release with the given tag, name and body.
// If the release already exists nothing happens and no error is returned.
// If pre is true the release will be a prerelease.
func (c *client) CreateRelease(id ident, name, body string, pre bool) error {
r, rsp, err := c.Repositories.GetReleaseByTag(ctxbg, id.org, id.repo, id.tag)
if rsp.StatusCode != http.StatusNotFound {
if err != nil {
return err
}
return nil
}
r = &github.RepositoryRelease{
TagName: &id.tag,
Name: &name,
Body: &body,
Prerelease: &pre,
}
_, _, err = c.Repositories.CreateRelease(ctxbg, id.org, id.repo, r)
return err
}
// DraftRelease creates a GitHub draft release with the given tag, name and body.
// If the release already exists nothing happens and no error is returned.
// If pre is true the release will be a prerelease.
func (c *client) DraftRelease(id ident, name, body string, pre bool) (*github.RepositoryRelease, error) {
r, err := c.GetDraft(id)
switch {
case err == nil:
return r, nil
case isNotFound(err):
default:
return nil, fmt.Errorf("get release: %s", err)
}
r = &github.RepositoryRelease{
TagName: github.String(id.tag),
Name: github.String(name),
Body: github.String(body),
Draft: github.Bool(true),
Prerelease: github.Bool(pre),
}
r, _, err = c.Repositories.CreateRelease(ctxbg, id.org, id.repo, r)
return r, err
}
// ListReleases returns a slice of releases for the given repo.
func (c *client) ListReleases(id ident) ([]*github.RepositoryRelease, error) {
rs, _, err := c.Repositories.ListReleases(ctxbg, id.org, id.repo,
&github.ListOptions{Page: 0})
if err != nil {
return []*github.RepositoryRelease{}, err
}
return rs, nil
}
// GetDraft returns the first release with a matching tag. The returned release
// may or may not actually be a draft.
func (c *client) GetDraft(id ident) (*github.RepositoryRelease, error) {
rs, err := c.ListReleases(id)
if err != nil {
return nil, err
}
for _, r := range rs {
if id.tag == r.GetTagName() {
return r, nil
}
}
return nil, errNotFound{id}
}
// GetRelease returns the release for a given tag, which may be "latest" for the
// latest full release.
func (c *client) GetRelease(id ident) (*github.RepositoryRelease, error) {
var (
r *github.RepositoryRelease
err error
)
switch id.tag {
case "edge":
rs, err := c.ListReleases(id)
if err != nil {
return nil, err
}
if len(rs) == 0 {
return nil, errNoReleases{id}
}
return rs[0], nil
case "stable":
fallthrough
case defaultTag:
r, _, err = c.Repositories.GetLatestRelease(ctxbg, id.org, id.repo)
default:
r, _, err = c.Repositories.GetReleaseByTag(ctxbg, id.org, id.repo, id.tag)
}
return r, err
}
// PublishRelease changes a release from draft to not draft. If the release
// does not exist an error is returned. If the release exists and is not a
// draft nothing happens and no error is returned.
func (c *client) PublishRelease(id ident) error {
var r *github.RepositoryRelease
var err error
//We have to retry this block of code because when we hit the publish release API in github,
//and the get draft API, the release that was published doesn't show up on the draft get because of potential
//read after write consistency issues on the github side of things. For now, retrying 3 times should do the trick
//if it's an errorNotFound from the GetDraft method.
for tries := 0; tries < 3; tries++ {
r, err = c.GetDraft(id)
switch err.(type) {
case nil:
if !r.GetDraft() {
return nil
}
*r.Draft = false
r, _, err = c.Repositories.EditRelease(ctxbg, id.org, id.repo, r.GetID(), r)
return err
case errNotFound:
time.Sleep(time.Second * time.Duration(2*(tries+1)))
break
default:
return fmt.Errorf("get release: %s", err)
}
}
return fmt.Errorf("get release: %s", err)
}
// CreateTag creates a tag on GitHub. If msg is blank a lightweight tag will be
// created. If the tag already exists, nothing happens. If the tag exists and
// does not resolve to the same commit sha, an error is returned.
func (c *client) CreateTag(id ident, sha, msg string) error {
refstr := "tags/" + id.tag
ref, rsp, err := c.Git.GetRef(ctxbg, id.org, id.repo, refstr)
if rsp.StatusCode != http.StatusNotFound {
if err != nil {
return err
}
if sha == ref.GetObject().GetSHA() {
return nil
}
if msg == "" {
return errors.New("ref " + refstr + " exists on github and the sha is incorrect")
}
t, rsp, err := c.Git.GetTag(ctxbg, id.org, id.repo, ref.GetObject().GetSHA())
if rsp.StatusCode != http.StatusNotFound {
if err != nil {
return err
}
if sha != t.GetObject().GetSHA() {
return errors.New("tag " + id.tag + " exists on github and the sha is incorrect")
}
}
return nil
}
err = nil
_, rsp, err = c.Repositories.GetCommit(ctxbg, id.org, id.repo, sha)
if err != nil {
if rsp.StatusCode == 422 {
return fmt.Errorf("create tag %s: sha %s not found, is the commit pushed?",
id.String(), sha)
}
return fmt.Errorf("create tag: verify sha %s: %s", sha, err)
}
obj := &github.GitObject{SHA: &sha, Type: github.String("commit")}
if msg != "" {
pld := &github.Tag{
Tag: &id.tag,
Object: obj,
Message: &msg,
}
t, _, err := c.Git.CreateTag(ctxbg, id.org, id.repo, pld)
if err != nil {
return fmt.Errorf("create annotated tag: %s", err)
}
obj.SHA = t.SHA
}
pld := &github.Reference{
Ref: &refstr,
Object: obj,
}
_, _, err = c.Git.CreateRef(ctxbg, id.org, id.repo, pld)
if err != nil {
return fmt.Errorf("create tag ref: %s", err)
}
return nil
}
// GlobAssets returns a slice of assets or an error and filters the result by
// using the ident as a glob (filepath.Match).
func (c *client) GlobAssets(id ident) ([]asset, error) {
r, err := c.GetRelease(id)
if err != nil {
return []asset{}, fmt.Errorf("get asset: %s", err)
}
id.tag = r.GetTagName()
as := []asset{}
for _, a := range r.Assets {
ok, err := filepath.Match(id.asset, a.GetName())
if err != nil {
return []asset{}, fmt.Errorf("%s: %s", id, err)
}
if !ok {
continue
}
nid := ident{
org: id.org,
repo: id.repo,
tag: id.tag,
asset: a.GetName(),
dst: id.dst,
}
if nid.dst == "" {
nid.dst = nid.asset
}
as = append(as, asset{a, r, nid})
}
if len(as) == 0 {
return as, errNotFound{id}
}
return as, nil
}
// List tags lists all the tag refs for a repo.
func (c *client) ListTags(id ident) ([]string, error) {
ts, _, err := c.Repositories.ListTags(ctxbg, id.org, id.repo,
&github.ListOptions{Page: 0})
if err != nil {
return []string{}, err
}
ss := make([]string, len(ts))
for i, t := range ts {
ss[i] = t.GetName()
}
return ss, nil
}
// downer performs downloaads using parallel workers. Call queue(dir, as) to
// append a slice of assets to download, such as returned by client.GlobAssets.
// Call wait() to wait on the workers and collect any errors.
// Attempting to queue after a wait will cause a panic.
type downer struct {
c *client
queue func(string, []asset)
wait func() []error
}
// newDowner creates a new downer using a client and a number of
// parallel workers. Calling newDowner starts the worker pool.
func newDowner(c *client, wkrs int) downer {
type dl struct {
dir string
a asset
}
dlc := make(chan dl)
done := make(chan struct{})
errs, eall := erraggr()
d := downer{
c: c,
queue: func(dir string, as []asset) {
for _, a := range as {
dlc <- dl{dir, a}
}
},
wait: func() []error {
close(dlc)
for i := 0; i < wkrs; i++ {
<-done
}
return <-eall
},
}
for i := 0; i < wkrs; i++ {
go func() {
for v := range dlc {
errs <- d.download(v.dir, v.a)
}
done <- struct{}{}
}()
}
return d
}
// download is called by workers for the downer
// don't call this directly! use d.queue(dir, as)
func (d *downer) download(dir string, a asset) error {
log.Printf("get %s", a.id)
rc, rd, err := d.c.Repositories.DownloadReleaseAsset(ctxbg,
a.id.org, a.id.repo, a.GetID())
if err != nil {
return fmt.Errorf("download %s: %s", a.id, err)
}
if rc == nil {
rsp, err := http.Get(rd)
if err != nil {
return fmt.Errorf("download redirect %s: %s", a.id, err)
}
rc = rsp.Body
}
defer rc.Close()
w := os.Stdout
if dir != "\x00" {
f, err := os.Create(filepath.Join(dir, a.id.dst))
if err != nil {
return fmt.Errorf("download create %s: %s", a.id, err)
}
defer f.Close()
w = f
}
_, err = io.Copy(w, rc)
if err != nil {
return fmt.Errorf("download copy %s: %s", a.id, err)
}
return err
}
// upper performs uploaads using parallel workers. Call queue(dst, src) to append
// an upload job. Call wait() to wait on the workers and collect any errors.
// Attempting to queue after a wait will cause a panic.
type upper struct {
c *client
r *github.RepositoryRelease
id ident
queue func(string, string)
wait func() []error
}
// newUpper creates a new upper for a release using a client and a number of
// parallel workers. Calling newUpper starts the worker pool.
func newUpper(c *client, wkrs int, id ident, r *github.RepositoryRelease) upper {
type ul struct {
dst string
src string
}
ulc := make(chan ul)
done := make(chan struct{})
errs, eall := erraggr()
u := upper{
c: c,
r: r,
id: id,
queue: func(dst, src string) {
ulc <- ul{dst, src}
},
wait: func() []error {
close(ulc)
for i := 0; i < wkrs; i++ {
<-done
}
return <-eall
},
}
for i := 0; i < wkrs; i++ {
go func() {
for v := range ulc {
errs <- u.upload(v.dst, v.src)
}
done <- struct{}{}
}()
}
return u
}
// upload is called by workers for the upper
// don't call this directly! use u.queue(dst, src)
func (u *upper) upload(dst string, src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return err
}
for _, a := range u.r.Assets {
if dst != a.GetName() {
continue
}
if st.Size() != int64(a.GetSize()) {
return errors.New("release asset " + u.id.tag + " " + dst + " exists and is a different size to " + src)
}
return nil
}
_, _, err = u.c.Repositories.UploadReleaseAsset(ctxbg,
u.id.org, u.id.repo, u.r.GetID(),
&github.UploadOptions{Name: dst}, f)
return err
}
type errNotFound struct {
ident
}
func isNotFound(err error) bool {
_, ok := err.(errNotFound)
return ok
}
func (e errNotFound) Error() string {
return fmt.Sprintf("%s was not found", e.ident.String())
}
type errNoReleases struct {
ident
}
func isNoReleases(err error) bool {
_, ok := err.(errNoReleases)
return ok
}
func (e errNoReleases) Error() string {
return fmt.Sprintf("%s has no releases", e.ident.String())
}
// regexp pattern for ident
const (
idSlugPart = `(?:([\d\w_-]+)/)?`
idRepoPart = `([\d\w_-]+)`
idTagPart = `(?:@([\d\w\._-]+))?`
idGlobPart = `(?::([\d\w\.\*\?\[\]\^_-]+))?`
idFilePart = `(?::([\d\w\._-]+))?`
idRe = "^" + idSlugPart + idRepoPart + idTagPart + idGlobPart + idFilePart + "$"
)
// regexp for ident
var (
idRx = regexp.MustCompile(idRe)
noGlobRx = regexp.MustCompile(`^[\d\w\._-]+$`)
)
// ident can identify a repo, tag, or asset and destination name.
type ident struct {
org, repo, tag, asset, dst string
}
func parseID(s string) (ident, bool) {
ms := idRx.FindStringSubmatch(s)
if len(ms) != 6 {
return ident{}, false
}
id := ident{ms[1], ms[2], ms[3], ms[4], ms[5]}
if id.org == "" {
id.org = defaultOrg
}
if id.org == "" {
log.Printf("%s has no org and HUBR_DEFAULT_ORG is not set", s)
return ident{}, false
}
if id.tag == "" {
id.tag = defaultTag
}
glob := !noGlobRx.MatchString(id.asset)
switch {
case glob && id.dst != "":
return ident{}, false
case !glob && id.dst == "":
id.dst = id.asset
}
return id, true
}
func (id ident) String() string {
s := id.org + "/" + id.repo
if id.tag != defaultTag {
s += "@" + id.tag
}
if id.asset != "" {
s += ":" + id.asset
}
if id.dst != id.asset && id.dst != "" {
s += ":" + id.dst
}
return s
}
// increment is a semver increment
type increment int
const (
noinc increment = iota
major
minor
patch
allinc
)
// parseIncrement converts a string to an increment.
func parseIncrement(s string) (increment, error) {
i := map[string]increment{
"major": major, "minor": minor, "patch": patch,
}[s]
if i == noinc {
return i, errors.New("not an increment: " + s)
}
return i, nil
}
// String returns a string representation of the increment.
func (i increment) String() string {
return map[increment]string{
noinc: "invalid", major: "major", minor: "minor", patch: "patch",
}[i]
}
// spec is a set of parameters to create or update a release.
type spec struct {
id ident
draft, pre, keepd bool
sha, name, body string
uploads []string
wkrs int
}
// release does exactly what it says. A tag is created if one does not
// exist. A release is created if one does not exist. Files listed in uploads
// are uploaded.
func (s spec) release() error {
c, err := newClient()
if err != nil {
return err
}
err = c.CreateTag(s.id, s.sha, "release "+s.name)
if err != nil {
return fmt.Errorf("tag: %s", err)
}
r, err := c.DraftRelease(s.id, s.name, s.body, s.pre)
if err != nil {
return fmt.Errorf("draft release: %s", err)
}
if len(s.uploads) > 0 {
u := newUpper(c, s.wkrs, s.id, r)
for _, src := range s.uploads {
dst := src
if !s.keepd {
dst = filepath.Base(src)
}
u.queue(dst, src)
log.Print("uploading ", src)
}
errs := u.wait()
if len(errs) > 0 {
for _, err := range errs {
log.Print(err)
}
return errors.New("uploads failed")
}
}
if s.draft {
log.Print(s.id.repo, " ", s.id.tag, " draft release updated")
return nil
}
err = c.PublishRelease(s.id)
if err != nil {
return fmt.Errorf("publish release: %s", err)
}
octolog(c, s.id.String()+" released!")
return nil
}
// versionRe matches a semver of the form 0.0.0 with any prefix or suffix.
var versionRe = regexp.MustCompile(`(\d+)(?:\.(\d+))?(?:\.(\d+))?`)
// version is a semver version of the form 0.0.0 with any prefix or suffix
type version string
// parseVersion converts a string into a version. It returns an error if s does
// not match the version regexp.
func parseVersion(s string) (version, error) {
if !versionRe.MatchString(s) {
return version(""), errors.New("version does not match 0.0.0 pattern")
}
return version(s), nil
}
// bump returns a new version incremented as instructed.
func (v version) bump(incr increment) version {
now := string(v)
ms := versionRe.FindStringSubmatch(now)
if len(ms) != 4 {
now = "v0.0.0"
ms = []string{"0.0.0", "0", "0", "0"}
}
i, _ := strconv.Atoi(ms[incr])
i++
ms[incr] = strconv.Itoa(i)
for i := incr + 1; i < allinc; i++ {
ms[i] = "0"
}
next := ms[major] + "." + ms[minor] + "." + ms[patch]
l := versionRe.FindStringIndex(now)
return version(now[:l[0]] + next + now[l[1]:])
}
// isBefore returns true if v is an earlier version than u. Any prefixes or
// suffixes are ignored.
func (v version) isBefore(u version) bool {
vs := versionRe.FindStringSubmatch(string(v))
if len(vs) != 4 {
vs = []string{"0.0.0", "0", "0", "0"}
}
us := versionRe.FindStringSubmatch(string(u))
if len(us) != 4 {
us = []string{"0.0.0", "0", "0", "0"}
}
for i := major; i < allinc; i++ {
v, _ := strconv.Atoi(vs[i])
u, _ := strconv.Atoi(us[i])
if v > u {
return false
}
if v < u {
return true
}
}
return false
}
// String returns the version string or v0.0.0 if the string is empty.
func (v version) String() string {
if v == "" {
return "v0.0.0"
}
return strings.TrimRight(string(v), "\n")
}
// versioner sifts through a local git repo for version information.
type versioner struct {
*git.Repository
path string
}
// newVersioner returns a versioner for a local git repo using the given file
// path of the VERSION file in the repository. The working directory must be
// inside a git repository.
func newVersioner(path string) (versioner, error) {
r, err := git.PlainOpenWithOptions(".", &git.PlainOpenOptions{DetectDotGit: true})
if err != nil {
return versioner{}, err
}
return versioner{r, path}, nil
}
// head returns the value of the VERSION file at HEAD.
func (vr versioner) head() (version, error) {
var v version
head, err := vr.Head()
if err != nil {
return v, err
}
c, err := vr.CommitObject(head.Hash())
if err != nil {
return v, err
}
return vr.at(c)
}
// at returns the value of the VERSION file at c.
func (vr versioner) at(c *object.Commit) (version, error) {
var v version
t, err := c.Tree()
if err != nil {
return v, err
}
f, err := t.File(vr.path)
if err == object.ErrFileNotFound {
return v, nil
}
if err != nil {
return v, err
}
s, err := f.Contents()
if err != nil {
return v, err
}
l := strings.SplitN(s, "\n", 2)
return parseVersion(l[0])
}
// logDiff returns the additions made to the version file in the last commit.
func (vr versioner) logDiff() ([]string, error) {
h, err := vr.Head()
if err != nil {
return []string{}, err
}
hc, err := vr.CommitObject(h.Hash())
if err != nil {
return []string{}, err
}
switch hc.NumParents() {
case 0:
return []string{}, nil
case 1:
default:
return []string{}, errors.New("head is a merge commit; merge commits cannot be releases")
}
ht, err := hc.Tree()
if err != nil {
return []string{}, err
}
pc, err := hc.Parent(0)
if err != nil {
return []string{}, err
}
pt, err := pc.Tree()
if err != nil {
return []string{}, err
}
ss := []string{}
chs, err := pt.Diff(ht)
for _, ch := range chs {
p, err := ch.Patch()
if err != nil {
return []string{}, err
}
for _, fp := range p.FilePatches() {
if fp.IsBinary() {
continue
}
if _, to := fp.Files(); to.Path() != vr.path {
continue
}
for _, c := range fp.Chunks() {
if c.Type() == diff.Add {
ss = append(ss, c.Content())
}
}
}
}
return ss, nil
}
// files returns a map of files and directories that have changed since the
// last release.
func (vr versioner) files() (map[string]bool, error) {
fs := map[string]bool{}
h, err := vr.Head()
if err != nil {
return fs, fmt.Errorf("head: %s", err)
}
hc, err := vr.CommitObject(h.Hash())
if err != nil {
return fs, fmt.Errorf("head commit: %s", err)
}
ok, err := vr.isRelease()
if err != nil {
return fs, fmt.Errorf("head is release: %s", err)
}
var vbase version
switch ok {
case true:
pc, err := hc.Parent(0)
if err != nil {
return fs, fmt.Errorf("head commit: %s", err)
}
vbase, err = vr.at(pc)
default:
vbase, err = vr.at(hc)
}
if err != nil {
return fs, fmt.Errorf("base version: %s", err)
}
snd, rcv := passCommits()
snd <- hc
var cmt *object.Commit
for c := range rcv {
switch {
case c == nil:
continue
case c.NumParents() == 0:
case c.NumParents() == 1:
v, err := vr.at(c)
if err != nil {
return fs, fmt.Errorf("version of %s: %s", c.Hash.String(), err)
}
if v.isBefore(vbase) {
continue
}
p, err := c.Parent(0)
if err != nil {
return fs, fmt.Errorf("parent of %s: %s", c.Hash.String(), err)
}
snd <- p
default:
err := c.Parents().ForEach(func(c *object.Commit) error {
v, err := vr.at(c)
if err != nil {
return err
}
if v.isBefore(vbase) {
return nil
}
snd <- c
return nil
})
if err != nil {
return fs, fmt.Errorf("merge %s: %s", c.Hash.String(), err)
}
}
cmt = c
}
if cmt == nil {
return fs, fmt.Errorf("cant get commits. missing VERSION?")
}
ht, err := hc.Tree()
if err != nil {
return fs, fmt.Errorf("head tree: %s", err)
}
ct, err := cmt.Tree()
if err != nil {
return fs, fmt.Errorf("commit tree: %s", err)
}