-
Notifications
You must be signed in to change notification settings - Fork 0
/
gentypes.go
93 lines (79 loc) · 2 KB
/
gentypes.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 gogen
import (
_ "embed"
"fmt"
"io"
"os"
"path"
"strings"
"github.com/jageros/goctl/api/spec"
apiutil "github.com/jageros/goctl/api/util"
"github.com/jageros/goctl/config"
"github.com/jageros/goctl/util"
"github.com/jageros/goctl/util/format"
)
const typesFile = "types"
//go:embed types.tpl
var typesTemplate string
// BuildTypes gen types to string
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\n")
}
if err := writeType(&builder, tp); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
}
}
return builder.String(), nil
}
func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
val, err := BuildTypes(api.Types)
if err != nil {
return err
}
typeFilename, err := format.FileNamingFormat(cfg.NamingFormat, typesFile)
if err != nil {
return err
}
typeFilename = typeFilename + ".go"
filename := path.Join(dir, typesDir, typeFilename)
os.Remove(filename)
return genFile(fileGenConfig{
dir: dir,
subdir: typesDir,
filename: typeFilename,
templateName: "typesTemplate",
category: category,
templateFile: typesTemplateFile,
builtinTemplate: typesTemplate,
data: map[string]any{
"types": val,
"containsTime": false,
},
})
}
func writeType(writer io.Writer, tp spec.Type) error {
structType, ok := tp.(spec.DefineStruct)
if !ok {
return fmt.Errorf("unspport struct type: %s", tp.Name())
}
fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name()))
for _, member := range structType.Members {
if member.IsInline {
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
return err
}
continue
}
if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil {
return err
}
}
fmt.Fprintf(writer, "}")
return nil
}