Adds stderr and returns exit status of the cmd executed (#2361)

Fixes #2351
This commit is contained in:
ebozduman
2018-01-23 13:17:47 +05:30
committed by Nitish Tiwari
parent 8fbbd0ee83
commit 83bb797389
3 changed files with 58 additions and 3 deletions
+1
View File
@@ -214,6 +214,7 @@ type findContext struct {
func mainFind(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
checkFindSyntax(ctx)
+18 -2
View File
@@ -98,6 +98,18 @@ func regexMatch(pattern, path string) bool {
return matched
}
func getExitStatus(err error) int {
if err == nil {
return 0
}
if pe, ok := err.(*exec.ExitError); ok {
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
return es.ExitStatus()
}
}
return 1
}
// execFind executes the input command line, additionally formats input
// for the command line in accordance with subsititution arguments.
func execFind(command string) {
@@ -105,11 +117,15 @@ func execFind(command string) {
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
console.Fatalln(err)
console.Print(console.Colorize("FindExecErr", stderr.String()))
// Return exit status of the command run
os.Exit(getExitStatus(err))
}
console.Print(out.String())
console.PrintC(out.String())
}
// watchFind - enables listening on the input path, listens for all file/object
+39 -1
View File
@@ -17,6 +17,8 @@
package cmd
import (
"os/exec"
"strings"
"testing"
"time"
)
@@ -386,7 +388,7 @@ func TestParseTime(t *testing.T) {
}
}
// Tests string substritution function.
// Tests string substitution function.
func TestStringReplace(t *testing.T) {
testCases := []struct {
str string
@@ -465,3 +467,39 @@ func TestStringReplace(t *testing.T) {
}
}
}
// Tests exit status, getExitStatus() function
func TestGetExitStatus(t *testing.T) {
testCases := []struct {
command string
expectedExitStatus int
}{
// Tests "No such file or directory", exit status code 2
{
command: "ls asdf",
expectedExitStatus: 2,
},
{
command: "cp x x",
expectedExitStatus: 1,
},
// expectedExitStatus for "command not found" case is 127,
// but exec command cannot capture anything since a process
// for the command could not be started at all,
// so the expectedExitStatus is 1
{
command: "asdf",
expectedExitStatus: 1,
},
}
for i, testCase := range testCases {
commandArgs := strings.Split(testCase.command, " ")
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
// Return exit status of the command run
exitStatus := getExitStatus(cmd.Run())
if exitStatus != testCase.expectedExitStatus {
t.Errorf("Test %d: Expected error status code for command \"%v\" is %v, got %v",
i+1, testCase.command, testCase.expectedExitStatus, exitStatus)
}
}
}