Skip to content

Commit cd32ef8

Browse files
authored
Merge pull request cli#1708 from cli/wsl-detection
Fallback browser when `xdg-open` does not exist
2 parents 3049db6 + 9058fee commit cd32ef8

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

pkg/browser/browser.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func ForOS(goos, url string) *exec.Cmd {
3030
r := strings.NewReplacer("&", "^&")
3131
args = append(args, "/c", "start", r.Replace(url))
3232
default:
33-
exe = "xdg-open"
33+
exe = linuxExe()
3434
args = append(args, url)
3535
}
3636

@@ -51,3 +51,19 @@ func FromLauncher(launcher, url string) (*exec.Cmd, error) {
5151
cmd.Stderr = os.Stderr
5252
return cmd, nil
5353
}
54+
55+
func linuxExe() string {
56+
exe := "xdg-open"
57+
58+
_, err := lookPath(exe)
59+
if err != nil {
60+
_, err := lookPath("wslview")
61+
if err == nil {
62+
exe = "wslview"
63+
}
64+
}
65+
66+
return exe
67+
}
68+
69+
var lookPath = exec.LookPath

pkg/browser/browser_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package browser
22

33
import (
4+
"errors"
45
"reflect"
56
"testing"
67
)
@@ -13,6 +14,7 @@ func TestForOS(t *testing.T) {
1314
tests := []struct {
1415
name string
1516
args args
17+
exe string
1618
want []string
1719
}{
1820
{
@@ -29,8 +31,18 @@ func TestForOS(t *testing.T) {
2931
goos: "linux",
3032
url: "https://example.com/path?a=1&b=2",
3133
},
34+
exe: "xdg-open",
3235
want: []string{"xdg-open", "https://example.com/path?a=1&b=2"},
3336
},
37+
{
38+
name: "WSL",
39+
args: args{
40+
goos: "linux",
41+
url: "https://example.com/path?a=1&b=2",
42+
},
43+
exe: "wslview",
44+
want: []string{"wslview", "https://example.com/path?a=1&b=2"},
45+
},
3446
{
3547
name: "Windows",
3648
args: args{
@@ -41,6 +53,14 @@ func TestForOS(t *testing.T) {
4153
},
4254
}
4355
for _, tt := range tests {
56+
lookPath = func(file string) (string, error) {
57+
if file == tt.exe {
58+
return file, nil
59+
} else {
60+
return "", errors.New("not found")
61+
}
62+
}
63+
4464
t.Run(tt.name, func(t *testing.T) {
4565
if cmd := ForOS(tt.args.goos, tt.args.url); !reflect.DeepEqual(cmd.Args, tt.want) {
4666
t.Errorf("ForOS() = %v, want %v", cmd.Args, tt.want)

0 commit comments

Comments
 (0)