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