-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathibazel.go
599 lines (509 loc) · 15.9 KB
/
ibazel.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
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ibazel
import (
"bytes"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/bazelbuild/bazel-watcher/internal/bazel"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/command"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/fswatcher"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/fswatcher/common"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/lifecycle_hooks"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/live_reload"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/log"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/output_runner"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/profiler"
"github.com/bazelbuild/bazel-watcher/internal/ibazel/workspace"
"github.com/bazelbuild/bazel-watcher/third_party/bazel/master/src/main/protobuf/blaze_query"
)
var osExit = os.Exit
var bazelNew = bazel.New
var commandDefaultCommand = command.DefaultCommand
var commandNotifyCommand = command.NotifyCommand
var exitMessages = map[os.Signal]string{
syscall.SIGINT: "Subprocess killed from getting SIGINT (trigger SIGINT again to stop ibazel)",
syscall.SIGTERM: "Subprocess killed from getting SIGTERM",
syscall.SIGHUP: "Subprocess killed from getting SIGHUP",
}
type State string
type runnableCommand func(...string) (*bytes.Buffer, error)
const (
DEBOUNCE_QUERY State = "DEBOUNCE_QUERY"
QUERY State = "QUERY"
WAIT State = "WAIT"
DEBOUNCE_RUN State = "DEBOUNCE_RUN"
RUN State = "RUN"
QUIT State = "QUIT"
)
const sourceQuery = "kind('source file', deps(set(%s)))"
const buildQuery = "buildfiles(deps(set(%s)))"
type IBazel struct {
debounceDuration time.Duration
cmd command.Command
args []string
bazelArgs []string
startupArgs []string
sigs chan os.Signal // Signals channel for the current process
interruptCount int
workspaceFinder workspace.Workspace
buildFileWatcher common.Watcher
sourceFileWatcher common.Watcher
filesWatched map[common.Watcher]map[string]struct{} // Inner map is a surrogate for a set
lifecycleListeners []Lifecycle
state State
}
func New(version string) (*IBazel, error) {
i := &IBazel{}
err := i.setup()
if err != nil {
return nil, err
}
i.debounceDuration = 100 * time.Millisecond
i.filesWatched = map[common.Watcher]map[string]struct{}{}
i.workspaceFinder = &workspace.MainWorkspace{}
i.sigs = make(chan os.Signal, 1)
signal.Notify(i.sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
liveReload := live_reload.New()
profiler := profiler.New(version)
outputRunner := output_runner.New()
lifecycleHooks := lifecycle_hooks.New()
liveReload.AddEventsListener(profiler)
i.lifecycleListeners = []Lifecycle{
liveReload,
profiler,
outputRunner,
lifecycleHooks,
}
info, _ := i.getInfo()
for _, l := range i.lifecycleListeners {
l.Initialize(&info)
}
go func() {
for {
i.handleSignals()
}
}()
return i, nil
}
func (i *IBazel) handleSignals() {
// Got an OS signal (SIGINT, SIGTERM, SIGHUP).
sig := <-i.sigs
if i.cmd == nil || !i.cmd.IsSubprocessRunning() {
osExit(3)
return
}
switch sig {
case syscall.SIGINT:
i.interruptCount++
switch {
case i.interruptCount > 2:
log.NewLine()
log.Fatal("Exiting from getting SIGINT 3 times")
osExit(3)
case i.interruptCount > 1:
i.cmd.Kill()
default:
go func() {
i.cmd.Terminate()
log.NewLine()
log.Log(exitMessages[sig])
}()
}
case syscall.SIGTERM, syscall.SIGHUP:
go func() {
i.cmd.Terminate()
log.NewLine()
log.Log(exitMessages[sig])
osExit(3)
}()
default:
log.Fatal("Got a signal that wasn't handled. Please file a bug against bazel-watcher that describes how you did this. This is a big problem.")
}
}
func (i *IBazel) newBazel() bazel.Bazel {
b := bazelNew()
b.SetStartupArgs(i.startupArgs)
b.SetArguments(i.bazelArgs)
return b
}
func (i *IBazel) SetBazelArgs(args []string) {
i.bazelArgs = args
}
func (i *IBazel) SetStartupArgs(args []string) {
i.startupArgs = args
}
func (i *IBazel) SetDebounceDuration(debounceDuration time.Duration) {
i.debounceDuration = debounceDuration
}
func (i *IBazel) Cleanup() {
i.buildFileWatcher.Close()
i.sourceFileWatcher.Close()
for _, l := range i.lifecycleListeners {
l.Cleanup()
}
}
func (i *IBazel) targetDecider(target string, rule *blaze_query.Rule) {
for _, l := range i.lifecycleListeners {
// TODO: As the name implies, it would be good to use this to make a
// determination about if future events should be routed to this listener.
// Why not do it now?
// Right now I don't track which file is associated with the end target. I
// just query for a list of all files that are rdeps of any target that is
// in the list of targets to build/test/run (although run can only have 1).
// Since I don't have that mapping right now the information doesn't
// presently exist to implement this properly. Additionally, since querying
// is currently in the critical path for getting something the user cares
// about on screen, I'm not sure that it is wise to do this in the first
// pass. It might be worth triggering the user action, launching their thing
// and then running a background thread to access the data.
l.TargetDecider(rule)
}
}
func (i *IBazel) changeDetected(targets []string, changeType string, change string) {
for _, l := range i.lifecycleListeners {
l.ChangeDetected(targets, changeType, change)
}
}
func (i *IBazel) beforeCommand(targets []string, command string) {
for _, l := range i.lifecycleListeners {
l.BeforeCommand(targets, command)
}
}
func (i *IBazel) afterCommand(targets []string, command string, success bool, output *bytes.Buffer) {
for _, l := range i.lifecycleListeners {
l.AfterCommand(targets, command, success, output)
}
}
func (i *IBazel) setup() error {
var err error
// Even though we are going to recreate this when the query happens, create
// the pointer we will use to refer to the watchers right now.
i.buildFileWatcher, err = fswatcher.NewWatcher()
if err != nil {
return err
}
i.sourceFileWatcher, err = fswatcher.NewWatcher()
if err != nil {
return err
}
return nil
}
// Run the specified target (singular) in the IBazel loop.
func (i *IBazel) Run(target string, args []string) error {
i.args = args
return i.loop("run", i.run, []string{target})
}
// Build the specified targets in the IBazel loop.
func (i *IBazel) Build(targets ...string) error {
return i.loop("build", i.build, targets)
}
// Test the specified targets in the IBazel loop.
func (i *IBazel) Test(targets ...string) error {
return i.loop("test", i.test, targets)
}
// Get code coverage for the specified targets in the IBazel loop.
func (i *IBazel) Coverage(targets ...string) error {
return i.loop("coverage", i.test, targets)
}
func (i *IBazel) loop(command string, commandToRun runnableCommand, targets []string) error {
joinedTargets := strings.Join(targets, " ")
i.state = QUERY
for {
i.iteration(command, commandToRun, targets, joinedTargets)
}
}
// fsnotify also triggers for file stat and read operations. Explicitly filter the modifying events
// to avoid triggering builds on file accesses (e.g. due to your IDE checking modified status).
const modifyingEvents = common.Write | common.Create | common.Rename | common.Remove
func (i *IBazel) iteration(command string, commandToRun runnableCommand, targets []string, joinedTargets string) {
switch i.state {
case WAIT:
select {
case e := <-i.sourceFileWatcher.Events():
if _, ok := i.filesWatched[i.sourceFileWatcher][e.Name]; ok && e.Op&modifyingEvents != 0 {
log.Logf("Changed: %q. Rebuilding...", e.Name)
i.changeDetected(targets, "source", e.Name)
i.state = DEBOUNCE_RUN
}
case e := <-i.buildFileWatcher.Events():
if _, ok := i.filesWatched[i.buildFileWatcher][e.Name]; ok && e.Op&modifyingEvents != 0 {
log.Logf("Build graph changed: %q. Requerying...", e.Name)
i.changeDetected(targets, "graph", e.Name)
i.state = DEBOUNCE_QUERY
}
}
case DEBOUNCE_QUERY:
select {
case e := <-i.buildFileWatcher.Events():
if _, ok := i.filesWatched[i.buildFileWatcher][e.Name]; ok && e.Op&modifyingEvents != 0 {
i.changeDetected(targets, "graph", e.Name)
}
i.state = DEBOUNCE_QUERY
case <-time.After(i.debounceDuration):
i.state = QUERY
}
case QUERY:
// Query for which files to watch.
log.Logf("Querying for files to watch...")
i.watchFiles(fmt.Sprintf(buildQuery, joinedTargets), i.buildFileWatcher)
i.watchFiles(fmt.Sprintf(sourceQuery, joinedTargets), i.sourceFileWatcher)
i.state = RUN
case DEBOUNCE_RUN:
select {
case e := <-i.sourceFileWatcher.Events():
if _, ok := i.filesWatched[i.sourceFileWatcher][e.Name]; ok && e.Op&modifyingEvents != 0 {
i.changeDetected(targets, "source", e.Name)
}
i.state = DEBOUNCE_RUN
case <-time.After(i.debounceDuration):
i.state = RUN
}
case RUN:
log.Logf("%s %s", strings.Title(verb(command)), joinedTargets)
i.beforeCommand(targets, command)
outputBuffer, err := commandToRun(targets...)
i.interruptCount = 0
i.afterCommand(targets, command, err == nil, outputBuffer)
i.state = WAIT
}
}
func verb(s string) string {
switch s {
case "run":
return "running"
default:
return fmt.Sprintf("%sing", s)
}
}
func (i *IBazel) build(targets ...string) (*bytes.Buffer, error) {
b := i.newBazel()
b.Cancel()
b.WriteToStderr(true)
b.WriteToStdout(true)
outputBuffer, err := b.Build(targets...)
if err != nil {
log.Errorf("Build error: %v", err)
return outputBuffer, err
}
return outputBuffer, nil
}
func (i *IBazel) test(targets ...string) (*bytes.Buffer, error) {
b := i.newBazel()
// Query the provided target patterns to construct a composite list
// Make a set that represents all the found rules.
targetRules := map[string]struct{}{}
for _, target := range targets {
rule, err := i.queryRule(target)
if err != nil {
log.Errorf("Error: %v", err)
}
targetRules[rule.GetName()] = struct{}{}
}
if len(targetRules) == 1 {
setStream := true
for _, arg := range b.Args() {
if strings.HasPrefix(arg, "--test_output=") {
setStream = false
}
}
if setStream {
log.Log("Found a single target test. Streaming results. You can override this by explicitly passing --test_output=summary")
b.SetArguments(append([]string{"--test_output=streamed"}, b.Args()...))
}
}
b.Cancel()
b.WriteToStderr(true)
b.WriteToStdout(true)
outputBuffer, err := b.Test(targets...)
if err != nil {
log.Errorf("Build error: %v", err)
return outputBuffer, err
}
return outputBuffer, err
}
func contains(l []string, e string) bool {
for _, i := range l {
if i == e {
return true
}
}
return false
}
func (i *IBazel) setupRun(target string) command.Command {
rule, err := i.queryRule(target)
if err != nil {
log.Errorf("Error: %v", err)
}
i.targetDecider(target, rule)
commandNotify := false
for _, attr := range rule.Attribute {
if *attr.Name == "tags" && *attr.Type == blaze_query.Attribute_STRING_LIST {
if contains(attr.StringListValue, "ibazel_notify_changes") {
commandNotify = true
}
}
}
if commandNotify {
log.Logf("Launching with notifications")
return commandNotifyCommand(i.startupArgs, i.bazelArgs, target, i.args)
} else {
return commandDefaultCommand(i.startupArgs, i.bazelArgs, target, i.args)
}
}
func (i *IBazel) run(targets ...string) (*bytes.Buffer, error) {
if i.cmd == nil {
// If the command is empty, we are in our first pass through the state
// machine and we need to make a command object.
i.cmd = i.setupRun(targets[0])
outputBuffer, err := i.cmd.Start()
if err != nil {
log.Errorf("Run start failed %v", err)
}
return outputBuffer, err
}
log.Logf("Notifying of changes")
outputBuffer := i.cmd.NotifyOfChanges()
return outputBuffer, nil
}
func (i *IBazel) queryRule(rule string) (*blaze_query.Rule, error) {
b := i.newBazel()
b.WriteToStderr(false)
b.WriteToStdout(false)
res, err := b.CQuery(i.cQueryArgs(rule)...)
if err != nil {
log.Errorf("Error running Bazel %v", err)
osExit(4)
}
for _, target := range res.Results {
switch *target.Target.Type {
case blaze_query.Target_RULE:
return target.Target.Rule, nil
}
}
return nil, errors.New("No information available")
}
func (i *IBazel) getInfo() (map[string]string, error) {
b := i.newBazel()
res, err := b.Info()
if err != nil {
log.Errorf("Error getting Bazel info %v", err)
return nil, err
}
return res, nil
}
func (i *IBazel) queryForSourceFiles(query string) ([]string, error) {
b := i.newBazel()
localRepositories, err := i.realLocalRepositoryPaths()
if err != nil {
return nil, err
}
res, err := b.Query(i.queryArgs(query)...)
if err != nil {
log.Errorf("Bazel query failed: %v", err)
return nil, err
}
workspacePath, err := i.workspaceFinder.FindWorkspace()
if err != nil {
log.Errorf("Error finding workspace: %v", err)
return nil, err
}
toWatch := make([]string, 0, len(res.GetTarget()))
for _, target := range res.GetTarget() {
switch *target.Type {
case blaze_query.Target_SOURCE_FILE:
label := target.GetSourceFile().GetName()
if strings.HasPrefix(label, "@") {
repo, target := parseTarget(label)
if realPath, ok := localRepositories[repo]; ok {
label = strings.Replace(target, ":", string(filepath.Separator), 1)
toWatch = append(toWatch, filepath.Join(realPath, label))
break
}
continue
}
if strings.HasPrefix(label, "//external") {
continue
}
label = strings.Replace(strings.TrimPrefix(label, "//"), ":", string(filepath.Separator), 1)
toWatch = append(toWatch, filepath.Join(workspacePath, label))
break
default:
log.Errorf("%v\n", target)
}
}
return toWatch, nil
}
func (i *IBazel) watchFiles(query string, watcher common.Watcher) {
toWatch, err := i.queryForSourceFiles(query)
if err != nil {
// If the query fails, just keep watching the same files as before
log.Errorf("Error querying for source files: %v", err)
return
}
filesWatched := map[string]struct{}{}
uniqueDirectories := map[string]struct{}{}
for _, file := range toWatch {
if _, err := os.Stat(file); !os.IsNotExist(err) {
filesWatched[file] = struct{}{}
}
parentDirectory, _ := filepath.Split(file)
// Add a watch to the file's parent directory, we might already have this dir in our set but thats OK
uniqueDirectories[parentDirectory] = struct{}{}
}
watchList := keys(uniqueDirectories)
err = watcher.UpdateAll(watchList)
if err != nil {
log.Errorf("Error(s) updating watch list:\n %v", err)
}
if len(filesWatched) == 0 {
log.Errorf("Didn't find any files to watch from query %s", query)
}
i.filesWatched[watcher] = filesWatched
}
func (i *IBazel) queryArgs(args ...string) []string {
queryArgs := append([]string(nil), args...)
for _, arg := range i.bazelArgs {
// List of args that should be passed to bazel query/cquery.
if strings.HasPrefix(arg, "--override_repository=") {
queryArgs = append(queryArgs, arg)
}
}
return queryArgs
}
func (i *IBazel) cQueryArgs(args ...string) []string {
// Unlike query, cquery can be affected by the majority of command line option.
cQueryArgs := append([]string(nil), args...)
cQueryArgs = append(cQueryArgs, i.bazelArgs...)
return cQueryArgs
}
func parseTarget(label string) (repo string, target string) {
parts := strings.Split(strings.TrimPrefix(label, "@"), "//")
return parts[0], parts[1]
}
func keys(m map[string]struct{}) []string {
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys
}