summaryrefslogtreecommitdiff
path: root/cmd/root.go
blob: 9e87b5b90ae8d506956611d4e8959fa91880f0da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cmd

import (
	"log"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// LogLevel Flag
var LogLevel = "info"
var LogFormat = "json"
var cfgFile string
var rootCmd = &cobra.Command{
	Use:   "apjournal",
	Short: "apjournal",
}

func init() {
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&cfgFile,
		"config", "", "config file (default is ./config.yml)")
	viper.SetConfigName("config")
	viper.AddConfigPath(".")                  // First try to load the config from the current directory
	viper.AddConfigPath("$HOME")              // Then try to load it from the HOME directory
	viper.AddConfigPath("/etc/apjournal/") // As a last resort try to load it from the /etc/
}

func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	}
	viper.SetEnvPrefix("CFG")
	viper.AutomaticEnv()
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("Can't read configuration file", "error", err)
	}
}

// Execute the commands
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Fatal("failed to execute", "error", err)
	}
}