From 4763cd08f0f63b9371a54156fa8e2b25124e6828 Mon Sep 17 00:00:00 2001 From: Ansgar Mertens Date: Mon, 4 Mar 2024 15:11:07 +0100 Subject: [PATCH] fix: be more graceful when trying to access the value of an invalid expression template for templates with a prefix --- hclsyntax/expression_template.go | 5 +++++ hclsyntax/expression_template_test.go | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/hclsyntax/expression_template.go b/hclsyntax/expression_template.go index 7c66d93c..6a8d0356 100644 --- a/hclsyntax/expression_template.go +++ b/hclsyntax/expression_template.go @@ -33,6 +33,11 @@ func (e *TemplateExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) marks := make(cty.ValueMarks) for _, part := range e.Parts { + if part == nil { + // we silently ignore nil parts as they only occur for configuration that is already known to be invalid + continue + } + partVal, partDiags := part.Value(ctx) diags = append(diags, partDiags...) diff --git a/hclsyntax/expression_template_test.go b/hclsyntax/expression_template_test.go index 3f7f12bc..7e986c82 100644 --- a/hclsyntax/expression_template_test.go +++ b/hclsyntax/expression_template_test.go @@ -439,6 +439,17 @@ trim`, } func TestTemplateExprGracefulValue(t *testing.T) { + // we don't care about diags since we know it's invalid config + expr, _ := ParseTemplate([]byte(`prefix${provider::}`), "", hcl.Pos{Line: 1, Column: 1, Byte: 0}) + + got, _ := expr.Value(nil) // this should not panic + + if !got.RawEquals(cty.StringVal("prefix")) { + t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, cty.NilVal) + } +} + +func TestTemplateExprWrappedGracefulValue(t *testing.T) { // we don't care about diags since we know it's invalid config expr, _ := ParseTemplate([]byte(`${provider::}`), "", hcl.Pos{Line: 1, Column: 1, Byte: 0})