-
Notifications
You must be signed in to change notification settings - Fork 3
/
generate_service.go
68 lines (53 loc) · 1.52 KB
/
generate_service.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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/urfave/cli/v2"
)
func generateServiceTemplate(name string) string {
builder := strings.Builder{}
builder.WriteString("package ")
builder.WriteString(name)
builder.WriteString("\n\n")
name = strings.ToUpper(name[:1]) + name[1:]
builder.WriteString("type ")
builder.WriteString(name)
builder.WriteString("Service struct{}\n\n")
builder.WriteString("func NewService() *")
builder.WriteString(name)
builder.WriteString("Service {\n")
builder.WriteString("\treturn &")
builder.WriteString(name)
builder.WriteString("Service{}\n")
builder.WriteString("}\n")
return builder.String()
}
func generateServiceCommand(ctx *cli.Context) error {
packagePath := ctx.Args().First()
elems := strings.Split(packagePath, "/")
for i := range elems {
elems[i] = strings.TrimSpace(elems[i])
if elems[i] == "" {
elems = append(elems[:i], elems[i+1:]...)
}
}
if len(elems) == 0 {
return fmt.Errorf("invalid package path, must not be empty")
}
packageName := elems[len(elems)-1]
path := strings.Join(elems, "/")
serviceTemplate := generateServiceTemplate(packageName)
servicePath := filepath.Join(path, "service.go")
if _, err := os.Stat(servicePath); !os.IsNotExist(err) {
return fmt.Errorf("service already exists")
}
if err := os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
if err := os.WriteFile(servicePath, []byte(serviceTemplate), 0644); err != nil {
return err
}
return nil
}