/
config.go
87 lines (72 loc) · 1.82 KB
/
config.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
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/MontFerret/cli/config"
)
// ConfigCommand command to manipulate with config file
func ConfigCommand(store *config.Store) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Manage Ferret configs",
Args: cobra.MaximumNArgs(0),
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
store.BindFlags(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmd.Help()
}
return fmt.Errorf("unknown command %q", args[0])
},
}
cmd.AddCommand(&cobra.Command{
Use: "get",
Short: "Get a Ferret config value by key",
Args: cobra.MinimumNArgs(1),
PreRun: func(cmd *cobra.Command, _ []string) {
store.BindFlags(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
val, err := store.Get(args[0])
if err == nil {
fmt.Println(val)
return nil
}
if err == config.ErrInvalidFlag {
return fmt.Errorf("%s\n%s", err, config.FlagsStr)
}
return err
},
})
cmd.AddCommand(&cobra.Command{
Use: "set",
Short: "Set a Ferret config value by key",
Args: cobra.MinimumNArgs(2),
PreRun: func(cmd *cobra.Command, _ []string) {
store.BindFlags(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
err := store.Set(args[0], args[1])
if err == config.ErrInvalidFlag {
return fmt.Errorf("%s\n%s", err, config.FlagsStr)
}
return err
},
})
cmd.AddCommand(&cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "Get a list of Ferret config values",
Args: cobra.MaximumNArgs(0),
PreRun: func(cmd *cobra.Command, _ []string) {
store.BindFlags(cmd)
},
Run: func(cmd *cobra.Command, _ []string) {
for _, kv := range store.List() {
fmt.Printf("%s: %v\n", kv.Key, kv.Value)
}
},
})
return cmd
}