| 1 |
package yaml |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"math" |
| 9 |
"reflect" |
| 10 |
"sort" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/goccy/go-yaml/ast" |
| 16 |
"github.com/goccy/go-yaml/internal/errors" |
| 17 |
"github.com/goccy/go-yaml/parser" |
| 18 |
"github.com/goccy/go-yaml/printer" |
| 19 |
"github.com/goccy/go-yaml/token" |
| 20 |
) |
| 21 |
|
| 22 |
const ( |
| 23 |
// DefaultIndentSpaces default number of space for indent |
| 24 |
DefaultIndentSpaces = 2 |
| 25 |
) |
| 26 |
|
| 27 |
// Encoder writes YAML values to an output stream. |
| 28 |
type Encoder struct { |
| 29 |
writer io.Writer |
| 30 |
opts []EncodeOption |
| 31 |
indent int |
| 32 |
indentSequence bool |
| 33 |
singleQuote bool |
| 34 |
isFlowStyle bool |
| 35 |
isJSONStyle bool |
| 36 |
useJSONMarshaler bool |
| 37 |
anchorCallback func(*ast.AnchorNode, interface{}) error |
| 38 |
anchorPtrToNameMap map[uintptr]string |
| 39 |
customMarshalerMap map[reflect.Type]func(interface{}) ([]byte, error) |
| 40 |
useLiteralStyleIfMultiline bool |
| 41 |
commentMap map[*Path][]*Comment |
| 42 |
written bool |
| 43 |
|
| 44 |
line int |
| 45 |
column int |
| 46 |
offset int |
| 47 |
indentNum int |
| 48 |
indentLevel int |
| 49 |
} |
| 50 |
|
| 51 |
// NewEncoder returns a new encoder that writes to w. |
| 52 |
// The Encoder should be closed after use to flush all data to w. |
| 53 |
func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder { |
| 54 |
return &Encoder{ |
| 55 |
writer: w, |
| 56 |
opts: opts, |
| 57 |
indent: DefaultIndentSpaces, |
| 58 |
anchorPtrToNameMap: map[uintptr]string{}, |
| 59 |
customMarshalerMap: map[reflect.Type]func(interface{}) ([]byte, error){}, |
| 60 |
line: 1, |
| 61 |
column: 1, |
| 62 |
offset: 0, |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
// Close closes the encoder by writing any remaining data. |
| 67 |
// It does not write a stream terminating string "...". |
| 68 |
func (e *Encoder) Close() error { |
| 69 |
return nil |
| 70 |
} |
| 71 |
|
| 72 |
// Encode writes the YAML encoding of v to the stream. |
| 73 |
// If multiple items are encoded to the stream, |
| 74 |
// the second and subsequent document will be preceded with a "---" document separator, |
| 75 |
// but the first will not. |
| 76 |
// |
| 77 |
// See the documentation for Marshal for details about the conversion of Go values to YAML. |
| 78 |
func (e *Encoder) Encode(v interface{}) error { |
| 79 |
return e.EncodeContext(context.Background(), v) |
| 80 |
} |
| 81 |
|
| 82 |
// EncodeContext writes the YAML encoding of v to the stream with context.Context. |
| 83 |
func (e *Encoder) EncodeContext(ctx context.Context, v interface{}) error { |
| 84 |
node, err := e.EncodeToNodeContext(ctx, v) |
| 85 |
if err != nil { |
| 86 |
return err |
| 87 |
} |
| 88 |
if err := e.setCommentByCommentMap(node); err != nil { |
| 89 |
return err |
| 90 |
} |
| 91 |
if !e.written { |
| 92 |
e.written = true |
| 93 |
} else { |
| 94 |
// write document separator |
| 95 |
_, _ = e.writer.Write([]byte("---\n")) |
| 96 |
} |
| 97 |
var p printer.Printer |
| 98 |
_, _ = e.writer.Write(p.PrintNode(node)) |
| 99 |
return nil |
| 100 |
} |
| 101 |
|
| 102 |
// EncodeToNode convert v to ast.Node. |
| 103 |
func (e *Encoder) EncodeToNode(v interface{}) (ast.Node, error) { |
| 104 |
return e.EncodeToNodeContext(context.Background(), v) |
| 105 |
} |
| 106 |
|
| 107 |
// EncodeToNodeContext convert v to ast.Node with context.Context. |
| 108 |
func (e *Encoder) EncodeToNodeContext(ctx context.Context, v interface{}) (ast.Node, error) { |
| 109 |
for _, opt := range e.opts { |
| 110 |
if err := opt(e); err != nil { |
| 111 |
return nil, err |
| 112 |
} |
| 113 |
} |
| 114 |
node, err := e.encodeValue(ctx, reflect.ValueOf(v), 1) |
| 115 |
if err != nil { |
| 116 |
return nil, err |
| 117 |
} |
| 118 |
return node, nil |
| 119 |
} |
| 120 |
|
| 121 |
func (e *Encoder) setCommentByCommentMap(node ast.Node) error { |
| 122 |
if e.commentMap == nil { |
| 123 |
return nil |
| 124 |
} |
| 125 |
for path, comments := range e.commentMap { |
| 126 |
n, err := path.FilterNode(node) |
| 127 |
if err != nil { |
| 128 |
return err |
| 129 |
} |
| 130 |
if n == nil { |
| 131 |
continue |
| 132 |
} |
| 133 |
for _, comment := range comments { |
| 134 |
commentTokens := []*token.Token{} |
| 135 |
for _, text := range comment.Texts { |
| 136 |
commentTokens = append(commentTokens, token.New(text, text, nil)) |
| 137 |
} |
| 138 |
commentGroup := ast.CommentGroup(commentTokens) |
| 139 |
switch comment.Position { |
| 140 |
case CommentHeadPosition: |
| 141 |
if err := e.setHeadComment(node, n, commentGroup); err != nil { |
| 142 |
return err |
| 143 |
} |
| 144 |
case CommentLinePosition: |
| 145 |
if err := e.setLineComment(node, n, commentGroup); err != nil { |
| 146 |
return err |
| 147 |
} |
| 148 |
case CommentFootPosition: |
| 149 |
if err := e.setFootComment(node, n, commentGroup); err != nil { |
| 150 |
return err |
| 151 |
} |
| 152 |
default: |
| 153 |
return ErrUnknownCommentPositionType |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
return nil |
| 158 |
} |
| 159 |
|
| 160 |
func (e *Encoder) setHeadComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error { |
| 161 |
parent := ast.Parent(node, filtered) |
| 162 |
if parent == nil { |
| 163 |
return ErrUnsupportedHeadPositionType(node) |
| 164 |
} |
| 165 |
switch p := parent.(type) { |
| 166 |
case *ast.MappingValueNode: |
| 167 |
if err := p.SetComment(comment); err != nil { |
| 168 |
return err |
| 169 |
} |
| 170 |
case *ast.MappingNode: |
| 171 |
if err := p.SetComment(comment); err != nil { |
| 172 |
return err |
| 173 |
} |
| 174 |
case *ast.SequenceNode: |
| 175 |
if len(p.ValueHeadComments) == 0 { |
| 176 |
p.ValueHeadComments = make([]*ast.CommentGroupNode, len(p.Values)) |
| 177 |
} |
| 178 |
var foundIdx int |
| 179 |
for idx, v := range p.Values { |
| 180 |
if v == filtered { |
| 181 |
foundIdx = idx |
| 182 |
break |
| 183 |
} |
| 184 |
} |
| 185 |
p.ValueHeadComments[foundIdx] = comment |
| 186 |
default: |
| 187 |
return ErrUnsupportedHeadPositionType(node) |
| 188 |
} |
| 189 |
return nil |
| 190 |
} |
| 191 |
|
| 192 |
func (e *Encoder) setLineComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error { |
| 193 |
switch filtered.(type) { |
| 194 |
case *ast.MappingValueNode, *ast.SequenceNode: |
| 195 |
// Line comment cannot be set for mapping value node. |
| 196 |
// It should probably be set for the parent map node |
| 197 |
if err := e.setLineCommentToParentMapNode(node, filtered, comment); err != nil { |
| 198 |
return err |
| 199 |
} |
| 200 |
default: |
| 201 |
if err := filtered.SetComment(comment); err != nil { |
| 202 |
return err |
| 203 |
} |
| 204 |
} |
| 205 |
return nil |
| 206 |
} |
| 207 |
|
| 208 |
func (e *Encoder) setLineCommentToParentMapNode(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error { |
| 209 |
parent := ast.Parent(node, filtered) |
| 210 |
if parent == nil { |
| 211 |
return ErrUnsupportedLinePositionType(node) |
| 212 |
} |
| 213 |
switch p := parent.(type) { |
| 214 |
case *ast.MappingValueNode: |
| 215 |
if err := p.Key.SetComment(comment); err != nil { |
| 216 |
return err |
| 217 |
} |
| 218 |
case *ast.MappingNode: |
| 219 |
if err := p.SetComment(comment); err != nil { |
| 220 |
return err |
| 221 |
} |
| 222 |
default: |
| 223 |
return ErrUnsupportedLinePositionType(parent) |
| 224 |
} |
| 225 |
return nil |
| 226 |
} |
| 227 |
|
| 228 |
func (e *Encoder) setFootComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error { |
| 229 |
parent := ast.Parent(node, filtered) |
| 230 |
if parent == nil { |
| 231 |
return ErrUnsupportedFootPositionType(node) |
| 232 |
} |
| 233 |
switch n := parent.(type) { |
| 234 |
case *ast.MappingValueNode: |
| 235 |
n.FootComment = comment |
| 236 |
case *ast.MappingNode: |
| 237 |
n.FootComment = comment |
| 238 |
case *ast.SequenceNode: |
| 239 |
n.FootComment = comment |
| 240 |
default: |
| 241 |
return ErrUnsupportedFootPositionType(n) |
| 242 |
} |
| 243 |
return nil |
| 244 |
} |
| 245 |
|
| 246 |
func (e *Encoder) encodeDocument(doc []byte) (ast.Node, error) { |
| 247 |
f, err := parser.ParseBytes(doc, 0) |
| 248 |
if err != nil { |
| 249 |
return nil, err |
| 250 |
} |
| 251 |
for _, docNode := range f.Docs { |
| 252 |
if docNode.Body != nil { |
| 253 |
return docNode.Body, nil |
| 254 |
} |
| 255 |
} |
| 256 |
return nil, nil |
| 257 |
} |
| 258 |
|
| 259 |
func (e *Encoder) isInvalidValue(v reflect.Value) bool { |
| 260 |
if !v.IsValid() { |
| 261 |
return true |
| 262 |
} |
| 263 |
kind := v.Type().Kind() |
| 264 |
if kind == reflect.Ptr && v.IsNil() { |
| 265 |
return true |
| 266 |
} |
| 267 |
if kind == reflect.Interface && v.IsNil() { |
| 268 |
return true |
| 269 |
} |
| 270 |
return false |
| 271 |
} |
| 272 |
|
| 273 |
type jsonMarshaler interface { |
| 274 |
MarshalJSON() ([]byte, error) |
| 275 |
} |
| 276 |
|
| 277 |
func (e *Encoder) existsTypeInCustomMarshalerMap(t reflect.Type) bool { |
| 278 |
if _, exists := e.customMarshalerMap[t]; exists { |
| 279 |
return true |
| 280 |
} |
| 281 |
|
| 282 |
globalCustomMarshalerMu.Lock() |
| 283 |
defer globalCustomMarshalerMu.Unlock() |
| 284 |
if _, exists := globalCustomMarshalerMap[t]; exists { |
| 285 |
return true |
| 286 |
} |
| 287 |
return false |
| 288 |
} |
| 289 |
|
| 290 |
func (e *Encoder) marshalerFromCustomMarshalerMap(t reflect.Type) (func(interface{}) ([]byte, error), bool) { |
| 291 |
if marshaler, exists := e.customMarshalerMap[t]; exists { |
| 292 |
return marshaler, exists |
| 293 |
} |
| 294 |
|
| 295 |
globalCustomMarshalerMu.Lock() |
| 296 |
defer globalCustomMarshalerMu.Unlock() |
| 297 |
if marshaler, exists := globalCustomMarshalerMap[t]; exists { |
| 298 |
return marshaler, exists |
| 299 |
} |
| 300 |
return nil, false |
| 301 |
} |
| 302 |
|
| 303 |
func (e *Encoder) canEncodeByMarshaler(v reflect.Value) bool { |
| 304 |
if !v.CanInterface() { |
| 305 |
return false |
| 306 |
} |
| 307 |
if e.existsTypeInCustomMarshalerMap(v.Type()) { |
| 308 |
return true |
| 309 |
} |
| 310 |
iface := v.Interface() |
| 311 |
switch iface.(type) { |
| 312 |
case BytesMarshalerContext: |
| 313 |
return true |
| 314 |
case BytesMarshaler: |
| 315 |
return true |
| 316 |
case InterfaceMarshalerContext: |
| 317 |
return true |
| 318 |
case InterfaceMarshaler: |
| 319 |
return true |
| 320 |
case time.Time: |
| 321 |
return true |
| 322 |
case time.Duration: |
| 323 |
return true |
| 324 |
case encoding.TextMarshaler: |
| 325 |
return true |
| 326 |
case jsonMarshaler: |
| 327 |
return e.useJSONMarshaler |
| 328 |
} |
| 329 |
return false |
| 330 |
} |
| 331 |
|
| 332 |
func (e *Encoder) encodeByMarshaler(ctx context.Context, v reflect.Value, column int) (ast.Node, error) { |
| 333 |
iface := v.Interface() |
| 334 |
|
| 335 |
if marshaler, exists := e.marshalerFromCustomMarshalerMap(v.Type()); exists { |
| 336 |
doc, err := marshaler(iface) |
| 337 |
if err != nil { |
| 338 |
return nil, err |
| 339 |
} |
| 340 |
node, err := e.encodeDocument(doc) |
| 341 |
if err != nil { |
| 342 |
return nil, err |
| 343 |
} |
| 344 |
return node, nil |
| 345 |
} |
| 346 |
|
| 347 |
if marshaler, ok := iface.(BytesMarshalerContext); ok { |
| 348 |
doc, err := marshaler.MarshalYAML(ctx) |
| 349 |
if err != nil { |
| 350 |
return nil, err |
| 351 |
} |
| 352 |
node, err := e.encodeDocument(doc) |
| 353 |
if err != nil { |
| 354 |
return nil, err |
| 355 |
} |
| 356 |
return node, nil |
| 357 |
} |
| 358 |
|
| 359 |
if marshaler, ok := iface.(BytesMarshaler); ok { |
| 360 |
doc, err := marshaler.MarshalYAML() |
| 361 |
if err != nil { |
| 362 |
return nil, err |
| 363 |
} |
| 364 |
node, err := e.encodeDocument(doc) |
| 365 |
if err != nil { |
| 366 |
return nil, err |
| 367 |
} |
| 368 |
return node, nil |
| 369 |
} |
| 370 |
|
| 371 |
if marshaler, ok := iface.(InterfaceMarshalerContext); ok { |
| 372 |
marshalV, err := marshaler.MarshalYAML(ctx) |
| 373 |
if err != nil { |
| 374 |
return nil, err |
| 375 |
} |
| 376 |
return e.encodeValue(ctx, reflect.ValueOf(marshalV), column) |
| 377 |
} |
| 378 |
|
| 379 |
if marshaler, ok := iface.(InterfaceMarshaler); ok { |
| 380 |
marshalV, err := marshaler.MarshalYAML() |
| 381 |
if err != nil { |
| 382 |
return nil, err |
| 383 |
} |
| 384 |
return e.encodeValue(ctx, reflect.ValueOf(marshalV), column) |
| 385 |
} |
| 386 |
|
| 387 |
if t, ok := iface.(time.Time); ok { |
| 388 |
return e.encodeTime(t, column), nil |
| 389 |
} |
| 390 |
|
| 391 |
if t, ok := iface.(time.Duration); ok { |
| 392 |
return e.encodeDuration(t, column), nil |
| 393 |
} |
| 394 |
|
| 395 |
if marshaler, ok := iface.(encoding.TextMarshaler); ok { |
| 396 |
doc, err := marshaler.MarshalText() |
| 397 |
if err != nil { |
| 398 |
return nil, err |
| 399 |
} |
| 400 |
node, err := e.encodeDocument(doc) |
| 401 |
if err != nil { |
| 402 |
return nil, err |
| 403 |
} |
| 404 |
return node, nil |
| 405 |
} |
| 406 |
|
| 407 |
if e.useJSONMarshaler { |
| 408 |
if marshaler, ok := iface.(jsonMarshaler); ok { |
| 409 |
jsonBytes, err := marshaler.MarshalJSON() |
| 410 |
if err != nil { |
| 411 |
return nil, err |
| 412 |
} |
| 413 |
doc, err := JSONToYAML(jsonBytes) |
| 414 |
if err != nil { |
| 415 |
return nil, err |
| 416 |
} |
| 417 |
node, err := e.encodeDocument(doc) |
| 418 |
if err != nil { |
| 419 |
return nil, err |
| 420 |
} |
| 421 |
return node, nil |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
return nil, errors.New("does not implemented Marshaler") |
| 426 |
} |
| 427 |
|
| 428 |
func (e *Encoder) encodeValue(ctx context.Context, v reflect.Value, column int) (ast.Node, error) { |
| 429 |
if e.isInvalidValue(v) { |
| 430 |
return e.encodeNil(), nil |
| 431 |
} |
| 432 |
if e.canEncodeByMarshaler(v) { |
| 433 |
node, err := e.encodeByMarshaler(ctx, v, column) |
| 434 |
if err != nil { |
| 435 |
return nil, err |
| 436 |
} |
| 437 |
return node, nil |
| 438 |
} |
| 439 |
switch v.Type().Kind() { |
| 440 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 441 |
return e.encodeInt(v.Int()), nil |
| 442 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 443 |
return e.encodeUint(v.Uint()), nil |
| 444 |
case reflect.Float32: |
| 445 |
return e.encodeFloat(v.Float(), 32), nil |
| 446 |
case reflect.Float64: |
| 447 |
return e.encodeFloat(v.Float(), 64), nil |
| 448 |
case reflect.Ptr: |
| 449 |
anchorName := e.anchorPtrToNameMap[v.Pointer()] |
| 450 |
if anchorName != "" { |
| 451 |
aliasName := anchorName |
| 452 |
alias := ast.Alias(token.New("*", "*", e.pos(column))) |
| 453 |
alias.Value = ast.String(token.New(aliasName, aliasName, e.pos(column))) |
| 454 |
return alias, nil |
| 455 |
} |
| 456 |
return e.encodeValue(ctx, v.Elem(), column) |
| 457 |
case reflect.Interface: |
| 458 |
return e.encodeValue(ctx, v.Elem(), column) |
| 459 |
case reflect.String: |
| 460 |
return e.encodeString(v.String(), column), nil |
| 461 |
case reflect.Bool: |
| 462 |
return e.encodeBool(v.Bool()), nil |
| 463 |
case reflect.Slice: |
| 464 |
if mapSlice, ok := v.Interface().(MapSlice); ok { |
| 465 |
return e.encodeMapSlice(ctx, mapSlice, column) |
| 466 |
} |
| 467 |
return e.encodeSlice(ctx, v) |
| 468 |
case reflect.Array: |
| 469 |
return e.encodeArray(ctx, v) |
| 470 |
case reflect.Struct: |
| 471 |
if v.CanInterface() { |
| 472 |
if mapItem, ok := v.Interface().(MapItem); ok { |
| 473 |
return e.encodeMapItem(ctx, mapItem, column) |
| 474 |
} |
| 475 |
if t, ok := v.Interface().(time.Time); ok { |
| 476 |
return e.encodeTime(t, column), nil |
| 477 |
} |
| 478 |
} |
| 479 |
return e.encodeStruct(ctx, v, column) |
| 480 |
case reflect.Map: |
| 481 |
return e.encodeMap(ctx, v, column), nil |
| 482 |
default: |
| 483 |
return nil, fmt.Errorf("unknown value type %s", v.Type().String()) |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
func (e *Encoder) pos(column int) *token.Position { |
| 488 |
return &token.Position{ |
| 489 |
Line: e.line, |
| 490 |
Column: column, |
| 491 |
Offset: e.offset, |
| 492 |
IndentNum: e.indentNum, |
| 493 |
IndentLevel: e.indentLevel, |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
func (e *Encoder) encodeNil() *ast.NullNode { |
| 498 |
value := "null" |
| 499 |
return ast.Null(token.New(value, value, e.pos(e.column))) |
| 500 |
} |
| 501 |
|
| 502 |
func (e *Encoder) encodeInt(v int64) *ast.IntegerNode { |
| 503 |
value := fmt.Sprint(v) |
| 504 |
return ast.Integer(token.New(value, value, e.pos(e.column))) |
| 505 |
} |
| 506 |
|
| 507 |
func (e *Encoder) encodeUint(v uint64) *ast.IntegerNode { |
| 508 |
value := fmt.Sprint(v) |
| 509 |
return ast.Integer(token.New(value, value, e.pos(e.column))) |
| 510 |
} |
| 511 |
|
| 512 |
func (e *Encoder) encodeFloat(v float64, bitSize int) ast.Node { |
| 513 |
if v == math.Inf(0) { |
| 514 |
value := ".inf" |
| 515 |
return ast.Infinity(token.New(value, value, e.pos(e.column))) |
| 516 |
} else if v == math.Inf(-1) { |
| 517 |
value := "-.inf" |
| 518 |
return ast.Infinity(token.New(value, value, e.pos(e.column))) |
| 519 |
} else if math.IsNaN(v) { |
| 520 |
value := ".nan" |
| 521 |
return ast.Nan(token.New(value, value, e.pos(e.column))) |
| 522 |
} |
| 523 |
value := strconv.FormatFloat(v, 'g', -1, bitSize) |
| 524 |
if !strings.Contains(value, ".") && !strings.Contains(value, "e") { |
| 525 |
// append x.0 suffix to keep float value context |
| 526 |
value = fmt.Sprintf("%s.0", value) |
| 527 |
} |
| 528 |
return ast.Float(token.New(value, value, e.pos(e.column))) |
| 529 |
} |
| 530 |
|
| 531 |
func (e *Encoder) isNeedQuoted(v string) bool { |
| 532 |
if e.isJSONStyle { |
| 533 |
return true |
| 534 |
} |
| 535 |
if e.useLiteralStyleIfMultiline && strings.ContainsAny(v, "\n\r") { |
| 536 |
return false |
| 537 |
} |
| 538 |
if e.isFlowStyle && strings.ContainsAny(v, `]},'"`) { |
| 539 |
return true |
| 540 |
} |
| 541 |
if token.IsNeedQuoted(v) { |
| 542 |
return true |
| 543 |
} |
| 544 |
return false |
| 545 |
} |
| 546 |
|
| 547 |
func (e *Encoder) encodeString(v string, column int) *ast.StringNode { |
| 548 |
if e.isNeedQuoted(v) { |
| 549 |
if e.singleQuote { |
| 550 |
v = quoteWith(v, '\'') |
| 551 |
} else { |
| 552 |
v = strconv.Quote(v) |
| 553 |
} |
| 554 |
} |
| 555 |
return ast.String(token.New(v, v, e.pos(column))) |
| 556 |
} |
| 557 |
|
| 558 |
func (e *Encoder) encodeBool(v bool) *ast.BoolNode { |
| 559 |
value := fmt.Sprint(v) |
| 560 |
return ast.Bool(token.New(value, value, e.pos(e.column))) |
| 561 |
} |
| 562 |
|
| 563 |
func (e *Encoder) encodeSlice(ctx context.Context, value reflect.Value) (*ast.SequenceNode, error) { |
| 564 |
if e.indentSequence { |
| 565 |
e.column += e.indent |
| 566 |
} |
| 567 |
column := e.column |
| 568 |
sequence := ast.Sequence(token.New("-", "-", e.pos(column)), e.isFlowStyle) |
| 569 |
for i := 0; i < value.Len(); i++ { |
| 570 |
node, err := e.encodeValue(ctx, value.Index(i), column) |
| 571 |
if err != nil { |
| 572 |
return nil, err |
| 573 |
} |
| 574 |
sequence.Values = append(sequence.Values, node) |
| 575 |
} |
| 576 |
if e.indentSequence { |
| 577 |
e.column -= e.indent |
| 578 |
} |
| 579 |
return sequence, nil |
| 580 |
} |
| 581 |
|
| 582 |
func (e *Encoder) encodeArray(ctx context.Context, value reflect.Value) (*ast.SequenceNode, error) { |
| 583 |
if e.indentSequence { |
| 584 |
e.column += e.indent |
| 585 |
} |
| 586 |
column := e.column |
| 587 |
sequence := ast.Sequence(token.New("-", "-", e.pos(column)), e.isFlowStyle) |
| 588 |
for i := 0; i < value.Len(); i++ { |
| 589 |
node, err := e.encodeValue(ctx, value.Index(i), column) |
| 590 |
if err != nil { |
| 591 |
return nil, err |
| 592 |
} |
| 593 |
sequence.Values = append(sequence.Values, node) |
| 594 |
} |
| 595 |
if e.indentSequence { |
| 596 |
e.column -= e.indent |
| 597 |
} |
| 598 |
return sequence, nil |
| 599 |
} |
| 600 |
|
| 601 |
func (e *Encoder) encodeMapItem(ctx context.Context, item MapItem, column int) (*ast.MappingValueNode, error) { |
| 602 |
k := reflect.ValueOf(item.Key) |
| 603 |
v := reflect.ValueOf(item.Value) |
| 604 |
value, err := e.encodeValue(ctx, v, column) |
| 605 |
if err != nil { |
| 606 |
return nil, err |
| 607 |
} |
| 608 |
if e.isMapNode(value) { |
| 609 |
value.AddColumn(e.indent) |
| 610 |
} |
| 611 |
return ast.MappingValue( |
| 612 |
token.New("", "", e.pos(column)), |
| 613 |
e.encodeString(k.Interface().(string), column), |
| 614 |
value, |
| 615 |
), nil |
| 616 |
} |
| 617 |
|
| 618 |
func (e *Encoder) encodeMapSlice(ctx context.Context, value MapSlice, column int) (*ast.MappingNode, error) { |
| 619 |
node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle) |
| 620 |
for _, item := range value { |
| 621 |
value, err := e.encodeMapItem(ctx, item, column) |
| 622 |
if err != nil { |
| 623 |
return nil, err |
| 624 |
} |
| 625 |
node.Values = append(node.Values, value) |
| 626 |
} |
| 627 |
return node, nil |
| 628 |
} |
| 629 |
|
| 630 |
func (e *Encoder) isMapNode(node ast.Node) bool { |
| 631 |
_, ok := node.(ast.MapNode) |
| 632 |
return ok |
| 633 |
} |
| 634 |
|
| 635 |
func (e *Encoder) encodeMap(ctx context.Context, value reflect.Value, column int) ast.Node { |
| 636 |
node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle) |
| 637 |
keys := make([]interface{}, len(value.MapKeys())) |
| 638 |
for i, k := range value.MapKeys() { |
| 639 |
keys[i] = k.Interface() |
| 640 |
} |
| 641 |
sort.Slice(keys, func(i, j int) bool { |
| 642 |
return fmt.Sprint(keys[i]) < fmt.Sprint(keys[j]) |
| 643 |
}) |
| 644 |
for _, key := range keys { |
| 645 |
k := reflect.ValueOf(key) |
| 646 |
v := value.MapIndex(k) |
| 647 |
value, err := e.encodeValue(ctx, v, column) |
| 648 |
if err != nil { |
| 649 |
return nil |
| 650 |
} |
| 651 |
if e.isMapNode(value) { |
| 652 |
value.AddColumn(e.indent) |
| 653 |
} |
| 654 |
node.Values = append(node.Values, ast.MappingValue( |
| 655 |
nil, |
| 656 |
e.encodeString(fmt.Sprint(key), column), |
| 657 |
value, |
| 658 |
)) |
| 659 |
} |
| 660 |
return node |
| 661 |
} |
| 662 |
|
| 663 |
// IsZeroer is used to check whether an object is zero to determine |
| 664 |
// whether it should be omitted when marshaling with the omitempty flag. |
| 665 |
// One notable implementation is time.Time. |
| 666 |
type IsZeroer interface { |
| 667 |
IsZero() bool |
| 668 |
} |
| 669 |
|
| 670 |
func (e *Encoder) isZeroValue(v reflect.Value) bool { |
| 671 |
kind := v.Kind() |
| 672 |
if z, ok := v.Interface().(IsZeroer); ok { |
| 673 |
if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { |
| 674 |
return true |
| 675 |
} |
| 676 |
return z.IsZero() |
| 677 |
} |
| 678 |
switch kind { |
| 679 |
case reflect.String: |
| 680 |
return len(v.String()) == 0 |
| 681 |
case reflect.Interface, reflect.Ptr: |
| 682 |
return v.IsNil() |
| 683 |
case reflect.Slice: |
| 684 |
return v.Len() == 0 |
| 685 |
case reflect.Map: |
| 686 |
return v.Len() == 0 |
| 687 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 688 |
return v.Int() == 0 |
| 689 |
case reflect.Float32, reflect.Float64: |
| 690 |
return v.Float() == 0 |
| 691 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 692 |
return v.Uint() == 0 |
| 693 |
case reflect.Bool: |
| 694 |
return !v.Bool() |
| 695 |
case reflect.Struct: |
| 696 |
vt := v.Type() |
| 697 |
for i := v.NumField() - 1; i >= 0; i-- { |
| 698 |
if vt.Field(i).PkgPath != "" { |
| 699 |
continue // private field |
| 700 |
} |
| 701 |
if !e.isZeroValue(v.Field(i)) { |
| 702 |
return false |
| 703 |
} |
| 704 |
} |
| 705 |
return true |
| 706 |
} |
| 707 |
return false |
| 708 |
} |
| 709 |
|
| 710 |
func (e *Encoder) encodeTime(v time.Time, column int) *ast.StringNode { |
| 711 |
value := v.Format(time.RFC3339Nano) |
| 712 |
if e.isJSONStyle { |
| 713 |
value = strconv.Quote(value) |
| 714 |
} |
| 715 |
return ast.String(token.New(value, value, e.pos(column))) |
| 716 |
} |
| 717 |
|
| 718 |
func (e *Encoder) encodeDuration(v time.Duration, column int) *ast.StringNode { |
| 719 |
value := v.String() |
| 720 |
if e.isJSONStyle { |
| 721 |
value = strconv.Quote(value) |
| 722 |
} |
| 723 |
return ast.String(token.New(value, value, e.pos(column))) |
| 724 |
} |
| 725 |
|
| 726 |
func (e *Encoder) encodeAnchor(anchorName string, value ast.Node, fieldValue reflect.Value, column int) (*ast.AnchorNode, error) { |
| 727 |
anchorNode := ast.Anchor(token.New("&", "&", e.pos(column))) |
| 728 |
anchorNode.Name = ast.String(token.New(anchorName, anchorName, e.pos(column))) |
| 729 |
anchorNode.Value = value |
| 730 |
if e.anchorCallback != nil { |
| 731 |
if err := e.anchorCallback(anchorNode, fieldValue.Interface()); err != nil { |
| 732 |
return nil, err |
| 733 |
} |
| 734 |
if snode, ok := anchorNode.Name.(*ast.StringNode); ok { |
| 735 |
anchorName = snode.Value |
| 736 |
} |
| 737 |
} |
| 738 |
if fieldValue.Kind() == reflect.Ptr { |
| 739 |
e.anchorPtrToNameMap[fieldValue.Pointer()] = anchorName |
| 740 |
} |
| 741 |
return anchorNode, nil |
| 742 |
} |
| 743 |
|
| 744 |
func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column int) (ast.Node, error) { |
| 745 |
node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle) |
| 746 |
structType := value.Type() |
| 747 |
structFieldMap, err := structFieldMap(structType) |
| 748 |
if err != nil { |
| 749 |
return nil, err |
| 750 |
} |
| 751 |
hasInlineAnchorField := false |
| 752 |
var inlineAnchorValue reflect.Value |
| 753 |
for i := 0; i < value.NumField(); i++ { |
| 754 |
field := structType.Field(i) |
| 755 |
if isIgnoredStructField(field) { |
| 756 |
continue |
| 757 |
} |
| 758 |
fieldValue := value.FieldByName(field.Name) |
| 759 |
structField := structFieldMap[field.Name] |
| 760 |
if structField.IsOmitEmpty && e.isZeroValue(fieldValue) { |
| 761 |
// omit encoding |
| 762 |
continue |
| 763 |
} |
| 764 |
ve := e |
| 765 |
if !e.isFlowStyle && structField.IsFlow { |
| 766 |
ve = &Encoder{} |
| 767 |
*ve = *e |
| 768 |
ve.isFlowStyle = true |
| 769 |
} |
| 770 |
value, err := ve.encodeValue(ctx, fieldValue, column) |
| 771 |
if err != nil { |
| 772 |
return nil, err |
| 773 |
} |
| 774 |
if e.isMapNode(value) { |
| 775 |
value.AddColumn(e.indent) |
| 776 |
} |
| 777 |
var key ast.MapKeyNode = e.encodeString(structField.RenderName, column) |
| 778 |
switch { |
| 779 |
case structField.AnchorName != "": |
| 780 |
anchorNode, err := e.encodeAnchor(structField.AnchorName, value, fieldValue, column) |
| 781 |
if err != nil { |
| 782 |
return nil, err |
| 783 |
} |
| 784 |
value = anchorNode |
| 785 |
case structField.IsAutoAlias: |
| 786 |
if fieldValue.Kind() != reflect.Ptr { |
| 787 |
return nil, fmt.Errorf( |
| 788 |
"%s in struct is not pointer type. but required automatically alias detection", |
| 789 |
structField.FieldName, |
| 790 |
) |
| 791 |
} |
| 792 |
anchorName := e.anchorPtrToNameMap[fieldValue.Pointer()] |
| 793 |
if anchorName == "" { |
| 794 |
return nil, errors.New( |
| 795 |
"cannot find anchor name from pointer address for automatically alias detection", |
| 796 |
) |
| 797 |
} |
| 798 |
aliasName := anchorName |
| 799 |
alias := ast.Alias(token.New("*", "*", e.pos(column))) |
| 800 |
alias.Value = ast.String(token.New(aliasName, aliasName, e.pos(column))) |
| 801 |
value = alias |
| 802 |
if structField.IsInline { |
| 803 |
// if both used alias and inline, output `<<: *alias` |
| 804 |
key = ast.MergeKey(token.New("<<", "<<", e.pos(column))) |
| 805 |
} |
| 806 |
case structField.AliasName != "": |
| 807 |
aliasName := structField.AliasName |
| 808 |
alias := ast.Alias(token.New("*", "*", e.pos(column))) |
| 809 |
alias.Value = ast.String(token.New(aliasName, aliasName, e.pos(column))) |
| 810 |
value = alias |
| 811 |
if structField.IsInline { |
| 812 |
// if both used alias and inline, output `<<: *alias` |
| 813 |
key = ast.MergeKey(token.New("<<", "<<", e.pos(column))) |
| 814 |
} |
| 815 |
case structField.IsInline: |
| 816 |
isAutoAnchor := structField.IsAutoAnchor |
| 817 |
if !hasInlineAnchorField { |
| 818 |
hasInlineAnchorField = isAutoAnchor |
| 819 |
} |
| 820 |
if isAutoAnchor { |
| 821 |
inlineAnchorValue = fieldValue |
| 822 |
} |
| 823 |
mapNode, ok := value.(ast.MapNode) |
| 824 |
if !ok { |
| 825 |
// if an inline field is null, skip encoding it |
| 826 |
if _, ok := value.(*ast.NullNode); ok { |
| 827 |
continue |
| 828 |
} |
| 829 |
return nil, errors.New("inline value is must be map or struct type") |
| 830 |
} |
| 831 |
mapIter := mapNode.MapRange() |
| 832 |
for mapIter.Next() { |
| 833 |
key := mapIter.Key() |
| 834 |
value := mapIter.Value() |
| 835 |
keyName := key.GetToken().Value |
| 836 |
if structFieldMap.isIncludedRenderName(keyName) { |
| 837 |
// if declared same key name, skip encoding this field |
| 838 |
continue |
| 839 |
} |
| 840 |
key.AddColumn(-e.indent) |
| 841 |
value.AddColumn(-e.indent) |
| 842 |
node.Values = append(node.Values, ast.MappingValue(nil, key, value)) |
| 843 |
} |
| 844 |
continue |
| 845 |
case structField.IsAutoAnchor: |
| 846 |
anchorNode, err := e.encodeAnchor(structField.RenderName, value, fieldValue, column) |
| 847 |
if err != nil { |
| 848 |
return nil, err |
| 849 |
} |
| 850 |
value = anchorNode |
| 851 |
} |
| 852 |
node.Values = append(node.Values, ast.MappingValue(nil, key, value)) |
| 853 |
} |
| 854 |
if hasInlineAnchorField { |
| 855 |
node.AddColumn(e.indent) |
| 856 |
anchorName := "anchor" |
| 857 |
anchorNode := ast.Anchor(token.New("&", "&", e.pos(column))) |
| 858 |
anchorNode.Name = ast.String(token.New(anchorName, anchorName, e.pos(column))) |
| 859 |
anchorNode.Value = node |
| 860 |
if e.anchorCallback != nil { |
| 861 |
if err := e.anchorCallback(anchorNode, value.Addr().Interface()); err != nil { |
| 862 |
return nil, err |
| 863 |
} |
| 864 |
if snode, ok := anchorNode.Name.(*ast.StringNode); ok { |
| 865 |
anchorName = snode.Value |
| 866 |
} |
| 867 |
} |
| 868 |
if inlineAnchorValue.Kind() == reflect.Ptr { |
| 869 |
e.anchorPtrToNameMap[inlineAnchorValue.Pointer()] = anchorName |
| 870 |
} |
| 871 |
return anchorNode, nil |
| 872 |
} |
| 873 |
return node, nil |
| 874 |
} |