/
new.go
184 lines (147 loc) · 3.88 KB
/
new.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
package new
import (
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"github.com/apex/log"
"github.com/jesseobrien/torque-cli/internal/scaffold"
"github.com/spf13/cobra"
)
var (
dry bool
moduleName string
customPath string
orm bool
InitCmd = &cobra.Command{
Use: "new [appname]",
Short: "Initialize a new Torque project directory",
Long: "",
Args: cobra.MinimumNArgs(1),
Run: executeInit,
}
)
func init() {
InitCmd.PersistentFlags().BoolVar(&dry, "dry-run", false, "Whether torque will do a dry run of scaffolding everything and clean up after.")
InitCmd.PersistentFlags().BoolVar(&orm, "orm", true, "If orm is false, torque will not generate ORM database files.")
InitCmd.PersistentFlags().StringVar(&customPath, "dir", "", "Provide a custom path to scaffold the project into.")
InitCmd.PersistentFlags().StringVar(&moduleName, "mod-name", "", "The go module name that will be used to initialize go.mod. If none is specified, the project name is used.")
}
func executeInit(cmd *cobra.Command, args []string) {
if len(args) < 1 {
log.Error("Required `appname` arg is missing.")
return
}
appName := args[0]
if !isValidAppName(appName) {
log.Error("`appname` argument is invalid. App names can only contain letters, numbers and - or _.")
return
}
appDir := "."
if customPath != "" {
if strings.HasSuffix(customPath, "/") {
customPath = customPath[:len(customPath)-len("/")]
}
appDir = customPath
}
appDir = fmt.Sprintf("%s/%s", appDir, appName)
log.Infof("🔨 Creating new app in directory %s", appDir)
if err := createProjectDirectories(appDir); err != nil {
cleanupProjectDirectory(appDir)
log.WithError(err).Error("creating root directory failed")
return
}
modName := appName
if moduleName != "" {
modName = moduleName
}
cfg := scaffold.ScaffoldConfig{
AppName: appName,
ModName: modName,
Path: appDir,
ORM: orm,
}
s := scaffold.NewScaffolder(cfg)
if err := s.ScaffoldNewProject(); err != nil {
cleanupProjectDirectory(appDir)
log.WithError(err).Error("scaffolding project files failed")
return
}
if err := initializeGoModule(modName); err != nil {
log.WithError(err).Error("go mod init failed")
return
}
log.Info("✅ Done. Happy building!")
if dry {
log.Info("Dry-run is enabled. Cleaning up...")
os.Remove(appDir)
}
}
func cleanupProjectDirectory(appName string) {
os.Remove(appName)
}
func initializeGoModule(modName string) error {
log.Infof("🔨 Running `go mod init %s`", modName)
cmd := exec.Command("go", "mod", "init", modName)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
log.Infof("🔨 Running `go mod tidy`")
cmd = exec.Command("go", "mod", "tidy")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return err
}
return nil
}
func createProjectDirectories(appName string) error {
log.Info("🔨 Scaffolding project directories.")
exists, err := os.Stat(appName)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if exists != nil {
files, err := os.ReadDir(appName)
if err != nil {
return err
}
if len(files) > 0 {
return fmt.Errorf("'%s' directory exists and is not empty", appName)
}
}
if _, err := os.Stat(appName); errors.Is(err, os.ErrNotExist) {
err := os.MkdirAll(appName, os.ModePerm)
if err != nil {
return err
}
}
if err := os.Chdir(appName); err != nil {
return err
}
directoryTree := []string{
"cmd/main",
"dist",
"internal/http",
"internal/data",
"tmp",
}
for _, directory := range directoryTree {
if err := os.MkdirAll(directory, os.ModePerm); err != nil {
cleanupProjectDirectory(appName)
return err
}
}
return nil
}
// Validate that the app name will work as a directory name
func isValidAppName(name string) bool {
reg := regexp.MustCompile(`^[^\\/()!?%*:|"<>\.]+$`)
return reg.MatchString(name)
}