Skip to content

Commit

Permalink
hcl2: avoid panic on unset variable
Browse files Browse the repository at this point in the history
Variables that are unset return the correct diagnostic but throw a panic when
we later parse the job body. Return early if there are any variable parsing
errors instead of continuing in a potentially invalid state.
  • Loading branch information
tgross committed Feb 18, 2021
1 parent 095ed2c commit 1a34c02
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
22 changes: 22 additions & 0 deletions jobspec2/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,28 @@ job "example" {
require.Equal(t, meta, out.Meta)
}

// TestParse_UnsetVariables asserts that variables that have neither types nor
// values return early instead of panicking.
func TestParse_UnsetVariables(t *testing.T) {
hcl := `
variable "region_var" {}
job "example" {
datacenters = [for s in ["dc1", "dc2"] : upper(s)]
region = var.region_var
}
`

_, err := ParseWithConfig(&ParseConfig{
Path: "input.hcl",
Body: []byte(hcl),
ArgVars: []string{},
AllowFS: true,
})

require.Error(t, err)
require.Contains(t, err.Error(), "Unset variable")
}

func TestParse_Locals(t *testing.T) {
hcl := `
variables {
Expand Down
7 changes: 7 additions & 0 deletions jobspec2/types.config.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ func (c *jobConfig) decodeBody(body hcl.Body) hcl.Diagnostics {
diags = append(diags, moreDiags...)
diags = append(diags, c.evaluateLocalVariables(c.LocalBlocks)...)

// Errors at this point are likely syntax errors which can result in
// invalid state when we try to decode the rest of the job. If we continue
// we may panic and that will obscure the error, so return early so the
// user can be told how to fix their jobspec.
if diags.HasErrors() {
return diags
}
nctx := c.EvalContext()

diags = append(diags, c.decodeJob(content, nctx)...)
Expand Down

0 comments on commit 1a34c02

Please sign in to comment.