github.com/nshntarora/pop@v0.1.2/soda/cmd/root.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 8 "github.com/nshntarora/pop" 9 "github.com/nshntarora/pop/internal/defaults" 10 "github.com/spf13/cobra" 11 ) 12 13 var cfgFile string 14 var env string 15 var version bool 16 17 // RootCmd is the entry point of soda CLI. 18 var RootCmd = &cobra.Command{ 19 SilenceUsage: true, 20 Short: "A tasty treat for all your database needs", 21 PersistentPreRun: func(c *cobra.Command, args []string) { 22 fmt.Printf("pop %s\n\n", Version) 23 24 /* NOTE: Do not use c.PersistentFlags. `c` is not always the 25 RootCmd. The naming is confusing. The meaning of "persistent" 26 in the `PersistentPreRun` is something like "this function will 27 be 'sticky' to all subcommands and will run for them. So `c` 28 can be any subcommands. 29 However, the meaning of "persistent" in the `PersistentFlags` 30 is, as the function comment said, "persistent FlagSet 31 specifically set in the **current command**" so it is sticky 32 to specific command! 33 34 Use c.Flags() or c.Root().Flags() here. 35 */ 36 37 // CLI flag has priority 38 if !c.Flags().Changed("env") { 39 env = defaults.String(os.Getenv("GO_ENV"), env) 40 } 41 // TODO! Only do this when the command needs it. 42 setConfigLocation() 43 pop.LoadConfigFile() 44 }, 45 RunE: func(cmd *cobra.Command, args []string) error { 46 if !version { 47 return cmd.Help() 48 } 49 return nil 50 }, 51 } 52 53 // Execute runs RunCmd. 54 func Execute() { 55 if err := RootCmd.Execute(); err != nil { 56 os.Exit(-1) 57 } 58 } 59 60 func init() { 61 RootCmd.Flags().BoolVarP(&version, "version", "v", false, "Show version information") 62 RootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "The configuration file you would like to use.") 63 RootCmd.PersistentFlags().StringVarP(&env, "env", "e", "development", "The environment you want to run migrations against. Will use $GO_ENV if set.") 64 RootCmd.PersistentFlags().BoolVarP(&pop.Debug, "debug", "d", false, "Use debug/verbose mode") 65 } 66 67 func setConfigLocation() { 68 if cfgFile != "" { 69 abs, err := filepath.Abs(cfgFile) 70 if err != nil { 71 return 72 } 73 dir, file := filepath.Split(abs) 74 pop.AddLookupPaths(dir) 75 pop.ConfigName = file 76 } 77 } 78 79 func getConn() *pop.Connection { 80 conn := pop.Connections[env] 81 if conn == nil { 82 fmt.Printf("There is no connection named %s defined!\n", env) 83 os.Exit(1) 84 } 85 return conn 86 }