forked from forbole/juno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
66 lines (53 loc) · 1.54 KB
/
cmd.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
package init
import (
"fmt"
"io/ioutil"
"os"
"github.com/gotabit/juno/v5/types/config"
"github.com/spf13/cobra"
)
const (
flagReplace = "replace"
)
// NewInitCmd returns the command that should be run in order to properly initialize Juno
func NewInitCmd(cfg *Config) *cobra.Command {
cmd := &cobra.Command{
Use: "init",
Short: "Initializes the configuration files",
RunE: func(cmd *cobra.Command, args []string) error {
// Create the config path if not present
if _, err := os.Stat(config.HomePath); os.IsNotExist(err) {
err = os.MkdirAll(config.HomePath, os.ModePerm)
if err != nil {
return err
}
}
replace, err := cmd.Flags().GetBool(flagReplace)
if err != nil {
return err
}
// Get the config file
configFilePath := config.GetConfigFilePath()
file, _ := os.Stat(configFilePath)
// Check if the file exists and replace is false
if file != nil && !replace {
return fmt.Errorf(
"configuration file already present at %s. If you wish to overwrite it, use the --%s flag",
configFilePath, flagReplace)
}
// Get the config from the flags
yamlCfg := cfg.GetConfigCreator()(cmd)
return writeConfig(yamlCfg, configFilePath)
},
}
cmd.Flags().Bool(flagReplace, false, "overrides any existing configuration")
return cmd
}
// writeConfig allows to write the given configuration into the file present at the given path
func writeConfig(cfg WritableConfig, path string) error {
bz, err := cfg.GetBytes()
if err != nil {
return err
}
return ioutil.WriteFile(path, bz, 0600)
}