github.com/bazelbuild/bazel-watcher@v0.25.2/internal/ibazel/lifecycle_hooks/lifecycle_hooks.go (about) 1 // Copyright 2018 The Bazel Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Implements lifecycle hooks for each command execution iteration. 16 17 package lifecycle_hooks 18 19 import ( 20 "bytes" 21 "flag" 22 23 "github.com/bazelbuild/bazel-watcher/internal/ibazel/log" 24 "github.com/bazelbuild/bazel-watcher/internal/ibazel/workspace" 25 "github.com/bazelbuild/bazel-watcher/third_party/bazel/master/src/main/protobuf/blaze_query" 26 "github.com/mattn/go-shellwords" 27 ) 28 29 var ( 30 runCommandBefore = flag.String("run_command_before", "", "A command to run before each execution") 31 runCommandAfter = flag.String("run_command_after", "", "A command to run after each execution") 32 runCommandAfterSuccess = flag.String("run_command_after_success", "", "A command to run after each successful execution") 33 runCommandAfterError = flag.String("run_command_after_error", "", "A command to run after each failed execution") 34 ) 35 36 type LifecycleHooks struct { 37 w workspace.Workspace 38 } 39 40 func New() *LifecycleHooks { 41 return &LifecycleHooks{ 42 w: &workspace.MainWorkspace{}, 43 } 44 } 45 46 func (l *LifecycleHooks) Initialize(info *map[string]string) {} 47 48 func (l *LifecycleHooks) TargetDecider(rule *blaze_query.Rule) {} 49 50 func (l *LifecycleHooks) ChangeDetected(targets []string, changeType string, change string) {} 51 52 func (l *LifecycleHooks) Cleanup() {} 53 54 func (l *LifecycleHooks) BeforeCommand(targets []string, command string) { 55 l.parseAndExecuteCommand(*runCommandBefore) 56 } 57 58 func (l *LifecycleHooks) AfterCommand(targets []string, command string, success bool, output *bytes.Buffer) { 59 l.parseAndExecuteCommand(*runCommandAfter) 60 if success { 61 l.parseAndExecuteCommand(*runCommandAfterSuccess) 62 } else { 63 l.parseAndExecuteCommand(*runCommandAfterError) 64 } 65 } 66 67 func (l *LifecycleHooks) parseAndExecuteCommand(commandToRun string) { 68 if commandToRun != "" { 69 commandAndArgs, err := shellwords.Parse(commandToRun) 70 71 if err != nil { 72 log.Fatalf("Fail to run command `%s`: %v", commandToRun, err) 73 } 74 75 l.w.ExecuteCommand(commandAndArgs[0], commandAndArgs[1:]) 76 } 77 }