github.com/terraform-linters/tflint-plugin-sdk@v0.22.0/hclext/parse.go (about) 1 package hclext 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/hashicorp/hcl/v2" 8 "github.com/hashicorp/hcl/v2/hclsyntax" 9 "github.com/hashicorp/hcl/v2/json" 10 ) 11 12 // ParseExpression is a wrapper that calls ParseExpression of hclsyntax and json based on the file extension. 13 // This function specializes in parsing intermediate expressions in the file, 14 // so it takes into account the hack on trailing newlines in heredoc. 15 func ParseExpression(src []byte, filename string, start hcl.Pos) (hcl.Expression, hcl.Diagnostics) { 16 if strings.HasSuffix(filename, ".tf") || strings.HasSuffix(filename, ".hcl") { 17 // HACK: Always add a newline to avoid heredoc parse errors. 18 // @see https://github.com/hashicorp/hcl/issues/441 19 src = []byte(string(src) + "\n") 20 return hclsyntax.ParseExpression(src, filename, start) 21 } 22 23 if strings.HasSuffix(filename, ".tf.json") { 24 return json.ParseExpressionWithStartPos(src, filename, start) 25 } 26 27 return nil, hcl.Diagnostics{ 28 { 29 Severity: hcl.DiagError, 30 Summary: "Unexpected file extension", 31 Detail: fmt.Sprintf("The file name `%s` is a file with an unexpected extension. Valid extensions are `.tf`, `.tf.json`, and `.hcl`.", filename), 32 }, 33 } 34 }