Skip to content

Commit

Permalink
fix(doesCommandExist): fix to exec.Command
Browse files Browse the repository at this point in the history
based on [this lovely example](https://siongui.github.io/2018/03/16/go-check-if-command-exists/), you cannot directly call a built-in command in some systems, so you much call it in a round-about way.

This commit also changes the `TestDoesCommandExist`: it checks if the runtime os is darwin or linux before attempting to use the commands
  • Loading branch information
ramfox committed May 9, 2019
1 parent f3941ae commit 4319db3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions cmd/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func printToPager(w io.Writer, buf *bytes.Buffer) (err error) {
}
}
}
pager := exec.Command(envPager, "-R")
pager := exec.Command("/bin/sh", "-c", envPager, "-R")
pager.Stdin = buf
pager.Stdout = w
err = pager.Run()
Expand Down Expand Up @@ -239,7 +239,7 @@ func doesCommandExist(cmdName string) bool {
if cmdName == "" {
return false
}
cmd := exec.Command("command", "-v", cmdName)
cmd := exec.Command("/bin/sh", "-c", "command -v "+cmdName)
if err := cmd.Run(); err != nil {
return false
}
Expand Down
13 changes: 8 additions & 5 deletions cmd/print_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"runtime"
"testing"
)

Expand Down Expand Up @@ -29,10 +30,12 @@ func TestPrintByteInfo(t *testing.T) {
}

func TestDoesCommandExist(t *testing.T) {
if doesCommandExist("ls") == false {
t.Error("ls command does not exist!")
}
if doesCommandExist("ls111") == true {
t.Error("ls111 command should not exist!")
if runtime.GOOS == "darwin" || runtime.GOOS == "linux" {
if doesCommandExist("ls") == false {
t.Error("ls command does not exist!")
}
if doesCommandExist("ls111") == true {
t.Error("ls111 command should not exist!")
}
}
}

0 comments on commit 4319db3

Please sign in to comment.