Skip to content

Commit

Permalink
no shell call on single command exec on *nix
Browse files Browse the repository at this point in the history
Instead of always using `sh -c` to run command lines on *nix check if it
is a single command (no spaces) and, if so, run that command directly.

This will give users on systems without 'sh' a way to run their commands.

Fixes #1508
  • Loading branch information
eikenb committed Aug 30, 2021
1 parent 78eedd3 commit 4859b68
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 8 deletions.
26 changes: 24 additions & 2 deletions manager/command-prep.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,33 @@

package manager

import (
"os/exec"
"strings"
)

func prepCommand(command string) ([]string, error) {
if len(command) == 0 {
switch len(strings.Fields(command)) {
case 0:
return []string{}, nil
case 1:
return []string{command}, nil
}

// default to 'sh' on path, else try a couple common absolute paths
shell := "sh"
if _, err := exec.LookPath(shell); err != nil {
for _, sh := range []string{"/bin/sh", "/usr/bin/sh"} {
if sh, err := exec.LookPath(sh); err == nil {
shell = sh
break
}
}
}
if shell == "" {
return []string{}, exec.ErrNotFound
}

cmd := []string{"sh", "-c", command}
cmd := []string{shell, "-c", command}
return cmd, nil
}
10 changes: 5 additions & 5 deletions manager/command-prep_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import (
)

func prepCommand(command string) ([]string, error) {
switch {
case len(command) == 0:
switch len(strings.Fields(command)) {
case 0:
return []string{}, nil
case len(strings.Fields(command)) > 1:
return []string{}, fmt.Errorf("only single commands supported on windows")
case 1:
return []string{command}, nil
}
return []string{command}, nil
return []string{}, fmt.Errorf("only single commands supported on windows")
}
20 changes: 19 additions & 1 deletion manager/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -1118,7 +1120,7 @@ func TestRunner_command(t *testing.T) {
{
name: "single",
input: "echo",
parsed: []string{"sh", "-c", "echo"},
parsed: []string{"echo"},
out: "\n",
},
{
Expand Down Expand Up @@ -1209,3 +1211,19 @@ func TestRunner_command(t *testing.T) {
})
}
}

func TestRunner_commandPath(t *testing.T) {
PATH := os.Getenv("PATH")
defer os.Setenv("PATH", PATH)
os.Setenv("PATH", "")
cmd, err := prepCommand("echo hi")
if err != nil && err != exec.ErrNotFound {
t.Fatal(err)
}
if len(cmd) != 3 {
t.Fatalf("unexpected command: %#v\n", cmd)
}
if filepath.Base(cmd[0]) != "sh" {
t.Fatalf("unexpected shell: %#v\n", cmd)
}
}

0 comments on commit 4859b68

Please sign in to comment.