-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
toml.go
89 lines (78 loc) · 2.12 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package storage
import (
"bytes"
"fmt"
"github.com/pelletier/go-toml"
"time"
)
func init() {
registerReadParser([]string{"toml"}, []string{".toml"}, &TOMLParser{})
registerWriteParser([]string{"toml"}, []string{".toml"}, &TOMLParser{})
}
// TOMLParser is a Parser implementation to handle toml files.
type TOMLParser struct {
}
// FromBytes returns some data that is represented by the given bytes.
func (p *TOMLParser) FromBytes(byteData []byte) (interface{}, error) {
var data interface{}
if err := toml.Unmarshal(byteData, &data); err != nil {
return data, fmt.Errorf("could not unmarshal data: %w", err)
}
return &BasicSingleDocument{
Value: data,
}, nil
}
// ToBytes returns a slice of bytes that represents the given value.
func (p *TOMLParser) ToBytes(value interface{}, options ...ReadWriteOption) ([]byte, error) {
buf := new(bytes.Buffer)
enc := toml.NewEncoder(buf)
colourise := false
for _, o := range options {
switch o.Key {
case OptionIndent:
if indent, ok := o.Value.(string); ok {
enc.Indentation(indent)
}
case OptionColourise:
if value, ok := o.Value.(bool); ok {
colourise = value
}
}
}
switch d := value.(type) {
case SingleDocument:
if err := enc.Encode(d.Document()); err != nil {
if err.Error() == "Only a struct or map can be marshaled to TOML" {
buf.Write([]byte(fmt.Sprintf("%v\n", d.Document())))
} else {
return nil, err
}
}
case MultiDocument:
for _, dd := range d.Documents() {
if err := enc.Encode(dd); err != nil {
if err.Error() == "Only a struct or map can be marshaled to TOML" {
buf.Write([]byte(fmt.Sprintf("%v\n", dd)))
} else {
return nil, err
}
}
}
case time.Time:
buf.Write([]byte(fmt.Sprintf("%s\n", d.Format(time.RFC3339))))
default:
if err := enc.Encode(d); err != nil {
if err.Error() == "Only a struct or map can be marshaled to TOML" {
buf.Write([]byte(fmt.Sprintf("%v\n", d)))
} else {
return nil, err
}
}
}
if colourise {
if err := ColouriseBuffer(buf, "toml"); err != nil {
return nil, fmt.Errorf("could not colourise output: %w", err)
}
}
return buf.Bytes(), nil
}