forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.go
More file actions
80 lines (67 loc) · 1.54 KB
/
browser.go
File metadata and controls
80 lines (67 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package browser
import (
"os"
"os/exec"
"runtime"
"strings"
"github.com/cli/safeexec"
"github.com/google/shlex"
)
// BrowserEnv simply returns the $BROWSER environment variable
func FromEnv() string {
return os.Getenv("BROWSER")
}
// Command produces an exec.Cmd respecting runtime.GOOS and $BROWSER environment variable
func Command(url string) (*exec.Cmd, error) {
launcher := FromEnv()
if launcher != "" {
return FromLauncher(launcher, url)
}
return ForOS(runtime.GOOS, url), nil
}
// ForOS produces an exec.Cmd to open the web browser for different OS
func ForOS(goos, url string) *exec.Cmd {
exe := "open"
var args []string
switch goos {
case "darwin":
args = append(args, url)
case "windows":
exe, _ = lookPath("cmd")
r := strings.NewReplacer("&", "^&")
args = append(args, "/c", "start", r.Replace(url))
default:
exe = linuxExe()
args = append(args, url)
}
cmd := exec.Command(exe, args...)
cmd.Stderr = os.Stderr
return cmd
}
// FromLauncher parses the launcher string based on shell splitting rules
func FromLauncher(launcher, url string) (*exec.Cmd, error) {
args, err := shlex.Split(launcher)
if err != nil {
return nil, err
}
exe, err := lookPath(args[0])
if err != nil {
return nil, err
}
args = append(args, url)
cmd := exec.Command(exe, args[1:]...)
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 = safeexec.LookPath