github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmdutil/web_browser.go (about)

     1  package cmdutil
     2  
     3  import (
     4  	"io"
     5  	"os/exec"
     6  
     7  	"github.com/cli/browser"
     8  	"github.com/cli/safeexec"
     9  	"github.com/google/shlex"
    10  )
    11  
    12  func NewBrowser(launcher string, stdout, stderr io.Writer) Browser {
    13  	return &webBrowser{
    14  		launcher: launcher,
    15  		stdout:   stdout,
    16  		stderr:   stderr,
    17  	}
    18  }
    19  
    20  type webBrowser struct {
    21  	launcher string
    22  	stdout   io.Writer
    23  	stderr   io.Writer
    24  }
    25  
    26  func (b *webBrowser) Browse(url string) error {
    27  	if b.launcher != "" {
    28  		launcherArgs, err := shlex.Split(b.launcher)
    29  		if err != nil {
    30  			return err
    31  		}
    32  		launcherExe, err := safeexec.LookPath(launcherArgs[0])
    33  		if err != nil {
    34  			return err
    35  		}
    36  		args := append(launcherArgs[1:], url)
    37  		cmd := exec.Command(launcherExe, args...)
    38  		cmd.Stdout = b.stdout
    39  		cmd.Stderr = b.stderr
    40  		return cmd.Run()
    41  	}
    42  
    43  	return browser.OpenURL(url)
    44  }
    45  
    46  type TestBrowser struct {
    47  	urls []string
    48  }
    49  
    50  func (b *TestBrowser) Browse(url string) error {
    51  	b.urls = append(b.urls, url)
    52  	return nil
    53  }
    54  
    55  func (b *TestBrowser) BrowsedURL() string {
    56  	if len(b.urls) > 0 {
    57  		return b.urls[0]
    58  	}
    59  	return ""
    60  }
    61  
    62  type _testing interface {
    63  	Errorf(string, ...interface{})
    64  	Helper()
    65  }
    66  
    67  func (b *TestBrowser) Verify(t _testing, url string) {
    68  	t.Helper()
    69  	if url != "" {
    70  		switch len(b.urls) {
    71  		case 0:
    72  			t.Errorf("expected browser to open URL %q, but it was never invoked", url)
    73  		case 1:
    74  			if url != b.urls[0] {
    75  				t.Errorf("expected browser to open URL %q, got %q", url, b.urls[0])
    76  			}
    77  		default:
    78  			t.Errorf("expected browser to open one URL, but was invoked %d times", len(b.urls))
    79  		}
    80  	} else if len(b.urls) > 0 {
    81  		t.Errorf("expected no browser to open, but was invoked %d times: %v", len(b.urls), b.urls)
    82  	}
    83  }