github.com/tomwright/dasel@v1.27.3/storage/toml.go (about) 1 package storage 2 3 import ( 4 "bytes" 5 "fmt" 6 "github.com/pelletier/go-toml" 7 "time" 8 ) 9 10 func init() { 11 registerReadParser([]string{"toml"}, []string{".toml"}, &TOMLParser{}) 12 registerWriteParser([]string{"toml"}, []string{".toml"}, &TOMLParser{}) 13 } 14 15 // TOMLParser is a Parser implementation to handle toml files. 16 type TOMLParser struct { 17 } 18 19 // FromBytes returns some data that is represented by the given bytes. 20 func (p *TOMLParser) FromBytes(byteData []byte) (interface{}, error) { 21 var data interface{} 22 if err := toml.Unmarshal(byteData, &data); err != nil { 23 return data, fmt.Errorf("could not unmarshal data: %w", err) 24 } 25 return &BasicSingleDocument{ 26 Value: data, 27 }, nil 28 } 29 30 // ToBytes returns a slice of bytes that represents the given value. 31 func (p *TOMLParser) ToBytes(value interface{}, options ...ReadWriteOption) ([]byte, error) { 32 buf := new(bytes.Buffer) 33 34 enc := toml.NewEncoder(buf) 35 36 colourise := false 37 38 for _, o := range options { 39 switch o.Key { 40 case OptionIndent: 41 if indent, ok := o.Value.(string); ok { 42 enc.Indentation(indent) 43 } 44 case OptionColourise: 45 if value, ok := o.Value.(bool); ok { 46 colourise = value 47 } 48 } 49 } 50 51 switch d := value.(type) { 52 case SingleDocument: 53 if err := enc.Encode(d.Document()); err != nil { 54 if err.Error() == "Only a struct or map can be marshaled to TOML" { 55 buf.Write([]byte(fmt.Sprintf("%v\n", d.Document()))) 56 } else { 57 return nil, err 58 } 59 } 60 case MultiDocument: 61 for _, dd := range d.Documents() { 62 if err := enc.Encode(dd); err != nil { 63 if err.Error() == "Only a struct or map can be marshaled to TOML" { 64 buf.Write([]byte(fmt.Sprintf("%v\n", dd))) 65 } else { 66 return nil, err 67 } 68 } 69 } 70 case time.Time: 71 buf.Write([]byte(fmt.Sprintf("%s\n", d.Format(time.RFC3339)))) 72 default: 73 if err := enc.Encode(d); err != nil { 74 if err.Error() == "Only a struct or map can be marshaled to TOML" { 75 buf.Write([]byte(fmt.Sprintf("%v\n", d))) 76 } else { 77 return nil, err 78 } 79 } 80 } 81 82 if colourise { 83 if err := ColouriseBuffer(buf, "toml"); err != nil { 84 return nil, fmt.Errorf("could not colourise output: %w", err) 85 } 86 } 87 88 return buf.Bytes(), nil 89 }