-
Notifications
You must be signed in to change notification settings - Fork 69
/
command.go
310 lines (259 loc) · 7.96 KB
/
command.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package profile
import (
"fmt"
"strconv"
"github.com/AlecAivazis/survey/v2"
"github.com/jedib0t/go-pretty/v6/text"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/newrelic/newrelic-cli/internal/client"
"github.com/newrelic/newrelic-cli/internal/config"
configAPI "github.com/newrelic/newrelic-cli/internal/config/api"
"github.com/newrelic/newrelic-cli/internal/output"
"github.com/newrelic/newrelic-cli/internal/utils"
"github.com/newrelic/newrelic-client-go/pkg/accounts"
)
const (
DefaultProfileName = "default"
defaultProfileString = " (default)"
)
var (
showKeys bool
flagRegion string
apiKey string
insightsInsertKey string
accountID int
licenseKey string
acceptDefaults bool
)
// Command is the base command for managing profiles
var Command = &cobra.Command{
Use: "profile",
Short: "Manage the authentication profiles for this tool",
Aliases: []string{
"profiles", // DEPRECATED: accept but not consistent with the rest of the singular usage
},
}
var cmdAdd = &cobra.Command{
Use: "add",
Short: "Add a new profile",
Long: `Add a new profile
The add command creates a new profile for use with the New Relic CLI.
API key and region are required. An Insights insert key is optional, but required
for posting custom events with the ` + "`newrelic events`" + `command.
`,
Aliases: []string{
"configure",
},
Example: "newrelic profile add --profile <profile> --region <region> --apiKey <apiKey> --insightsInsertKey <insightsInsertKey> --accountId <accountId> --licenseKey <licenseKey>",
PreRun: requireProfileName,
Run: func(cmd *cobra.Command, args []string) {
addStringValueToProfile(config.FlagProfileName, apiKey, config.APIKey, "User API Key", nil, nil)
addStringValueToProfile(config.FlagProfileName, flagRegion, config.Region, "Region", nil, []string{"US", "EU"})
addIntValueToProfile(config.FlagProfileName, accountID, config.AccountID, "Account ID", fetchAccountIDs)
addStringValueToProfile(config.FlagProfileName, insightsInsertKey, config.InsightsInsertKey, "Insights Insert Key", fetchInsightsInsertKey(), nil)
addStringValueToProfile(config.FlagProfileName, licenseKey, config.LicenseKey, "License Key", fetchLicenseKey(), nil)
profile, err := configAPI.GetDefaultProfileName()
if err != nil {
log.Fatal(err)
}
if profile == "" {
if err := configAPI.SetDefaultProfile(config.FlagProfileName); err != nil {
log.Fatal(err)
}
}
log.Info("success")
},
}
func addStringValueToProfile(profileName string, val string, key config.FieldKey, label string, defaultFunc func() (string, error), selectValues []string) {
if val == "" {
defaultValue := configAPI.GetProfileString(profileName, key)
if defaultValue == "" && defaultFunc != nil {
d, err := defaultFunc()
if err != nil {
log.Debug(err)
} else {
defaultValue = d
}
}
prompt := &survey.Input{
Message: fmt.Sprintf("%s:", label),
Default: defaultValue,
}
if selectValues != nil {
prompt.Suggest = func(string) []string { return selectValues }
}
var input string
if !acceptDefaults {
if err := survey.AskOne(prompt, &input); err != nil {
log.Fatal(err)
}
}
if input != "" {
val = input
} else {
val = defaultValue
}
}
if err := configAPI.SetProfileValue(profileName, key, val); err != nil {
log.Fatal(err)
}
}
func addIntValueToProfile(profileName string, val int, key config.FieldKey, label string, defaultFunc func() ([]int, error)) {
if val == 0 {
prompt := &survey.Input{
Message: fmt.Sprintf("%s:", label),
}
defaultValue := configAPI.GetProfileInt(profileName, key)
if defaultValue == 0 && defaultFunc != nil {
d, err := defaultFunc()
if err != nil {
log.Debug(err)
} else {
if len(d) == 1 {
defaultValue = d[0]
} else if len(d) > 0 {
prompt.Suggest = func(string) []string { return utils.IntSliceToStringSlice(d) }
}
}
}
if defaultValue != 0 {
prompt.Default = strconv.Itoa(defaultValue)
}
var input string
if !acceptDefaults {
if err := survey.AskOne(prompt, &input); err != nil {
log.Fatal(err)
}
}
if input != "" {
i, err := strconv.Atoi(input)
if err != nil {
log.Fatal(err)
}
val = i
} else {
val = defaultValue
}
}
if err := configAPI.SetProfileValue(profileName, key, val); err != nil {
log.Fatal(err)
}
}
// fetchAccountID will try and retrieve the available account IDs for the given user.
func fetchAccountIDs() (ids []int, err error) {
client, err := client.NewClient(config.FlagProfileName)
if err != nil {
return nil, err
}
params := accounts.ListAccountsParams{
Scope: &accounts.RegionScopeTypes.IN_REGION,
}
accounts, err := client.Accounts.ListAccounts(params)
if err != nil {
return nil, err
}
for _, a := range accounts {
ids = append(ids, a.ID)
}
return ids, nil
}
var cmdDefault = &cobra.Command{
Use: "default",
Short: "Set the default profile name",
Long: `Set the default profile name
The default command sets the profile to use by default using the specified name.
`,
Example: "newrelic profile default --profile <profile>",
Run: func(cmd *cobra.Command, args []string) {
err := configAPI.SetDefaultProfile(config.FlagProfileName)
if err != nil {
log.Fatal(err)
}
log.Info("success")
},
}
var cmdList = &cobra.Command{
Use: "list",
Short: "List the profiles available",
Long: `List the profiles available
The list command prints out the available profiles' credentials.
`,
Example: "newrelic profile list",
Run: func(cmd *cobra.Command, args []string) {
list := []map[string]interface{}{}
for _, p := range configAPI.GetProfileNames() {
out := map[string]interface{}{}
name := p
if p == configAPI.GetActiveProfileName() {
name += text.FgHiBlack.Sprint(defaultProfileString)
}
out["Name"] = name
configAPI.ForEachProfileFieldDefinition(p, func(d config.FieldDefinition) {
v := configAPI.GetProfileString(p, d.Key)
if !showKeys && d.Sensitive {
v = text.FgHiBlack.Sprint(utils.Obfuscate(v))
}
out[string(d.Key)] = v
})
list = append(list, out)
}
output.Text(list)
},
Aliases: []string{
"ls",
},
}
var cmdDelete = &cobra.Command{
Use: "delete",
Short: "Delete a profile",
Long: `Delete a profile
The delete command removes the profile specified by name.
`,
Example: "newrelic profile delete --profile <profile>",
Run: func(cmd *cobra.Command, args []string) {
err := configAPI.RemoveProfile(config.FlagProfileName)
if err != nil {
log.Fatal(err)
}
log.Info("success")
},
Aliases: []string{
"remove",
"rm",
},
}
func requireProfileName(cmd *cobra.Command, args []string) {
if config.FlagProfileName == "" {
log.Fatal("the --profile argument is required")
}
}
func init() {
// Add
Command.AddCommand(cmdAdd)
cmdAdd.Flags().StringVarP(&flagRegion, "region", "r", "", "the US or EU region")
cmdAdd.Flags().StringVarP(&apiKey, "apiKey", "", "", "your personal API key")
cmdAdd.Flags().StringVarP(&insightsInsertKey, "insightsInsertKey", "", "", "your Insights insert key")
cmdAdd.Flags().StringVarP(&licenseKey, "licenseKey", "", "", "your license key")
cmdAdd.Flags().IntVarP(&accountID, "accountId", "", 0, "your account ID")
cmdAdd.Flags().BoolVarP(&acceptDefaults, "acceptDefaults", "y", false, "suppress prompts and accept default values")
// Default
Command.AddCommand(cmdDefault)
// List
Command.AddCommand(cmdList)
cmdList.Flags().BoolVarP(&showKeys, "show-keys", "s", false, "list the profiles on your keychain")
// Remove
Command.AddCommand(cmdDelete)
}
func fetchLicenseKey() func() (string, error) {
accountID := configAPI.GetProfileInt(config.FlagProfileName, config.AccountID)
return func() (string, error) {
return client.FetchLicenseKey(accountID, config.FlagProfileName)
}
}
func fetchInsightsInsertKey() func() (string, error) {
accountID := configAPI.GetProfileInt(config.FlagProfileName, config.AccountID)
return func() (string, error) {
return client.FetchInsightsInsertKey(accountID, config.FlagProfileName)
}
}