gomplate icon indicating copy to clipboard operation
gomplate copied to clipboard

Unable to pass a Slice of string keys to coll.Pick()

Open kevitan opened this issue 2 years ago • 1 comments

I would like to use coll.Pick() to filter out some values to generate a sub-map. The keys that I need are dynamically generated, and at first I thought I could just do something like

{{ $resultMap := coll.Pick ($mapWithMyKeys | keys) ($largerMap) }}

but I kept getting an error :

error calling Pick: wrong key type: must be string, got []string

I realized that the input was not supposed to be an array, rather just a bunch of strings in order. So I began trying to figure a way to unpack the array in-line, however, I think the function is still treating the space-delimited list as a single string?

{{ $resultMap := coll.Pick (conv.Join ($mapWithMyKeys | keys) " ") ($largerMap) }}
len: {{ len (keys $resultMap }}  // <-- still evals to 0

I even tried quoting each member of the array, to no avail:

{{ $resultMap := coll.Pick (conv.Join ($mapWithMyKeys | keys) "\" \"" | quote ) ($largerMap) }}

am I missing something obvious here?

I have made absolutely certain that the keys I'm filtering on do exist in the target map.

edit: upon trying some more debugging, i realise the above code snippet ends up preserving the backslashes to escape the quotes:

"key-1\" \"key-2\" \"key-3"

This is a result of the quote function quoting the entire string.

When I try it by using printf:

{{ $resultMap := coll.Pick (conv.Join ($mapWithMyKeys | keys) "\" \"" | printf "\"%s\"" ) ($largerMap) }}

at least the keys print out in quotes:

"key-1" "key-2" "key-3"

but still cannot be parsed as multiple keys, and instead still returns 0 matches from the coll.Pick() call.

kevitan avatar May 25 '23 21:05 kevitan

Hmm... Indeed this is because coll.Pick is designed only to handle a number of inline strings, not a slice. It should be fairly straightforward to add slice support though.

There isn't going to be a good workaround for this unfortunately. I'll enhance the coll.Pick function so it can support a slice.

hairyhenderson avatar May 26 '23 13:05 hairyhenderson

This'll be fixed by #2069 and available in v4.0.0

hairyhenderson avatar May 12 '24 16:05 hairyhenderson