-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
363 lines (304 loc) · 8.5 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
osexec "os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/hanwen/go-fuse/fuse/nodefs"
"github.com/hanwen/go-fuse/fuse/pathfs"
"github.com/linuxerwang/gobazel/conf"
"github.com/linuxerwang/gobazel/exec"
"github.com/linuxerwang/gobazel/gopathfs"
)
const (
initialConf = `gobazel {
go-path: ""
go-pkg-prefix: "test.com"
# go-ide-cmd: "/usr/bin/atom"
go-ide-cmd: "/usr/bin/code"
# go-ide-cmd: "/usr/bin/liteide"
build {
rules: [
]
ignore-dirs: [
"bazel-.*",
"third-party.*",
]
}
vendor-dirs: [
"third-party-go/vendor",
]
ignore-dirs: [
"bazel-.*",
"third-party.*",
]
fall-through-dirs: [
".vscode",
]
}
`
bzlQuery = "kind(%s, deps(%s/...))"
)
const (
gobzlPidFile = ".gobazelpid"
gobzlRcFile = ".gobazelrc"
bzlWsFile = "WORKSPACE"
)
var (
debug = flag.Bool("debug", false, "Enable debug output.")
build = flag.Bool("build", false, "Build all packages.")
daemon = flag.Bool("daemon", true, "To detach from parent process.")
detached = flag.Bool("detached", false, "The current process has been detached from parent process. Do not set it manually, it's only used by gobazel to detach itself.")
dirs gopathfs.Dirs
version string
)
func init() {
dirs = gopathfs.Dirs{}
wd, err := os.Getwd()
if err != nil {
fmt.Println("Failed to get the current working directory,", err)
os.Exit(2)
}
// The command has to be executed in a bazel workspace.
dirs.Workspace = wd
dirs.GobzlConf = filepath.Join(wd, gobzlRcFile)
dirs.GobzlPid = filepath.Join(wd, gobzlPidFile)
}
func usage() {
fmt.Println(`gobazel: A fuse mount tool for bazel to support Golang.
Usage:
gobazel [options]
OR to show its version:
gobazel version
Note:
This command has to be executed in a bazel workspace (where your WORKSPACE file reside).
Options:`)
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
for _, arg := range flag.Args() {
if strings.ToLower(arg) == "version" {
fmt.Println("Version:", version)
return
}
}
// The command has to be executed in a bazel workspace.
if _, err := os.Stat(filepath.Join(dirs.Workspace, bzlWsFile)); err != nil {
fmt.Println("Error, the command has to be run in a bazel workspace,", err)
os.Exit(2)
}
for _, arg := range flag.Args() {
if strings.ToLower(arg) == "stop" {
fmt.Printf("Stopping existing gobazel process for workspace %s.\n", dirs.Workspace)
stopExistingProcess()
return
}
}
cfg := loadConfig()
if _, err := os.Stat(filepath.Join(dirs.Workspace, gobzlPidFile)); !os.IsNotExist(err) {
fmt.Println("File .gobazelpid for another gobazel process exists. Start IDE")
startIDE(cfg)
return
}
if *daemon && !*detached {
pid, err := detach()
if err != nil {
fmt.Println(err)
os.Exit(2)
}
fmt.Printf("gobazel is running detached. To stop it, run \"kill -SIGQUIT %d\".\n", pid)
return
}
// Create a FUSE virtual file system on dirs.SrcDir.
nfs := pathfs.NewPathNodeFs(gopathfs.NewGoPathFs(*debug, cfg, &dirs), nil)
server, _, err := nodefs.MountRoot(dirs.SrcDir, nfs.Root(), nil)
if err != nil {
fmt.Printf("Mount fail: %v\n", err)
os.Exit(2)
}
fmt.Printf("Mounted bazel source folder to %s. You need to set %s as your GOPATH. \n\n Ctrl+C to exit.\n", dirs.SrcDir, cfg.GoPath)
if err := ioutil.WriteFile(filepath.Join(dirs.Workspace, gobzlPidFile), []byte(fmt.Sprintf("%d", os.Getpid())), os.ModePerm); err != nil {
fmt.Printf("Failed to write to file %s: %v\n", gobzlPidFile, err)
os.Exit(2)
}
// Handle ctl+c.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGABRT, syscall.SIGQUIT, syscall.SIGINT)
go func() {
for {
<-c
fmt.Printf("\nUnmount %s.\n", dirs.SrcDir)
if err := server.Unmount(); err != nil {
fmt.Println("Error to unmount,", err)
continue
}
os.Exit(0)
}
}()
go func() {
time.Sleep(time.Second)
// If set to build all packages.
if *build {
fmt.Println("\nBuilding all package, it may take seconds to a few minutes, depending on how many pakcages you have ...")
if cfg.Build == nil {
fmt.Println("No build config found in .gobazelrc, ignored.")
return
}
// Best effort run, errors are ignored.
bazelBuild(cfg, &dirs)
}
// If a Go IDE is specified, start it with the proper GOPATH.
if cfg.GoIdeCmd != "" {
fmt.Println("\nStarting IDE ...")
startIDE(cfg)
}
}()
server.Serve()
}
func loadConfig() *conf.GobazelConf {
// File gobazel.cfg holds configurations for gobazel.
if _, err := os.Stat(dirs.GobzlConf); err != nil {
if os.IsNotExist(err) {
if err = ioutil.WriteFile(dirs.GobzlConf, []byte(initialConf), 0644); err != nil {
fmt.Printf("Failed to create file %s, %+v.\n", dirs.GobzlConf, err)
os.Exit(2)
}
fmt.Printf("Created gobazel config file %s, please customize it and run the command again.\n", dirs.GobzlConf)
os.Exit(0)
} else {
fmt.Println(err)
}
}
cfg := conf.LoadConfig(dirs.GobzlConf)
if cfg.GoPath == "" {
fmt.Println("Error, go-path has to be set in your .gobazelrc file.")
os.Exit(2)
}
if cfg.GoPkgPrefix == "" {
fmt.Println("Error, go-pkg-prefix has to be set in your .gobazelrc file.")
os.Exit(2)
}
dirs.BinDir = filepath.Join(cfg.GoPath, "bin")
os.Mkdir(dirs.BinDir, 0755)
dirs.PkgDir = filepath.Join(cfg.GoPath, "pkg")
os.Mkdir(dirs.PkgDir, 0755)
dirs.SrcDir = filepath.Join(cfg.GoPath, "src")
os.Mkdir(dirs.SrcDir, 0755)
return cfg
}
func bazelBuild(cfg *conf.GobazelConf, dirs *gopathfs.Dirs) {
ignoreRegexes := make([]*regexp.Regexp, len(cfg.Build.Ignores))
for i, ign := range cfg.Build.Ignores {
ignoreRegexes[i] = regexp.MustCompile(ign)
}
f, err := os.Open(dirs.Workspace)
if err != nil {
fmt.Println("Failed to read workspace,", err)
os.Exit(2)
}
defer f.Close()
fis, err := f.Readdir(-1)
if err != nil {
fmt.Println("Failed to read workspace,", err)
os.Exit(2)
}
targets := map[string]struct{}{}
projects := []string{}
outterLoop:
for _, fi := range fis {
fmt.Printf("Folder %s ... ", fi.Name())
if !fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
fmt.Println("ignored.")
continue
}
for _, re := range ignoreRegexes {
if re.MatchString(fi.Name()) {
fmt.Println("ignored.")
continue outterLoop
}
}
projects = append(projects, fi.Name())
// Check if there are given bazel build targets in this directory.
cmd := [4]string{"bazel", "query", "--keep_going", ""}
for _, rule := range cfg.Build.Rules {
cmd[3] = fmt.Sprintf(bzlQuery, rule, fi.Name())
exec.RunBazelQuery(dirs.Workspace, fi.Name(), cmd[:], targets)
}
fmt.Println("done.")
}
// Execute bazel build.
for target := range targets {
exec.RunBazelBuild(dirs.Workspace, target)
}
// Run go install for all first party projects.
for _, proj := range projects {
exec.RunGoWalkInstall(cfg, dirs.Workspace, proj)
}
}
func detach() (int, error) {
cwd, err := os.Getwd()
if err != nil {
return 0, err
}
args := append(os.Args, "--detached")
cmd := osexec.Command(args[0], args[1:]...)
cmd.Dir = cwd
err = cmd.Start()
if err != nil {
return 0, err
}
pid := cmd.Process.Pid
cmd.Process.Release()
return pid, nil
}
func stopExistingProcess() {
pidFile := filepath.Join(dirs.Workspace, gobzlPidFile)
if _, err := os.Stat(pidFile); err != nil {
fmt.Printf("There is no file .gobazelpid in workspace %s.\n", dirs.Workspace)
return
}
b, err := ioutil.ReadFile(pidFile)
if err != nil {
fmt.Printf("Failed to read from .gobazelpid, %v.\n", err)
os.Exit(2)
}
pid, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 32)
if err != nil {
fmt.Printf("Invalid pid in .gobazelpid, %v.\n", string(b))
os.Exit(2)
}
p, err := os.FindProcess(int(pid))
if err != nil {
fmt.Printf("Failed to find process %d.\n", pid)
os.Remove(pidFile)
os.Exit(2)
}
if err := p.Signal(syscall.SIGQUIT); err != nil {
fmt.Printf("Failed to send SIGQUIT to process %d.\n", pid)
os.Exit(2)
}
// Check if the mount point is still mounted (only works on linux).
time.Sleep(time.Second)
if b, err := ioutil.ReadFile("/proc/mounts"); err == nil {
if idx := strings.Index(string(b), dirs.SrcDir); idx > -1 {
osexec.Command("fusermount", "-u", dirs.SrcDir).CombinedOutput()
}
}
os.Remove(pidFile)
}
func startIDE(cfg *conf.GobazelConf) {
if err := exec.RunCommand(cfg, cfg.GoIdeCmd+" "+dirs.SrcDir); err != nil {
fmt.Println("Error to run IDE, ", err)
}
}