2023-01-05 20:51:45 +00:00
|
|
|
package generator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/dave/jennifer/jen"
|
2023-01-05 21:02:11 +00:00
|
|
|
"go.arsenm.dev/go-lemmy/cmd/gen/parser"
|
2023-01-05 20:51:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
|
|
|
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 {
|
2023-01-05 21:42:24 +00:00
|
|
|
g.Id(field.Name).Id(field.Type).Tag(map[string]string{
|
|
|
|
"json": field.OrigName,
|
2023-01-05 20:51:45 +00:00
|
|
|
"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))
|
2023-01-05 20:51:45 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return f.Render(s.w)
|
|
|
|
}
|