Skip to content

Commit

Permalink
Support for omitempty, as well as tests for omitempty.
Browse files Browse the repository at this point in the history
  • Loading branch information
bbuck committed May 1, 2015
1 parent 443a628 commit d918309
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
42 changes: 42 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,21 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value) {
if keyName == "" {
keyName = sft.Name
}

opts := strings.Split(keyName, ",")
keyName = opts[0]
omitEmpty := false
if len(opts) > 1 {
for _, opt := range opts[1:] {
if opt == "omitempty" {
omitEmpty = true
}
}
}
if omitEmpty && isEmpty(sf) {
continue
}

enc.encode(key.add(keyName), sf)
}
}
Expand Down Expand Up @@ -433,6 +448,33 @@ func tomlArrayType(rv reflect.Value) tomlType {
return firstType
}

func isEmpty(rv reflect.Value) bool {
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if rv.Int() == 0 {
return true
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if rv.Uint() == 0 {
return true
}
case reflect.Float32, reflect.Float64:
if rv.Float() == 0.0 {
return true
}
case reflect.String:
if len(strings.TrimSpace(rv.String())) == 0 {
return true
}
case reflect.Array, reflect.Slice, reflect.Map:
if rv.Len() == 0 {
return true
}
}

return false
}

func (enc *Encoder) newline() {
if enc.hasWritten {
enc.wf("\n")
Expand Down
14 changes: 14 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,20 @@ func TestEncodeArrayHashWithNormalHashOrder(t *testing.T) {
encodeExpected(t, "array hash with normal hash order", val, expected, nil)
}

func TestEncodeWithOmitEmpty(t *testing.T) {
type simple struct {
User string `toml:"user"`
Pass string `toml:"password,omitempty"`
}

value := simple{"Testing", ""}
expected := fmt.Sprintf("user = %q\n", value.User)
encodeExpected(t, "simple with omitempty, is empty", value, expected, nil)
value.Pass = "some password"
expected = fmt.Sprintf("user = %q\npassword = %q\n", value.User, value.Pass)
encodeExpected(t, "simple with omitempty, not empty", value, expected, nil)
}

func encodeExpected(
t *testing.T, label string, val interface{}, wantStr string, wantErr error,
) {
Expand Down

0 comments on commit d918309

Please sign in to comment.