Skip to content

Commit

Permalink
fix(cli): change the setCmdByOS function to include auxiliary routine…
Browse files Browse the repository at this point in the history
…s and add test
  • Loading branch information
dudustri committed Jun 6, 2024
1 parent 476e82d commit fa369ac
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 7 deletions.
29 changes: 22 additions & 7 deletions cli/cmd/report/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var ReportCmd = &cobra.Command{
}

func openURL(url string) error {
cmd, args, err := setCmdByOS()
cmd, args, err := setCmdByOS(runtime.GOOS, isWSL)
if err != nil {
return err
}
Expand All @@ -33,21 +33,20 @@ func openURL(url string) error {
return exec.Command(cmd, args...).Start()
}

func setCmdByOS() (string, []string, error) {
switch runtime.GOOS {
func setCmdByOS(os string, wsl func() (*bool, error)) (string, []string, error) {
switch os {
case "windows":
return "cmd", []string{"/c", "start"}, nil
case "darwin":
return "open", nil, nil
case "freebsd", "openbsd", "netbsd":
return "xdg-open", nil, nil
case "linux":
out, err := exec.Command("sh", "-c", "grep -i Microsoft /proc/version").Output()
wsl, err := wsl()
if err != nil {
fmt.Println("Error:", err)
return "", nil, err
return "", nil, errors.New("unexpected linux subsystem check error")
}
if string(out) != "" {
if *wsl {
return "sensible-browser", nil, nil
} else {
return "xdg-open", nil, nil
Expand All @@ -56,3 +55,19 @@ func setCmdByOS() (string, []string, error) {
return "", nil, errors.New("it wasn't possible to identify your OS")
}
}

func isWSL() (*bool, error) {
var wsl bool
out, err := exec.Command("sh", "-c", "grep -i Windows /proc/version").Output()
if err != nil && err.Error() != "exit status 1" {
fmt.Println("Error:", err)
return nil, err
}
if len(out) != 0 {
wsl = true
} else {
wsl = false
}

return &wsl, nil
}
43 changes: 43 additions & 0 deletions cli/cmd/report/report_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package report

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestSetCmdByOS(t *testing.T) {
tests := []struct {
goos string
wsl bool
expected string
args []string
errExpected bool
}{
{"windows", false, "cmd", []string{"/c", "start"}, false},
{"darwin", false, "open", nil, false},
{"freebsd", false, "xdg-open", nil, false},
{"linux", false, "xdg-open", nil, false},
{"linux", true, "sensible-browser", nil, false},
{"unknown", false, "", nil, true},
}

for _, test := range tests {
t.Run(test.goos, func(t *testing.T) {
isWSLfake := func() (*bool, error) {
return &test.wsl, nil
}

cmd, args, err := setCmdByOS(test.goos, isWSLfake)
if test.errExpected {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, test.expected, cmd)
assert.Equal(t, test.args, args)
}
})
}
}

// TODO: test isWSL() and openURL(...)

0 comments on commit fa369ac

Please sign in to comment.