forked from Zenithar/go-pkg
/
builder.go
107 lines (91 loc) · 2.58 KB
/
builder.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package cmd
import (
"fmt"
"sort"
"strings"
"github.com/Stoakes/go-pkg/log"
"github.com/Stoakes/go-pkg/types"
"github.com/alecthomas/hcl"
defaults "github.com/mcuadros/go-defaults"
toml "github.com/pelletier/go-toml"
"github.com/spf13/cobra"
"go.uber.org/zap"
yaml "gopkg.in/yaml.v2"
)
var configNewAsEnvFlag bool
// ConfigFileExportFormat controls format for configuration to file export
type ConfigFileExportFormat int
const (
// Hcl export config as HCL file
Hcl ConfigFileExportFormat = iota
// Toml export config as Toml file
Toml
// Yaml export config as Yaml file. default
Yaml
// None does not export config as file
None
)
// NewConfigCommand initialize a cobra config command tree
func NewConfigCommand(conf interface{}, envPrefix string, exportFormat ConfigFileExportFormat) *cobra.Command {
// Uppercase the prefix
upPrefix := strings.ToUpper(envPrefix)
// config
configCmd := &cobra.Command{
Use: "config",
Aliases: []string{"cfg"},
Short: "Manage Service Configuration",
}
// config new
configNewCmd := &cobra.Command{
Use: "new",
Short: "Initialize a default configuration",
Run: func(cmd *cobra.Command, args []string) {
defaults.SetDefaults(conf)
if !configNewAsEnvFlag {
if exportFormat == Toml {
btes, err := toml.Marshal(conf)
if err != nil {
log.For(cmd.Context()).Fatal("Error during configuration export", zap.Error(err))
}
fmt.Fprintf(cmd.OutOrStdout(), string(btes))
return
}
if exportFormat == Hcl {
btes, err := hcl.Marshal(conf)
if err != nil {
log.For(cmd.Context()).Fatal("Error during configuration export", zap.Error(err))
}
fmt.Fprintf(cmd.OutOrStdout(), string(btes))
return
}
if exportFormat == None {
return
}
// Yaml is default export format
btes, err := yaml.Marshal(conf)
if err != nil {
log.For(cmd.Context()).Fatal("Error during configuration export", zap.Error(err))
}
fmt.Fprintf(cmd.OutOrStdout(), string(btes))
return
}
m, err := types.AsEnvVariables(conf, upPrefix, true)
if err != nil {
log.For(cmd.Context()).Fatal("Error during environment variables processing", zap.Error(err))
}
keys := []string{}
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(cmd.OutOrStdout(), "export %s=\"%s\"\n", k, m[k])
}
},
}
// flags
configNewCmd.Flags().BoolVar(&configNewAsEnvFlag, "env", false, "Print configuration as environment variable")
configCmd.AddCommand(configNewCmd)
// Return base command
return configCmd
}