github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/command/jsonprovider/block.go (about)

     1  package jsonprovider
     2  
     3  import (
     4  	"github.com/eliastor/durgaform/internal/configs/configschema"
     5  )
     6  
     7  type block struct {
     8  	Attributes      map[string]*attribute `json:"attributes,omitempty"`
     9  	BlockTypes      map[string]*blockType `json:"block_types,omitempty"`
    10  	Description     string                `json:"description,omitempty"`
    11  	DescriptionKind string                `json:"description_kind,omitempty"`
    12  	Deprecated      bool                  `json:"deprecated,omitempty"`
    13  }
    14  
    15  type blockType struct {
    16  	NestingMode string `json:"nesting_mode,omitempty"`
    17  	Block       *block `json:"block,omitempty"`
    18  	MinItems    uint64 `json:"min_items,omitempty"`
    19  	MaxItems    uint64 `json:"max_items,omitempty"`
    20  }
    21  
    22  func marshalBlockTypes(nestedBlock *configschema.NestedBlock) *blockType {
    23  	if nestedBlock == nil {
    24  		return &blockType{}
    25  	}
    26  	ret := &blockType{
    27  		Block:       marshalBlock(&nestedBlock.Block),
    28  		MinItems:    uint64(nestedBlock.MinItems),
    29  		MaxItems:    uint64(nestedBlock.MaxItems),
    30  		NestingMode: nestingModeString(nestedBlock.Nesting),
    31  	}
    32  	return ret
    33  }
    34  
    35  func marshalBlock(configBlock *configschema.Block) *block {
    36  	if configBlock == nil {
    37  		return &block{}
    38  	}
    39  
    40  	ret := block{
    41  		Deprecated:      configBlock.Deprecated,
    42  		Description:     configBlock.Description,
    43  		DescriptionKind: marshalStringKind(configBlock.DescriptionKind),
    44  	}
    45  
    46  	if len(configBlock.Attributes) > 0 {
    47  		attrs := make(map[string]*attribute, len(configBlock.Attributes))
    48  		for k, attr := range configBlock.Attributes {
    49  			attrs[k] = marshalAttribute(attr)
    50  		}
    51  		ret.Attributes = attrs
    52  	}
    53  
    54  	if len(configBlock.BlockTypes) > 0 {
    55  		blockTypes := make(map[string]*blockType, len(configBlock.BlockTypes))
    56  		for k, bt := range configBlock.BlockTypes {
    57  			blockTypes[k] = marshalBlockTypes(bt)
    58  		}
    59  		ret.BlockTypes = blockTypes
    60  	}
    61  
    62  	return &ret
    63  }
    64  
    65  func nestingModeString(mode configschema.NestingMode) string {
    66  	switch mode {
    67  	case configschema.NestingSingle:
    68  		return "single"
    69  	case configschema.NestingGroup:
    70  		return "group"
    71  	case configschema.NestingList:
    72  		return "list"
    73  	case configschema.NestingSet:
    74  		return "set"
    75  	case configschema.NestingMap:
    76  		return "map"
    77  	default:
    78  		return "invalid"
    79  	}
    80  }