Skip to content

Commit c1c82ec

Browse files
committed
automatically open browser
1 parent 3f20cac commit c1c82ec

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

cmd/src/login.go

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"fmt"
77
"io"
88
"os"
9+
"os/exec"
10+
"runtime"
911
"strings"
1012
"time"
1113

@@ -170,9 +172,7 @@ func loginCmd(ctx context.Context, p loginParams) error {
170172

171173
if p.useOAuth {
172174
fmt.Fprintln(out)
173-
fmt.Fprintf(out, "To use this access token, set the following environment variables in your terminal:\n\n")
174-
fmt.Fprintf(out, " export SRC_ENDPOINT=%s\n", endpointArg)
175-
fmt.Fprintf(out, " export SRC_ACCESS_TOKEN=%s\n", cfg.AccessToken)
175+
fmt.Fprintf(out, "Authenticated with OAuth credentials")
176176
}
177177

178178
fmt.Fprintln(out)
@@ -185,12 +185,16 @@ func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, cli
185185
return "", err
186186
}
187187

188-
fmt.Fprintln(out)
189-
fmt.Fprintf(out, "To authenticate, visit %s and enter the code: %s\n", authResp.VerificationURI, authResp.UserCode)
190-
if authResp.VerificationURIComplete != "" {
191-
fmt.Fprintln(out)
192-
fmt.Fprintf(out, "Alternatively, you can open: %s\n", authResp.VerificationURIComplete)
188+
authURL := authResp.VerificationURIComplete
189+
msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL)
190+
if authURL == "" {
191+
authURL = authResp.VerificationURI
192+
msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode)
193193
}
194+
_ = openInBrowser(authURL)
195+
fmt.Fprintln(out)
196+
fmt.Fprint(out, msg)
197+
194198
fmt.Fprintln(out)
195199
fmt.Fprint(out, "Waiting for authorization...")
196200
defer fmt.Fprintf(out, "DONE\n\n")
@@ -207,3 +211,21 @@ func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, cli
207211

208212
return tokenResp.AccessToken, nil
209213
}
214+
215+
func openInBrowser(url string) error {
216+
if url == "" {
217+
return nil
218+
}
219+
220+
var cmd *exec.Cmd
221+
switch runtime.GOOS {
222+
case "darwin":
223+
cmd = exec.Command("open", url)
224+
case "windows":
225+
// "start" is a cmd.exe built-in; the empty string is the window title.
226+
cmd = exec.Command("cmd", "/c", "start", "", url)
227+
default:
228+
cmd = exec.Command("xdg-open", url)
229+
}
230+
return cmd.Run()
231+
}

0 commit comments

Comments
 (0)