diff --git a/pkg/util/exec/exec.go b/pkg/util/exec/exec.go index ae87a9485..58054c374 100644 --- a/pkg/util/exec/exec.go +++ b/pkg/util/exec/exec.go @@ -200,7 +200,7 @@ func (*CommandExecutor) ExecuteCommandWithOutputFile(command, outfileArg string, cmd := exec.Command(command, arg...) cmdOut, err := cmd.CombinedOutput() if err != nil { - cmdOut = []byte(fmt.Sprintf("%s. %s", string(cmdOut), string(err.(*exec.ExitError).Stderr))) + cmdOut = []byte(fmt.Sprintf("%s. %s", string(cmdOut), assertErrorType(err))) } // if there was anything that went to stdout/stderr then log it, even before we return an error if string(cmdOut) != "" { @@ -282,7 +282,7 @@ func runCommandWithOutput(cmd *exec.Cmd, combinedOutput bool) (string, error) { } else { output, err = cmd.Output() if err != nil { - output = []byte(fmt.Sprintf("%s. %s", string(output), string(err.(*exec.ExitError).Stderr))) + output = []byte(fmt.Sprintf("%s. %s", string(output), assertErrorType(err))) } } @@ -298,3 +298,14 @@ func runCommandWithOutput(cmd *exec.Cmd, combinedOutput bool) (string, error) { func logCommand(command string, arg ...string) { logger.Debugf("Running command: %s %s", command, strings.Join(arg, " ")) } + +func assertErrorType(err error) string { + switch errType := err.(type) { + case *exec.ExitError: + return string(errType.Stderr) + case *exec.Error: + return errType.Error() + } + + return "" +} diff --git a/pkg/util/exec/exec_test.go b/pkg/util/exec/exec_test.go new file mode 100644 index 000000000..dd948d0d4 --- /dev/null +++ b/pkg/util/exec/exec_test.go @@ -0,0 +1,45 @@ +/* +Copyright 2020 The Rook 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 exec + +import ( + "errors" + "os/exec" + "testing" +) + +func Test_assertErrorType(t *testing.T) { + type args struct { + err error + } + tests := []struct { + name string + args args + want string + }{ + {"unknown error type", args{err: errors.New("i don't know this error")}, ""}, + {"exec.exitError type", args{err: &exec.ExitError{Stderr: []byte("this is an error")}}, "this is an error"}, + {"exec.Error type", args{err: &exec.Error{Name: "my error", Err: errors.New("this is an error")}}, "exec: \"my error\": this is an error"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := assertErrorType(tt.args.err); got != tt.want { + t.Errorf("assertErrorType() = %v, want %v", got, tt.want) + } + }) + } +}