-
Notifications
You must be signed in to change notification settings - Fork 6
/
context.go
70 lines (60 loc) · 1.32 KB
/
context.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
67
68
69
70
package domain
import (
"github.com/pkg/errors"
"github.com/plumming/dx/pkg/cmd"
"k8s.io/client-go/tools/clientcmd/api"
)
// Context defines Kubernetes context.
type Context struct {
cmd.CommonOptions
Context string
Config *api.Config
}
// NewContext creates a new Context.
func NewContext() *Context {
c := &Context{}
return c
}
// Validate input.
func (c *Context) Validate() error {
k := c.Kuber()
var err error
c.Config, err = k.LoadAPIConfig()
if err != nil {
return err
}
if c.Context == "" {
c.Context, err = c.selectContext()
if err != nil {
return errors.Wrap(err, "failed to select context")
}
}
return nil
}
// Run the cmd.
func (c *Context) Run() error {
k := c.Kuber()
var err error
c.Config, err = k.SetKubeContext(c.Context, c.Config)
if err != nil {
return err
}
return nil
}
func (c *Context) selectContext() (string, error) {
contexts := c.loadContexts()
prompter := c.Prompter()
currentContext := c.Config.CurrentContext
ctx, err := prompter.SelectFromOptionsWithDefault("Select a context:", currentContext, contexts)
if err != nil {
return "", errors.Wrap(err, "failed selecting context from prompter")
}
return ctx, nil
}
func (c *Context) loadContexts() []string {
var contexts []string
for k := range c.Config.Contexts {
contexts = append(contexts, k)
}
return contexts
}