forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gencomponents.go
64 lines (54 loc) · 1.29 KB
/
gencomponents.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
package tsgen
import (
_ "embed"
"path"
"strings"
"text/template"
"github.com/mikokutou1/go-zero-m/tools/goctl/api/spec"
apiutil "github.com/mikokutou1/go-zero-m/tools/goctl/api/util"
"github.com/mikokutou1/go-zero-m/tools/goctl/util/pathx"
)
//go:embed components.tpl
var componentsTemplate string
func genComponents(dir string, api *spec.ApiSpec) error {
types := api.Types
if len(types) == 0 {
return nil
}
val, err := buildTypes(types)
if err != nil {
return err
}
outputFile := apiutil.ComponentName(api) + ".ts"
filename := path.Join(dir, outputFile)
if err := pathx.RemoveIfExist(filename); err != nil {
return err
}
fp, created, err := apiutil.MaybeCreateFile(dir, ".", outputFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
t := template.Must(template.New("componentsTemplate").Parse(componentsTemplate))
return t.Execute(fp, map[string]string{
"componentTypes": val,
})
}
func buildTypes(types []spec.Type) (string, error) {
var builder strings.Builder
first := true
for _, tp := range types {
if first {
first = false
} else {
builder.WriteString("\n")
}
if err := writeType(&builder, tp); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
}
}
return builder.String(), nil
}