github.com/xgoffin/jenkins-library@v1.154.0/cmd/shellExecute.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os/exec" 6 7 "github.com/pkg/errors" 8 9 "github.com/SAP/jenkins-library/pkg/command" 10 "github.com/SAP/jenkins-library/pkg/log" 11 "github.com/SAP/jenkins-library/pkg/piperutils" 12 "github.com/SAP/jenkins-library/pkg/telemetry" 13 ) 14 15 type shellExecuteUtils interface { 16 command.ExecRunner 17 piperutils.FileUtils 18 } 19 20 type shellExecuteUtilsBundle struct { 21 *command.Command 22 *piperutils.Files 23 } 24 25 func newShellExecuteUtils() shellExecuteUtils { 26 utils := shellExecuteUtilsBundle{ 27 Command: &command.Command{}, 28 Files: &piperutils.Files{}, 29 } 30 utils.Stdout(log.Writer()) 31 utils.Stderr(log.Writer()) 32 return &utils 33 } 34 35 func shellExecute(config shellExecuteOptions, telemetryData *telemetry.CustomData) { 36 utils := newShellExecuteUtils() 37 38 err := runShellExecute(&config, telemetryData, utils) 39 if err != nil { 40 log.Entry().WithError(err).Fatal("step execution failed") 41 } 42 } 43 44 func runShellExecute(config *shellExecuteOptions, telemetryData *telemetry.CustomData, utils shellExecuteUtils) error { 45 // check input data 46 // example for script: sources: ["./script.sh"] 47 for _, source := range config.Sources { 48 // check if the script is physically present 49 exists, err := utils.FileExists(source) 50 if err != nil { 51 log.Entry().WithError(err).Error("failed to check for defined script") 52 return fmt.Errorf("failed to check for defined script: %w", err) 53 } 54 if !exists { 55 log.Entry().WithError(err).Errorf("the script '%v' could not be found: %v", source, err) 56 return fmt.Errorf("the script '%v' could not be found", source) 57 } 58 log.Entry().Info("starting running script:", source) 59 err = utils.RunExecutable(source) 60 if err != nil { 61 log.Entry().Errorln("starting running script:", source) 62 } 63 // handle exit code 64 if ee, ok := err.(*exec.ExitError); ok { 65 switch ee.ExitCode() { 66 case 0: 67 // success 68 return nil 69 case 1: 70 return errors.Wrap(err, "an error occurred while executing the script") 71 default: 72 // exit code 2 or >2 - unstable 73 return errors.Wrap(err, "script execution unstable or something went wrong") 74 } 75 } else if err != nil { 76 return errors.Wrap(err, "script execution error occurred") 77 } 78 } 79 80 return nil 81 }