MCPcopy Create free account
hub / github.com/devspace-sh/devspace / NewClientByContext

Function NewClientByContext

pkg/devspace/kubectl/util/util.go:15–92  ·  view source on GitHub ↗
(context, namespace string, switchContext bool, kubeLoader kubeconfig.Loader)

Source from the content-addressed store, hash-verified

13const localContext = "incluster"
14
15func NewClientByContext(context, namespace string, switchContext bool, kubeLoader kubeconfig.Loader) (clientcmd.ClientConfig, string, string, bool, error) {
16 // Load new raw config
17 kubeConfigOriginal, err := kubeLoader.LoadRawConfig()
18 if err != nil {
19 return nil, "", "", false, err
20 }
21
22 // We clone the config here to avoid changing the single loaded config
23 kubeConfig := kubeConfigOriginal.DeepCopy()
24 if len(kubeConfig.Clusters) == 0 {
25 // try to load in cluster config
26 config, err := rest.InClusterConfig()
27 if err != nil {
28 return nil, "", "", false, errors.Errorf("kube config is invalid")
29 }
30
31 currentNamespace, err := inClusterNamespace()
32 if err != nil {
33 currentNamespace = "default"
34 }
35 if namespace != "" {
36 currentNamespace = namespace
37 }
38
39 rawConfig, err := ConvertRestConfigToRawConfig(config, currentNamespace)
40 if err != nil {
41 return nil, "", "", false, errors.Wrap(err, "convert in cluster config")
42 }
43
44 return clientcmd.NewNonInteractiveClientConfig(*rawConfig, localContext, &clientcmd.ConfigOverrides{}, clientcmd.NewDefaultClientConfigLoadingRules()), localContext, currentNamespace, true, nil
45 }
46
47 // If we should use a certain kube context use that
48 var (
49 activeContext = kubeConfig.CurrentContext
50 activeNamespace = metav1.NamespaceDefault
51 saveConfig = false
52 )
53
54 // Set active context
55 if context != "" && activeContext != context {
56 activeContext = context
57 if switchContext {
58 kubeConfig.CurrentContext = activeContext
59 saveConfig = true
60 }
61 }
62
63 // Set active namespace
64 if kubeConfig.Contexts[activeContext] != nil {
65 if kubeConfig.Contexts[activeContext].Namespace != "" {
66 activeNamespace = kubeConfig.Contexts[activeContext].Namespace
67 }
68
69 if namespace != "" && activeNamespace != namespace {
70 activeNamespace = namespace
71 kubeConfig.Contexts[activeContext].Namespace = activeNamespace
72 if switchContext {

Callers 1

NewClientFromContextFunction · 0.92

Calls 6

inClusterNamespaceFunction · 0.85
LoadRawConfigMethod · 0.65
DeepCopyMethod · 0.65
SaveConfigMethod · 0.65
ErrorfMethod · 0.45

Tested by

no test coverage detected