Skip to content

Commit

Permalink
cli: Fix kv import for keys with trailing slash
Browse files Browse the repository at this point in the history
Correctly import keys names that end in a trailing slash.

Fixes #10906
  • Loading branch information
blake committed Dec 18, 2021
1 parent 2df20d1 commit 82b9527
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
17 changes: 16 additions & 1 deletion command/kv/imp/kv_import.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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))
}
}

0 comments on commit 82b9527

Please sign in to comment.