about summary refs log tree commit diff
path: root/main.go
blob: 8ce0254fb4ee6ff31ed599484311b297416badb0 (plain)
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
package main

import (
	"bytes"
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	bflag "github.com/terinjokes/bakelite/internal/flag"
	"golang.org/x/sync/semaphore"
)

type kvs map[string]string

func (o kvs) Strings() []string {
	str := []string{}
	for k, v := range o {
		str = append(str, k+"="+v)
	}

	return str
}

var cgo bool
var ldflags string
var platformFields []string

func main() {
	flags := flag.NewFlagSet("bakelite", flag.ExitOnError)
	flags.BoolVar(&cgo, "cgo", false, "enables cgo (may require your own toolchain).")
	flags.StringVar(&ldflags, "ldflags", "", "arguments to pass on each go tool compile invocation.")
	flags.Var((*bflag.StringsValue)(&platformFields), "platforms", "modify the list of platforms built")
	flags.Usage = func() {
		fmt.Println("usage: bakelite [build flags] [packages]")
		fmt.Println(`
Bakelite compiles the packages named by the import paths for multiple GOOS and
GOARCH combinations. It does not install their results.

When compiling a package, Bakelite writes the result to output files named
after the source directory in the form "$package_$goos_$goarch". The '.exe'
suffix is added when writing a Windows executable.

Multiple packages may be given to Bakelite, the result of each are saved as
described in the preceding paragraph.

The build flags recognized by Bakelite:

	-ldflags 'flag list'
		arguments to pass on each go tool compile invocation.

The Bakelite specific flags:

	-cgo
		passes CGO_ENABLED=1 to the build environment.
		May require a build toolchain for each GOOS and GOARCH combination.
	-platforms 'platform list'
		modify the built platforms.
		Platforms are prefixed with "-" to remove from the set and "+" to add
		to the set. They can be specified sparsely as just the OS, or as a
		complete GOOS/GOARCH declaration. If the special platform "-" is
		provided as the first platform, the default set is disabled. See below
		for the default list of platforms.

By default Bakelite builds for the following platforms:

	darwin/386
	darwin/amd64
	dragonfly/amd64
	freebsd/386
	freebsd/amd64
	linux/386
	linux/amd64
	linux/ppc64
	linux/ppc64le
	linux/mips
	linux/mipsle
	linux/mips64
	linux/mips64le
	netbsd/386
	netbsd/amd64
	openbsd/386
	openbsd/amd64
	plan9/386
	plan9/amd64
	solaris/amd64
	windows/386
	windows/amd64

All the flags that take a list of arguments accept a space-separated
list of strings.

For more about specifying packages, see 'go help packages'.
For more about calling between Go and C/C++, run 'go help c'.

See also: go build, go install, go clean.
			`)
	}
	if err := flags.Parse(os.Args[1:]); err != nil {
		flags.Usage()
		os.Exit(-1)
	}

	packages := flags.Args()
	if len(packages) == 0 {
		fmt.Println("fatal: Expected at least one package.")
		os.Exit(-1)
	}

	plBuilder, _ := NewPlatformBuilder()
	if len(platformFields) > 0 && platformFields[0] == "-" {
		platformFields = platformFields[1:]
	} else {
		plBuilder = plBuilder.WithDefaults()
	}
	if len(platformFields) != 0 {
		plBuilder = parsePlatforms(plBuilder, platformFields)
	}

	platforms := plBuilder.Build()

	environ := parseEnvironment(os.Environ())

	var (
		parallelJobs = runtime.NumCPU()
		sem          = semaphore.NewWeighted(int64(parallelJobs))
		ctx          = context.Background()
	)

	fmt.Printf("info: running bakelite with %d jobs\n", parallelJobs)

	var errored bool
	for _, platform := range platforms {
		for _, pkg := range packages {
			if err := sem.Acquire(ctx, 1); err != nil {
				log.Printf("failed to acquire semaphore: %s", err)
				errored = true
				break
			}

			go func(platform Platform, pkg string) {
				defer sem.Release(1)
				err := build(ctx, environ, platform, pkg)

				if err != nil {
					errored = true
				}
			}(platform, pkg)
		}
	}

	if err := sem.Acquire(ctx, int64(parallelJobs)); err != nil {
		log.Printf("failed to acquire semaphore: %s", err)
		errored = true
	}

	if errored {
		os.Exit(1)
	}
}

func build(ctx context.Context, environ kvs, platform Platform, pkg string) error {
	name := fmt.Sprintf("%s-%s-%s", filepath.Base(pkg), platform.OS, platform.Arch)

	if platform.OS == OS_WINDOWS {
		name += ".exe"
	}

	env := kvs{}
	for key, val := range environ {
		env[key] = val
	}

	env["GOOS"] = string(platform.OS)
	env["GOARCH"] = string(platform.Arch)

	if cgo {
		env["CGO_ENABLED"] = "1"
	} else {
		env["CGO_ENABLED"] = "0"
	}

	var stdout bytes.Buffer
	var stderr bytes.Buffer

	args := []string{
		"build",
		"-o",
		name,
	}

	if ldflags != "" {
		args = append(args, "-ldflags", ldflags)
	}

	args = append(args, pkg)

	cmd := exec.CommandContext(context.Background(), "go", args...)
	cmd.Env = env.Strings()
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	fmt.Printf("info: Running build for %s @ %s/%s…\n", pkg, platform.OS, platform.Arch)
	err := cmd.Run()

	if err != nil {
		log.Printf("fatal: There was an error! goos='%s' goarch='%s' err='%s' stdout='%s' stderr='%s'", platform.OS, platform.Arch, err, stdout.String(), stderr.String())
	}

	return err
}

func parsePlatforms(plBuilder *PlatformBuilder, fields []string) *PlatformBuilder {
	for _, f := range fields {
		switch f[0] {
		case '-':
			if strings.ContainsRune(f, '/') {
				sp := strings.Split(f[1:], "/")
				p := Platform{
					OS:   OS(sp[0]),
					Arch: Arch(sp[1]),
				}

				plBuilder = plBuilder.WithoutPlatform(p)
			} else {
				plBuilder = plBuilder.WithoutOS(OS(f[1:]))
			}
		case '+':
			if strings.ContainsRune(f, '/') {
				sp := strings.Split(f[1:], "/")
				p := Platform{
					OS:   OS(sp[0]),
					Arch: Arch(sp[1]),
				}

				plBuilder = plBuilder.WithPlatform(p)
			} else {
				plBuilder = plBuilder.WithOS(OS(f[1:]))
			}
		}
	}

	return plBuilder
}

func parseEnvironment(environ []string) kvs {
	env := kvs{}
	for _, s := range environ {
		split := strings.SplitN(s, "=", 2)
		env[split[0]] = split[1]
	}

	return env
}