From 6640997fc12addf42af535e76d0fb8c0ffc0806a Mon Sep 17 00:00:00 2001 From: cskh Date: Thu, 28 Jul 2022 10:54:25 -0400 Subject: [PATCH] fix (cli): import empty directory to kv (#13939) * fix (cli): import empty directory to kv - when import an empty directory like foo/, the import command will remove the trailing /, making it a non-directory key. - This change fixes the bug by adding back the / if the imported key is an directory --- command/kv/imp/kv_import.go | 5 ++++ command/kv/imp/kv_import_test.go | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/command/kv/imp/kv_import.go b/command/kv/imp/kv_import.go index 6188dbf4fc..d5796f24d2 100644 --- a/command/kv/imp/kv_import.go +++ b/command/kv/imp/kv_import.go @@ -84,6 +84,11 @@ func (c *cmd) Run(args []string) int { Value: value, } + // if the key is a directory, we need to append / + if len(entry.Key) > 0 && entry.Key[len(entry.Key)-1] == '/' { + pair.Key += "/" + } + w := api.WriteOptions{Namespace: entry.Namespace} if _, err := client.KV().Put(pair, &w); err != nil { c.UI.Error(fmt.Sprintf("Error! Failed writing data for key %s: %s", pair.Key, err)) diff --git a/command/kv/imp/kv_import_test.go b/command/kv/imp/kv_import_test.go index fb238b3aaf..3be9d54182 100644 --- a/command/kv/imp/kv_import_test.go +++ b/command/kv/imp/kv_import_test.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/consul/agent" "github.com/mitchellh/cli" + "github.com/stretchr/testify/require" ) func TestKVImportCommand_noTabs(t *testing.T) { @@ -15,6 +16,47 @@ func TestKVImportCommand_noTabs(t *testing.T) { } } +func TestKVImportCommand_EmptyDir(t *testing.T) { + if testing.Short() { + t.Skip("too slow for testing.Short") + } + + t.Parallel() + a := agent.NewTestAgent(t, ``) + defer a.Shutdown() + client := a.Client() + + const json = `[ + { + "key": "foo/", + "flags": 0, + "value": "" + } + ]` + + ui := cli.NewMockUi() + c := New(ui) + c.testStdin = strings.NewReader(json) + + args := []string{ + "-http-addr=" + a.HTTPAddr(), + "-", + } + + code := c.Run(args) + if code != 0 { + t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) + } + + pair, _, err := client.KV().Get("foo", nil) + require.NoError(t, err) + require.Nil(t, pair) + + pair, _, err = client.KV().Get("foo/", nil) + require.NoError(t, err) + require.Equal(t, "foo/", pair.Key) +} + func TestKVImportCommand(t *testing.T) { if testing.Short() { t.Skip("too slow for testing.Short")