| 1 |
package yaml |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"io" |
| 7 |
"reflect" |
| 8 |
"sync" |
| 9 |
|
| 10 |
"github.com/goccy/go-yaml/ast" |
| 11 |
"github.com/goccy/go-yaml/internal/errors" |
| 12 |
) |
| 13 |
|
| 14 |
// BytesMarshaler interface may be implemented by types to customize their |
| 15 |
// behavior when being marshaled into a YAML document. The returned value |
| 16 |
// is marshaled in place of the original value implementing Marshaler. |
| 17 |
// |
| 18 |
// If an error is returned by MarshalYAML, the marshaling procedure stops |
| 19 |
// and returns with the provided error. |
| 20 |
type BytesMarshaler interface { |
| 21 |
MarshalYAML() ([]byte, error) |
| 22 |
} |
| 23 |
|
| 24 |
// BytesMarshalerContext interface use BytesMarshaler with context.Context. |
| 25 |
type BytesMarshalerContext interface { |
| 26 |
MarshalYAML(context.Context) ([]byte, error) |
| 27 |
} |
| 28 |
|
| 29 |
// InterfaceMarshaler interface has MarshalYAML compatible with github.com/go-yaml/yaml package. |
| 30 |
type InterfaceMarshaler interface { |
| 31 |
MarshalYAML() (interface{}, error) |
| 32 |
} |
| 33 |
|
| 34 |
// InterfaceMarshalerContext interface use InterfaceMarshaler with context.Context. |
| 35 |
type InterfaceMarshalerContext interface { |
| 36 |
MarshalYAML(context.Context) (interface{}, error) |
| 37 |
} |
| 38 |
|
| 39 |
// BytesUnmarshaler interface may be implemented by types to customize their |
| 40 |
// behavior when being unmarshaled from a YAML document. |
| 41 |
type BytesUnmarshaler interface { |
| 42 |
UnmarshalYAML([]byte) error |
| 43 |
} |
| 44 |
|
| 45 |
// BytesUnmarshalerContext interface use BytesUnmarshaler with context.Context. |
| 46 |
type BytesUnmarshalerContext interface { |
| 47 |
UnmarshalYAML(context.Context, []byte) error |
| 48 |
} |
| 49 |
|
| 50 |
// InterfaceUnmarshaler interface has UnmarshalYAML compatible with github.com/go-yaml/yaml package. |
| 51 |
type InterfaceUnmarshaler interface { |
| 52 |
UnmarshalYAML(func(interface{}) error) error |
| 53 |
} |
| 54 |
|
| 55 |
// InterfaceUnmarshalerContext interface use InterfaceUnmarshaler with context.Context. |
| 56 |
type InterfaceUnmarshalerContext interface { |
| 57 |
UnmarshalYAML(context.Context, func(interface{}) error) error |
| 58 |
} |
| 59 |
|
| 60 |
// MapItem is an item in a MapSlice. |
| 61 |
type MapItem struct { |
| 62 |
Key, Value interface{} |
| 63 |
} |
| 64 |
|
| 65 |
// MapSlice encodes and decodes as a YAML map. |
| 66 |
// The order of keys is preserved when encoding and decoding. |
| 67 |
type MapSlice []MapItem |
| 68 |
|
| 69 |
// ToMap convert to map[interface{}]interface{}. |
| 70 |
func (s MapSlice) ToMap() map[interface{}]interface{} { |
| 71 |
v := map[interface{}]interface{}{} |
| 72 |
for _, item := range s { |
| 73 |
v[item.Key] = item.Value |
| 74 |
} |
| 75 |
return v |
| 76 |
} |
| 77 |
|
| 78 |
// Marshal serializes the value provided into a YAML document. The structure |
| 79 |
// of the generated document will reflect the structure of the value itself. |
| 80 |
// Maps and pointers (to struct, string, int, etc) are accepted as the in value. |
| 81 |
// |
| 82 |
// Struct fields are only marshaled if they are exported (have an upper case |
| 83 |
// first letter), and are marshaled using the field name lowercased as the |
| 84 |
// default key. Custom keys may be defined via the "yaml" name in the field |
| 85 |
// tag: the content preceding the first comma is used as the key, and the |
| 86 |
// following comma-separated options are used to tweak the marshaling process. |
| 87 |
// Conflicting names result in a runtime error. |
| 88 |
// |
| 89 |
// The field tag format accepted is: |
| 90 |
// |
| 91 |
// `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)` |
| 92 |
// |
| 93 |
// The following flags are currently supported: |
| 94 |
// |
| 95 |
// omitempty Only include the field if it's not set to the zero |
| 96 |
// value for the type or to empty slices or maps. |
| 97 |
// Zero valued structs will be omitted if all their public |
| 98 |
// fields are zero, unless they implement an IsZero |
| 99 |
// method (see the IsZeroer interface type), in which |
| 100 |
// case the field will be included if that method returns true. |
| 101 |
// |
| 102 |
// flow Marshal using a flow style (useful for structs, |
| 103 |
// sequences and maps). |
| 104 |
// |
| 105 |
// inline Inline the field, which must be a struct or a map, |
| 106 |
// causing all of its fields or keys to be processed as if |
| 107 |
// they were part of the outer struct. For maps, keys must |
| 108 |
// not conflict with the yaml keys of other struct fields. |
| 109 |
// |
| 110 |
// anchor Marshal with anchor. If want to define anchor name explicitly, use anchor=name style. |
| 111 |
// Otherwise, if used 'anchor' name only, used the field name lowercased as the anchor name |
| 112 |
// |
| 113 |
// alias Marshal with alias. If want to define alias name explicitly, use alias=name style. |
| 114 |
// Otherwise, If omitted alias name and the field type is pointer type, |
| 115 |
// assigned anchor name automatically from same pointer address. |
| 116 |
// |
| 117 |
// In addition, if the key is "-", the field is ignored. |
| 118 |
// |
| 119 |
// For example: |
| 120 |
// |
| 121 |
// type T struct { |
| 122 |
// F int `yaml:"a,omitempty"` |
| 123 |
// B int |
| 124 |
// } |
| 125 |
// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" |
| 126 |
// yaml.Marshal(&T{F: 1}) // Returns "a: 1\nb: 0\n" |
| 127 |
func Marshal(v interface{}) ([]byte, error) { |
| 128 |
return MarshalWithOptions(v) |
| 129 |
} |
| 130 |
|
| 131 |
// MarshalWithOptions serializes the value provided into a YAML document with EncodeOptions. |
| 132 |
func MarshalWithOptions(v interface{}, opts ...EncodeOption) ([]byte, error) { |
| 133 |
return MarshalContext(context.Background(), v, opts...) |
| 134 |
} |
| 135 |
|
| 136 |
// MarshalContext serializes the value provided into a YAML document with context.Context and EncodeOptions. |
| 137 |
func MarshalContext(ctx context.Context, v interface{}, opts ...EncodeOption) ([]byte, error) { |
| 138 |
var buf bytes.Buffer |
| 139 |
if err := NewEncoder(&buf, opts...).EncodeContext(ctx, v); err != nil { |
| 140 |
return nil, err |
| 141 |
} |
| 142 |
return buf.Bytes(), nil |
| 143 |
} |
| 144 |
|
| 145 |
// ValueToNode convert from value to ast.Node. |
| 146 |
func ValueToNode(v interface{}, opts ...EncodeOption) (ast.Node, error) { |
| 147 |
var buf bytes.Buffer |
| 148 |
node, err := NewEncoder(&buf, opts...).EncodeToNode(v) |
| 149 |
if err != nil { |
| 150 |
return nil, err |
| 151 |
} |
| 152 |
return node, nil |
| 153 |
} |
| 154 |
|
| 155 |
// Unmarshal decodes the first document found within the in byte slice |
| 156 |
// and assigns decoded values into the out value. |
| 157 |
// |
| 158 |
// Struct fields are only unmarshalled if they are exported (have an |
| 159 |
// upper case first letter), and are unmarshalled using the field name |
| 160 |
// lowercased as the default key. Custom keys may be defined via the |
| 161 |
// "yaml" name in the field tag: the content preceding the first comma |
| 162 |
// is used as the key, and the following comma-separated options are |
| 163 |
// used to tweak the marshaling process (see Marshal). |
| 164 |
// Conflicting names result in a runtime error. |
| 165 |
// |
| 166 |
// For example: |
| 167 |
// |
| 168 |
// type T struct { |
| 169 |
// F int `yaml:"a,omitempty"` |
| 170 |
// B int |
| 171 |
// } |
| 172 |
// var t T |
| 173 |
// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) |
| 174 |
// |
| 175 |
// See the documentation of Marshal for the format of tags and a list of |
| 176 |
// supported tag options. |
| 177 |
func Unmarshal(data []byte, v interface{}) error { |
| 178 |
return UnmarshalWithOptions(data, v) |
| 179 |
} |
| 180 |
|
| 181 |
// UnmarshalWithOptions decodes with DecodeOptions the first document found within the in byte slice |
| 182 |
// and assigns decoded values into the out value. |
| 183 |
func UnmarshalWithOptions(data []byte, v interface{}, opts ...DecodeOption) error { |
| 184 |
return UnmarshalContext(context.Background(), data, v, opts...) |
| 185 |
} |
| 186 |
|
| 187 |
// UnmarshalContext decodes with context.Context and DecodeOptions. |
| 188 |
func UnmarshalContext(ctx context.Context, data []byte, v interface{}, opts ...DecodeOption) error { |
| 189 |
dec := NewDecoder(bytes.NewBuffer(data), opts...) |
| 190 |
if err := dec.DecodeContext(ctx, v); err != nil { |
| 191 |
if err == io.EOF { |
| 192 |
return nil |
| 193 |
} |
| 194 |
return err |
| 195 |
} |
| 196 |
return nil |
| 197 |
} |
| 198 |
|
| 199 |
// NodeToValue converts node to the value pointed to by v. |
| 200 |
func NodeToValue(node ast.Node, v interface{}, opts ...DecodeOption) error { |
| 201 |
var buf bytes.Buffer |
| 202 |
if err := NewDecoder(&buf, opts...).DecodeFromNode(node, v); err != nil { |
| 203 |
return err |
| 204 |
} |
| 205 |
return nil |
| 206 |
} |
| 207 |
|
| 208 |
// FormatError is a utility function that takes advantage of the metadata |
| 209 |
// stored in the errors returned by this package's parser. |
| 210 |
// |
| 211 |
// If the second argument `colored` is true, the error message is colorized. |
| 212 |
// If the third argument `inclSource` is true, the error message will |
| 213 |
// contain snippets of the YAML source that was used. |
| 214 |
func FormatError(e error, colored, inclSource bool) string { |
| 215 |
var pp errors.PrettyPrinter |
| 216 |
if errors.As(e, &pp) { |
| 217 |
var buf bytes.Buffer |
| 218 |
pp.PrettyPrint(&errors.Sink{Buffer: &buf}, colored, inclSource) |
| 219 |
return buf.String() |
| 220 |
} |
| 221 |
|
| 222 |
return e.Error() |
| 223 |
} |
| 224 |
|
| 225 |
// YAMLToJSON convert YAML bytes to JSON. |
| 226 |
func YAMLToJSON(bytes []byte) ([]byte, error) { |
| 227 |
var v interface{} |
| 228 |
if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil { |
| 229 |
return nil, err |
| 230 |
} |
| 231 |
out, err := MarshalWithOptions(v, JSON()) |
| 232 |
if err != nil { |
| 233 |
return nil, err |
| 234 |
} |
| 235 |
return out, nil |
| 236 |
} |
| 237 |
|
| 238 |
// JSONToYAML convert JSON bytes to YAML. |
| 239 |
func JSONToYAML(bytes []byte) ([]byte, error) { |
| 240 |
var v interface{} |
| 241 |
if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil { |
| 242 |
return nil, err |
| 243 |
} |
| 244 |
out, err := Marshal(v) |
| 245 |
if err != nil { |
| 246 |
return nil, err |
| 247 |
} |
| 248 |
return out, nil |
| 249 |
} |
| 250 |
|
| 251 |
var ( |
| 252 |
globalCustomMarshalerMu sync.Mutex |
| 253 |
globalCustomUnmarshalerMu sync.Mutex |
| 254 |
globalCustomMarshalerMap = map[reflect.Type]func(interface{}) ([]byte, error){} |
| 255 |
globalCustomUnmarshalerMap = map[reflect.Type]func(interface{}, []byte) error{} |
| 256 |
) |
| 257 |
|
| 258 |
// RegisterCustomMarshaler overrides any encoding process for the type specified in generics. |
| 259 |
// If you want to switch the behavior for each encoder, use `CustomMarshaler` defined as EncodeOption. |
| 260 |
// |
| 261 |
// NOTE: If type T implements MarshalYAML for pointer receiver, the type specified in RegisterCustomMarshaler must be *T. |
| 262 |
// If RegisterCustomMarshaler and CustomMarshaler of EncodeOption are specified for the same type, |
| 263 |
// the CustomMarshaler specified in EncodeOption takes precedence. |
| 264 |
func RegisterCustomMarshaler[T any](marshaler func(T) ([]byte, error)) { |
| 265 |
globalCustomMarshalerMu.Lock() |
| 266 |
defer globalCustomMarshalerMu.Unlock() |
| 267 |
|
| 268 |
var typ T |
| 269 |
globalCustomMarshalerMap[reflect.TypeOf(typ)] = func(v interface{}) ([]byte, error) { |
| 270 |
return marshaler(v.(T)) |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
// RegisterCustomUnmarshaler overrides any decoding process for the type specified in generics. |
| 275 |
// If you want to switch the behavior for each decoder, use `CustomUnmarshaler` defined as DecodeOption. |
| 276 |
// |
| 277 |
// NOTE: If RegisterCustomUnmarshaler and CustomUnmarshaler of DecodeOption are specified for the same type, |
| 278 |
// the CustomUnmarshaler specified in DecodeOption takes precedence. |
| 279 |
func RegisterCustomUnmarshaler[T any](unmarshaler func(*T, []byte) error) { |
| 280 |
globalCustomUnmarshalerMu.Lock() |
| 281 |
defer globalCustomUnmarshalerMu.Unlock() |
| 282 |
|
| 283 |
var typ *T |
| 284 |
globalCustomUnmarshalerMap[reflect.TypeOf(typ)] = func(v interface{}, b []byte) error { |
| 285 |
return unmarshaler(v.(*T), b) |
| 286 |
} |
| 287 |
} |