1/*
2Copyright © 2019 NAME HERE <EMAIL ADDRESS>
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16package main
17
18import (
19	"fmt"
20	"os"
21
22	"github.com/spf13/cobra"
23
24	homedir "github.com/mitchellh/go-homedir"
25	"github.com/spf13/viper"
26)
27
28var cfgFile string
29
30// rootCmd represents the base command when called without any subcommands
31var rootCmd = &cobra.Command{
32	Use:   "example",
33	Short: "A brief description of your application",
34	Long: `A longer description that spans multiple lines and likely contains
35examples and usage of using your application. For example:
36
37Cobra is a CLI library for Go that empowers applications.
38This application is a tool to generate the needed files
39to quickly create a Cobra application.`,
40	// Uncomment the following line if your bare application
41	// has an action associated with it:
42	//	Run: func(cmd *cobra.Command, args []string) { },
43}
44
45// Execute adds all child commands to the root command and sets flags appropriately.
46// This is called by main.main(). It only needs to happen once to the rootCmd.
47func Execute() {
48	if err := rootCmd.Execute(); err != nil {
49		fmt.Println(err)
50		os.Exit(1)
51	}
52}
53
54func init() {
55	cobra.OnInitialize(initConfig)
56
57	// Here you will define your flags and configuration settings.
58	// Cobra supports persistent flags, which, if defined here,
59	// will be global for your application.
60
61	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.example.yaml)")
62
63	// Cobra also supports local flags, which will only run
64	// when this action is called directly.
65	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
66}
67
68// initConfig reads in config file and ENV variables if set.
69func initConfig() {
70	if cfgFile != "" {
71		// Use config file from the flag.
72		viper.SetConfigFile(cfgFile)
73	} else {
74		// Find home directory.
75		home, err := homedir.Dir()
76		if err != nil {
77			fmt.Println(err)
78			os.Exit(1)
79		}
80
81		// Search config in home directory with name ".example" (without extension).
82		viper.AddConfigPath(home)
83		viper.SetConfigName(".example")
84	}
85
86	viper.AutomaticEnv() // read in environment variables that match
87
88	// If a config file is found, read it in.
89	if err := viper.ReadInConfig(); err == nil {
90		fmt.Println("Using config file:", viper.ConfigFileUsed())
91	}
92}
93