mirror of
https://github.com/Dadido3/go-typst.git
synced 2025-04-11 12:13:16 +00:00
Add struct tag support
This commit is contained in:
parent
7b0454ae68
commit
d9b6725592
@ -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 {
|
||||
|
@ -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)"},
|
||||
|
Loading…
Reference in New Issue
Block a user