added function for adding string flags

This commit is contained in:
Peter Morton 2023-05-01 18:28:10 -05:00
parent 05acb8bc8b
commit 32fa31bcac

View File

@ -7,6 +7,7 @@ import (
"fmt"
"os"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
@ -48,23 +49,33 @@ func init() {
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.tps.yaml)")
rootCmd.PersistentFlags().StringVar(&Hostname, "hostname", "", "Environment hostname")
rootCmd.MarkFlagRequired("hostname")
viper.BindPFlag("hostname", rootCmd.PersistentFlags().Lookup("hostname"))
rootCmd.PersistentFlags().StringVar(&Username, "username", "apiclient", "API username")
viper.BindPFlag("username", rootCmd.PersistentFlags().Lookup("username"))
rootCmd.PersistentFlags().StringVar(&Password, "password", "apiclient", "API password")
viper.BindPFlag("password", rootCmd.PersistentFlags().Lookup("password"))
rootCmd.PersistentFlags().StringVar(&ClientId, "clientId", "default", "clientId or tenantId for API calls")
viper.BindPFlag("clientId", rootCmd.PersistentFlags().Lookup("clientId"))
addStringFlag(&Hostname, "hostname", "", "Environment hostname")
addStringFlag(&Username, "username", "apiclient", "API username")
addStringFlag(&Password, "password", "apiclient", "API password")
addStringFlag(&ClientId, "clientId", "default", "clientId or tenantId for API calls")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging")
viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))
err := viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))
if err != nil {
log.Error(err)
os.Exit(1)
}
// Cobra also supports local flags, which will only run
// when this action is called directly.
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func addStringFlag(p *string, key string, value string, usage string) {
rootCmd.PersistentFlags().StringVar(p, key, value, usage)
err := viper.BindPFlag(key, rootCmd.PersistentFlags().Lookup(key))
if err != nil {
log.Error(err)
os.Exit(1)
}
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {