github.com/reconquest/executil-go@v0.0.0-20181110204642-1f5c2d67813f/error.go (about) 1 package executil 2 3 import ( 4 "fmt" 5 "os/exec" 6 7 "github.com/reconquest/karma-go" 8 ) 9 10 type CommandWithArgs interface { 11 GetArgs() []string 12 } 13 14 // Error records the actual combined output of executed command, original error 15 // and executed cmd. 16 type Error struct { 17 // RunErr is a original occurred error. 18 RunErr error 19 20 // Cmd is a original executed command. 21 // can be *exec.Command or lexec.Command 22 Cmd interface{} 23 24 // Output is a combined output of executing command. 25 Output []byte 26 } 27 28 // Error returns string representation of Error type. 29 func (err *Error) Error() string { 30 args := err.GetArgs() 31 if len(args) == 0 { 32 return err.RunErr.Error() 33 } 34 35 value := fmt.Sprintf("exec %q error (%s) ", args, err.RunErr) 36 if len(err.Output) > 0 { 37 value = value + "with output:\n" + string(err.Output) 38 } else { 39 value = value + "without output" 40 } 41 42 return value 43 } 44 45 // HierarchicalError returns hierarchical string representation using karma 46 // package. 47 func (err *Error) HierarchicalError() string { 48 args := err.GetArgs() 49 if len(args) == 0 { 50 return err.RunErr.Error() 51 } 52 53 runError := err.RunErr 54 if len(err.Output) > 0 { 55 runError = karma.Push(runError, string(err.Output)) 56 } 57 58 return karma.Format(runError, "exec %q error", args).Error() 59 } 60 61 func (err *Error) GetArgs() []string { 62 if cmd, ok := err.Cmd.(CommandWithArgs); ok { 63 return cmd.GetArgs() 64 } else if cmd, ok := err.Cmd.(*exec.Cmd); ok { 65 return cmd.Args 66 } 67 68 return []string{} 69 }