-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcobra.go
61 lines (48 loc) · 1.3 KB
/
cobra.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
package config
import (
"os"
"strings"
"github.com/skos-ninja/config-loader/pkg/context"
"github.com/skos-ninja/config-loader/pkg/parser"
"github.com/spf13/cobra"
)
var configFlag = ""
func Init(cmd *cobra.Command) {
cmd.PersistentFlags().StringVar(&configFlag, "config", configFlag, "Set the json config data (Input types: file path, environment var name, flag name)")
}
func Load(cmd *cobra.Command, config interface{}) error {
return load(cmd, config)
}
func MustLoad(cmd *cobra.Command, config interface{}) {
err := load(cmd, config)
if err != nil {
panic(err)
}
}
func load(cmd *cobra.Command, config interface{}) error {
ctx := context.GetContextWithCmd(cmd)
// Try to read the config json from a file
s, _ := os.ReadFile(configFlag)
err := setJSONConfig(string(s), config)
if err != nil {
return err
}
// Try to read the config json from an env
d, _ := parser.EnvironmentParser{}.GetString(ctx, strings.ToUpper(configFlag))
err = setJSONConfig(d, config)
if err != nil {
return err
}
// Try to read the config json from a flag
flag, _ := parser.FlagParser{}.GetString(ctx, configFlag)
err = setJSONConfig(flag, config)
if err != nil {
return err
}
// Perform parsing on each field
err = parser.ParseStruct(ctx, config, false)
if err != nil {
return err
}
return nil
}