-
Notifications
You must be signed in to change notification settings - Fork 0
/
change_environment.go
107 lines (93 loc) · 2.49 KB
/
change_environment.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
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
"github.com/percosis-labs/percosis/v16/app"
)
const (
EnvVariable = "PERCOSISD_ENVIRONMENT"
EnvMainnet = "mainnet"
EnvLocalnet = "localpercosis"
)
// ExportAirdropSnapshotCmd generates a snapshot.json from a provided exported genesis.json.
func ChangeEnvironmentCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "set-env [new env]",
Short: "Set home environment variables for commands",
Long: `Set home environment variables for commands
Example:
percosisd set-env mainnet
percosisd set-env localpercosis
percosisd set-env $HOME/.custom-dir
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
newEnv := args[0]
currentEnvironment := getHomeEnvironment()
fmt.Println("Current environment: ", currentEnvironment)
if _, err := environmentNameToPath(newEnv); err != nil {
return err
}
fmt.Println("New environment: ", newEnv)
envMap := make(map[string]string)
envMap[EnvVariable] = newEnv
err := godotenv.Write(envMap, filepath.Join(app.DefaultNodeHome, ".env"))
if err != nil {
return err
}
return nil
},
}
return cmd
}
// PrintEnvironmentCmd prints the current environment.
func PrintEnvironmentCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "get-env",
Short: "Prints the current environment",
Long: `Prints the current environment
Example:
percosisd get-env'
Returns one of:
- mainnet implying $HOME/.percosisd
- localpercosis implying $HOME/.percosisd-local
- localpercosis
- custom path`,
RunE: func(cmd *cobra.Command, args []string) error {
environment := getHomeEnvironment()
path, err := environmentNameToPath(environment)
if err != nil {
return err
}
fmt.Println("Environment name: ", environment)
fmt.Println("Environment path: ", path)
return nil
},
}
return cmd
}
func environmentNameToPath(environmentName string) (string, error) {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
switch environmentName {
case EnvMainnet:
return app.DefaultNodeHome, nil
case EnvLocalnet:
return filepath.Join(userHomeDir, ".percosisd-local/"), nil
default:
percosisdPath := filepath.Join(userHomeDir, environmentName)
_, err := os.Stat(percosisdPath)
if os.IsNotExist(err) {
// Creating new environment directory
if err := os.Mkdir(percosisdPath, os.ModePerm); err != nil {
return "", err
}
}
return percosisdPath, nil
}
}