-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcreate.go
More file actions
92 lines (76 loc) · 2.08 KB
/
create.go
File metadata and controls
92 lines (76 loc) · 2.08 KB
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
package wallet
import (
"fmt"
"strings"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/oasisprotocol/cli/cmd/common"
"github.com/oasisprotocol/cli/config"
"github.com/oasisprotocol/cli/wallet"
)
var accKind string
var createCmd = &cobra.Command{
Use: "create [<name>]",
Short: "Create a new account",
Args: cobra.MaximumNArgs(1),
Run: func(_ *cobra.Command, args []string) {
cfg := config.Global()
var name string
switch len(args) {
case 0:
name = generateAccountName(cfg)
default:
name = args[0]
checkAccountExists(cfg, name)
}
af, err := wallet.Load(accKind)
cobra.CheckErr(err)
// Ask for passphrase to encrypt the wallet with.
var passphrase string
if af.RequiresPassphrase() {
passphrase = common.AskNewPassphrase()
}
accCfg := &config.Account{
Kind: accKind,
}
err = accCfg.SetConfigFromFlags()
cobra.CheckErr(err)
err = cfg.Wallet.Create(name, passphrase, accCfg)
cobra.CheckErr(err)
err = cfg.Save()
cobra.CheckErr(err)
},
}
func generateAccountName(cfg *config.Config) string {
for i := 1; ; i++ {
name := fmt.Sprintf("account_%d", i)
if _, ok := cfg.Wallet.All[name]; ok {
continue
}
if _, ok := cfg.AddressBook.All[name]; ok {
continue
}
return name
}
}
func checkAccountExists(cfg *config.Config, name string) {
if _, exists := cfg.Wallet.All[name]; exists {
cobra.CheckErr(fmt.Errorf("account '%s' already exists in the wallet", name))
}
if _, exists := cfg.AddressBook.All[name]; exists {
cobra.CheckErr(fmt.Errorf("address named '%s' already exists in the address book", name))
}
}
func init() {
flags := flag.NewFlagSet("", flag.ContinueOnError)
kinds := make([]string, 0, len(wallet.AvailableKinds()))
for _, w := range wallet.AvailableKinds() {
kinds = append(kinds, w.Kind())
}
flags.StringVar(&accKind, "kind", "file", fmt.Sprintf("Account kind [%s]", strings.Join(kinds, ", ")))
// TODO: Group flags in usage by tweaking the usage template/function.
for _, af := range wallet.AvailableKinds() {
flags.AddFlagSet(af.Flags())
}
createCmd.Flags().AddFlagSet(flags)
}