-
Notifications
You must be signed in to change notification settings - Fork 6
/
cli.go
221 lines (188 loc) · 5.95 KB
/
cli.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package cli
import (
"fmt"
"log"
"os"
"path"
"runtime"
"strings"
"github.com/cherryservers/cherryctl/internal/outputs"
"github.com/cherryservers/cherrygo/v3"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
const (
envPrefix = "CHERRY"
configPathSuffix = "/.config/cherry"
defaultContext = "default"
)
type Client struct {
apiClient *cherrygo.Client
fields *[]string
queryParams map[string]string
cfgFile string
context string
outputFormat string
cherryToken string
apiURL string
Version string
rootCmd *cobra.Command
viper *viper.Viper
}
func (c *Client) SetToken(token string) {
c.cherryToken = token
}
func NewClient(cherryToken, apiURL, Version string) *Client {
return &Client{
cherryToken: cherryToken,
apiURL: apiURL,
Version: Version,
}
}
func (c *Client) API(cmd *cobra.Command) *cherrygo.Client {
if c.cherryToken == "" {
log.Fatal("Cherry Servers API authentication token not provided. Please set the 'CHERRY_AUTH_TOKEN' environment variable or create a configuration file using 'cherryctl init'.")
}
if c.apiClient == nil {
args := []cherrygo.ClientOpt{cherrygo.WithAuthToken(c.cherryToken), cherrygo.WithUserAgent("cherry-cli/" + c.Version)}
if c.apiURL != "" {
args = append(args, cherrygo.WithURL(c.apiURL))
}
client, err := cherrygo.NewClient(args...)
if err != nil {
return nil
}
c.apiClient = client
}
return c.apiClient
}
func (c *Client) Format() outputs.Format {
format := outputs.FormatTable
switch f := outputs.Format(c.outputFormat); f {
case "":
break
case outputs.FormatTable,
outputs.FormatJSON,
outputs.FormatYAML:
format = f
default:
log.Printf("unknown format: %q. Using default.", f)
}
return format
}
func (c *Client) NewCommand() *cobra.Command {
// rootCmd represents the base command when called without any subcommands
rootCmd := &cobra.Command{
Use: "cherryctl",
Short: "Cherry Servers Command Line Interface (CLI)",
Long: `cherryctl is a command line interface (CLI) for Cherry Servers API`,
DisableAutoGenTag: true,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
c.Config(cmd)
},
}
rootCmd.PersistentFlags().String("token", "", "API Token (CHERRY_AUTH_TOKEN)")
rootCmd.PersistentFlags().String("auth-token", "", "API Token (Alias)")
authtoken := rootCmd.PersistentFlags().Lookup("auth-token")
authtoken.Hidden = true
rootCmd.PersistentFlags().StringVar(&c.cfgFile, "config", c.cfgFile, "Path to JSON or YAML configuration file")
rootCmd.PersistentFlags().StringVar(&c.context, "context", defaultContext, "Specify a custom context name")
rootCmd.PersistentFlags().StringVar(&c.apiURL, "api-url", c.apiURL, "Override default API endpoint")
rootCmd.PersistentFlags().StringVarP(&c.outputFormat, "output", "o", "", "Output format (*table, json, yaml)")
c.fields = rootCmd.PersistentFlags().StringSlice("fields", nil, "Comma separated object field names to output in result. Fields can be used for list and get actions.")
rootCmd.Version = c.Version
c.rootCmd = rootCmd
return c.rootCmd
}
func (c *Client) Config(cmd *cobra.Command) *viper.Viper {
if cmd.Name() != "init" {
if c.viper == nil {
v := viper.New()
v.AutomaticEnv()
replacer := strings.NewReplacer("-", "_", ".", "_")
v.SetEnvKeyReplacer(replacer)
if c.cfgFile != "" {
// Use config file from the flag.
v.SetConfigFile(c.cfgFile)
} else {
// Backward compatability (cherry was renamed to default)
if c.context == defaultContext {
if _, err := os.Stat(c.ConfigFilePath(defaultContext, true)); err != nil {
if _, err := os.Stat(c.ConfigFilePath("cherry", true)); err != nil {
log.Fatalln(fmt.Errorf("Couldn't find configuration file. To initiate run `cherryctl init` command"))
} else {
c.context = "cherry"
}
}
}
// Use context file from the flag.
configDir := defaultConfigPath()
v.SetConfigName(c.context)
v.AddConfigPath(configDir)
}
if err := v.ReadInConfig(); err != nil {
log.Fatalln(fmt.Errorf("Could not read config: %s", err))
}
c.cfgFile = v.ConfigFileUsed()
v.SetEnvPrefix(envPrefix)
c.viper = v
bindFlags(cmd, v)
}
flagToken := cmd.Flag("token").Value.String()
envToken := cmd.Flag("auth-token").Value.String()
c.cherryToken = flagToken
if envToken != "" {
c.cherryToken = envToken
}
return c.viper
}
return nil
}
// Credit to https://carolynvanslyck.com/blog/2020/08/sting-of-the-viper/
func bindFlags(cmd *cobra.Command, v *viper.Viper) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
// Environment variables can't have dashes in them, so bind them to their equivalent
// keys with underscores, e.g. --favorite-color to STING_FAVORITE_COLOR
// if strings.Contains(f.Name, "-") {
// envVarSuffix := strings.ToUpper(strings.ReplaceAll(f.Name, "-", "_"))
// _ = v.BindEnv(f.Name, fmt.Sprintf("%s_%s", envPrefix, envVarSuffix))
// }
// Apply the viper config value to the flag when the flag is not set and viper has a value
if !f.Changed && v.IsSet(f.Name) {
val := v.Get(f.Name)
_ = cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
}
})
}
func defaultConfigPath() string {
return path.Join(userHomeDir(), configPathSuffix)
}
func (c *Client) ConfigFilePath(context string, withExtension bool) string {
dir := defaultConfigPath()
config := path.Join(dir, context)
if withExtension {
config = config + ".yaml"
}
return config
}
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func (c *Client) GetOptions() *cherrygo.GetOptions {
getOptions := &cherrygo.GetOptions{}
if c.rootCmd.Flags().Changed("fields") {
getOptions.Fields = *c.fields
}
if c.rootCmd.Flags().Changed("query-params") {
getOptions.QueryParams = *&c.queryParams
}
return getOptions
}