diff --git a/cli/cmd/report/report.go b/cli/cmd/report/report.go index 22ddd40..043461c 100644 --- a/cli/cmd/report/report.go +++ b/cli/cmd/report/report.go @@ -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 } @@ -33,8 +33,8 @@ 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": @@ -42,12 +42,11 @@ func setCmdByOS() (string, []string, error) { 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 @@ -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 +} diff --git a/cli/cmd/report/report_test.go b/cli/cmd/report/report_test.go new file mode 100644 index 0000000..5ffb3c6 --- /dev/null +++ b/cli/cmd/report/report_test.go @@ -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(...)