From 1609c04a4534a48f2dff157222a2ae30c832cc2e Mon Sep 17 00:00:00 2001 From: Phodal HUANG Date: Wed, 23 Oct 2019 22:19:18 +0800 Subject: [PATCH] feat: add cli for test --- cmd/root.go | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ helloworld.go | 16 ++---------- 2 files changed, 70 insertions(+), 14 deletions(-) create mode 100644 cmd/root.go diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..2deff3b --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,68 @@ +package cmd + +import ( + "fmt" + + homedir "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var ( + // Used for flags. + cfgFile string + userLicense string + + rootCmd = &cobra.Command{ + Use: "phocli", + Short: "A generator for Cobra based Applications", + Long: `phocli`, + } +) + +// Execute executes the root command. +func Execute() error { + + fmt.Println(rootCmd.Flag("author").Value.String()) + return rootCmd.Execute() + +} + +func init() { + cobra.OnInitialize(initConfig) + + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") + rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") + rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") + rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) + viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) + viper.SetDefault("author", "NAME HERE ") + viper.SetDefault("license", "apache") + + //rootCmd.AddCommand(addCmd) + //rootCmd.AddCommand(initCmd) +} + +func initConfig() { + if cfgFile != "" { + // Use config file from the flag. + viper.SetConfigFile(cfgFile) + } else { + // Find home directory. + home, err := homedir.Dir() + if err != nil { + //er(err) + } + + // Search config in home directory with name ".cobra" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".cobra") + } + + viper.AutomaticEnv() + + if err := viper.ReadInConfig(); err == nil { + fmt.Println("Using config file:", viper.ConfigFileUsed()) + } +} diff --git a/helloworld.go b/helloworld.go index 25c8c49..231c3ff 100644 --- a/helloworld.go +++ b/helloworld.go @@ -1,21 +1,9 @@ package main import ( - "fmt" - "os" - "strings" - - "./imp" + "./cmd" ) func main() { - var a [3]int // array of 3 integers - - // Print the elements only. - for _, v := range a { - fmt.Printf("%d\n", v) - } - - imp.Count(1) - fmt.Println(strings.Join(os.Args[1:], " ")) + cmd.Execute() } -- GitLab