-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_controller.go
93 lines (77 loc) · 2.35 KB
/
make_controller.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
package command
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/dptsi/its-go/script/templates"
"github.com/stoewer/go-strcase"
)
type MakeController struct{}
func (c *MakeController) Key() string {
return "make:controller"
}
func (c *MakeController) Name() string {
return "Create new controller handler"
}
func (c *MakeController) Description() string {
return "Create new controller handler and its boilerplate"
}
func (c *MakeController) Usage() string {
return fmt.Sprintf("%s <snake_case_module_name> <snake_case_controller_name>", c.Key())
}
func (c *MakeController) Handler(args []string) error {
if len(args) == 0 {
return fmt.Errorf("no module name provided")
}
if len(args) == 1 {
return fmt.Errorf("no controller name provided")
}
modName := args[0]
snakeCaseName := args[1]
mod, err := newModule(modName)
suffix := "_controller"
if strings.HasSuffix(snakeCaseName, suffix) {
snakeCaseName = strings.TrimSuffix(snakeCaseName, suffix)
fmt.Printf("tidak perlu pakai suffix %s ya rekan2\n", suffix)
fmt.Printf("suffix yang ada akan ditambahkan otomatis\n")
fmt.Printf("kedepannya cukup jalankan script dengan `%s %s %s` saja\n", c.Key(), modName, snakeCaseName)
}
if err != nil {
return fmt.Errorf("error detecting module: %w", err)
}
if err := mod.checkExist(); err != nil {
return fmt.Errorf("error detecting module: %w", err)
}
path := filepath.Join(mod.joinPath("internal/presentation/controllers"), fmt.Sprintf("%s_controller.go", snakeCaseName))
if err := c.createControllerFile(mod, snakeCaseName, path); err != nil {
return fmt.Errorf("error when creating %s: %w", path, err)
}
fmt.Printf("controller %s berhasil dibuat pada %s!\n", snakeCaseName, path)
return nil
}
func (c *MakeController) createControllerFile(mod *module, snakeCaseName, path string) error {
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("file %s already exists", path)
}
controller, err := os.Create(path)
if err != nil {
return err
}
defer controller.Close()
template, err := template.New("module_controller").Parse(templates.ModuleController)
if err != nil {
return err
}
type Data struct {
NamePascalCase string
}
data := Data{
NamePascalCase: strcase.UpperCamelCase(snakeCaseName),
}
if err := template.Execute(controller, data); err != nil {
return err
}
return controller.Sync()
}