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
This commit is contained in:
cskh 2022-07-28 10:54:25 -04:00 committed by GitHub
parent 8a7e60b10b
commit 416a673c6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

@ -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))

View File

@ -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")