Skip to content

Commit

Permalink
Skip fields with toml:"-", even when they're unsupported types
Browse files Browse the repository at this point in the history
Previously something like this would fail to encode due to func being an
unsupported type:

	struct {
		Str  string `toml:"str"
		Func func() `toml:"-"`
	}

But that's not really needed in this case, since we will never encode it
anyway.

Fixes #345
  • Loading branch information
arp242 committed Feb 12, 2022
1 parent 87b9f05 commit 01e5516
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
if f.PkgPath != "" && !f.Anonymous { /// Skip unexported fields.
continue
}
opts := getOptions(f.Tag)
if opts.skip {
continue
}

frv := rv.Field(i)

Expand Down
27 changes: 27 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,33 @@ func TestEncode32bit(t *testing.T) {
nil)
}

// Skip invalid types if it has toml:"-"
//
// https://github.com/BurntSushi/toml/issues/345
func TestEncodeSkipInvalidType(t *testing.T) {
buf := new(bytes.Buffer)
err := NewEncoder(buf).Encode(struct {
Str string `toml:"str"`
Arr []func() `toml:"-"`
Map map[string]interface{} `toml:"-"`
Func func() `toml:"-"`
}{
Str: "a",
Arr: []func(){func() {}},
Map: map[string]interface{}{"f": func() {}},
Func: func() {},
})
if err != nil {
t.Fatal(err)
}

have := buf.String()
want := "str = \"a\"\n"
if have != want {
t.Errorf("\nwant: %q\nhave: %q\n", want, have)
}
}

func encodeExpected(t *testing.T, label string, val interface{}, want string, wantErr error) {
t.Helper()

Expand Down

0 comments on commit 01e5516

Please sign in to comment.