forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
88 lines (72 loc) · 2.35 KB
/
root.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
package main
import (
goflag "flag"
"fmt"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)
type RootCmd struct {
configFile string
cobraCommand *cobra.Command
}
var rootCommand = RootCmd{
cobraCommand: &cobra.Command{
Use: "channels",
Short: "channels applies software from a channel",
},
}
func Execute() {
goflag.Set("logtostderr", "true")
goflag.CommandLine.Parse([]string{})
if err := rootCommand.cobraCommand.Execute(); err != nil {
exitWithError(err)
}
}
func init() {
cobra.OnInitialize(initConfig)
cmd := rootCommand.cobraCommand
cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
cmd.PersistentFlags().StringVar(&rootCommand.configFile, "config", "", "config file (default is $HOME/.channels.yaml)")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if rootCommand.configFile != "" {
// enable ability to specify config file via flag
viper.SetConfigFile(rootCommand.configFile)
}
viper.SetConfigName(".channels") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
func (c *RootCmd) AddCommand(cmd *cobra.Command) {
c.cobraCommand.AddCommand(cmd)
}
func (c *RootCmd) KubernetesClient() (*release_1_3.Clientset, error) {
config := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{})
clientConfig, err := config.ClientConfig()
if err != nil {
if clientcmd.IsEmptyConfig(err) {
glog.V(2).Infof("No client config found; will use default config")
clientConfig, err = clientcmd.DefaultClientConfig.ClientConfig()
if err != nil {
return nil, fmt.Errorf("cannot build default kube config settings: %v", err)
}
} else {
return nil, fmt.Errorf("cannot load kubecfg settings: %v", err)
}
}
k8sClient, err := release_1_3.NewForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("cannot build kube client: %v", err)
}
return k8sClient, err
}