Skip to content

Commit

Permalink
Fix bug encoding YAML.
Browse files Browse the repository at this point in the history
  • Loading branch information
plusvic committed Feb 26, 2019
1 parent d97a38b commit a62e542
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
18 changes: 12 additions & 6 deletions yaml/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,27 +105,33 @@ func (enc *Encoder) encodeMap(m reflect.Value, indent int, prefix string) (err e

for i, k := range keys {
keyPrinter(enc.w, "%s: ", k)
vk := m.MapIndex(k)
if indentIncr, err = enc.lineBreakV(vk, indent); err != nil {
v := m.MapIndex(k)
if indentIncr, err = enc.lineBreakV(v, indent); err != nil {
return err
}
if err = enc.encodeValue(vk, indent+indentIncr, prefix+k.String()); err != nil {
if err = enc.encodeValue(v, indent+indentIncr, prefix+k.String()); err != nil {
return err
}
switch v.Kind() {
case reflect.Interface:
v = v.Elem()
case reflect.Ptr:
v = v.Elem()
}
vt := v.Type()
ks := k.String()
vt := vk.Elem().Type()
// If key is "date" or ends with "_date" and value is json.Number, this
// field is a date.
isDate := (ks == "date" || strings.HasSuffix(ks, "_date")) &&
vt.Name() == "Number" && vt.PkgPath() == "encoding/json"
// If this field is a date let's add a comment with the date in a
// human-readable format.
if isDate {
ts, err := strconv.ParseInt(vk.Elem().String(), 10, 64)
ts, err := strconv.ParseInt(v.String(), 10, 64)
if err != nil {
panic(err)
}
commentPrinter(enc.w, " # %v ", time.Unix(ts, 0))
commentPrinter(enc.w, " # %v", time.Unix(ts, 0))
}
if i < n-1 {
err = enc.lineBreak(indent)
Expand Down
10 changes: 10 additions & 0 deletions yaml/yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,16 @@ var tests = []T{
numeral: "second"
`),
},
{
data: struct {
Foo_date json.Number
}{
Foo_date: "10000",
},
yaml: Y(`
Foo_date: 10000 # 1970-01-01 03:46:40 +0100 CET
`),
},
}

func TestYAML(t *testing.T) {
Expand Down

0 comments on commit a62e542

Please sign in to comment.