Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(login): use BROWSER environment variable to open browser window #34926

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}