forked from 0xPolygon/polygon-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflag_loader.go
More file actions
78 lines (62 loc) · 1.72 KB
/
flag_loader.go
File metadata and controls
78 lines (62 loc) · 1.72 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
package flag_loader
import (
"fmt"
"os"
"math/big"
"github.com/spf13/cobra"
)
const (
rpcUrlFlagName, rpcUrlEnvVar = "rpc-url", "ETH_RPC_URL"
privateKeyFlagName, privateKeyEnvVar = "private-key", "PRIVATE_KEY"
)
type BigIntValue struct {
Val *big.Int
}
func (b *BigIntValue) String() string {
// Return the decimal representation
return b.Val.String()
}
func (b *BigIntValue) Set(s string) error {
// Parse the string in base 10
if _, ok := b.Val.SetString(s, 10); !ok {
return fmt.Errorf("invalid big integer: %q", s)
}
return nil
}
func (b *BigIntValue) Type() string {
return "big.Int"
}
func GetRpcUrlFlagValue(cmd *cobra.Command) *string {
v, _ := getFlagValue(cmd, rpcUrlFlagName, rpcUrlEnvVar, false)
return v
}
func GetRequiredRpcUrlFlagValue(cmd *cobra.Command) (*string, error) {
return getFlagValue(cmd, rpcUrlFlagName, rpcUrlEnvVar, true)
}
func GetPrivateKeyFlagValue(cmd *cobra.Command) *string {
v, _ := getFlagValue(cmd, privateKeyFlagName, privateKeyEnvVar, false)
return v
}
func GetRequiredPrivateKeyFlagValue(cmd *cobra.Command) (*string, error) {
return getFlagValue(cmd, privateKeyFlagName, privateKeyEnvVar, true)
}
func getFlagValue(cmd *cobra.Command, flagName, envVarName string, required bool) (*string, error) {
flag := cmd.Flag(flagName)
var flagValue string
if flag.Changed {
flagValue = flag.Value.String()
}
flagDefaultValue := flag.DefValue
envVarValue := os.Getenv(envVarName)
value := flagDefaultValue
if envVarValue != "" {
value = envVarValue
}
if flag.Changed {
value = flagValue
}
if required && (!flag.Changed && envVarValue == "") {
return nil, fmt.Errorf("required flag(s) \"%s\" not set", flagName)
}
return &value, nil
}