-
Notifications
You must be signed in to change notification settings - Fork 1
/
init.go
270 lines (242 loc) · 6.03 KB
/
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package new
import (
"bytes"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/brix-go/brix/config"
"github.com/brix-go/brix/pkg/helper"
"github.com/spf13/cobra"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
var text = "A tool for generating golang project"
var coloredText = "\x1B[38;2;66;211;146m" + text + "\x1B[39m"
type Bar struct {
percent int64 // progress percentage
cur int64 // current progress
total int64 // total value for progress
rate string // the actual progress bar to be printed
graph string // the fill value for progress bar
}
type Project struct {
ProjectName string `survey:"name"`
}
var CmdNew = &cobra.Command{
Use: "new",
Example: "brix new demo-api",
Short: "create a new project.",
Long: `create a new project with brix layout.`,
Run: run,
}
var (
repoURL string
)
func init() {
CmdNew.Flags().StringVarP(&repoURL, "repo-url", "r", repoURL, "layout repo")
}
func NewProject() *Project {
return &Project{}
}
func run(cmd *cobra.Command, args []string) {
p := NewProject()
if len(args) == 0 {
err := survey.AskOne(&survey.Input{
Message: "What is your project name?",
Help: "project name.",
Suggest: nil,
}, &p.ProjectName, survey.WithValidator(survey.Required))
if err != nil {
return
}
} else {
p.ProjectName = args[0]
}
// clone repo
yes, err := p.cloneTemplate()
if err != nil || !yes {
return
}
err = p.replacePackageName()
if err != nil || !yes {
return
}
err = p.replacePackageName()
if err != nil || !yes {
return
}
err = p.modTidy()
if err != nil || !yes {
return
}
p.rmGit()
//p.installWire()
fmt.Sprintf("\n \n,-----. ,--. \n| |) /_ ,--.--.`--',--. ,--. \n| .-. \\| .--',--. \\ `' / \n| '--' /| | | | / /. \\ \n`------' `--' `--''--' '--' \n \n%s", coloredText)
fmt.Printf("🎉 Project \u001B[36m%s\u001B[0m created successfully!\n\n", p.ProjectName)
fmt.Printf("Done. Now run:\n\n")
fmt.Printf("› \033[36mcd %s \033[0m\n", p.ProjectName)
fmt.Printf("› \033[36mbrix run \033[0m\n\n")
}
func (p *Project) cloneTemplate() (bool, error) {
stat, _ := os.Stat(p.ProjectName)
if stat != nil {
var overwrite = false
prompt := &survey.Confirm{
Message: fmt.Sprintf("Folder %s already exists, do you want to overwrite it?", p.ProjectName),
Help: "Remove old project and create new project.",
}
err := survey.AskOne(prompt, &overwrite)
if err != nil {
return false, err
}
if !overwrite {
return false, nil
}
err = os.RemoveAll(p.ProjectName)
if err != nil {
fmt.Println("remove old project error: ", err)
return false, err
}
}
repo := config.FiberRepo
if repoURL == "" {
layout := ""
prompt := &survey.Select{
Message: "Please select a framework:",
Options: []string{
"Fiber",
"Gin Gonic",
},
Description: func(value string, index int) string {
if index == 1 {
return " - It has rich functions such as db, jwt, redis, migration, test, etc"
}
return " - It has rich functions such as db, jwt, redis, kafka, migration, test, etc"
},
}
err := survey.AskOne(prompt, &layout)
if err != nil {
return false, err
}
if layout == "Fiber" {
repo = config.FiberRepo
}
if layout == "Gin Gonic" {
repo = config.GinRepo
}
err = os.RemoveAll(p.ProjectName)
if err != nil {
fmt.Println("remove old project error: ", err)
return false, err
}
} else {
repo = repoURL
}
cmd := exec.Command("git", "clone", repo, p.ProjectName)
_, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("git clone %s error: %s\n", repo, err)
return false, err
}
fmt.Println("Generating project ", p.ProjectName)
var bar Bar
bar.NewOption(0, 100)
for i := 0; i <= 100; i++ {
time.Sleep(500 * time.Millisecond)
bar.Play(int64(i))
}
bar.Finish()
return true, nil
}
func (p *Project) replacePackageName() error {
packageName := helper.GetProjectName(p.ProjectName)
err := p.replaceFiles(packageName)
if err != nil {
return err
}
cmd := exec.Command("go", "mod", "edit", "-module", p.ProjectName)
cmd.Dir = p.ProjectName
_, err = cmd.CombinedOutput()
if err != nil {
fmt.Println("go mod edit error: ", err)
return err
}
return nil
}
func (p *Project) modTidy() error {
fmt.Println("go mod tidy")
cmd := exec.Command("go", "mod", "tidy")
cmd.Dir = p.ProjectName
if err := cmd.Run(); err != nil {
fmt.Println("go mod tidy error: ", err)
return err
}
return nil
}
func (p *Project) rmGit() {
os.RemoveAll(p.ProjectName + "/.git")
}
func (p *Project) installWire() {
fmt.Printf("go install %s\n", config.WireCmd)
cmd := exec.Command("go", "install", config.WireCmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("go install %s error\n", err)
}
}
func (p *Project) replaceFiles(packageName string) error {
err := filepath.Walk(p.ProjectName, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".go" {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
newData := bytes.ReplaceAll(data, []byte(packageName), []byte(p.ProjectName))
if err := os.WriteFile(path, newData, 0644); err != nil {
return err
}
return nil
})
if err != nil {
fmt.Println("walk file error: ", err)
return err
}
return nil
}
func (bar *Bar) NewOption(start, total int64) {
bar.cur = start
bar.total = total
if bar.graph == "" {
bar.graph = "█"
}
bar.percent = bar.getPercent()
for i := 0; i < int(bar.percent); i += 2 {
bar.rate += bar.graph // initial progress position
}
}
func (bar *Bar) getPercent() int64 {
return int64((float32(bar.cur) / float32(bar.total)) * 100)
}
func (bar *Bar) Play(cur int64) {
bar.cur = cur
last := bar.percent
bar.percent = bar.getPercent()
if bar.percent != last && bar.percent%2 == 0 {
bar.rate += bar.graph
}
fmt.Printf("\r[%-50s]%3d%% %8d/%d", bar.rate, bar.percent, bar.cur, bar.total)
}
func (bar *Bar) Finish() {
fmt.Println()
}