forked from justjanne/powerline-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment-kube.go
105 lines (93 loc) · 2.24 KB
/
segment-kube.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
package main
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"fmt"
"gopkg.in/yaml.v2"
)
type KubeContext struct {
Context struct {
Cluster string
Namespace string
User string
}
Name string
}
type KubeConfig struct {
Contexts []KubeContext `yaml:"contexts"`
CurrentContext string `yaml:"current-context"`
}
func homePath() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
}
return os.Getenv(env)
}
func readKubeConfig(config *KubeConfig, path string) (err error) {
absolutePath, err := filepath.Abs(path)
if err != nil {
return
}
fileContent, err := ioutil.ReadFile(absolutePath)
if err != nil {
return
}
err = yaml.Unmarshal(fileContent, config)
if err != nil {
return
}
return
}
func segmentKube(p *powerline) {
paths := append(strings.Split(os.Getenv("KUBECONFIG"), ":"), path.Join(homePath(), ".kube", "config"))
config := &KubeConfig{}
for _, configPath := range paths {
if readKubeConfig(config, configPath) == nil {
break
}
}
cluster := ""
namespace := ""
for _, context := range config.Contexts {
if context.Name == config.CurrentContext {
cluster = context.Context.Cluster
namespace = context.Context.Namespace
break
}
}
// When you use gke your clusters may look something like gke_projectname_availability-zone_cluster-01
// instead I want it to read as `cluster-01`
// So we remove the first 3 segments of this string, if the flag is set, and there are enough segments
if strings.HasPrefix(cluster, "gke") && *p.args.ShortenGKENames {
segments := strings.Split(cluster, "_")
if len(segments) > 3 {
cluster = strings.Join(segments[3:], "_")
}
}
// Only draw the icon once
kubeIconHasBeenDrawnYet := false
if cluster != "" {
kubeIconHasBeenDrawnYet = true
p.appendSegment("kube-cluster", segment{
content: fmt.Sprintf("⎈ %s", cluster),
foreground: p.theme.KubeClusterFg,
background: p.theme.KubeClusterBg,
})
}
if namespace != "" {
content := namespace
if !kubeIconHasBeenDrawnYet {
content = fmt.Sprintf("⎈ %s", content)
}
p.appendSegment("kube-namespace", segment{
content: content,
foreground: p.theme.KubeNamespaceFg,
background: p.theme.KubeNamespaceBg,
})
}
}