-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubernetes.go
95 lines (83 loc) · 2.29 KB
/
kubernetes.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
package plugin
import (
"fmt"
"io/ioutil"
"os"
"github.com/josledp/termcolor"
yaml "gopkg.in/yaml.v2"
)
//Kubernetes is the plugin struct
type Kubernetes struct {
context string
namespace string
}
type k8sconfig struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Preferences map[string]string `yaml:"preferences"`
CurrentContext string `yaml:"current-context"`
Clusters []struct {
Name string `yaml:"name"`
Cluster map[string]string `yaml:"cluster"`
} `yaml:"clusters"`
Contexts []struct {
Name string `yaml:"name"`
Context map[string]string `yaml:"context"`
} `yaml:"contexts"`
Users []struct {
Name string `yaml:"name"`
User map[string]interface{} `yaml:"user"`
} `yaml:"users"`
}
//Name returns the plugin name
func (Kubernetes) Name() string {
return "k8s"
}
//Help returns help information about this plugin
func (Kubernetes) Help() (description string, options map[string]string) {
description = "This plugins show the current context for kubernetes with its namespace"
return
}
//Load is the load function of the plugin
func (k *Kubernetes) Load(Prompter) error {
file := os.Getenv("KUBECONFIG")
if file == "" {
file = os.Getenv("HOME") + string(os.PathSeparator) + ".kube/config"
}
if _, err := os.Stat(file); err != nil {
return nil
}
f, err := os.Open(file)
if err != nil {
return fmt.Errorf("unable to open %s: %v", file, err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return fmt.Errorf("unable to read file %s: %v", file, err)
}
var out k8sconfig
err = yaml.Unmarshal(data, &out)
if err != nil {
return fmt.Errorf("unable to unmarshal file %s: %v", file, err)
}
k.context = out.CurrentContext
for _, c := range out.Contexts {
if c.Name == k.context {
if _, ok := c.Context["namespace"]; ok {
k.namespace = c.Context["namespace"]
} else {
k.namespace = "default"
}
break
}
}
return nil
}
//Get returns the string to use in the prompt
func (k Kubernetes) Get(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode) {
if k.context != "" {
return format(fmt.Sprintf("%s(%s)", k.context, k.namespace), termcolor.FgHiBlue), []termcolor.Mode{termcolor.FgHiBlue}
}
return "", nil
}