-
Notifications
You must be signed in to change notification settings - Fork 0
/
moonshot_configs.go
68 lines (56 loc) 路 1.54 KB
/
moonshot_configs.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
package moonshot
import (
"context"
"encoding/json"
"os"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/spy16/moonshot/config"
"github.com/spy16/moonshot/errors"
"github.com/spy16/moonshot/log"
)
func (app *App) cmdShowConfigs(ctx context.Context) *cobra.Command {
var format string
cmd := &cobra.Command{
Use: "configs",
Short: "Show currently loaded configurations",
Run: func(cmd *cobra.Command, args []string) {
if err := app.loadConfigs(cmd); err != nil {
log.Fatalf(ctx, "failed to load configurations: %v", err)
}
m := map[string]interface{}{}
if err := mapstructure.Decode(app.CfgPtr, &m); err != nil {
log.Fatalf(ctx, "failed to unmarshal configs: %v", err)
}
var err error
if format == "json" {
err = json.NewEncoder(os.Stdout).Encode(m)
} else if format == "yaml" || format == "yml" {
err = yaml.NewEncoder(os.Stdout).Encode(m)
} else {
err = errors.New("unknown format")
}
if err != nil {
log.Fatalf(ctx, "failed to display configs: %v", err)
}
},
}
cmd.Flags().StringVarP(&format, "format", "f", "yaml", "Output format")
return cmd
}
func (app *App) loadConfigs(cmd *cobra.Command) error {
opts := []config.Option{
config.WithName(strings.ToLower(app.Name)),
config.WithEnv(""),
}
cfgFile, err := cmd.Flags().GetString("config")
if err == nil && cfgFile != "" {
opts = append(opts, config.WithFile(cfgFile))
}
if err := config.Load(app.CfgPtr, opts...); err != nil {
return err
}
return nil
}