diff options
author | Mike JS. Choi <mkchoi212@icloud.com> | 2017-12-31 14:37:50 -0600 |
---|---|---|
committer | Mike JS. Choi <mkchoi212@icloud.com> | 2017-12-31 14:37:50 -0600 |
commit | 4ee25ece549ff1d56fe38feeac5a3f78b78cc630 (patch) | |
tree | c63495d845e97307dc6f22ffe511c69f9ab328e6 | |
parent | 7456d0a07fe50a47a30fff35af82ee099766df74 (diff) |
Add command file to handle os.Exec related functions
-rw-r--r-- | command.go | 43 | ||||
-rw-r--r-- | git.go | 8 |
2 files changed, 49 insertions, 2 deletions
diff --git a/command.go b/command.go new file mode 100644 index 0000000..009f620 --- /dev/null +++ b/command.go @@ -0,0 +1,43 @@ +package main + +import ( + "bytes" + "os/exec" + "syscall" +) + +// RunCommand runs the given command with arguemtns and returns the output +// Refer to https://stackoverflow.com/questions/10385551/get-exit-code-go +func RunCommand(name string, dir string, args ...string) (stdout string, stderr string, exitCode int) { + var outbuf, errbuf bytes.Buffer + cmd := exec.Command(name, args...) + cmd.Dir = dir + cmd.Stdout = &outbuf + cmd.Stderr = &errbuf + + err := cmd.Run() + stdout = outbuf.String() + stderr = errbuf.String() + + if err != nil { + // try to get the exit code + if exitError, ok := err.(*exec.ExitError); ok { + ws := exitError.Sys().(syscall.WaitStatus) + exitCode = ws.ExitStatus() + } else { + // This will happen (in OSX) if `name` is not available in $PATH, + // in this situation, exit code could not be get, and stderr will be + // empty string very likely, so we use the default fail code, and format err + // to string and set to stderr + exitCode = 1 + if stderr == "" { + stderr = err.Error() + } + } + } else { + // success, exitCode should be 0 if go is ok + ws := cmd.ProcessState.Sys().(syscall.WaitStatus) + exitCode = ws.ExitStatus() + } + return +} @@ -6,13 +6,17 @@ import ( "syscall" ) -func RunCommand(name string, dir string, args ...string) (stderr string, exitCode int) { - var errbuf bytes.Buffer +// RunCommand runs the given command with arguemtns and returns the output +// Refer to https://stackoverflow.com/questions/10385551/get-exit-code-go +func RunCommand(name string, dir string, args ...string) (stdout string, stderr string, exitCode int) { + var outbuf, errbuf bytes.Buffer cmd := exec.Command(name, args...) cmd.Dir = dir + cmd.Stdout = &outbuf cmd.Stderr = &errbuf err := cmd.Run() + stdout = outbuf.String() stderr = errbuf.String() if err != nil { |