This repository has been archived by the owner on Jan 19, 2023. It is now read-only.
/
kubeconfig.go
82 lines (61 loc) · 1.7 KB
/
kubeconfig.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
/*
Copyright (c) 2019 the Octant contributors. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package kubeconfig
import (
"path/filepath"
"sort"
"k8s.io/client-go/tools/clientcmd"
"github.com/vmware-tanzu/octant/internal/util/strings"
)
//go:generate mockgen -destination=./fake/mock_loader.go -package=fake github.com/vmware-tanzu/octant/internal/kubeconfig Loader
// KubeConfig describes a kube config for dash.
type KubeConfig struct {
Contexts []Context
CurrentContext string
}
// Context describes a kube config context.
type Context struct {
Name string `json:"name"`
}
// Loader is an interface for loading kube config.
type Loader interface {
Load(filename string) (*KubeConfig, error)
}
// FSLoaderOpt is an option for configuring FSLoader.
type FSLoaderOpt func(loader *FSLoader)
// FSLoader loads kube configs from the file system.
type FSLoader struct {
}
var _ Loader = (*FSLoader)(nil)
// NewFSLoader creates an instance of FSLoader.
func NewFSLoader(options ...FSLoaderOpt) *FSLoader {
l := &FSLoader{}
for _, option := range options {
option(l)
}
return l
}
// Load loads a kube config contexts from a list of files.
func (l *FSLoader) Load(fileList string) (*KubeConfig, error) {
chain := strings.Deduplicate(filepath.SplitList(fileList))
loadingRules := &clientcmd.ClientConfigLoadingRules{
Precedence: chain,
}
config, err := loadingRules.Load()
if err != nil {
return nil, err
}
var list []Context
for name := range config.Contexts {
list = append(list, Context{Name: name})
}
sort.Slice(list, func(i, j int) bool {
return list[i].Name < list[j].Name
})
return &KubeConfig{
Contexts: list,
CurrentContext: config.CurrentContext,
}, nil
}