func CombineBlock()

in types/hcl.go [314:372]


func CombineBlock(blocks []*hclwrite.Block, output *hclwrite.Block, isForEach bool) map[string][]hclwrite.Tokens {
	attrNameSet := make(map[string]bool)
	for _, b := range blocks {
		for attrName := range b.Body().Attributes() {
			attrNameSet[attrName] = true
		}
	}
	attrValueMap := make(map[string][]hclwrite.Tokens)
	for attrName := range attrNameSet {
		values := make([]string, len(blocks))
		tokens := make([]hclwrite.Tokens, len(blocks))
		for i, b := range blocks {
			if b == nil {
				values[i] = "null"
				tokens[i] = nil
				continue
			}
			attr := b.Body().GetAttribute(attrName)
			if attr == nil {
				values[i] = "null"
				tokens[i] = nil
			} else {
				tokens[i] = b.Body().GetAttribute(attrName).Expr().BuildTokens(nil)
				values[i] = strings.TrimSpace(string(tokens[i].Bytes()))
			}
		}
		switch {
		case helper.IsArrayWithSameValue(values):
			output.Body().SetAttributeRaw(attrName, blocks[0].Body().GetAttribute(attrName).Expr().BuildTokens(nil))
		case isForEach:
			output.Body().SetAttributeRaw(attrName, helper.GetTokensForExpression("each.value."+attrName))
			attrValueMap[attrName] = tokens
		default:
			output.Body().SetAttributeRaw(attrName, helper.GetTokensForExpression(fmt.Sprintf("%s${count.index}%s", helper.Prefix(values), helper.Suffix(values))))
			attrValueMap[attrName] = tokens
		}
	}

	blockNameSet := make(map[string]bool)
	for _, b := range blocks {
		for _, nb := range b.Body().Blocks() {
			blockNameSet[nb.Type()] = true
		}
	}
	for blockName := range blockNameSet {
		nestedBlocks := make([]*hclwrite.Block, len(blocks))
		for i, b := range blocks {
			if nestedBlock := b.Body().FirstMatchingBlock(blockName, []string{}); nestedBlock != nil {
				nestedBlocks[i] = nestedBlock
			}
		}
		outputNestedBlock := output.Body().AppendNewBlock(blockName, []string{})
		tempMap := CombineBlock(nestedBlocks, outputNestedBlock, isForEach)
		for k, v := range tempMap {
			attrValueMap[k] = v
		}
	}
	return attrValueMap
}