2022-10-18 12:37:50 +00:00
|
|
|
package codegen
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"text/template"
|
|
|
|
|
2023-05-24 11:04:29 +00:00
|
|
|
"git.kmsign.ru/royalcat/repogen/internal/code"
|
2022-10-18 12:37:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const structTemplate = `
|
|
|
|
type {{.Name}} struct {
|
|
|
|
{{.GenFields}}
|
|
|
|
}
|
|
|
|
`
|
|
|
|
|
|
|
|
// StructBuilder is an implementer of a struct.
|
|
|
|
type StructBuilder struct {
|
|
|
|
Name string
|
|
|
|
Fields code.StructFields
|
|
|
|
}
|
|
|
|
|
|
|
|
// Impl writes struct declatation code to the buffer.
|
|
|
|
func (sb StructBuilder) Impl(buffer *bytes.Buffer) error {
|
|
|
|
tmpl, err := template.New("struct").Parse(structTemplate)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// writing to a buffer should not cause errors.
|
|
|
|
_ = tmpl.Execute(buffer, sb)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sb StructBuilder) GenFields() string {
|
|
|
|
var fieldLines []string
|
|
|
|
for _, field := range sb.Fields {
|
|
|
|
fieldLine := fmt.Sprintf("\t%s %s", field.Name, field.Type.Code())
|
2023-04-19 12:42:08 +00:00
|
|
|
if len(field.Tag) > 0 {
|
|
|
|
fieldLine += fmt.Sprintf(" `%s`", string(field.Tag))
|
2022-10-18 12:37:50 +00:00
|
|
|
}
|
|
|
|
fieldLines = append(fieldLines, fieldLine)
|
|
|
|
}
|
|
|
|
return strings.Join(fieldLines, "\n")
|
|
|
|
}
|