forked from constabulary/gb
/
main.go
216 lines (181 loc) · 5.02 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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/constabulary/gb"
"github.com/constabulary/gb/cmd"
"github.com/constabulary/gb/cmd/gb/internal/match"
"github.com/constabulary/gb/internal/debug"
)
var (
fs = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
cwd string
)
const (
// disable to keep working directory
destroyContext = true
)
func init() {
fs.StringVar(&cwd, "R", cmd.MustGetwd(), "set the project root") // actually the working directory to start the project root search
fs.Usage = usage
}
var commands = make(map[string]*cmd.Command)
// registerCommand registers a command for main.
// registerCommand should only be called from init().
func registerCommand(command *cmd.Command) {
setCommandDefaults(command)
commands[command.Name] = command
}
// atExit functions are called in sequence at the exit of the program.
var atExit []func() error
// exit runs all atExit functions, then calls os.Exit(code).
func exit(code int) {
for _, fn := range atExit {
fn()
}
os.Exit(code)
}
func fatalf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", args...)
exit(1)
}
func main() {
args := os.Args
if len(args) < 2 || args[1] == "-h" {
fs.Usage() // usage calles exit(2)
}
name := args[1]
if name == "help" {
help(args[2:])
exit(0)
}
command := lookupCommand(name)
// add extra flags if necessary
command.AddFlags(fs)
// parse 'em
err := command.FlagParse(fs, args)
if err != nil {
fatalf("could not parse flags: %v", err)
}
// reset args to the leftovers from fs.Parse
args = fs.Args()
// if this is the plugin command, ensure the name of the
// plugin is first in the list of arguments.
if command == commands["plugin"] {
args = append([]string{name}, args...)
}
// if cwd was passed in via -R, make sure it is absolute
cwd, err := filepath.Abs(cwd)
if err != nil {
fatalf("could not make project root absolute: %v", err)
}
// construct a project context at the current working directory.
ctx, err := newContext(cwd)
if err != nil {
fatalf("unable to construct context: %v", err)
}
// unless the command wants to handle its own arguments, process
// arguments into import paths.
if !command.SkipParseArgs {
srcdir := filepath.Join(ctx.Projectdir(), "src")
for _, a := range args {
// support the "all" build alias. This used to be handled
// in match.ImportPaths, but that's too messy, so if "all"
// is present in the args, replace it with "..." and set cwd
// to srcdir.
if a == "all" {
args = []string{"..."}
cwd = srcdir
break
}
}
args = match.ImportPaths(srcdir, cwd, args)
}
debug.Debugf("args: %v", args)
if destroyContext {
atExit = append(atExit, ctx.Destroy)
}
// add additional paths from the depfile
addDepfileDeps(ctx)
if err := command.Run(ctx, args); err != nil {
fatalf("command %q failed: %v", name, err)
}
exit(0)
}
func lookupCommand(name string) *cmd.Command {
command, ok := commands[name]
if (command != nil && !command.Runnable()) || !ok {
plugin, err := lookupPlugin(name)
if err != nil {
fmt.Fprintf(os.Stderr, "FATAL: unknown command %q\n", name)
fs.Usage() // usage calles exit(2)
}
command = &cmd.Command{
Run: func(ctx *gb.Context, args []string) error {
args = append([]string{plugin}, args...)
env := cmd.MergeEnv(os.Environ(), map[string]string{
"GB_PROJECT_DIR": ctx.Projectdir(),
})
cmd := exec.Cmd{
Path: plugin,
Args: args,
Env: env,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
return cmd.Run()
},
// plugin should not interpret arguments
SkipParseArgs: true,
}
}
setCommandDefaults(command)
return command
}
func setCommandDefaults(command *cmd.Command) {
// add a dummy default AddFlags field if none provided.
if command.AddFlags == nil {
command.AddFlags = func(*flag.FlagSet) {}
}
// add the default flag parsing if not overrriden.
if command.FlagParse == nil {
command.FlagParse = func(fs *flag.FlagSet, args []string) error {
return fs.Parse(args[2:])
}
}
}
func newContext(cwd string) (*gb.Context, error) {
return cmd.NewContext(
cwd, // project root
gb.GcToolchain(),
gb.Gcflags(gcflags...),
gb.Ldflags(ldflags...),
gb.Tags(buildtags...),
func(c *gb.Context) error {
if !race {
return nil
}
// check this is a supported platform
if runtime.GOARCH != "amd64" {
fatalf("race detector not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
}
switch runtime.GOOS {
case "linux", "windows", "darwin", "freebsd":
// supported
default:
fatalf("race detector not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// check the race runtime is built
_, err := os.Stat(filepath.Join(runtime.GOROOT(), "pkg", fmt.Sprintf("%s_%s_race", runtime.GOOS, runtime.GOARCH), "runtime.a"))
if os.IsNotExist(err) || err != nil {
fatalf("go installation at %s is missing race support. See https://getgb.io/faq/#missing-race-support", runtime.GOROOT())
}
return gb.WithRace(c)
},
)
}