File: browser.go

package info (click to toggle)
golang-github-cli-go-gh 1.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 444 kB
  • sloc: makefile: 2
file content (80 lines) | stat: -rw-r--r-- 1,854 bytes parent folder | download | duplicates (2)
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 facilitates opening of URLs in a web browser.
package browser

import (
	"io"
	"os"
	"os/exec"

	cliBrowser "github.com/cli/browser"
	"github.com/cli/go-gh/pkg/config"
	"github.com/cli/safeexec"
	"github.com/google/shlex"
)

// Browser represents a web browser that can be used to open up URLs.
type Browser struct {
	launcher string
	stderr   io.Writer
	stdout   io.Writer
}

// New initializes a Browser. If a launcher is not specified
// one is determined based on environment variables or from the
// configuration file.
// The order of precedence for determining a launcher is:
// - Specified launcher;
// - GH_BROWSER environment variable;
// - browser option from configuration file;
// - BROWSER environment variable.
func New(launcher string, stdout, stderr io.Writer) Browser {
	if launcher == "" {
		launcher = resolveLauncher()
	}
	b := Browser{
		launcher: launcher,
		stderr:   stderr,
		stdout:   stdout,
	}
	return b
}

// Browse opens the launcher and navigates to the specified URL.
func (b *Browser) Browse(url string) error {
	return b.browse(url, nil)
}

func (b *Browser) browse(url string, env []string) error {
	if b.launcher == "" {
		return cliBrowser.OpenURL(url)
	}
	launcherArgs, err := shlex.Split(b.launcher)
	if err != nil {
		return err
	}
	launcherExe, err := safeexec.LookPath(launcherArgs[0])
	if err != nil {
		return err
	}
	args := append(launcherArgs[1:], url)
	cmd := exec.Command(launcherExe, args...)
	cmd.Stdout = b.stdout
	cmd.Stderr = b.stderr
	if env != nil {
		cmd.Env = env
	}
	return cmd.Run()
}

func resolveLauncher() string {
	if ghBrowser := os.Getenv("GH_BROWSER"); ghBrowser != "" {
		return ghBrowser
	}
	cfg, err := config.Read()
	if err == nil {
		if cfgBrowser, _ := cfg.Get([]string{"browser"}); cfgBrowser != "" {
			return cfgBrowser
		}
	}
	return os.Getenv("BROWSER")
}