Debian Codegraph @

debian/go/src/golang.org/x/telemetry/cmd/gotelemetry/internal/browser/browser.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package browser provides utilities for interacting with users' browsers.
6 // This is a copy of the go project's src/cmd/internal/browser.
7 package browser
8
9 import (
10 "os"
11 "os/exec"
12 "runtime"
13 "time"
14 )
15
16 // Commands returns a list of possible commands to use to open a url.
17 func Commands() [][]string {
18 var cmds [][]string
19 if exe := os.Getenv("BROWSER"); exe != "" {
20 cmds = append(cmds, []string{exe})
21 }
22 switch runtime.GOOS {
23 case "darwin":
24 cmds = append(cmds, []string{"/usr/bin/open"})
25 case "windows":
26 cmds = append(cmds, []string{"cmd", "/c", "start"})
27 default:
28 if os.Getenv("DISPLAY") != "" {
29 // xdg-open is only for use in a desktop environment.
30 cmds = append(cmds, []string{"xdg-open"})
31 }
32 }
33 cmds = append(cmds,
34 []string{"chrome"},
35 []string{"google-chrome"},
36 []string{"chromium"},
37 []string{"firefox"},
38 )
39 return cmds
40 }
41
42 // Open tries to open url in a browser and reports whether it succeeded.
43 func Open(url string) bool {
44 for _, args := range Commands() {
45 cmd := exec.Command(args[0], append(args[1:], url)...)
46 if cmd.Start() == nil && appearsSuccessful(cmd, 3*time.Second) {
47 return true
48 }
49 }
50 return false
51 }
52
53 // appearsSuccessful reports whether the command appears to have run successfully.
54 // If the command runs longer than the timeout, it's deemed successful.
55 // If the command runs within the timeout, it's deemed successful if it exited cleanly.
56 func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool {
57 errc := make(chan error, 1)
58 go func() {
59 errc <- cmd.Wait()
60 }()
61
62 select {
63 case <-time.After(timeout):
64 return true
65 case err := <-errc:
66 return err == nil
67 }
68 }