-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
159 lines (142 loc) · 4.3 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"fmt"
"k8s.io/client-go/tools/clientcmd/api"
"os"
"sort"
"strings"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/helper"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube"
"github.com/jenkins-x/jx-helpers/v3/pkg/stringhelpers"
"github.com/jenkins-x/jx-helpers/v3/pkg/termcolor"
"github.com/jenkins-x/jx-kube-client/v3/pkg/kubeclient"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
"github.com/spf13/cobra"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/templates"
"github.com/jenkins-x/jx-helpers/v3/pkg/input/survey"
"github.com/jenkins-x/jx-helpers/v3/pkg/options"
"k8s.io/client-go/tools/clientcmd"
)
type ContextOptions struct {
options.BaseOptions
Args []string
Filter string
}
var (
version string
context_long = templates.LongDesc(`
Displays or changes the current Kubernetes context (cluster).`)
context_example = templates.Examples(`
# to select the context to switch to
jx context
# view the current context
jx context -b`)
)
func Main() *cobra.Command {
o := ContextOptions{}
cmd := &cobra.Command{
Use: "jx-context",
Short: "View or change the current Kubernetes context (Kubernetes cluster)",
Long: context_long,
Example: context_example,
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
_, _, filteredContextNames, err := o.filteredContextNames()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var contextNames []string
for _, v := range filteredContextNames {
if strings.HasPrefix(v, toComplete) {
contextNames = append(contextNames, v)
}
}
return contextNames, cobra.ShellCompDirectiveNoFileComp
},
Version: version,
Run: func(cmd *cobra.Command, args []string) {
o.Args = args
err := o.Run()
helper.CheckErr(err)
},
}
o.AddBaseFlags(cmd)
cmd.Flags().StringVarP(&o.Filter, "filter", "f", "", "Filter the list of contexts to switch between using the given text")
return cmd
}
func main() {
if err := Main().Execute(); err != nil {
os.Exit(1)
}
os.Exit(0)
}
func (o *ContextOptions) Run() error {
config, po, contextNames, err := o.filteredContextNames()
if err != nil {
return err
}
ctxName := ""
args := o.Args
if len(args) > 0 {
ctxName = args[0]
if stringhelpers.StringArrayIndex(contextNames, ctxName) < 0 {
return options.InvalidArg(ctxName, contextNames)
}
}
if ctxName == "" && !o.BatchMode {
defaultCtxName := config.CurrentContext
pick, err := o.PickContext(contextNames, defaultCtxName)
if err != nil {
return err
}
ctxName = pick
}
info := termcolor.ColorInfo
if ctxName != "" && ctxName != config.CurrentContext {
ctx := config.Contexts[ctxName]
if ctx == nil {
return fmt.Errorf("could not find Kubernetes context %s", ctxName)
}
newConfig := *config
newConfig.CurrentContext = ctxName
err = clientcmd.ModifyConfig(po, newConfig, false)
if err != nil {
return fmt.Errorf("failed to update the kube config %s", err)
}
log.Logger().Infof("Now using namespace '%s' from context named '%s' on server '%s'.\n",
info(ctx.Namespace), info(newConfig.CurrentContext), info(kube.Server(config, ctx)))
} else {
ns := kube.CurrentNamespace(config)
server := kube.CurrentServer(config)
log.Logger().Infof("Using namespace '%s' from context named '%s' on server '%s'.\n",
info(ns), info(config.CurrentContext), info(server))
}
return nil
}
func (o *ContextOptions) filteredContextNames() (*api.Config, *clientcmd.PathOptions, []string, error) {
config, po, err := kubeclient.LoadConfig()
if err != nil {
return nil, nil, nil, err
}
if config == nil || config.Contexts == nil || len(config.Contexts) == 0 {
return nil, nil, nil, fmt.Errorf("no Kubernetes contexts available! Try create or connect to cluster")
}
var contextNames []string
for k, v := range config.Contexts {
if k != "" && v != nil {
if o.Filter == "" || strings.Contains(k, o.Filter) {
contextNames = append(contextNames, k)
}
}
}
sort.Strings(contextNames)
return config, po, contextNames, nil
}
func (o *ContextOptions) PickContext(names []string, defaultValue string) (string, error) {
if len(names) == 0 {
return "", nil
}
if len(names) == 1 {
return names[0], nil
}
return survey.NewInput().PickNameWithDefault(names, "Change Kubernetes context:", defaultValue, "")
}