From 685b67df33b196f5f6aea60ba141c15d602906cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Serta=C3=A7=20=C3=96zercan?= <852750+sozercan@users.noreply.github.com> Date: Sat, 15 Apr 2023 16:20:18 -0700 Subject: [PATCH] fix: handle kubeconfig (#24) --- cmd/cli/kubernetes.go | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/cmd/cli/kubernetes.go b/cmd/cli/kubernetes.go index 9127965..8907fce 100644 --- a/cmd/cli/kubernetes.go +++ b/cmd/cli/kubernetes.go @@ -3,7 +3,6 @@ package cli import ( "bytes" "context" - "flag" "path/filepath" "k8s.io/apimachinery/pkg/api/meta" @@ -19,20 +18,17 @@ import ( "k8s.io/client-go/util/homedir" ) -const defaultNamespace = "default" // TODO: get from kubeconfig - -// TODO: get existing objects and pass to prompt +const defaultNamespace = "default" func applyManifest(completion string) error { - var kubeconfig *string - if home := homedir.HomeDir(); home != "" { - kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") + var kubeConfig string + if *kubernetesConfigFlags.KubeConfig == "" { + kubeConfig = filepath.Join(homedir.HomeDir(), ".kube", "config") } else { - kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") + kubeConfig = *kubernetesConfigFlags.KubeConfig } - flag.Parse() - config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) + config, err := clientcmd.BuildConfigFromFlags("", kubeConfig) if err != nil { return err } @@ -47,6 +43,25 @@ func applyManifest(completion string) error { return err } + var namespace string + if *kubernetesConfigFlags.Namespace == "" { + clientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( + &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfig}, + &clientcmd.ConfigOverrides{ + CurrentContext: "", + }).RawConfig() + if err != nil { + return err + } + if clientConfig.Contexts[clientConfig.CurrentContext].Namespace == "" { + namespace = defaultNamespace + } else { + namespace = clientConfig.Contexts[clientConfig.CurrentContext].Namespace + } + } else { + namespace = *kubernetesConfigFlags.Namespace + } + manifest := []byte(completion) decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(manifest), 100) for { @@ -80,7 +95,7 @@ func applyManifest(completion string) error { var dri dynamic.ResourceInterface if mapping.Scope.Name() == meta.RESTScopeNameNamespace { if unstructuredObj.GetNamespace() == "" { - unstructuredObj.SetNamespace(defaultNamespace) + unstructuredObj.SetNamespace(namespace) } dri = dd.Resource(mapping.Resource).Namespace(unstructuredObj.GetNamespace()) } else {