github.com/zntrio/harp/v2@v2.0.9/pkg/template/values/hcl2/hcl2.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package hcl2
    19  
    20  import (
    21  	"encoding/json"
    22  	"fmt"
    23  
    24  	"github.com/hashicorp/hcl/v2"
    25  	"github.com/hashicorp/hcl/v2/hclsyntax"
    26  )
    27  
    28  // Parser is a HCL2 parser.
    29  type Parser struct{}
    30  
    31  // Unmarshal HCL2.0 scripts.
    32  func (h *Parser) Unmarshal(p []byte, v interface{}) error {
    33  	file, diags := hclsyntax.ParseConfig(p, "", hcl.Pos{Byte: 0, Line: 1, Column: 1})
    34  
    35  	if diags.HasErrors() {
    36  		var details []error
    37  		details = append(details, diags.Errs()...)
    38  		return fmt.Errorf("parse hcl2 config: \n %s", details)
    39  	}
    40  
    41  	content, err := convertFile(file)
    42  	if err != nil {
    43  		return fmt.Errorf("convert hcl2 to json: %w", err)
    44  	}
    45  
    46  	j, err := json.Marshal(content)
    47  	if err != nil {
    48  		return fmt.Errorf("marshal hcl2 to json: %w", err)
    49  	}
    50  
    51  	if err := json.Unmarshal(j, v); err != nil {
    52  		return fmt.Errorf("unmarshal hcl2 json: %w", err)
    53  	}
    54  
    55  	return nil
    56  }