forked from aergoio/aergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
117 lines (95 loc) · 2.43 KB
/
root.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
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package cmd
import (
"fmt"
"log"
"os"
"github.com/aergoio/aergo/cmd/aergocli/util"
"github.com/spf13/cobra"
"google.golang.org/grpc"
)
const aergosystem = "aergo.system"
var (
// Used for test.
test bool
// Used for flags.
home string
cfgFile string
host string
port int32
privKey string
pw string
dataDir string
from string
to string
amount string
unit string
name string
address string
stateroot string
proof bool
compressed bool
staking bool
remote bool
importFormat string
rootConfig CliConfig
rootCmd = &cobra.Command{
Use: "aergocli",
Short: "Aergo light commandline interface",
Long: `Aergo is right`,
PersistentPreRun: connectAergo,
PersistentPostRun: disconnectAergo,
}
)
func init() {
log.SetOutput(os.Stderr)
cobra.OnInitialize(initConfig)
rootCmd.SetOutput(os.Stdout)
rootCmd.PersistentFlags().StringVar(&home, "home", "", "aergo cli home path")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is cliconfig.toml)")
rootCmd.PersistentFlags().StringVarP(&host, "host", "H", "localhost", "Host address to aergo server")
rootCmd.PersistentFlags().Int32VarP(&port, "port", "p", 7845, "Port number to aergo server")
}
func initConfig() {
cliCtx := NewCliContext(home, cfgFile)
cliCtx.Vc.BindPFlag("host", rootCmd.PersistentFlags().Lookup("host"))
cliCtx.Vc.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))
cliCtx.BindPFlags(rootCmd.PersistentFlags())
rootConfig = cliCtx.GetDefaultConfig().(CliConfig)
err := cliCtx.LoadOrCreateConfig(&rootConfig)
if err != nil {
log.Fatalf("Fail to load configuration file %v: %v", cliCtx.Vc.ConfigFileUsed(), err)
}
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
// GetServerAddress return ip address and port of server
func GetServerAddress() string {
return fmt.Sprintf("%s:%d", rootConfig.Host, rootConfig.Port)
}
func connectAergo(cmd *cobra.Command, args []string) {
if test {
return
}
serverAddr := GetServerAddress()
opts := []grpc.DialOption{grpc.WithInsecure()}
var ok bool
client, ok = util.GetClient(serverAddr, opts).(*util.ConnClient)
if !ok {
log.Fatal("internal error. wrong RPC client type")
}
}
func disconnectAergo(cmd *cobra.Command, args []string) {
if test {
return
}
if client != nil {
client.Close()
}
}