1// Copyright © 2015 Steve Francia <spf@spf13.com>.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package cmd
15
16import (
17	"fmt"
18
19	homedir "github.com/mitchellh/go-homedir"
20	"github.com/spf13/cobra"
21	"github.com/spf13/viper"
22)
23
24var (
25	// Used for flags.
26	cfgFile     string
27	userLicense string
28
29	rootCmd = &cobra.Command{
30		Use:   "cobra",
31		Short: "A generator for Cobra based Applications",
32		Long: `Cobra is a CLI library for Go that empowers applications.
33This application is a tool to generate the needed files
34to quickly create a Cobra application.`,
35	}
36)
37
38// Execute executes the root command.
39func Execute() error {
40	return rootCmd.Execute()
41}
42
43func init() {
44	cobra.OnInitialize(initConfig)
45
46	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
47	rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
48	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
49	rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
50	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
51	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
52	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
53	viper.SetDefault("license", "apache")
54
55	rootCmd.AddCommand(addCmd)
56	rootCmd.AddCommand(initCmd)
57}
58
59func initConfig() {
60	if cfgFile != "" {
61		// Use config file from the flag.
62		viper.SetConfigFile(cfgFile)
63	} else {
64		// Find home directory.
65		home, err := homedir.Dir()
66		if err != nil {
67			er(err)
68		}
69
70		// Search config in home directory with name ".cobra" (without extension).
71		viper.AddConfigPath(home)
72		viper.SetConfigName(".cobra")
73	}
74
75	viper.AutomaticEnv()
76
77	if err := viper.ReadInConfig(); err == nil {
78		fmt.Println("Using config file:", viper.ConfigFileUsed())
79	}
80}
81