-
Notifications
You must be signed in to change notification settings - Fork 2
/
toml.go
55 lines (45 loc) · 1.36 KB
/
toml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package toml
import (
"fmt"
"io"
"io/ioutil"
"reflect"
"github.com/vimeo/dials"
"github.com/vimeo/dials/common"
"github.com/vimeo/dials/tagformat"
"github.com/vimeo/dials/transform"
tomlparser "github.com/pelletier/go-toml"
)
// TOMLTagName is the name of the `"toml"` tag.
const TOMLTagName = "toml"
// Decoder is a decoder than understands TOML.
type Decoder struct {
}
// Decode will read from `r` and parse it as TOML depositing the relevant values
// in `t`.
func (d *Decoder) Decode(r io.Reader, t *dials.Type) (reflect.Value, error) {
tomlBytes, err := ioutil.ReadAll(r)
if err != nil {
return reflect.Value{}, fmt.Errorf("error reading TOML: %s", err)
}
// Use the TagCopyingMangler to copy over TOML tags from dials tags if TOML
// tags aren't specified.
tfmr := transform.NewTransformer(t.Type(),
&tagformat.TagCopyingMangler{
SrcTag: common.DialsTagName, NewTag: TOMLTagName})
val, tfmErr := tfmr.Translate()
if tfmErr != nil {
return reflect.Value{}, fmt.Errorf("failed to convert tags: %s", tfmErr)
}
// Get a pointer to our value, so we can pass that.
instance := val.Addr().Interface()
err = tomlparser.Unmarshal(tomlBytes, instance)
if err != nil {
return reflect.Value{}, err
}
unmangledVal, unmangleErr := tfmr.ReverseTranslate(val)
if unmangleErr != nil {
return reflect.Value{}, unmangleErr
}
return unmangledVal, nil
}