-
Notifications
You must be signed in to change notification settings - Fork 9
/
prompt.go
567 lines (462 loc) · 12.7 KB
/
prompt.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
* Copyright 2017-2022 Provide Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package common
import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"github.com/manifoldco/promptui"
"github.com/provideplatform/provide-go/api/baseline"
"github.com/provideplatform/provide-go/api/ident"
"github.com/provideplatform/provide-go/api/nchain"
"github.com/provideplatform/provide-go/api/vault"
"github.com/spf13/cobra"
)
const requireAccountSelectLabel = "Select an account"
const requireApplicationSelectLabel = "Select an application"
const requireConnectorSelectLabel = "Select a connector"
const requireNetworkSelectLabel = "Select a network"
const requireL2NetworkSelectLabel = "Select an l2 network"
const requireOrganizationSelectLabel = "Select an organization"
const requireVaultSelectLabel = "Select a vault"
const requireWalletSelectLabel = "Select a wallet"
const requireWorkgroupSelectLabel = "Select a workgroup"
var commands map[string]*cobra.Command
func normaliseCmd(cmd *cobra.Command, args []string) (string, string) {
flag, _ := regexp.Compile("\\[(.*)")
r, _ := regexp.Compile("\\--(.*)")
usedCommand := strings.Split(cmd.UseLine(), flag.FindString(cmd.UseLine()))
normalisedCommand := strings.TrimSpace(strings.Join(usedCommand, ""))
argsLine := strings.TrimSpace(strings.Join(args, " "))
rmFlagsLine := strings.Split(normalisedCommand, r.FindString(normalisedCommand))
normalisedOutput := strings.TrimSpace(strings.Join(rmFlagsLine, ""))
return normalisedOutput, argsLine
}
func CacheCommands(cmd *cobra.Command) {
if commands == nil {
commands = map[string]*cobra.Command{}
}
command, _ := normaliseCmd(cmd, nil)
hashCmd := sha256.Sum256([]byte(command))
commands[string(hashCmd[:])] = cmd
for _, child := range cmd.Commands() {
CacheCommands(child)
}
}
func CmdExists(cmd *cobra.Command, args []string) (bool, string) {
command, arguments := normaliseCmd(cmd, args)
argsCommandNormalised := fmt.Sprintf("%s %s", command, arguments)
hashCmd := sha256.Sum256([]byte(argsCommandNormalised))
return commands[string(hashCmd[:])] != nil, argsCommandNormalised
}
func CmdExistsOrExit(cmd *cobra.Command, args []string) {
exists, command := CmdExists(cmd, args)
if !exists {
fmt.Printf("%s is not a valid command", command)
os.Exit(1)
}
}
// RequireApplication is equivalent to a required --application flag
func RequireApplication() error {
if ApplicationID != "" {
return nil
}
opts := make([]string, 0)
apps, _ := ident.ListApplications(RequireUserAccessToken(), map[string]interface{}{})
for _, app := range apps {
opts = append(opts, *app.Name)
}
prompt := promptui.Select{
Label: requireApplicationSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
Application = apps[i]
ApplicationID = apps[i].ID.String()
return nil
}
// RequireWorkgroup is equivalent to a required --workgroup flag
func RequireWorkgroup() error {
if WorkgroupID != "" {
token, err := ResolveOrganizationToken()
if err != nil {
return err
}
wg, err := baseline.GetWorkgroupDetails(*token.AccessToken, WorkgroupID, map[string]interface{}{})
if err != nil {
return err
}
raw, err := json.Marshal(wg)
if err != nil {
return err
}
err = json.Unmarshal(raw, &Workgroup)
return err
}
var token string
// FIXME-- should check if token is in memory
tkn, err := ident.CreateToken(RequireUserAccessToken(), map[string]interface{}{
"scope": "offline_access",
"organization_id": OrganizationID,
})
if err == nil && tkn.AccessToken != nil {
token = *tkn.AccessToken
} else if err != nil {
token = RequireUserAccessToken()
}
opts := make([]string, 0)
workgroups, _ := baseline.ListWorkgroups(token, map[string]interface{}{})
for _, app := range workgroups {
opts = append(opts, *app.Name)
}
prompt := promptui.Select{
Label: requireWorkgroupSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
WorkgroupID = workgroups[i].ID.String()
wg := workgroups[i]
raw, err := json.Marshal(wg)
if err != nil {
return err
}
err = json.Unmarshal(raw, &Workgroup)
return err
}
// RequireConnector is equivalent to a required --connector flag
func RequireConnector(params map[string]interface{}) error {
if ConnectorID != "" {
return nil
}
opts := make([]string, 0)
connectors, _ := nchain.ListConnectors(RequireAPIToken(), params)
for _, connector := range connectors {
opts = append(opts, *connector.Name)
}
prompt := promptui.Select{
Label: requireConnectorSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
ConnectorID = connectors[i].ID.String()
return nil
}
// RequireNetwork is equivalent to a required --network flag
func RequireNetwork() error {
if NetworkID != "" {
return nil
}
opts := make([]string, 0)
networks, _ := nchain.ListNetworks(RequireUserAccessToken(), map[string]interface{}{})
for _, network := range networks {
opts = append(opts, *network.Name)
}
prompt := promptui.Select{
Label: requireNetworkSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
NetworkID = networks[i].ID.String()
return nil
}
// RequireL1Network is equivalent to a required --network flag; but list options filtered to show only public l1 networks
func RequireL1Network() error {
if NetworkID != "" {
return nil
}
opts := make([]string, 0)
networks, _ := nchain.ListNetworks(RequireUserAccessToken(), map[string]interface{}{
"public": "true",
"layer2": "false",
})
for _, network := range networks {
opts = append(opts, *network.Name)
}
prompt := promptui.Select{
Label: requireNetworkSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
NetworkID = networks[i].ID.String()
return nil
}
// RequireL2Network is equivalent to a required --l2 flag; but list options filtered to show only public l2 networks
func RequireL2Network() error {
if L2NetworkID != "" {
return nil
}
opts := make([]string, 0)
networks, _ := nchain.ListNetworks(RequireUserAccessToken(), map[string]interface{}{
"public": "true",
"layer2": "true",
})
for _, network := range networks {
opts = append(opts, *network.Name)
}
prompt := promptui.Select{
Label: requireNetworkSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
L2NetworkID = networks[i].ID.String()
return nil
}
// RequireOrganization is equivalent to a required --organization flag
func RequireOrganization() error {
if OrganizationID != "" {
// TODO-- should also check if Organization is set; if so, check that IDs match, else refetch and re-set Organization -- same for other similar Require() methods
org, _ := ident.GetOrganizationDetails(RequireUserAccessToken(), OrganizationID, map[string]interface{}{})
raw, err := json.Marshal(org)
if err != nil {
return err
}
err = json.Unmarshal(raw, &Organization)
return err
}
opts := make([]string, 0)
orgs, _ := ident.ListOrganizations(RequireUserAccessToken(), map[string]interface{}{})
for _, org := range orgs {
opts = append(opts, *org.Name)
}
prompt := promptui.Select{
Label: requireOrganizationSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
OrganizationID = *orgs[i].ID
org := orgs[i]
raw, err := json.Marshal(org)
if err != nil {
return err
}
err = json.Unmarshal(raw, &Organization)
return err
}
// RequireVault is equivalent to a required --vault flag
func RequireVault() error {
if VaultID != "" {
return nil
}
opts := make([]string, 0)
vaults, _ := vault.ListVaults(RequireAPIToken(), map[string]interface{}{})
for _, vlt := range vaults {
opts = append(opts, *vlt.Name)
}
prompt := promptui.Select{
Label: requireVaultSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
VaultID = vaults[i].ID.String()
return nil
}
// RequireAccount is equivalent to a required --account flag
func RequireAccount(params map[string]interface{}) error {
if AccountID != "" {
return nil
}
opts := make([]string, 0)
accounts, _ := nchain.ListAccounts(RequireAPIToken(), params)
for _, acct := range accounts {
opts = append(opts, *acct.PublicKey)
}
prompt := promptui.Select{
Label: requireWalletSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
AccountID = accounts[i].ID.String()
return nil
}
// RequireWallet is equivalent to a required --wallet flag
func RequireWallet() error {
if WalletID != "" {
return nil
}
opts := make([]string, 0)
wallets, _ := nchain.ListWallets(RequireAPIToken(), map[string]interface{}{})
for _, wallet := range wallets {
opts = append(opts, *wallet.PublicKey)
}
prompt := promptui.Select{
Label: requireWalletSelectLabel,
Items: opts,
}
i, _, err := prompt.Run()
if err != nil {
return err
}
WalletID = wallets[i].ID.String()
return nil
}
var MandatoryValidation = func(input string) error {
if input == "" {
return errors.New("required")
}
return nil
}
var EmailValidation = func(input string) error {
if input == "" {
return errors.New("email is required")
}
re := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
if !re.MatchString(input) {
return errors.New("invalid email")
}
return nil
}
// RequireTermsOfServiceAgreement is equivalent to a required --terms flag
func RequireTermsOfServiceAgreement() bool {
prompt := promptui.Prompt{
IsConfirm: true,
Label: "I have read and accept the terms of service (https://provide.services/terms)",
}
result, err := prompt.Run()
if err != nil {
return false
}
return strings.ToLower(result) == "y" // this may be redundant bc if err != nil, then result != "y"
}
// RequirePrivacyPolicyAgreement is equivalent to a required --privacy flag
func RequirePrivacyPolicyAgreement() bool {
prompt := promptui.Prompt{
IsConfirm: true,
Label: "I have read and accept the privacy policy (https://provide.services/privacy-policy)",
}
result, err := prompt.Run()
if err != nil {
return false
}
return strings.ToLower(result) == "y"
}
var MandatoryNumberValidation = func(input string) error {
if len(input) < 1 {
return errors.New("field cant be nil")
}
_, err := strconv.ParseFloat(input, 64)
if err != nil {
return errors.New("invalid number")
}
return nil
}
var NumberValidation = func(input string) error {
_, err := strconv.ParseFloat(input, 64)
if err != nil {
return errors.New("invalid number")
}
return nil
}
var NoValidation = func(input string) error {
return nil
}
var JSONValidation = func(input string) error {
if len(input) < 1 {
return errors.New("field cant be nil")
}
var js map[string]interface{}
if json.Unmarshal([]byte(input), &js) != nil {
return errors.New("invalid JSON")
}
return nil
}
var HexValidation = func(input string) error {
re := regexp.MustCompile("^0x[0-9a-fA-F]{40}$")
isHex := re.MatchString(input)
if !isHex {
return errors.New("input is not a Hex")
}
return nil
}
func FreeInput(label string, defaultValue string, validate func(string) error) string {
var prompt = promptui.Prompt{}
if label == "Password" {
prompt = promptui.Prompt{
Label: label,
Validate: validate,
Default: defaultValue,
Mask: '*',
}
} else {
prompt = promptui.Prompt{
Label: label,
Validate: validate,
Default: defaultValue,
}
}
result, err := prompt.Run()
if err != nil {
os.Exit(1)
return err.Error()
}
return result
}
func SelectInput(args []string, label string) string {
prompt := promptui.Select{
Label: label,
Items: args,
}
_, result, err := prompt.Run()
if err != nil {
os.Exit(1)
return err.Error()
}
return result
}
func PromptPagination(paginate bool, page uint64, rpp uint64) (uint64, uint64) {
if paginate {
if page == DefaultPage {
result := FreeInput("Page", fmt.Sprintf("%d", DefaultPage), MandatoryNumberValidation)
page, _ = strconv.ParseUint(result, 10, 64)
}
if rpp == DefaultRpp {
result := FreeInput("RPP", fmt.Sprintf("%d", DefaultRpp), MandatoryValidation)
rpp, _ = strconv.ParseUint(result, 10, 64)
}
}
return page, rpp
}