...
1
16
17 package genericclioptions
18
19 import (
20 "fmt"
21
22 "k8s.io/apimachinery/pkg/api/meta"
23 "k8s.io/client-go/discovery"
24 "k8s.io/client-go/rest"
25 "k8s.io/client-go/restmapper"
26 "k8s.io/client-go/tools/clientcmd"
27 clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
28 )
29
30
31
32 type TestConfigFlags struct {
33 clientConfig clientcmd.ClientConfig
34 discoveryClient discovery.CachedDiscoveryInterface
35 restMapper meta.RESTMapper
36 }
37
38
39
40 func (f *TestConfigFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig {
41 if f.clientConfig == nil {
42 panic("attempt to obtain a test RawKubeConfigLoader with no clientConfig specified")
43 }
44 return f.clientConfig
45 }
46
47
48
49
50
51 func (f *TestConfigFlags) ToRESTConfig() (*rest.Config, error) {
52 return f.ToRawKubeConfigLoader().ClientConfig()
53 }
54
55
56
57 func (f *TestConfigFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
58 return f.discoveryClient, nil
59 }
60
61
62
63 func (f *TestConfigFlags) ToRESTMapper() (meta.RESTMapper, error) {
64 if f.restMapper != nil {
65 return f.restMapper, nil
66 }
67 if f.discoveryClient != nil {
68 mapper := restmapper.NewDeferredDiscoveryRESTMapper(f.discoveryClient)
69 expander := restmapper.NewShortcutExpander(mapper, f.discoveryClient, nil)
70 return expander, nil
71 }
72 return nil, fmt.Errorf("no restmapper")
73 }
74
75
76 func (f *TestConfigFlags) WithClientConfig(clientConfig clientcmd.ClientConfig) *TestConfigFlags {
77 f.clientConfig = clientConfig
78 return f
79 }
80
81
82 func (f *TestConfigFlags) WithRESTMapper(mapper meta.RESTMapper) *TestConfigFlags {
83 f.restMapper = mapper
84 return f
85 }
86
87
88 func (f *TestConfigFlags) WithDiscoveryClient(c discovery.CachedDiscoveryInterface) *TestConfigFlags {
89 f.discoveryClient = c
90 return f
91 }
92
93
94 func (f *TestConfigFlags) WithNamespace(ns string) *TestConfigFlags {
95 if f.clientConfig == nil {
96 panic("attempt to obtain a test RawKubeConfigLoader with no clientConfig specified")
97 }
98 f.clientConfig = &namespacedClientConfig{
99 delegate: f.clientConfig,
100 namespace: ns,
101 }
102 return f
103 }
104
105
106 func NewTestConfigFlags() *TestConfigFlags {
107 return &TestConfigFlags{}
108 }
109
110 type namespacedClientConfig struct {
111 delegate clientcmd.ClientConfig
112 namespace string
113 }
114
115 func (c *namespacedClientConfig) Namespace() (string, bool, error) {
116 return c.namespace, len(c.namespace) > 0, nil
117 }
118
119 func (c *namespacedClientConfig) RawConfig() (clientcmdapi.Config, error) {
120 return c.delegate.RawConfig()
121 }
122 func (c *namespacedClientConfig) ClientConfig() (*rest.Config, error) {
123 return c.delegate.ClientConfig()
124 }
125 func (c *namespacedClientConfig) ConfigAccess() clientcmd.ConfigAccess {
126 return c.delegate.ConfigAccess()
127 }
128
View as plain text