-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.go
91 lines (74 loc) · 1.72 KB
/
generate.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
package facto
import (
_ "embed"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"unicode"
)
var (
//go:embed templates/factory.go.tmpl
factoryTmpl string
)
// Generate a factory on a given root directory and
// a name for it (passed in args).
func Generate(root string, args []string) error {
if len(args) < 2 {
return fmt.Errorf("generate: please provide a name for the factory")
}
name := args[1]
tmpl, err := template.New("factory").Parse(factoryTmpl)
if err != nil {
return err
}
folder := filepath.Join(root, "factories")
err = os.MkdirAll(folder, 0777)
if err != nil {
return fmt.Errorf("error creating factories folder: %w", err)
}
file, err := os.Create(filepath.Join(folder, snakeCase(name)+".go"))
if err != nil {
return fmt.Errorf("error creating file: %w", err)
}
data := struct {
Name string
}{
Name: camelCase(name),
}
err = tmpl.Execute(file, data)
if err != nil {
return fmt.Errorf("error creating executing template: %w", err)
}
return nil
}
func camelCase(s string) string {
s = strings.ReplaceAll(s, "_", " ")
s = strings.ReplaceAll(s, "-", " ")
p := strings.Fields(s)
var g []string
for _, value := range p {
g = append(g, strings.Title(value))
}
return strings.Join(g, "")
}
func snakeCase(s string) string {
var res = make([]rune, 0, len(s))
var p = '_'
for i, r := range s {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
res = append(res, '_')
} else if unicode.IsUpper(r) && i > 0 {
if unicode.IsLetter(p) && !unicode.IsUpper(p) || unicode.IsDigit(p) {
res = append(res, '_', unicode.ToLower(r))
} else {
res = append(res, unicode.ToLower(r))
}
} else {
res = append(res, unicode.ToLower(r))
}
p = r
}
return string(res)
}