github.com/emmahsax/go-git-helper@v0.0.8-0.20240519163017-907b9de0fa52/internal/executor/executor.go (about) 1 package executor 2 3 import ( 4 "errors" 5 "os" 6 "os/exec" 7 ) 8 9 type ExecutorInterface interface { 10 Exec(execType string, command string, args ...string) ([]byte, error) 11 } 12 13 type Executor struct { 14 Args []string 15 Command string 16 Debug bool 17 } 18 19 func NewExecutor(debug bool) *Executor { 20 return &Executor{ 21 Debug: debug, 22 } 23 } 24 25 func (e *Executor) Exec(execType string, command string, args ...string) ([]byte, error) { 26 e.Command = command 27 e.Args = args 28 29 switch execType { 30 case "actionAndOutput": 31 o, e := actionAndOutput(command, args) 32 return o, e 33 case "waitAndStdout": 34 return []byte{}, waitAndStdout(command, args) 35 default: 36 return []byte{}, errors.New("invalid exec type") 37 } 38 } 39 40 func actionAndOutput(command string, args []string) ([]byte, error) { 41 cmd := exec.Command(command, args...) 42 output, err := cmd.CombinedOutput() 43 if err != nil { 44 return nil, err 45 } 46 47 return output, nil 48 } 49 50 func waitAndStdout(command string, args []string) error { 51 origStdout := os.Stdout 52 origStderr := os.Stderr 53 54 cmd := exec.Command(command, args...) 55 cmd.Stdout = os.Stdout 56 cmd.Stderr = os.Stderr 57 58 err := cmd.Start() 59 if err != nil { 60 return err 61 } 62 63 err = cmd.Wait() 64 if err != nil { 65 return err 66 } 67 68 os.Stdout = origStdout 69 os.Stderr = origStderr 70 71 return nil 72 }