go-lemmy/cmd/gen/generator/struct.go

53 lines
1.1 KiB
Go
Raw Normal View History

package generator
import (
"io"
"strings"
"github.com/dave/jennifer/jen"
2023-04-21 02:27:38 +00:00
"go.elara.ws/go-lemmy/cmd/gen/parser"
)
type StructGenerator struct {
w io.Writer
PkgName string
}
func NewStruct(w io.Writer, pkgName string) *StructGenerator {
return &StructGenerator{w, pkgName}
}
func (s *StructGenerator) Generate(items []parser.Item) error {
f := jen.NewFile(s.PkgName)
2023-04-21 02:27:38 +00:00
f.HeaderComment("Code generated by go.elara.ws/go-lemmy/cmd/gen (struct generator). DO NOT EDIT.")
2023-01-07 22:40:18 +00:00
for _, item := range items {
if item.Struct != nil {
st := item.Struct
f.Type().Id(st.Name).StructFunc(func(g *jen.Group) {
for _, field := range st.Fields {
g.Id(field.Name).Id(field.Type).Tag(map[string]string{
"json": field.OrigName,
"url": field.OrigName + ",omitempty",
})
}
if strings.HasSuffix(st.Name, "Response") {
g.Id("LemmyResponse")
}
})
} else if item.Enum != nil {
e := item.Enum
f.Type().Id(e.Name).String()
f.Const().DefsFunc(func(g *jen.Group) {
for _, member := range e.Members {
2023-01-05 21:02:11 +00:00
g.Id(e.Name + string(member)).Id(e.Name).Op("=").Lit(string(member))
}
})
}
}
return f.Render(s.w)
}