Skip to content

Commit

Permalink
init: warn if no requirements specified
Browse files Browse the repository at this point in the history
When users call `packer init' on a template that does not specify a
`required_plugin' block, the command succeeds but does nothing, which is
not helpful for users that may expect their plugins to install.

To remedy that problem, we now output a message like what `packer
plugins required' does on templates without such a block, so that users
have an idea of what to change in order to get the command to work.
  • Loading branch information
lbajolet-hashicorp committed Sep 27, 2023
1 parent d56db70 commit c0e5947
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
8 changes: 8 additions & 0 deletions command/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ func (c *InitCommand) RunContext(buildCtx context.Context, cla *InitArgs) int {
return ret
}

if len(reqs) == 0 {
c.Ui.Message(`
No plugins requirement found, make sure you reference a Packer config
containing a packer.required_plugins block. See
https://www.packer.io/docs/templates/hcl_templates/blocks/packer
for more info.`)
}

opts := plugingetter.ListInstallationsOptions{
FromFolders: c.Meta.CoreConfig.Components.PluginConfig.KnownPluginFolders,
BinaryInstallationOptions: plugingetter.BinaryInstallationOptions{
Expand Down
53 changes: 53 additions & 0 deletions command/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"path/filepath"
"runtime"
"sort"
"strings"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -414,3 +415,55 @@ func (opts initTestGoGetPlugin) fn(t *testing.T, _ testCaseInit) {
t.Fatalf("get: %v", err)
}
}

// TestInitCmd aims to test the init command, with output validation
func TestInitCmd(t *testing.T) {
tests := []struct {
name string
args []string
expectedCode int
outputCheck func(string, string) error
}{
{
name: "Ensure init warns on template without required_plugin blocks",
args: []string{
testFixture("hcl", "build-var-in-pp.pkr.hcl"),
},
expectedCode: 0,
outputCheck: func(stdout, stderr string) error {
if !strings.Contains(stdout, "No plugins requirement found") {
return fmt.Errorf("command should warn about plugin requirements not found, but did not")
}
return nil
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &InitCommand{
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())
}
})
}
}

0 comments on commit c0e5947

Please sign in to comment.