fix crash when build.sources is set to an invalid name

the `build` body doesn't have any labels and we were trying to display those.
I also added a test.
This commit is contained in:
Adrien Delorme 2020-01-06 14:29:43 +01:00
parent 1b532fc816
commit 5ef1893b00
3 changed files with 19 additions and 4 deletions

View File

@ -0,0 +1,4 @@
build {
sources = ["ami"]
}

View File

@ -51,11 +51,11 @@ func (p *Parser) decodeBuildConfig(block *hcl.Block) (*BuildBlock, hcl.Diagnosti
if ref == NoSource { if ref == NoSource {
diags = append(diags, &hcl.Diagnostic{ diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError, Severity: hcl.DiagError,
Summary: "Invalid " + sourceLabel + " reference", Summary: "Invalid " + sourceLabel + " reference: " + buildFrom,
Detail: "A " + sourceLabel + " type must start with a letter and " + Detail: "A " + sourceLabel + " type must start with a letter and " +
"may contain only letters, digits, underscores, and dashes." + "may contain only letters, digits, underscores, and dashes." +
"A valid source reference looks like: `source.type.name`", "A valid source reference looks like: `source.type.name`",
Subject: &block.LabelRanges[0], Subject: block.DefRange.Ptr(),
}) })
continue continue
} }
@ -67,7 +67,7 @@ func (p *Parser) decodeBuildConfig(block *hcl.Block) (*BuildBlock, hcl.Diagnosti
Detail: "A " + sourceLabel + " type must start with a letter and " + Detail: "A " + sourceLabel + " type must start with a letter and " +
"may contain only letters, digits, underscores, and dashes." + "may contain only letters, digits, underscores, and dashes." +
"A valid source reference looks like: `source.type.name`", "A valid source reference looks like: `source.type.name`",
Subject: &block.LabelRanges[0], Subject: block.DefRange.Ptr(),
}) })
continue continue
} }
@ -75,7 +75,8 @@ func (p *Parser) decodeBuildConfig(block *hcl.Block) (*BuildBlock, hcl.Diagnosti
build.Froms = append(build.Froms, ref) build.Froms = append(build.Froms, ref)
} }
content, diags := b.Config.Content(buildSchema) content, moreDiags := b.Config.Content(buildSchema)
diags = append(diags, moreDiags...)
for _, block := range content.Blocks { for _, block := range content.Blocks {
switch block.Type { switch block.Type {
case buildProvisionerLabel: case buildProvisionerLabel:

View File

@ -83,6 +83,16 @@ func TestParse_build(t *testing.T) {
[]packer.Build{}, []packer.Build{},
false, false,
}, },
{"invalid source",
defaultParser,
parseTestArgs{"testdata/build/invalid_source_reference.pkr.hcl"},
&PackerConfig{
Builds: nil,
},
true, true,
[]packer.Build{},
false,
},
} }
testParse(t, tests) testParse(t, tests)
} }