Add struct tag support

This commit is contained in:
David Vogel 2024-12-20 18:33:07 +01:00
parent 7b0454ae68
commit d9b6725592
2 changed files with 18 additions and 2 deletions

View File

@ -242,11 +242,19 @@ func (e *VariableEncoder) encodeStruct(v reflect.Value, t reflect.Type) error {
for i := 0; i < t.NumField(); i++ {
ft, fv := t.Field(i), v.Field(i)
if ft.PkgPath == "" { // Ignore unexported fields.
fieldName := ft.Name
if name, ok := ft.Tag.Lookup("typst"); ok {
// Omit fields that have their name set to "-".
if name == "-" {
continue
}
fieldName = name
}
if err := e.writeIndentationCharacters(); err != nil {
return err
}
// TODO: Allow name customization via struct tags
if err := e.writeStringLiteral([]byte(ft.Name)); err != nil {
if err := e.writeStringLiteral([]byte(fieldName)); err != nil {
return err
}
if err := e.writeString(": "); err != nil {

View File

@ -126,6 +126,14 @@ func TestVariableEncoder(t *testing.T) {
Foo string
Bar int
}{"Hey!", 12345}, false, "(\n \"Foo\": \"Hey!\",\n \"Bar\": 12345,\n)"},
{"struct with tags", struct {
Foo string `typst:"foo"`
Bar int `typst:"😀"`
}{"Hey!", 12345}, false, "(\n \"foo\": \"Hey!\",\n \"😀\": 12345,\n)"},
{"struct with tags omitting", struct {
Foo string `typst:"foo"`
Bar int `typst:"-"`
}{"Hey!", 12345}, false, "(\n \"foo\": \"Hey!\",\n)"},
{"struct empty", struct{}{}, false, "()"},
{"struct empty pointer", (*struct{})(nil), false, "none"},
{"map string string", map[string]string{"Foo": "Bar", "Foo2": "Electric Foogaloo"}, false, "(\n \"Foo\": \"Bar\",\n \"Foo2\": \"Electric Foogaloo\",\n)"},