Skip to content

Commit

Permalink
feat(login): use BROWSER environment variable to open browser window
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbrewer committed Apr 2, 2024
1 parent df738d4 commit 8571497
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
9 changes: 8 additions & 1 deletion commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ func initCommands(

wd := WorkingDir(originalWorkingDir, os.Getenv("TF_DATA_DIR"))

var browserLauncher webbrowser.Launcher
if _, ok := os.LookupEnv("TF_BROWSER_ENV"); ok {
browserLauncher = webbrowser.NewBrowserEnvLauncher()
} else {
browserLauncher = webbrowser.NewNativeLauncher()
}

meta := command.Meta{
WorkingDir: wd,
Streams: streams,
Expand All @@ -95,7 +102,7 @@ func initCommands(
Ui: Ui,

Services: services,
BrowserLauncher: webbrowser.NewNativeLauncher(),
BrowserLauncher: browserLauncher,

RunningInAutomation: inAutomation,
CLIConfigDir: configDir,
Expand Down
37 changes: 37 additions & 0 deletions internal/command/webbrowser/browserenv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

package webbrowser

import (
"context"
"fmt"
"os"
"os/exec"
"time"

"github.com/pkg/browser"
)

// NewBrowserEnvLauncher creates and returns a Launcher that will attempt to use
// BROWSER environment , otherwise full back to the browser-launching mechanisms of
// the operating system where the program is currently running.
func NewBrowserEnvLauncher() Launcher {
return browserEnvLauncher{}
}

type browserEnvLauncher struct{}

func (l browserEnvLauncher) OpenURL(url string) error {
browserEnv := os.Getenv("BROWSER")
if browserEnv != "" {
browserSh := fmt.Sprintf("%s '%s'", browserEnv, url)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "sh", "-c", browserSh)
_, err := cmd.CombinedOutput()
return err
}

return browser.OpenURL(url)
}

0 comments on commit 8571497

Please sign in to comment.