Skip to content

Instantly share code, notes, and snippets.

@flowerinthenight
Last active July 29, 2021 09:44
Show Gist options
  • Save flowerinthenight/c1d3267a6e5cc26b9025b4eed74ce00a to your computer and use it in GitHub Desktop.
Save flowerinthenight/c1d3267a6e5cc26b9025b4eed74ce00a to your computer and use it in GitHub Desktop.
package main
import (
goflag "flag"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"k8s.io/klog"
)
var (
str = "hello world"
rootCmd = &cobra.Command{
Use: "echo",
Short: "use klog with cobra",
Long: "Use klog together with cobra.",
}
)
func init() {
rootCmd.Flags().SortFlags = false
rootCmd.AddCommand(
RunCmd(),
)
klog.InitFlags(nil)
goflag.Parse()
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
}
func RunCmd() *cobra.Command {
runcmd := &cobra.Command{
Use: "run",
Short: "run command",
Long: "Run command.",
Run: func(cmd *cobra.Command, args []string) {
klog.Infof("echo=%v", str)
},
}
runcmd.Flags().SortFlags = false
runcmd.Flags().StringVar(&str, "str", str, "string to print")
return runcmd
}
func main() {
if err := rootCmd.Execute(); err != nil {
klog.Fatalf("root cmd execute failed, err=%v", err)
}
}
@ursuad
Copy link

ursuad commented Mar 28, 2019

would it be possible to integrate this with the root command, for example not having to do ./cobraklog run --logtostderr --str "hello alien world" but just ./cobraklog --logtostderr --str "hello alien world"

@ursuad
Copy link

ursuad commented Mar 28, 2019

This seems to be working:


import (
	"flag"
	"fmt"
	"github.com/spf13/pflag"
	"k8s.io/klog"
	"os"

	"github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "cobratest",
	Short: "A brief description of your application",
	Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
		Run: func(cmd *cobra.Command, args []string) {
			klog.V(1).Info("Test logging")
			print("test")
		},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	klog.InitFlags(nil)
	// Make cobra aware of select glog flags
	// Enabling all flags causes unwanted deprecation warnings from glog to always print in plugin mode
	pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup("v"))
	pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup("logtostderr"))
	pflag.CommandLine.Set("logtostderr", "true")

	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobratest.yaml)")

	// 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")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".cobratest" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".cobratest")
	}

	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())
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment