github.com/seeker-insurance/kit@v0.0.13/cmd/cmd.go (about) 1 //Package cmd contains helper functions for working with the Cobra command-line interface: github.com/spf13/cobra 2 package cmd 3 4 import ( 5 "github.com/seeker-insurance/kit/assets" 6 "github.com/seeker-insurance/kit/cmd/api" 7 "github.com/seeker-insurance/kit/cmd/migrate" 8 "github.com/seeker-insurance/kit/config" 9 "github.com/seeker-insurance/kit/log" 10 "github.com/spf13/cobra" 11 ) 12 13 var ( 14 Root *cobra.Command 15 childCommands []*cobra.Command 16 availableCommands = make(map[string]*cobra.Command) 17 verbose bool 18 cfgFile string 19 NoDb bool 20 ) 21 22 //Add a child command to the root 23 func Add(command *cobra.Command) { 24 childCommands = append(childCommands, command) 25 } 26 27 //Use the commands with the names specified 28 func Use(cmds ...string) { 29 for _, key := range cmds { 30 Add(availableCommands[key]) 31 } 32 } 33 34 //Init initalizes the cobra CLI for the specified command, if any 35 func Init(appName string, rootCmd *cobra.Command, get assets.AssetGet, dir assets.AssetDir) error { 36 assets.Manager = &assets.AssetManager{Get: get, Dir: dir} 37 38 if rootCmd == nil { 39 log.Info("cmd.Init: rootCmd is nil") 40 } else { 41 addRoot(rootCmd) 42 } 43 44 return config.Load(appName, cfgFile) 45 } 46 47 func addRoot(cmd *cobra.Command) { 48 Root = cmd 49 50 Root.PersistentFlags().BoolVar(&verbose, "verbose", false, "more verbose error reporting") 51 Root.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $PWD/config.yaml)") 52 Root.PersistentFlags().BoolVar(&NoDb, "nodb", false, "allow DB-less execution") 53 54 for _, c := range childCommands { 55 if c != nil { 56 Root.AddCommand(c) 57 } 58 } 59 } 60 61 func init() { 62 availableCommands["api"] = api.ApiCmd 63 availableCommands["migrate"] = migrate.MigrateCmd 64 }