Skip to content

Commit

Permalink
Merge pull request cli#1708 from cli/wsl-detection
Browse files Browse the repository at this point in the history
Fallback browser when `xdg-open` does not exist
  • Loading branch information
mislav authored Sep 16, 2020
2 parents 3049db6 + 9058fee commit cd32ef8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
18 changes: 17 additions & 1 deletion pkg/browser/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func ForOS(goos, url string) *exec.Cmd {
r := strings.NewReplacer("&", "^&")
args = append(args, "/c", "start", r.Replace(url))
default:
exe = "xdg-open"
exe = linuxExe()
args = append(args, url)
}

Expand All @@ -51,3 +51,19 @@ func FromLauncher(launcher, url string) (*exec.Cmd, error) {
cmd.Stderr = os.Stderr
return cmd, nil
}

func linuxExe() string {
exe := "xdg-open"

_, err := lookPath(exe)
if err != nil {
_, err := lookPath("wslview")
if err == nil {
exe = "wslview"
}
}

return exe
}

var lookPath = exec.LookPath
20 changes: 20 additions & 0 deletions pkg/browser/browser_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package browser

import (
"errors"
"reflect"
"testing"
)
Expand All @@ -13,6 +14,7 @@ func TestForOS(t *testing.T) {
tests := []struct {
name string
args args
exe string
want []string
}{
{
Expand All @@ -29,8 +31,18 @@ func TestForOS(t *testing.T) {
goos: "linux",
url: "https://example.com/path?a=1&b=2",
},
exe: "xdg-open",
want: []string{"xdg-open", "https://example.com/path?a=1&b=2"},
},
{
name: "WSL",
args: args{
goos: "linux",
url: "https://example.com/path?a=1&b=2",
},
exe: "wslview",
want: []string{"wslview", "https://example.com/path?a=1&b=2"},
},
{
name: "Windows",
args: args{
Expand All @@ -41,6 +53,14 @@ func TestForOS(t *testing.T) {
},
}
for _, tt := range tests {
lookPath = func(file string) (string, error) {
if file == tt.exe {
return file, nil
} else {
return "", errors.New("not found")
}
}

t.Run(tt.name, func(t *testing.T) {
if cmd := ForOS(tt.args.goos, tt.args.url); !reflect.DeepEqual(cmd.Args, tt.want) {
t.Errorf("ForOS() = %v, want %v", cmd.Args, tt.want)
Expand Down

0 comments on commit cd32ef8

Please sign in to comment.