Skip to content

Commit

Permalink
feat(context): ask to use HCLOUD_TOKEN when creating new context (#582)
Browse files Browse the repository at this point in the history
Closes #576
  • Loading branch information
phm07 committed Oct 25, 2023
1 parent d638f05 commit 54e582a
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions internal/cmd/context/create.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package context

import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"strings"
"syscall"

"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/term"

"github.com/hetznercloud/cli/internal/state"
)
Expand Down Expand Up @@ -40,25 +42,44 @@ func runCreate(cli *state.State, _ *cobra.Command, args []string) error {

context := &state.ConfigContext{Name: name}

for {
fmt.Printf("Token: ")
btoken, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Print("\n")
if err != nil {
return err
}
token := string(bytes.TrimSpace(btoken))
if token == "" {
continue
var token string

envToken := os.Getenv("HCLOUD_TOKEN")
if envToken != "" {
if len(envToken) != 64 {
fmt.Println("Warning: HCLOUD_TOKEN is set, but token is invalid (must be exactly 64 characters long)")
} else {
fmt.Print("The HCLOUD_TOKEN environment variable is set. Do you want to use the token from HCLOUD_TOKEN for the new context? (Y/n): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
if s := strings.ToLower(scanner.Text()); s == "" || s == "y" || s == "yes" {
token = envToken
}
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}

if token == "" {
for {
fmt.Printf("Token: ")
btoken, err := term.ReadPassword(syscall.Stdin)

Check failure on line 64 in internal/cmd/context/create.go

View workflow job for this annotation

GitHub Actions / build

cannot use syscall.Stdin (variable of type syscall.Handle) as int value in argument to term.ReadPassword
fmt.Print("\n")
if err != nil {
return err
}
token = string(bytes.TrimSpace(btoken))
if token == "" {
continue
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}
break
}
context.Token = token
break
}

context.Token = token

cli.Config.Contexts = append(cli.Config.Contexts, context)
cli.Config.ActiveContext = context

Expand Down

0 comments on commit 54e582a

Please sign in to comment.