-
Notifications
You must be signed in to change notification settings - Fork 14
/
magefile.go
993 lines (857 loc) · 24.9 KB
/
magefile.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
//go:build mage
// Self-contained go-project magefile.
//nolint:deadcode,gochecknoglobals,gochecknoinits,wrapcheck,varnamelen,gomnd,forcetypeassert,forbidigo,funlen,gocognit,cyclop,nolintlint
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math/bits"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"gopkg.in/yaml.v3"
archiver "github.com/mholt/archiver"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"github.com/magefile/mage/target"
"github.com/integralist/go-findroot/find"
"github.com/pkg/errors"
"github.com/rogpeppe/go-internal/modfile"
"github.com/samber/lo"
)
var (
errAutogenMultipleScriptSections = errors.New("found multiple managed script sections")
errAutogenUnknownPreCommitScriptFormat = errors.New("unknown pre-commit script format")
errPlatformNotSupported = errors.New("current platform is not supported")
errParallelBuildFailed = errors.New("parallel build failed")
errLintBisect = errors.New("error during lint bisect")
)
var curDir = func() string {
name, _ := os.Getwd()
return name
}()
const (
constCoverageDir = ".coverage"
constToolBinDir = ".bin"
constGitHookDir = "githooks"
constBinDir = "bin"
constReleaseDir = "release"
constCmdDir = "cmd"
constCoverFile = ".cover.out"
constJunitDir = ".junit"
)
const (
constManagedScriptSectionHead = "## ++ BUILD SYSTEM MANAGED - DO NOT EDIT ++ ##"
constManagedScriptSectionFoot = "## -- BUILD SYSTEM MANAGED - DO NOT EDIT -- ##"
)
// normalizePath turns a path into an absolute path and removes symlinks.
func normalizePath(name string) string {
absPath := must(filepath.Abs(name))
return absPath
}
// binRootName is set to the name of the directory by default.
var binRootName = func() string {
return must(find.Repo()).Path
}()
// dockerImageName is set to the name of the directory by default.
var dockerImageName = func() string {
return binRootName
}()
var coverageDir = normalizePath(path.Join(curDir, constCoverageDir))
var toolsBinDir = normalizePath(path.Join(curDir, constToolBinDir))
var gitHookDir = normalizePath(path.Join(curDir, constGitHookDir))
var binDir = normalizePath(path.Join(curDir, constBinDir))
var releaseDir = normalizePath(path.Join(curDir, constReleaseDir))
var cmdDir = normalizePath(path.Join(curDir, constCmdDir))
var junitDir = normalizePath(path.Join(curDir, constJunitDir))
var outputDirs = []string{binDir, releaseDir, coverageDir, junitDir}
//nolint:unused,varcheck
var containerName = func() string {
if name := os.Getenv("CONTAINER_NAME"); name != "" {
return name
}
return dockerImageName
}()
type Platform struct {
OS string
Arch string
BinSuffix string
}
func (p *Platform) String() string {
return fmt.Sprintf("%s-%s", p.OS, p.Arch)
}
func (p *Platform) PlatformDir() string {
platformDir := path.Join(binDir, fmt.Sprintf("%s_%s_%s", productName, versionShort, p.String()))
return platformDir
}
func (p *Platform) PlatformBin(cmd string) string {
platformBin := fmt.Sprintf("%s%s", cmd, p.BinSuffix)
return path.Join(p.PlatformDir(), platformBin)
}
func (p *Platform) ArchiveDir() string {
return fmt.Sprintf("%s_%s_%s", productName, versionShort, p.String())
}
func (p *Platform) ReleaseBase() string {
return path.Join(releaseDir, fmt.Sprintf("%s_%s_%s", productName, versionShort, p.String()))
}
// platforms is the list of platforms we build for.
var platforms []Platform = []Platform{
{"linux", "arm", ""},
{"linux", "arm64", ""},
{"linux", "amd64", ""},
{"linux", "386", ""},
{"darwin", "amd64", ""},
{"darwin", "arm64", ""},
{"windows", "amd64", ".exe"},
{"windows", "386", ".exe"},
{"freebsd", "amd64", ""},
}
// platformsLookup is the lookup map of the above list by <OS>/<Arch>.
var platformsLookup map[string]Platform = func() map[string]Platform {
ret := make(map[string]Platform, len(platforms))
for _, platform := range platforms {
ret[platform.String()] = platform
}
return ret
}()
// productName can be overridden by environ product name.
var productName = func() string {
if name := os.Getenv("PRODUCT_NAME"); name != "" {
return name
}
name, _ := os.Getwd()
return path.Base(name)
}()
// Source files.
var goSrc []string
var goDirs []string
var goPkgs []string
var goCmds []string
// Function to calculate the version symbol
var versionSymbol = func() string {
gomodBytes := lo.Must(ioutil.ReadFile("go.mod"))
parsedGoMod := lo.Must(modfile.ParseLax("go.mod", gomodBytes, nil))
return fmt.Sprintf("%s/version.Version", parsedGoMod.Module.Mod.Path)
}
var version = func() string {
if v := os.Getenv("VERSION"); v != "" {
return v
}
out, _ := sh.Output("git", "describe", "--dirty")
if out == "" {
// Try and at least describe the git commit.
out, _ = sh.Output("git", "describe", "--dirty", "--always")
if out != "" {
return fmt.Sprintf("v0.0.0-0-%s", out)
}
return "v0.0.0"
}
return out
}()
var versionShort = func() string {
if v := os.Getenv("VERSION_SHORT"); v != "" {
return v
}
out, _ := sh.Output("git", "describe", "--abbrev=0")
if out == "" {
return "v0.0.0"
}
return out
}()
var concurrency = func() int {
if v := os.Getenv("CONCURRENCY"); v != "" {
pv, err := strconv.ParseUint(v, 10, bits.UintSize)
if err != nil {
panic(err)
}
// Ensure we always have at least 1 process
if int(pv) < 1 {
return 1
}
return int(pv)
}
return runtime.NumCPU()
}()
var linterDeadline = func() time.Duration {
if v := os.Getenv("LINTER_DEADLINE"); v != "" {
d, _ := time.ParseDuration(v)
if d != 0 {
return d
}
}
return time.Minute
}()
func Log(args ...interface{}) {
if mg.Verbose() {
fmt.Println(args...)
}
}
var concurrencyQueue chan struct{}
var concurrencyWg *sync.WaitGroup
// concurrentRun calls a function while respecting concurrency limits, and
// returns a promise-like function which will resolve to the value.
func concurrentRun[T any](fn func() T) func() T {
concurrencyQueue <- struct{}{} // Acquire a job
concurrencyWg.Add(1) // Ensure we can wait
rCh := make(chan T)
go func() {
rCh <- fn()
<-concurrencyQueue // Release a job
concurrencyWg.Done() // Mark job finished
}()
return func() T {
return <-rCh
}
}
// waitResults accepts a map of operations and waits for them all to complete.
func waitResults(m map[string]func() error) func() error {
type dispatch struct {
k string
v error
}
resultQueue := make(chan dispatch, len(m))
for k, fn := range m {
go func(k string, fn func() error) {
resultQueue <- dispatch{
k: k,
v: fn(),
}
}(k, fn)
}
return func() error {
buildError := false
for i := 0; i < len(m); i++ {
result := <-resultQueue
if result.v != nil {
buildError = true
fmt.Printf("Error: %s: %s\n", result.k, result.v)
}
}
if buildError {
return errParallelBuildFailed
}
return nil
}
}
func init() {
// Initialize concurrency queue
concurrencyQueue = make(chan struct{}, concurrency)
concurrencyWg = &sync.WaitGroup{}
// Set environment
os.Setenv("PATH", fmt.Sprintf("%s:%s", toolsBinDir, os.Getenv("PATH")))
os.Setenv("GOBIN", toolsBinDir)
Log("Build PATH: ", os.Getenv("PATH"))
Log("Concurrency:", concurrency)
goSrc = func() []string {
results := new([]string)
err := filepath.Walk(".", func(relpath string, info os.FileInfo, _ error) error {
// Ensure absolute path so globs work
path, err := filepath.Abs(relpath)
if err != nil {
panic(err)
}
// Look for files
if info.IsDir() {
return nil
}
// Exclusions
for _, exclusion := range []string{toolsBinDir, binDir, releaseDir, coverageDir} {
if strings.HasPrefix(path, exclusion) {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
if strings.Contains(path, "/vendor/") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if strings.Contains(path, ".git") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") {
return nil
}
*results = append(*results, path)
return nil
})
if err != nil {
panic(err)
}
return *results
}()
goDirs = func() []string {
resultMap := make(map[string]struct{})
for _, path := range goSrc {
absDir, err := filepath.Abs(filepath.Dir(path))
if err != nil {
panic(err)
}
resultMap[absDir] = struct{}{}
}
results := []string{}
for k := range resultMap {
results = append(results, k)
}
return results
}()
goPkgs = func() []string {
results := []string{}
out, err := sh.Output("go", "list", "./...")
if err != nil {
panic(err)
}
for _, line := range strings.Split(out, "\n") {
if !strings.Contains(line, "/vendor/") {
results = append(results, line)
}
}
return results
}()
goCmds = func() []string {
results := []string{}
finfos, err := ioutil.ReadDir(cmdDir)
if err != nil {
panic(err)
}
for _, finfo := range finfos {
results = append(results, finfo.Name())
}
return results
}()
// Ensure output dirs exist
for _, dir := range outputDirs {
panicOnError(os.MkdirAll(dir, os.FileMode(0777)))
}
}
// must consumes an error from a function.
func must[T any](result T, err error) T {
if err != nil {
panic(err)
}
return result
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
// concurrencyLimitedBuild executes a certain number of commands limited by concurrency.
func concurrencyLimitedBuild(buildCmds ...interface{}) error {
resultsCh := make(chan error, len(buildCmds))
concurrencyControl := make(chan struct{}, concurrency)
for _, buildCmd := range buildCmds {
go func(buildCmd interface{}) {
concurrencyControl <- struct{}{}
resultsCh <- buildCmd.(func() error)()
<-concurrencyControl
}(buildCmd)
}
// Doesn't work at the moment
// mg.Deps(buildCmds...)
results := []error{}
var resultErr error = nil
for len(results) < len(buildCmds) {
err := <-resultsCh
results = append(results, err)
if err != nil {
fmt.Println(err)
resultErr = errors.Wrap(errParallelBuildFailed, "concurrencyLimitedBuild command failure")
}
fmt.Printf("Finished %v of %v\n", len(results), len(buildCmds))
}
return resultErr
}
// Tools builds build tools of the project and is depended on by all other build targets.
func Tools() (err error) {
// Catch panics and convert to errors
defer func() {
if perr := recover(); perr != nil {
err = perr.(error)
}
}()
toolBuild := func(toolType string, tools ...[]string) error {
toolTargets := []interface{}{}
for _, toolImport := range tools {
binName := toolImport[0]
localToolImport := toolImport[1]
if binName != "" {
if _, err := os.Stat(path.Join(toolsBinDir, binName)); err == nil {
// Skip named binary which we already have
continue
}
}
f := func() error {
return sh.Run("go", "install", "-v", localToolImport)
}
toolTargets = append(toolTargets, f)
}
Log("Build", toolType, "tools")
if berr := concurrencyLimitedBuild(toolTargets...); berr != nil {
return berr
}
return nil
}
// golangci-lint don't want to support if it's not a binary release, so
// don't go-install.
if berr := toolBuild("static", []string{"", "github.com/golangci/golangci-lint/cmd/[email protected]"},
[]string{"gocovmerge", "github.com/wadey/gocovmerge@latest"}); berr != nil {
return berr
}
return nil
}
func lintArgs(args ...string) []string {
returnedArgs := []string{"-j", fmt.Sprintf("%v", concurrency), fmt.Sprintf(
"--timeout=%s", linterDeadline.String())}
returnedArgs = append(returnedArgs, args...)
return returnedArgs
}
// Lint runs gometalinter for code quality. CI will run this before accepting PRs.
func Lint() error {
mg.Deps(Tools)
extraArgs := lintArgs("run")
extraArgs = append(extraArgs, goDirs...)
return sh.RunV("golangci-lint", extraArgs...)
}
// LintBisect runs the linters one directory at a time.
// It is useful for finding problems where golangci-lint won't compile and
// doesn't emit an error message.
func LintBisect() error {
errs := []error{}
for _, goDir := range goDirs {
fmt.Println("Linting:", goDir)
err := sh.RunV("golangci-lint", lintArgs("run", goDir)...)
if err != nil {
fmt.Println("LINT ERROR IN:", goDir)
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errLintBisect
}
return nil
}
// listLinters gets the golangci-lint config
func listLinters() ([]string, error) {
cmd := exec.Command("golangci-lint", "linters")
output, err := cmd.Output()
if err != nil {
return []string{}, errors.Wrap(err, "golangci-lint linters failed to run")
}
bio := bufio.NewReader(bytes.NewBuffer(output))
linters := []string{}
for {
line, _ := bio.ReadString('\n')
line = strings.Trim(line, " \n\t")
if line == "" {
continue
}
if line == "Enabled by your configuration linters:" {
continue
}
if line == "Disabled by your configuration linters:" {
// Done
break
}
linter := strings.Split(line, ":")[0]
linter = strings.Split(linter, "(")[0]
linter = strings.Trim(linter, " \n\t")
linters = append(linters, linter)
}
return linters, nil
}
// LintersBisect runs all linters in golangci-lint one at a time.
// It is useful find broken linters.
func LintersBisect() error {
linters, err := listLinters()
if err != nil {
return errors.Wrap(err, "LintersBisect: listLinters failed")
}
errs := map[string]error{}
// Annoyingly, we have to override .golangci.yml to allow us to pick linters
// one by one.
golangCi := make(map[string]interface{})
_ = yaml.Unmarshal(must(ioutil.ReadFile(".golangci.yml")), golangCi)
delete(golangCi, "linters")
tempConfig, err := ioutil.TempFile("", ".golangci.*.yml")
if err != nil {
return errors.Wrap(err, "LintersBisect: TempFile failed")
}
_ = must(tempConfig.Write(must(yaml.Marshal(golangCi))))
defer os.Remove(tempConfig.Name())
for _, linter := range linters {
extraArgs := lintArgs("run",
fmt.Sprintf("--config=%s", tempConfig.Name()),
"--disable-all",
fmt.Sprintf("--enable=%s", linter))
extraArgs = append(extraArgs, goDirs...)
err := sh.RunV("golangci-lint", extraArgs...)
if err != nil {
errs[linter] = err
}
}
if len(errs) > 0 {
for linter := range errs {
fmt.Println("FAILED LINTER:", linter)
}
return errLintBisect
}
return nil
}
// fmt runs golangci-lint with the formatter options.
func formattingLinter(doFixes bool) error {
mg.Deps(Tools)
args := []string{"run", "--no-config", "--disable-all", "--enable=gofmt", "--enable=goimports", "--enable=godot"}
if doFixes {
args = append(args, "--fix")
}
return sh.RunV("golangci-lint", args...)
}
// Style checks formatting of the file. CI will run this before acceptiing PRs.
func Style() error {
return formattingLinter(false)
}
// Fmt automatically formats all source code files.
func Fmt() error {
return formattingLinter(true)
}
func listCoverageFiles() ([]string, error) {
result := []string{}
finfos, derr := ioutil.ReadDir(coverageDir)
if derr != nil {
return result, derr
}
for _, finfo := range finfos {
result = append(result, path.Join(coverageDir, finfo.Name()))
}
return result, nil
}
// Test run test suite.
func Test() error {
mg.Deps(Tools)
// Ensure coverage directory exists
if err := os.MkdirAll(coverageDir, os.FileMode(0777)); err != nil {
return err
}
// Clean up coverage directory
coverFiles, derr := listCoverageFiles()
if derr != nil {
return derr
}
for _, coverFile := range coverFiles {
if err := sh.Rm(coverFile); err != nil {
return err
}
}
// Run tests
//coverProfiles := []string{}
for _, pkg := range goPkgs {
coverProfile := path.Join(coverageDir,
fmt.Sprintf("%s%s", strings.ReplaceAll(pkg, "/", "-"), ".out"))
testErr := sh.Run("go", "test", "-v", "-covermode", "count", fmt.Sprintf("-coverprofile=%s", coverProfile),
pkg)
if testErr != nil {
return testErr
}
//coverProfiles = append(coverProfiles, coverProfile)
}
return nil
}
// Coverage sums up the coverage profiles in .coverage. It does not clean up after itself or before.
func Coverage() error {
// Clean up coverage directory
coverFiles, derr := listCoverageFiles()
if derr != nil {
return derr
}
mergedCoverage, err := sh.Output("gocovmerge", coverFiles...)
if err != nil {
return err
}
return ioutil.WriteFile(constCoverFile, []byte(mergedCoverage), os.FileMode(0777))
}
// All runs a full suite suitable for CI
//
//nolint:unparam
func All() error {
mg.SerialDeps(Style, Lint, Test, Coverage, Release)
return nil
}
// GithubReleaseMatrix emits a line to setup build matrix jobs for release builds.
//
//nolint:unparam
func GithubReleaseMatrix() error {
output := make([]string, 0, len(platforms))
for _, platform := range platforms {
output = append(output, platform.String())
}
jsonData := must(json.Marshal(output))
fmt.Printf("::set-output name=release-matrix::%s\n", string(jsonData))
return nil
}
func makeBuilder(cmd string, platform Platform) func() error {
f := func() error {
cmdSrc := fmt.Sprintf("./%s/%s", must(filepath.Rel(curDir, cmdDir)), cmd)
Log("Make platform binary directory:", platform.PlatformDir())
if err := os.MkdirAll(platform.PlatformDir(), os.FileMode(0777)); err != nil {
return errors.Wrapf(err, "error making directory: cmd: %s", cmd)
}
Log("Checking for changes:", platform.PlatformBin(cmd))
if changed, err := target.Path(platform.PlatformBin(cmd), goSrc...); !changed {
if err != nil {
if !os.IsNotExist(err) {
return errors.Wrapf(err, "error while checking for changes: cmd: %s", cmd)
}
} else {
return nil
}
}
fmt.Println("Building", platform.PlatformBin(cmd))
return sh.RunWith(map[string]string{"CGO_ENABLED": "0", "GOOS": platform.OS, "GOARCH": platform.Arch},
"go", "build", "-a", "-ldflags", fmt.Sprintf("-buildid='' -extldflags '-static' -X %s=%s", versionSymbol(), version),
"-trimpath", "-o", platform.PlatformBin(cmd), cmdSrc)
}
return f
}
func getCurrentPlatform() *Platform {
var curPlatform *Platform
for _, p := range platforms {
if p.OS == runtime.GOOS && p.Arch == runtime.GOARCH {
storedP := p
curPlatform = &storedP
}
}
Log("Determined current platform:", curPlatform)
return curPlatform
}
// Binary build a binary for the current platform.
func Binary() error {
curPlatform := getCurrentPlatform()
if curPlatform == nil {
return errPlatformNotSupported
}
if err := ReleaseBin(curPlatform.String()); err != nil {
return err
}
buildResults := map[string]func() error{}
for _, cmd := range goCmds {
buildResults[cmd] = concurrentRun(func() error {
// Make a root symlink to the build
cmdPath := path.Join(curDir, cmd)
os.Remove(cmdPath)
if err := os.Symlink(curPlatform.PlatformBin(cmd), cmdPath); err != nil {
return err
}
return nil
})
}
return waitResults(buildResults)()
}
// doReleaseBin handles the deferred building of an actual release binary.
//
//nolint:gocritic
func doReleaseBin(OSArch string) func() error {
platform, ok := platformsLookup[OSArch]
if !ok {
return func() error { return errors.Wrapf(errPlatformNotSupported, "ReleaseBin: %s", OSArch) }
}
buildResults := map[string]func() error{}
for _, cmd := range goCmds {
buildResults[cmd] = concurrentRun(makeBuilder(cmd, platform))
}
return waitResults(buildResults)
}
// ReleaseBin builds cross-platform release binaries under the bin/ directory.
//
//nolint:gocritic
func ReleaseBin(OSArch string) error {
return doReleaseBin(OSArch)()
}
// ReleaseBinAll builds cross-platform release binaries under the bin/ directory.
func ReleaseBinAll() error {
buildResults := map[string]func() error{}
for OSArch := range platformsLookup {
buildResults[fmt.Sprintf("build-%s", OSArch)] = doReleaseBin(OSArch)
}
return waitResults(buildResults)()
}
// Release builds release archives under the release/ directory.
//
//nolint:gocritic
func doRelease(OSArch string) func() error {
platform, ok := platformsLookup[OSArch]
if !ok {
return func() error { return errors.Wrapf(errPlatformNotSupported, "ReleaseBin: %s", OSArch) }
}
return func() error {
if err := ReleaseBin(OSArch); err != nil {
return err
}
archiveCmds := map[string]func() error{}
if platform.OS == "windows" {
// build a zip binary as well
archiveName := fmt.Sprintf("%s.zip", platform.ReleaseBase())
archiveCmds[archiveName] = concurrentRun(func() error {
if _, err := os.Stat(archiveName); err == nil {
_ = os.Remove(archiveName)
}
archiveDir := path.Join(binDir, platform.ArchiveDir())
fmt.Println("Archiving", archiveName)
return archiver.NewZip().Archive([]string{archiveDir}, archiveName)
})
}
// build tar gz
archiveName := fmt.Sprintf("%s.tar.gz", platform.ReleaseBase())
archiveCmds[archiveName] = concurrentRun(func() error {
if _, err := os.Stat(archiveName); err == nil {
_ = os.Remove(archiveName)
}
archiveDir := path.Join(binDir, platform.ArchiveDir())
fmt.Println("Archiving", archiveName)
return archiver.NewTarGz().Archive([]string{archiveDir}, archiveName)
})
return waitResults(archiveCmds)()
}
}
// PlatformTargets prints the list of target platforms
func PlatformTargets() error {
platforms := make([]string, 0, len(platformsLookup))
for platform := range platformsLookup {
platforms = append(platforms, platform)
}
sort.Strings(platforms)
for _, platform := range platforms {
fmt.Println(platform)
}
return nil
}
// Release a binary archive for a specific platform
//
//nolint:gocritic
func Release(OSArch string) error {
return doRelease(OSArch)()
}
// Release builds release archives under the release/ directory.
func ReleaseAll() error {
buildResults := map[string]func() error{}
for OSArch := range platformsLookup {
buildResults[fmt.Sprintf("release-%s", OSArch)] = doRelease(OSArch)
}
return waitResults(buildResults)()
}
// Clean deletes build output and cleans up the working directory.
func Clean() error {
for _, name := range goCmds {
if err := sh.Rm(path.Join(binDir, name)); err != nil {
return err
}
}
for _, name := range outputDirs {
if err := sh.Rm(name); err != nil {
return err
}
}
return nil
}
// Debug prints the value of internal state variables
//
//nolint:unparam
func Debug() error {
fmt.Println("Source Files:", goSrc)
fmt.Println("Packages:", goPkgs)
fmt.Println("Directories:", goDirs)
fmt.Println("Command Paths:", goCmds)
fmt.Println("Output Dirs:", outputDirs)
fmt.Println("PATH:", os.Getenv("PATH"))
fmt.Println("Version:", version)
fmt.Println("Version short:", versionShort)
fmt.Println("Version symbol:", versionSymbol())
return nil
}
// Autogen configure local git repository with commit hooks.
func Autogen() error {
fmt.Println("Installing git hooks in local repository...")
for _, fname := range must(ioutil.ReadDir(gitHookDir)) {
hookName := fname.Name()
if !fname.IsDir() {
continue
}
gitHookPath := fmt.Sprintf(".git/hooks/%s", hookName)
repoHookPath := path.Join(gitHookDir, fname.Name())
scripts := []string{}
for _, scriptName := range must(ioutil.ReadDir(repoHookPath)) {
if scriptName.IsDir() {
continue
}
fullHookPath := path.Join(gitHookDir, hookName, scriptName.Name())
relHookPath := must(filepath.Rel(binRootName, fullHookPath))
scripts = append(scripts, relHookPath)
data, err := ioutil.ReadFile(gitHookPath)
if err != nil {
data = []byte("#!/bin/bash\n")
}
splitHook := strings.Split(string(data), "\n")
if strings.TrimRight(splitHook[0], " \t") != "#!/bin/bash" {
fmt.Printf("Don't know how to update your %s script.\n", hookName)
return errAutogenUnknownPreCommitScriptFormat
}
headAt := -1
tailAt := -1
for idx, line := range splitHook {
// Search until header.
if strings.TrimPrefix(line, " ") == constManagedScriptSectionHead {
if headAt != -1 {
fmt.Println("Found multiple managed script sections in ", fname.Name(), "first was at line ", headAt, "second was at line ", idx)
return errAutogenMultipleScriptSections
}
headAt = idx
continue
} else if strings.TrimPrefix(line, " ") == constManagedScriptSectionFoot {
if tailAt != -1 {
fmt.Println("Found multiple managed script sections in ", fname.Name(), "first was at line ", headAt, "second was at line ", idx)
return errAutogenMultipleScriptSections
}
tailAt = idx + 1
continue
}
}
if headAt == -1 {
headAt = 1
}
if tailAt == -1 {
tailAt = len(splitHook)
}
scriptPackage := []string{constManagedScriptSectionHead}
scriptPackage = append(scriptPackage, "# These lines were added by go run mage.go autogen.", "")
for _, scriptPath := range scripts {
scriptPackage = append(scriptPackage, fmt.Sprintf("\"./%s\" || exit $?", scriptPath))
}
scriptPackage = append(scriptPackage, "", constManagedScriptSectionFoot)
updatedScript := splitHook[:headAt]
updatedScript = append(updatedScript, scriptPackage...)
updatedScript = append(updatedScript, splitHook[tailAt:]...)
err = ioutil.WriteFile(gitHookPath, []byte(strings.Join(updatedScript, "\n")),
os.FileMode(0755))
if err != nil {
return err
}
}
}
return nil
}