2021-09-01 19:03:24 +03:00
|
|
|
// Copyright 2018 Microsoft. All rights reserved.
|
|
|
|
// MIT License
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2022-03-14 19:08:17 +03:00
|
|
|
"runtime/debug"
|
|
|
|
|
2021-09-01 19:03:24 +03:00
|
|
|
"github.com/spf13/cobra"
|
2021-12-02 20:55:36 +03:00
|
|
|
"github.com/spf13/pflag"
|
|
|
|
"github.com/spf13/viper"
|
2022-03-14 19:08:17 +03:00
|
|
|
"k8s.io/klog"
|
2021-09-01 19:03:24 +03:00
|
|
|
)
|
|
|
|
|
2021-12-02 20:55:36 +03:00
|
|
|
const (
|
|
|
|
flagVersion = "version"
|
|
|
|
flagKubeConfigPath = "kubeconfig"
|
|
|
|
)
|
|
|
|
|
|
|
|
var flagDefaults = map[string]string{
|
|
|
|
flagKubeConfigPath: "",
|
|
|
|
}
|
|
|
|
|
2021-09-01 19:03:24 +03:00
|
|
|
// Version is populated by make during build.
|
|
|
|
var version string
|
|
|
|
|
2022-03-14 19:08:17 +03:00
|
|
|
// panicRecoverAndExitWithStackTrace - recovery from panic, print a failure message and stack trace and exit the program
|
|
|
|
func panicRecoverAndExitWithStackTrace() {
|
|
|
|
if r := recover(); r != nil {
|
2022-09-03 00:00:32 +03:00
|
|
|
klog.Infoln(r)
|
2022-03-14 19:08:17 +03:00
|
|
|
klog.Errorf("Stack trace: %s", string(debug.Stack()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-01 19:03:24 +03:00
|
|
|
func main() {
|
2022-03-14 19:08:17 +03:00
|
|
|
defer panicRecoverAndExitWithStackTrace()
|
|
|
|
|
2021-10-08 23:52:38 +03:00
|
|
|
rootCmd := NewRootCmd()
|
2021-12-02 20:55:36 +03:00
|
|
|
|
|
|
|
if version != "" {
|
|
|
|
viper.Set(flagVersion, version)
|
|
|
|
}
|
|
|
|
|
|
|
|
cobra.OnInitialize(func() {
|
|
|
|
viper.AutomaticEnv()
|
|
|
|
initCommandFlags(rootCmd.Commands())
|
|
|
|
})
|
|
|
|
|
2021-09-01 19:03:24 +03:00
|
|
|
cobra.CheckErr(rootCmd.Execute())
|
|
|
|
}
|
2021-12-02 20:55:36 +03:00
|
|
|
|
|
|
|
func initCommandFlags(commands []*cobra.Command) {
|
|
|
|
for _, cmd := range commands {
|
|
|
|
// bind vars from env or conf to pflags
|
|
|
|
err := viper.BindPFlags(cmd.Flags())
|
|
|
|
cobra.CheckErr(err)
|
|
|
|
|
|
|
|
c := cmd
|
|
|
|
c.Flags().VisitAll(func(flag *pflag.Flag) {
|
|
|
|
if viper.IsSet(flag.Name) && viper.GetString(flag.Name) != "" {
|
|
|
|
err := c.Flags().Set(flag.Name, viper.GetString(flag.Name))
|
|
|
|
cobra.CheckErr(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
// call recursively on subcommands
|
|
|
|
if cmd.HasSubCommands() {
|
|
|
|
initCommandFlags(cmd.Commands())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|