This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
/
cmd_init.go
103 lines (86 loc) · 1.89 KB
/
cmd_init.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
package letitgo
import (
"fmt"
"io/ioutil"
"os"
"github.com/NoUseFreak/letitgo/internal/app/ui"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
survey "github.com/AlecAivazis/survey/v2"
yaml "gopkg.in/yaml.v2"
)
var initCmd = &cobra.Command{
Use: "init",
Short: "Init LetItGo config file",
Long: `Init`,
Run: executeInit,
}
func init() {
rootCmd.AddCommand(initCmd)
}
func executeInit(cmd *cobra.Command, args []string) {
ui.Title("LetItGo")
content, err := getData()
if err != nil {
logrus.Error(err)
os.Exit(1)
}
cfgFile, _ := cmd.Flags().GetString("config")
_, err = os.Stat(cfgFile)
if os.IsNotExist(err) {
ui.Phase("Creating config")
if err := ioutil.WriteFile(cfgFile, []byte(content), 0644); err != nil {
ui.Error(err.Error())
os.Exit(1)
}
os.Exit(0)
}
ui.Phase("Printing config")
fmt.Println("\n\n---\n" + content)
}
func getData() (string, error) {
name := ""
_ = survey.AskOne(&survey.Input{
Message: "Project name",
}, &name)
description := ""
_ = survey.AskOne(&survey.Input{
Message: "Project description",
}, &description)
enabled := []yaml.MapSlice{}
for _, a := range getActions() {
if askEnableAction(a.Name()) {
action := yaml.MapSlice{{
Key: "type",
Value: a.Name(),
}}
for k, v := range a.GetInitConfig() {
action = append(action, yaml.MapItem{
Key: k,
Value: v,
})
}
enabled = append(enabled, action)
}
}
ligcfg := map[string]interface{}{
"letitgo": yaml.MapSlice{
{Key: "name", Value: name},
{Key: "description", Value: description},
{Key: "actions", Value: enabled},
},
}
out, err := yaml.Marshal(ligcfg)
if err != nil {
return "", err
}
return string(out), nil
}
func askEnableAction(name string) bool {
response := false
_ = survey.AskOne(&survey.Confirm{
Message: fmt.Sprintf("Enable action %s", name),
Default: true,
}, &response)
return response
}