MCPcopy Create free account
hub / github.com/goccy/go-yaml / encodeStruct

Method encodeStruct

encode.go:873–996  ·  view source on GitHub ↗
(ctx context.Context, value reflect.Value, column int)

Source from the content-addressed store, hash-verified

871}
872
873func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column int) (ast.Node, error) {
874 node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
875 structType := value.Type()
876 fieldMap, err := structFieldMap(structType)
877 if err != nil {
878 return nil, err
879 }
880 hasInlineAnchorField := false
881 var inlineAnchorValue reflect.Value
882 for i := 0; i < value.NumField(); i++ {
883 field := structType.Field(i)
884 if isIgnoredStructField(field) {
885 continue
886 }
887 fieldValue := value.FieldByName(field.Name)
888 sf := fieldMap[field.Name]
889 if (e.omitZero || sf.IsOmitZero) && e.isOmittedByOmitZero(fieldValue) {
890 // omit encoding by omitzero tag or OmitZero option.
891 continue
892 }
893 if e.omitEmpty && e.isOmittedByOmitEmptyOption(fieldValue) {
894 // omit encoding by OmitEmpty option.
895 continue
896 }
897 if sf.IsOmitEmpty && e.isOmittedByOmitEmptyTag(fieldValue) {
898 // omit encoding by omitempty tag.
899 continue
900 }
901 ve := e
902 if !e.isFlowStyle && sf.IsFlow {
903 ve = &Encoder{}
904 *ve = *e
905 ve.isFlowStyle = true
906 }
907 encoded, err := ve.encodeValue(ctx, fieldValue, column)
908 if err != nil {
909 return nil, err
910 }
911 if e.isMapNode(encoded) {
912 encoded.AddColumn(e.indentNum)
913 }
914 var key ast.MapKeyNode = e.encodeString(sf.RenderName, column)
915 switch {
916 case encoded.Type() == ast.AliasType:
917 if aliasName := sf.AliasName; aliasName != "" {
918 alias, ok := encoded.(*ast.AliasNode)
919 if !ok {
920 return nil, errors.ErrUnexpectedNodeType(encoded.Type(), ast.AliasType, encoded.GetToken())
921 }
922 got := alias.Value.String()
923 if aliasName != got {
924 return nil, fmt.Errorf("expected alias name is %q but got %q", aliasName, got)
925 }
926 }
927 if sf.IsInline {
928 // if both used alias and inline, output `<<: *alias`
929 key = ast.MergeKey(token.New("<<", "<<", e.pos(column)))
930 }

Callers 1

encodeValueMethod · 0.95

Calls 15

posMethod · 0.95
isOmittedByOmitZeroMethod · 0.95
isMapNodeMethod · 0.95
encodeStringMethod · 0.95
encodeAnchorMethod · 0.95
setAnchorMethod · 0.95
MappingFunction · 0.92
NewFunction · 0.92
ErrUnexpectedNodeTypeFunction · 0.92
MergeKeyFunction · 0.92

Tested by

no test coverage detected