github.com/hashicorp/hcl/v2@v2.20.0/cmd/hcldec/vars.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package main 5 6 import ( 7 "fmt" 8 "strings" 9 10 "github.com/hashicorp/hcl/v2" 11 "github.com/zclconf/go-cty/cty" 12 ) 13 14 func parseVarsArg(src string, argIdx int) (map[string]cty.Value, hcl.Diagnostics) { 15 fakeFn := fmt.Sprintf("<vars argument %d>", argIdx) 16 f, diags := parser.ParseJSON([]byte(src), fakeFn) 17 if f == nil { 18 return nil, diags 19 } 20 vals, valsDiags := parseVarsBody(f.Body) 21 diags = append(diags, valsDiags...) 22 return vals, diags 23 } 24 25 func parseVarsFile(filename string) (map[string]cty.Value, hcl.Diagnostics) { 26 var f *hcl.File 27 var diags hcl.Diagnostics 28 29 if strings.HasSuffix(filename, ".json") { 30 f, diags = parser.ParseJSONFile(filename) 31 } else { 32 f, diags = parser.ParseHCLFile(filename) 33 } 34 35 if f == nil { 36 return nil, diags 37 } 38 39 vals, valsDiags := parseVarsBody(f.Body) 40 diags = append(diags, valsDiags...) 41 return vals, diags 42 43 } 44 45 func parseVarsBody(body hcl.Body) (map[string]cty.Value, hcl.Diagnostics) { 46 attrs, diags := body.JustAttributes() 47 if attrs == nil { 48 return nil, diags 49 } 50 51 vals := make(map[string]cty.Value, len(attrs)) 52 for name, attr := range attrs { 53 val, valDiags := attr.Expr.Value(nil) 54 diags = append(diags, valDiags...) 55 vals[name] = val 56 } 57 return vals, diags 58 } 59 60 // varSpecs is an implementation of pflag.Value that accumulates a list of 61 // raw values, ignoring any quoting. This is similar to pflag.StringSlice 62 // but does not complain if there are literal quotes inside the value, which 63 // is important for us to accept JSON literals here. 64 type varSpecs []string 65 66 func (vs *varSpecs) String() string { 67 return strings.Join([]string(*vs), ", ") 68 } 69 70 func (vs *varSpecs) Set(new string) error { 71 *vs = append(*vs, new) 72 return nil 73 } 74 75 func (vs *varSpecs) Type() string { 76 return "json-or-file" 77 }