Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli: Fix kv import for keys with trailing slash #11888

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion command/kv/imp/kv_import.go
Expand Up @@ -11,6 +11,7 @@ import (
"io/ioutil"
"os"
"path"
"strings"

"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/command/flags"
Expand Down Expand Up @@ -78,8 +79,22 @@ func (c *cmd) Run(args []string) int {
return 1
}

var buf strings.Builder
if c.prefix != "" {
// Append prefix to key
buf.WriteString(path.Join(c.prefix, entry.Key))

// path.Join() removes trailing slashes.
// Re-add the trailing slash if it was previously present on the key
if strings.HasSuffix(entry.Key, "/") {
buf.WriteString("/")
}
} else {
buf.WriteString(entry.Key)
}

pair := &api.KVPair{
Key: path.Join(c.prefix, entry.Key),
Key: buf.String(),
Flags: entry.Flags,
Value: value,
}
Expand Down
19 changes: 19 additions & 0 deletions command/kv/imp/kv_import_test.go
Expand Up @@ -86,6 +86,11 @@ func TestKVImportPrefixCommand(t *testing.T) {
"key": "foo",
"flags": 0,
"value": "YmFyCg=="
},
{
"key": "foo/b/",
"flags": 0,
"value": null
}
]`

Expand Down Expand Up @@ -121,4 +126,18 @@ func TestKVImportPrefixCommand(t *testing.T) {
if strings.TrimSpace(string(pair.Value)) != "bar" {
t.Fatalf("bad: expected: bar, got %s", pair.Value)
}

// Ensure trailing slash is preserved on import
pair, _, err = client.KV().Get("sub/foo/b/", nil)
if err != nil {
t.Fatal(err)
}

if pair == nil {
t.Fatalf("bad: expected: %+v, got nil", pair)
}

if len(pair.Value) != 0 {
t.Fatalf("bad: expected: null, got %s", string(pair.Value))
}
}