Skip to content

Commit

Permalink
add auto open browser
Browse files Browse the repository at this point in the history
Signed-off-by: Weifeng Wang <[email protected]>
  • Loading branch information
qclaogui committed Jan 23, 2024
1 parent 9039a5f commit 3196f79
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions internal/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
"os"
"os/exec"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
)

func ExecuteCommand(command string, args ...string) error {
Expand Down Expand Up @@ -49,8 +51,61 @@ func ExecuteCommand(command string, args ...string) error {
if err != nil {
os.Exit(1) // Exit with a status code of 1 upon failure
}
browser(target)
}
}

return nil
}

func browser(target string) {
if strings.HasPrefix(target, "up-") {
OpenBrowser("http://localhost:3000/explore")
} else if strings.HasPrefix(target, "deploy-") {
OpenBrowser("http://localhost:8080/explore")
}
return
}

// openArgs returns a list of possible args to use to open a url.
func openArgs() []string {
var cmds []string
switch runtime.GOOS {
case "darwin":
cmds = []string{"/usr/bin/open"}
case "windows":
cmds = []string{"cmd", "/c", "start"}
default:
if os.Getenv("DISPLAY") != "" {
// xdg-open is only for use in a desktop environment.
cmds = []string{"xdg-open"}
}
}

return cmds
}

// OpenBrowser tries to open url in a browser and reports whether it succeeded.
func OpenBrowser(url string) bool {
args := openArgs()
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd.Start() == nil && appearsSuccessful(cmd, 5*time.Second) {
return true
}
return false
}

// appearsSuccessful reports whether the command appears to have run successfully.
// If the command runs longer than the timeout, it's deemed successful.
// If the command runs within the timeout, it's deemed successful if it exited cleanly.
func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool {
errc := make(chan error, 1)
go func() { errc <- cmd.Wait() }()

select {
case <-time.After(timeout):
return true
case err := <-errc:
return err == nil
}
}

0 comments on commit 3196f79

Please sign in to comment.