From 191d7c100792cc9c64e5332b4e718bce780a6269 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Fri, 12 Aug 2016 14:19:42 -0400 Subject: [PATCH 1/2] Fix panic when showing empty state Fixes a nil dereference when there's no state to print. Fix some slice declaration to use the recommended style when allocations don't matter. --- command/state_show.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/command/state_show.go b/command/state_show.go index d9a4f1d08b..1f5096e63d 100644 --- a/command/state_show.go +++ b/command/state_show.go @@ -45,22 +45,27 @@ func (c *StateShowCommand) Run(args []string) int { return 1 } + if len(results) == 0 { + return 0 + } + instance, err := c.filterInstance(results) if err != nil { c.Ui.Error(err.Error()) return 1 } + is := instance.Value.(*terraform.InstanceState) // Sort the keys - keys := make([]string, 0, len(is.Attributes)) + var keys []string for k, _ := range is.Attributes { keys = append(keys, k) } sort.Strings(keys) // Build the output - output := make([]string, 0, len(is.Attributes)+1) + var output []string output = append(output, fmt.Sprintf("id | %s", is.ID)) for _, k := range keys { if k != "id" { From 1be5a650fc60fe30e2c09fd6948492e1619b1c16 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Fri, 12 Aug 2016 15:01:25 -0400 Subject: [PATCH 2/2] Add test for showing an empty state Make sure we don't panic if there's no state to print --- command/state_show_test.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/command/state_show_test.go b/command/state_show_test.go index 1e2dba08c2..cbcfb46d8c 100644 --- a/command/state_show_test.go +++ b/command/state_show_test.go @@ -126,6 +126,29 @@ func TestStateShow_noState(t *testing.T) { } } +func TestStateShow_emptyState(t *testing.T) { + state := &terraform.State{} + + statePath := testStateFile(t, state) + + p := testProvider() + ui := new(cli.MockUi) + c := &StateShowCommand{ + Meta: Meta{ + ContextOpts: testCtxConfig(p), + Ui: ui, + }, + } + + args := []string{ + "-state", statePath, + "test_instance.foo", + } + if code := c.Run(args); code != 0 { + t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) + } +} + const testStateShowOutput = ` id = bar bar = value