forked from hetznercloud/cli
/
context_create.go
66 lines (55 loc) · 1.31 KB
/
context_create.go
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
package cli
import (
"bytes"
"errors"
"fmt"
"strings"
"syscall"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
func newContextCreateCommand(cli *CLI) *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(runContextCreate),
}
return cmd
}
func runContextCreate(cli *CLI, cmd *cobra.Command, args []string) error {
if !cli.Terminal() {
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 := &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
}
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
}