From 3196f799f9d1c86a974da246be878752c0db58cf Mon Sep 17 00:00:00 2001 From: Weifeng Wang Date: Tue, 23 Jan 2024 11:59:48 +0800 Subject: [PATCH] add auto open browser Signed-off-by: Weifeng Wang --- internal/common.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/internal/common.go b/internal/common.go index 7c7fc92c..db6a9e44 100644 --- a/internal/common.go +++ b/internal/common.go @@ -9,8 +9,10 @@ import ( "os" "os/exec" "os/signal" + "runtime" "strings" "syscall" + "time" ) func ExecuteCommand(command string, args ...string) error { @@ -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 + } +}