From e94b8766cb1db6a9f88dd095928ca6b213aacc11 Mon Sep 17 00:00:00 2001 From: Lucas Bajolet Date: Tue, 20 Sep 2022 17:27:42 -0400 Subject: [PATCH] build: exit immediately if no builds and diags When a template with some builds to run ends its GetBuilds with an error, and no builds produced, we can exit immediately without printing more errors. --- command/build.go | 3 ++ command/build_test.go | 60 ++++++++++++++++++++++ command/test-fixtures/hcl/no_build.pkr.hcl | 3 ++ 3 files changed, 66 insertions(+) create mode 100644 command/test-fixtures/hcl/no_build.pkr.hcl diff --git a/command/build.go b/command/build.go index 46a64757b..9cb7cce0a 100644 --- a/command/build.go +++ b/command/build.go @@ -128,6 +128,9 @@ func (c *BuildCommand) RunContext(buildCtx context.Context, cla *BuildArgs) int // here, something could have gone wrong but we still want to run valid // builds. ret = writeDiags(c.Ui, nil, diags) + if len(builds) == 0 && ret != 0 { + return ret + } if cla.Debug { c.Ui.Say("Debug mode enabled. Builds will not be parallelized.") diff --git a/command/build_test.go b/command/build_test.go index 2fdaffd07..cb24f15cd 100644 --- a/command/build_test.go +++ b/command/build_test.go @@ -1111,3 +1111,63 @@ func TestBuildCommand_ParseArgs(t *testing.T) { }) } } + +// TestBuildCmd aims to test the build command, with output validation +func TestBuildCmd(t *testing.T) { + tests := []struct { + name string + args []string + expectedCode int + outputCheck func(string, string) error + }{ + { + name: "hcl - no build block error", + args: []string{ + testFixture("hcl", "no_build.pkr.hcl"), + }, + expectedCode: 1, + outputCheck: func(_, err string) error { + if !strings.Contains(err, "Error: Missing build block") { + return fmt.Errorf("expected 'Error: Missing build block' in output, did not find it") + } + + nbErrs := strings.Count(err, "Error: ") + if nbErrs != 1 { + return fmt.Errorf( + "error: too many errors in stdout for build block, expected 1, got %d", + nbErrs) + } + + return nil + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &BuildCommand{ + Meta: TestMetaFile(t), + } + + exitCode := c.Run(tt.args) + if exitCode != tt.expectedCode { + t.Errorf("process exit code mismatch: expected %d, got %d", + tt.expectedCode, + exitCode) + } + + out, stderr := GetStdoutAndErrFromTestMeta(t, c.Meta) + err := tt.outputCheck(out, stderr) + if err != nil { + if len(out) != 0 { + t.Logf("command stdout: %q", out) + } + + if len(stderr) != 0 { + t.Logf("command stderr: %q", stderr) + } + t.Error(err.Error()) + } + }) + } +} diff --git a/command/test-fixtures/hcl/no_build.pkr.hcl b/command/test-fixtures/hcl/no_build.pkr.hcl new file mode 100644 index 000000000..ae75d38be --- /dev/null +++ b/command/test-fixtures/hcl/no_build.pkr.hcl @@ -0,0 +1,3 @@ +source "null" "papaya" { + communicator = "none" +}