Skip to content

Commit

Permalink
Add ability to encode comments with desc tag
Browse files Browse the repository at this point in the history
  • Loading branch information
jbsmith7741 committed Sep 28, 2017
1 parent a368813 commit d30b7e2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
8 changes: 8 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,13 +368,21 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value) {
continue
}

enc.addComment(key.add(keyName), sft.Tag)
enc.encode(key.add(keyName), sf)
}
}
writeFields(fieldsDirect)
writeFields(fieldsSub)
}

func (enc *Encoder) addComment(key Key, tag reflect.StructTag) {
if s, ok := tag.Lookup("desc"); ok {
enc.wf("%s#%s\n", enc.indentStr(key), s)
enc.hasWritten = false
}
}

// tomlTypeName returns the TOML type name of the Go value's type. It is
// used to determine whether the types of array elements are mixed (which is
// forbidden). If the Go value is nil, then it is illegal for it to be an array
Expand Down
42 changes: 42 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,48 @@ ArrayOfMixedSlices = [[1, 2], ["a", "b"]]
},
wantError: errAnything,
},
"simple fields with comments": {
input: struct {
Int1 int `desc:"an integer"`
Float float64 `desc:"a float"`
Bool bool `desc:"a bool"`
}{0, 0.0, false},
wantOutput: "#an integer\nInt1 = 0\n#a float\nFloat = 0.0\n#a bool\nBool = false\n",
},
"embedded struct with comments": {
input: struct {
Parent struct {
Name string `desc:"my name"`
Value int `desc:"my value"`
} `desc:"parent"`
}{struct {
Name string `desc:"my name"`
Value int `desc:"my value"`
}{"hello", 10}},
wantOutput: "#parent\n[Parent]\n #my name\n Name = \"hello\"\n #my value\n Value = 10\n",
},
"slice with comments": {
input: struct {
Primes []int `desc:"prime numbers"`
}{[]int{1, 2, 3, 5, 7}},
wantOutput: "#prime numbers\nPrimes = [1, 2, 3, 5, 7]\n",
},
"map with comments": {
input: struct {
Library map[string]interface{} `desc:"a library"`
}{map[string]interface{}{"name":"hello", "age": 99}},
wantOutput: "#a library\n[Library]\n age = 99\n name = \"hello\"\n",
},
"2 layer embedded struct with comments": {
input: struct {
Parent struct {
Child struct {
Int int `desc:"child int"`
} `desc:"child struct"`
} `desc:"parent struct"`
} {},
wantOutput: "#parent struct\n[Parent]\n #child struct\n [Parent.Child]\n #child int\n Int = 0\n",
},
}
for label, test := range tests {
encodeExpected(t, label, test.input, test.wantOutput, test.wantError)
Expand Down

0 comments on commit d30b7e2

Please sign in to comment.