Merge pull request #1708 from cli/wsl-detection

Fallback browser when `xdg-open` does not exist
This commit is contained in:
Mislav Marohnić 2020-09-16 18:16:27 +02:00 committed by GitHub
commit cd32ef8389
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 1 deletions

View file

@ -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)
}
@ -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

View file

@ -1,6 +1,7 @@
package browser
import (
"errors"
"reflect"
"testing"
)
@ -13,6 +14,7 @@ func TestForOS(t *testing.T) {
tests := []struct {
name string
args args
exe string
want []string
}{
{
@ -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{
@ -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)