-
Notifications
You must be signed in to change notification settings - Fork 5
/
root.go
89 lines (68 loc) · 2.18 KB
/
root.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cmd
import (
"path/filepath"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/barnbridge/internal-api/config"
)
var log = logrus.WithField("module", "main")
var (
configPath string
version bool
verbose, vverbose bool
RootCmd = &cobra.Command{
Use: "internal-api",
Short: "Run the BarnBridge internal api",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
err := viper.BindPFlags(cmd.Flags())
if err != nil {
log.Fatal(err)
}
if configPath != "" {
// get the filepath
abs, err := filepath.Abs(configPath)
if err != nil {
log.Error("Error reading filepath: ", err.Error())
}
// get the config name
base := filepath.Base(abs)
// get the path
path := filepath.Dir(abs)
//
viper.SetConfigName(strings.Split(base, ".")[0])
viper.AddConfigPath(path)
}
viper.AddConfigPath(".")
// Find and read the config file; Handle errors reading the config file
if err := viper.ReadInConfig(); err != nil {
log.Info("Could not load config file. Falling back to args. Error: ", err)
}
buildDBConnectionString()
initLogging()
config.Load()
},
Run: func(cmd *cobra.Command, args []string) {
// fall back on default help if no args/flags are passed
cmd.HelpFunc()(cmd, args)
},
}
)
func init() {
cobra.OnInitialize(func() {
viper.Set("version", RootCmd.Version)
})
viper.SetEnvPrefix("BB")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
viper.AutomaticEnv()
// persistent flags
RootCmd.PersistentFlags().StringVar(&configPath, "config", "", "/path/to/config.yml")
RootCmd.PersistentFlags().BoolVar(&verbose, "v", false, "Set all logging modules to debug (shorthand for `--logging=*=debug`)")
RootCmd.PersistentFlags().BoolVar(&vverbose, "vv", false, "Set all logging modules to trace (shorthand for `--logging=*=trace`)")
RootCmd.PersistentFlags().String("logging", "*=info", "Display debug messages")
viper.BindPFlag("logging", RootCmd.Flag("logging"))
// local flags;
RootCmd.Flags().BoolVar(&version, "version", false, "Display the current version of this CLI")
addMetricsFlags(RootCmd)
}