Skip to content

Commit

Permalink
Merge pull request mistifyio#90 from corhere/cmderror-args
Browse files Browse the repository at this point in the history
Properly substitute command path in `Run()` error
  • Loading branch information
nshalman authored May 22, 2023
2 parents 3950394 + d68a132 commit c86e2d4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
7 changes: 5 additions & 2 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ func (c *command) Run(arg ...string) ([][]string, error) {
cmd.Stderr = &stderr

id := uuid.New().String()
joinedArgs := strings.Join(cmd.Args, " ")
joinedArgs := cmd.Path
if len(cmd.Args) > 1 {
joinedArgs = strings.Join(append([]string{cmd.Path}, cmd.Args[1:]...), " ")
}

logger.Log([]string{"ID:" + id, "START", joinedArgs})
if err := cmd.Run(); err != nil {
return nil, &Error{
Err: err,
Debug: strings.Join([]string{cmd.Path, joinedArgs[1:]}, " "),
Debug: joinedArgs,
Stderr: stderr.String(),
}
}
Expand Down
33 changes: 33 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package zfs

import (
"errors"
"os/exec"
"reflect"
"testing"
)
Expand Down Expand Up @@ -36,3 +38,34 @@ func TestParseLine(t *testing.T) {
})
}
}

func TestCommandError(t *testing.T) {
cmd := &command{Command: "false"}
expectedPath, err := exec.LookPath(cmd.Command)
if err != nil {
t.Fatal(err)
}

for _, tt := range []struct {
name string
args []string
expectedDebug string
}{
{name: "NoArgs", expectedDebug: expectedPath},
{name: "WithArgs", args: []string{"foo"}, expectedDebug: expectedPath + " foo"},
} {
t.Run(tt.name, func(t *testing.T) {
_, err := cmd.Run(tt.args...)
if err == nil {
t.Fatal("command.Run: wanted error, got nil")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("command.Run (error): wanted *Error, got %T (%[1]v)", err)
}
if e.Debug != tt.expectedDebug {
t.Fatalf("command.Run (error): wanted Debug %q, got %q", tt.expectedDebug, e.Debug)
}
})
}
}

0 comments on commit c86e2d4

Please sign in to comment.