...

Source file src/github.com/cli/go-gh/v2/pkg/browser/browser.go

Documentation: github.com/cli/go-gh/v2/pkg/browser

     1  // Package browser facilitates opening of URLs in a web browser.
     2  package browser
     3  
     4  import (
     5  	"io"
     6  	"os"
     7  	"os/exec"
     8  
     9  	cliBrowser "github.com/cli/browser"
    10  	"github.com/cli/go-gh/v2/pkg/config"
    11  	"github.com/cli/safeexec"
    12  	"github.com/google/shlex"
    13  )
    14  
    15  // Browser represents a web browser that can be used to open up URLs.
    16  type Browser struct {
    17  	launcher string
    18  	stderr   io.Writer
    19  	stdout   io.Writer
    20  }
    21  
    22  // New initializes a Browser. If a launcher is not specified
    23  // one is determined based on environment variables or from the
    24  // configuration file.
    25  // The order of precedence for determining a launcher is:
    26  // - Specified launcher;
    27  // - GH_BROWSER environment variable;
    28  // - browser option from configuration file;
    29  // - BROWSER environment variable.
    30  func New(launcher string, stdout, stderr io.Writer) *Browser {
    31  	if launcher == "" {
    32  		launcher = resolveLauncher()
    33  	}
    34  	b := &Browser{
    35  		launcher: launcher,
    36  		stderr:   stderr,
    37  		stdout:   stdout,
    38  	}
    39  	return b
    40  }
    41  
    42  // Browse opens the launcher and navigates to the specified URL.
    43  func (b *Browser) Browse(url string) error {
    44  	return b.browse(url, nil)
    45  }
    46  
    47  func (b *Browser) browse(url string, env []string) error {
    48  	if b.launcher == "" {
    49  		return cliBrowser.OpenURL(url)
    50  	}
    51  	launcherArgs, err := shlex.Split(b.launcher)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	launcherExe, err := safeexec.LookPath(launcherArgs[0])
    56  	if err != nil {
    57  		return err
    58  	}
    59  	args := append(launcherArgs[1:], url)
    60  	cmd := exec.Command(launcherExe, args...)
    61  	cmd.Stdout = b.stdout
    62  	cmd.Stderr = b.stderr
    63  	if env != nil {
    64  		cmd.Env = env
    65  	}
    66  	return cmd.Run()
    67  }
    68  
    69  func resolveLauncher() string {
    70  	if ghBrowser := os.Getenv("GH_BROWSER"); ghBrowser != "" {
    71  		return ghBrowser
    72  	}
    73  	cfg, err := config.Read(nil)
    74  	if err == nil {
    75  		if cfgBrowser, _ := cfg.Get([]string{"browser"}); cfgBrowser != "" {
    76  			return cfgBrowser
    77  		}
    78  	}
    79  	return os.Getenv("BROWSER")
    80  }
    81  

View as plain text