/
build.go
138 lines (117 loc) · 2.72 KB
/
build.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
package common
import (
"fmt"
"io/ioutil"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/magefile/mage/sh"
"github.com/pkg/errors"
)
const (
osLinux = "linux"
osWindows = "windows"
osDarwin = "darwin"
windowsBinExtension = ".exe"
)
var (
// Architectures is a list of architectures to build binaries for.
Architectures = []string{"amd64", "arm"}
// OSList is a list of all OSes to build binaries for.
OSList = []string{osLinux, osWindows, osDarwin}
)
// BuildAll builds all binaries for all OSes and architectures.
func BuildAll(args ...string) error {
version, err := Version()
if err != nil {
return err
}
commit, err := Commit()
if err != nil {
return err
}
date := time.Now().UTC().Format(time.RFC3339)
UI.Normal().
WithStringValue("version", version).
WithStringValue("commit", commit).
WithStringValue("date", date).
Msgf("Will build all commands.")
cmds, err := ioutil.ReadDir("cmd")
if err != nil {
return errors.Wrap(err, "failed to read contents of './cmd' dir")
}
for _, c := range cmds {
if !c.IsDir() || strings.HasPrefix(c.Name(), ".") {
continue
}
for _, a := range Architectures {
for _, o := range OSList {
UI.Normal().
WithStringValue("os", o).
WithStringValue("arch", a).
WithStringValue("cmd", c.Name()).
Msg("Building.")
out := filepath.Join(cwd, "bin", fmt.Sprintf("%s-%s", o, a), c.Name())
if o == osWindows {
out += windowsBinExtension
}
err := sh.RunWithV(map[string]string{
"GOOS": o,
"GOARCH": a,
},
"go",
append(
append([]string{"build"}, args...),
[]string{"-o", out, filepath.Join(cwd, "cmd", c.Name())}...,
)...,
)
if err != nil {
return err
}
}
}
}
return nil
}
// Build builds the project.
func Build(args ...string) error {
version, err := Version()
if err != nil {
return err
}
commit, err := Commit()
if err != nil {
return err
}
date := time.Now().UTC().Format(time.RFC3339)
UI.Normal().
WithStringValue("version", version).
WithStringValue("commit", commit).
WithStringValue("date", date).
Msgf("Building.")
cmds, err := ioutil.ReadDir("cmd")
if err != nil {
return errors.Wrap(err, "failed to read contents of './cmd' dir")
}
for _, c := range cmds {
if !c.IsDir() || strings.HasPrefix(c.Name(), ".") {
continue
}
out := filepath.Join(cwd, "bin", fmt.Sprintf("%s-%s", runtime.GOOS, runtime.GOARCH), c.Name())
if runtime.GOOS == osWindows {
out += windowsBinExtension
}
err := sh.RunV(
"go",
append(
append([]string{"build"}, args...),
[]string{"-o", out, filepath.Join(cwd, "cmd", c.Name())}...,
)...,
)
if err != nil {
return err
}
}
return nil
}