You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/tsgen/gencomponents.go

68 lines
1.3 KiB
Go

4 years ago
package tsgen
import (
"path"
"strings"
"text/template"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/util/pathx"
4 years ago
)
const (
componentsTemplate = `// Code generated by goctl. DO NOT EDIT.
4 years ago
{{.componentTypes}}
`
)
func genComponents(dir string, api *spec.ApiSpec) error {
types := api.Types
4 years ago
if len(types) == 0 {
return nil
}
val, err := buildTypes(types)
4 years ago
if err != nil {
return err
}
outputFile := apiutil.ComponentName(api) + ".ts"
filename := path.Join(dir, outputFile)
if err := pathx.RemoveIfExist(filename); err != nil {
4 years ago
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) {
4 years ago
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")
4 years ago
}
}
return builder.String(), nil
}