1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
package context
import (
"bytes"
"errors"
"fmt"
"strings"
"syscall"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"github.com/hetznercloud/cli/internal/state"
)
func newCreateCommand(cli *state.State) *cobra.Command {
cmd := &cobra.Command{
Use: "create [FLAGS] NAME",
Short: "Create a new context",
Args: cobra.ExactArgs(1),
TraverseChildren: true,
DisableFlagsInUseLine: true,
RunE: cli.Wrap(runCreate),
}
return cmd
}
func runCreate(cli *state.State, _ *cobra.Command, args []string) error {
if !state.StdoutIsTerminal() {
return errors.New("context create is an interactive command")
}
name := strings.TrimSpace(args[0])
if name == "" {
return errors.New("invalid name")
}
if cli.Config.ContextByName(name) != nil {
return errors.New("name already used")
}
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
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}
context.Token = token
break
}
cli.Config.Contexts = append(cli.Config.Contexts, context)
cli.Config.ActiveContext = context
if err := cli.WriteConfig(); err != nil {
return err
}
fmt.Printf("Context %s created and activated\n", name)
return nil
}
|