|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/hostinger/api-cli/cmd/vps" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "github.com/spf13/viper" |
| 10 | +) |
| 11 | + |
| 12 | +var cfgFile string |
| 13 | + |
| 14 | +var ( |
| 15 | + OutputFormat string |
| 16 | + validFormats = []string{"json", "table", "tree"} |
| 17 | +) |
| 18 | + |
| 19 | +var RootCmd = &cobra.Command{ |
| 20 | + Use: "hapi", |
| 21 | + Short: "Hostinger API Command Line Interface", |
| 22 | + Long: ``, |
| 23 | +} |
| 24 | + |
| 25 | +// Execute adds all child commands to the root command and sets flags appropriately. |
| 26 | +// This is called by main.main(). It only needs to happen once to the rootCmd. |
| 27 | +func Execute() { |
| 28 | + err := RootCmd.Execute() |
| 29 | + if err != nil { |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func init() { |
| 35 | + cobra.OnInitialize(initConfig) |
| 36 | + |
| 37 | + RootCmd.DisableAutoGenTag = true |
| 38 | + |
| 39 | + RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file (default is $HOME/.hapi.yaml)") |
| 40 | + RootCmd.PersistentFlags().StringVar(&OutputFormat, "format", "", "Output format type (json|table|tree), default: table") |
| 41 | + |
| 42 | + RootCmd.RegisterFlagCompletionFunc("format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 43 | + return validFormats, cobra.ShellCompDirectiveNoFileComp |
| 44 | + }) |
| 45 | + |
| 46 | + RootCmd.AddCommand(vps.VpsGroupCmd) |
| 47 | +} |
| 48 | + |
| 49 | +func initConfig() { |
| 50 | + if cfgFile != "" { |
| 51 | + viper.SetConfigFile(cfgFile) |
| 52 | + } else { |
| 53 | + home, err := os.UserHomeDir() |
| 54 | + cobra.CheckErr(err) |
| 55 | + |
| 56 | + viper.AddConfigPath(home) |
| 57 | + viper.SetConfigType("yaml") |
| 58 | + viper.SetConfigName(".hapi") |
| 59 | + } |
| 60 | + |
| 61 | + viper.AutomaticEnv() // read in environment variables that match |
| 62 | + if err := viper.ReadInConfig(); err == nil { |
| 63 | + fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) |
| 64 | + } |
| 65 | +} |
0 commit comments