Debian Codegraph @

yaml.go

raw symbols SCIP
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 // NodeUnmarshaler interface is similar to BytesUnmarshaler but provide related AST node instead of raw YAML source.
61 type NodeUnmarshaler interface {
62 UnmarshalYAML(ast.Node) error
63 }
64
65 // NodeUnmarshalerContext interface is similar to BytesUnmarshaler but provide related AST node instead of raw YAML source.
66 type NodeUnmarshalerContext interface {
67 UnmarshalYAML(context.Context, ast.Node) error
68 }
69
70 // MapItem is an item in a MapSlice.
71 type MapItem struct {
72 Key, Value interface{}
73 }
74
75 // MapSlice encodes and decodes as a YAML map.
76 // The order of keys is preserved when encoding and decoding.
77 type MapSlice []MapItem
78
79 // ToMap convert to map[interface{}]interface{}.
80 func (s MapSlice) ToMap() map[interface{}]interface{} {
81 v := map[interface{}]interface{}{}
82 for _, item := range s {
83 v[item.Key] = item.Value
84 }
85 return v
86 }
87
88 // Marshal serializes the value provided into a YAML document. The structure
89 // of the generated document will reflect the structure of the value itself.
90 // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
91 //
92 // Struct fields are only marshaled if they are exported (have an upper case
93 // first letter), and are marshaled using the field name lowercased as the
94 // default key. Custom keys may be defined via the "yaml" name in the field
95 // tag: the content preceding the first comma is used as the key, and the
96 // following comma-separated options are used to tweak the marshaling process.
97 // Conflicting names result in a runtime error.
98 //
99 // The field tag format accepted is:
100 //
101 // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
102 //
103 // The following flags are currently supported:
104 //
105 // omitempty Only include the field if it's not set to the zero
106 // value for the type or to empty slices or maps.
107 // Zero valued structs will be omitted if all their public
108 // fields are zero, unless they implement an IsZero
109 // method (see the IsZeroer interface type), in which
110 // case the field will be included if that method returns true.
111 // Note that this definition is slightly different from the Go's
112 // encoding/json 'omitempty' definition. It combines some elements
113 // of 'omitempty' and 'omitzero'. See https://github.com/goccy/go-yaml/issues/695.
114 //
115 // omitzero The omitzero tag behaves in the same way as the interpretation of the omitzero tag in the encoding/json library.
116 // 1) If the field type has an "IsZero() bool" method, that will be used to determine whether the value is zero.
117 // 2) Otherwise, the value is zero if it is the zero value for its type.
118 //
119 // flow Marshal using a flow style (useful for structs,
120 // sequences and maps).
121 //
122 // inline Inline the field, which must be a struct or a map,
123 // causing all of its fields or keys to be processed as if
124 // they were part of the outer struct. For maps, keys must
125 // not conflict with the yaml keys of other struct fields.
126 //
127 // anchor Marshal with anchor. If want to define anchor name explicitly, use anchor=name style.
128 // Otherwise, if used 'anchor' name only, used the field name lowercased as the anchor name
129 //
130 // alias Marshal with alias. If want to define alias name explicitly, use alias=name style.
131 // Otherwise, If omitted alias name and the field type is pointer type,
132 // assigned anchor name automatically from same pointer address.
133 //
134 // In addition, if the key is "-", the field is ignored.
135 //
136 // For example:
137 //
138 // type T struct {
139 // F int `yaml:"a,omitempty"`
140 // B int
141 // }
142 // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
143 // yaml.Marshal(&T{F: 1}) // Returns "a: 1\nb: 0\n"
144 func Marshal(v interface{}) ([]byte, error) {
145 return MarshalWithOptions(v)
146 }
147
148 // MarshalWithOptions serializes the value provided into a YAML document with EncodeOptions.
149 func MarshalWithOptions(v interface{}, opts ...EncodeOption) ([]byte, error) {
150 return MarshalContext(context.Background(), v, opts...)
151 }
152
153 // MarshalContext serializes the value provided into a YAML document with context.Context and EncodeOptions.
154 func MarshalContext(ctx context.Context, v interface{}, opts ...EncodeOption) ([]byte, error) {
155 var buf bytes.Buffer
156 if err := NewEncoder(&buf, opts...).EncodeContext(ctx, v); err != nil {
157 return nil, err
158 }
159 return buf.Bytes(), nil
160 }
161
162 // ValueToNode convert from value to ast.Node.
163 func ValueToNode(v interface{}, opts ...EncodeOption) (ast.Node, error) {
164 var buf bytes.Buffer
165 node, err := NewEncoder(&buf, opts...).EncodeToNode(v)
166 if err != nil {
167 return nil, err
168 }
169 return node, nil
170 }
171
172 // Unmarshal decodes the first document found within the in byte slice
173 // and assigns decoded values into the out value.
174 //
175 // Struct fields are only unmarshalled if they are exported (have an
176 // upper case first letter), and are unmarshalled using the field name
177 // lowercased as the default key. Custom keys may be defined via the
178 // "yaml" name in the field tag: the content preceding the first comma
179 // is used as the key, and the following comma-separated options are
180 // used to tweak the marshaling process (see Marshal).
181 // Conflicting names result in a runtime error.
182 //
183 // For example:
184 //
185 // type T struct {
186 // F int `yaml:"a,omitempty"`
187 // B int
188 // }
189 // var t T
190 // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
191 //
192 // See the documentation of Marshal for the format of tags and a list of
193 // supported tag options.
194 func Unmarshal(data []byte, v interface{}) error {
195 return UnmarshalWithOptions(data, v)
196 }
197
198 // UnmarshalWithOptions decodes with DecodeOptions the first document found within the in byte slice
199 // and assigns decoded values into the out value.
200 func UnmarshalWithOptions(data []byte, v interface{}, opts ...DecodeOption) error {
201 return UnmarshalContext(context.Background(), data, v, opts...)
202 }
203
204 // UnmarshalContext decodes with context.Context and DecodeOptions.
205 func UnmarshalContext(ctx context.Context, data []byte, v interface{}, opts ...DecodeOption) error {
206 dec := NewDecoder(bytes.NewBuffer(data), opts...)
207 if err := dec.DecodeContext(ctx, v); err != nil {
208 if err == io.EOF {
209 return nil
210 }
211 return err
212 }
213 return nil
214 }
215
216 // NodeToValue converts node to the value pointed to by v.
217 func NodeToValue(node ast.Node, v interface{}, opts ...DecodeOption) error {
218 var buf bytes.Buffer
219 if err := NewDecoder(&buf, opts...).DecodeFromNode(node, v); err != nil {
220 return err
221 }
222 return nil
223 }
224
225 // FormatError is a utility function that takes advantage of the metadata
226 // stored in the errors returned by this package's parser.
227 //
228 // If the second argument `colored` is true, the error message is colorized.
229 // If the third argument `inclSource` is true, the error message will
230 // contain snippets of the YAML source that was used.
231 func FormatError(e error, colored, inclSource bool) string {
232 var yamlErr Error
233 if errors.As(e, &yamlErr) {
234 return yamlErr.FormatError(colored, inclSource)
235 }
236
237 return e.Error()
238 }
239
240 // YAMLToJSON convert YAML bytes to JSON.
241 func YAMLToJSON(bytes []byte) ([]byte, error) {
242 var v interface{}
243 if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil {
244 return nil, err
245 }
246 out, err := MarshalWithOptions(v, JSON())
247 if err != nil {
248 return nil, err
249 }
250 return out, nil
251 }
252
253 // JSONToYAML convert JSON bytes to YAML.
254 func JSONToYAML(bytes []byte) ([]byte, error) {
255 var v interface{}
256 if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil {
257 return nil, err
258 }
259 out, err := Marshal(v)
260 if err != nil {
261 return nil, err
262 }
263 return out, nil
264 }
265
266 var (
267 globalCustomMarshalerMu sync.Mutex
268 globalCustomUnmarshalerMu sync.Mutex
269 globalCustomMarshalerMap = map[reflect.Type]func(context.Context, interface{}) ([]byte, error){}
270 globalCustomUnmarshalerMap = map[reflect.Type]func(context.Context, interface{}, []byte) error{}
271 )
272
273 // RegisterCustomMarshaler overrides any encoding process for the type specified in generics.
274 // If you want to switch the behavior for each encoder, use `CustomMarshaler` defined as EncodeOption.
275 //
276 // NOTE: If type T implements MarshalYAML for pointer receiver, the type specified in RegisterCustomMarshaler must be *T.
277 // If RegisterCustomMarshaler and CustomMarshaler of EncodeOption are specified for the same type,
278 // the CustomMarshaler specified in EncodeOption takes precedence.
279 func RegisterCustomMarshaler[T any](marshaler func(T) ([]byte, error)) {
280 globalCustomMarshalerMu.Lock()
281 defer globalCustomMarshalerMu.Unlock()
282
283 var typ T
284 globalCustomMarshalerMap[reflect.TypeOf(typ)] = func(ctx context.Context, v interface{}) ([]byte, error) {
285 return marshaler(v.(T))
286 }
287 }
288
289 // RegisterCustomMarshalerContext overrides any encoding process for the type specified in generics.
290 // Similar to RegisterCustomMarshalerContext, but allows passing a context to the unmarshaler function.
291 func RegisterCustomMarshalerContext[T any](marshaler func(context.Context, T) ([]byte, error)) {
292 globalCustomMarshalerMu.Lock()
293 defer globalCustomMarshalerMu.Unlock()
294
295 var typ T
296 globalCustomMarshalerMap[reflect.TypeOf(typ)] = func(ctx context.Context, v interface{}) ([]byte, error) {
297 return marshaler(ctx, v.(T))
298 }
299 }
300
301 // RegisterCustomUnmarshaler overrides any decoding process for the type specified in generics.
302 // If you want to switch the behavior for each decoder, use `CustomUnmarshaler` defined as DecodeOption.
303 //
304 // NOTE: If RegisterCustomUnmarshaler and CustomUnmarshaler of DecodeOption are specified for the same type,
305 // the CustomUnmarshaler specified in DecodeOption takes precedence.
306 func RegisterCustomUnmarshaler[T any](unmarshaler func(*T, []byte) error) {
307 globalCustomUnmarshalerMu.Lock()
308 defer globalCustomUnmarshalerMu.Unlock()
309
310 var typ *T
311 globalCustomUnmarshalerMap[reflect.TypeOf(typ)] = func(ctx context.Context, v interface{}, b []byte) error {
312 return unmarshaler(v.(*T), b)
313 }
314 }
315
316 // RegisterCustomUnmarshalerContext overrides any decoding process for the type specified in generics.
317 // Similar to RegisterCustomUnmarshalerContext, but allows passing a context to the unmarshaler function.
318 func RegisterCustomUnmarshalerContext[T any](unmarshaler func(context.Context, *T, []byte) error) {
319 globalCustomUnmarshalerMu.Lock()
320 defer globalCustomUnmarshalerMu.Unlock()
321
322 var typ *T
323 globalCustomUnmarshalerMap[reflect.TypeOf(typ)] = func(ctx context.Context, v interface{}, b []byte) error {
324 return unmarshaler(ctx, v.(*T), b)
325 }
326 }