jg icon indicating copy to clipboard operation
jg copied to clipboard

Allow for variable substitution

Open apognu opened this issue 5 years ago • 2 comments

Currently (as far as I know), if one wants to use variables substitution in a filter expressions, it becomes a mess of escaped quotes that is diffcult to write and read, like so:

$ jg ".people[{\"craft\":\"$CRAFT\"}]"

Maybe allowing for single quotes in the filter would clean it up a bit:

$ jg ".people[{'craft':'$CRAFT'}]"

Another possibility, but that will only work for keys and value that do not contain : or ], would be to allow dropping the quotes altogether. Though it might be more difficult to implement. Something like:

$ jg ".people[{craft:$CRAFT}]"

What do you think?

apognu avatar May 05 '19 16:05 apognu

Hey Antoine, Thanks for taking the time for this feedback. :)

I've been giving this some thought and I'm still playing around with ideas, so no decisions made, but here are some thoughts.

Starting at the end; dropping the quotes all together wouldn't work for a variety of reason such as the fact that we want to support every value that's possible in standard JSON, such as $ or } etc.

I'm not crazy about the single quotes idea because it drives the syntax further away from standard JSON (which will be unintuitive to users of the CLI, IMHO). In addition, to be honest, relying on the standard BASH substitution doesn't really sit well with me... because it always feels very implicit (it's why I always spend 2 hours on every sed command I try 😂). So, I'm not saying no to the single quote idea, but I'd rather explore other options first.

One idea I'm playing around with (in my head, so far) is passing in variables using a different CLI argument, and doing the substitution ourselves.

For example:

export VIDEO_MIME="mp4"
jg -e '.video.mimes[*="{}"]' --params "$VIDEO_MIME"

This would substitute internally as:

jg -e '.video.mimes[*="mp4"]'

We could also implement this slightly differently, where you specify the key too:

export VIDEO_MIME="mp4"
jg -e '.video.mimes[*="$VIDEO_MIME"]' --params "VIDEO_MIME=$VIDEO_MIME"

But this feels far too verbose, so I'd opt for the first implementation.

What do you think of that approach?

gmmorris avatar May 05 '19 21:05 gmmorris

Sorry it took a while, but I've now added a release (0.1.7) with the above implementation.

If you try using the params flag you can pass in as many parameters as you wish. Each {} marker will be replaced until no more {} s can be found or no more params have been specified.

So for example, this will work:

export VIDEO_MIME="mp4"
jg -e '.video.mimes[*="{}"]' --params "$VIDEO_MIME"

and will be treated as:

jg -e '.video.mimes[*="mp4"]'

I'll add it to the docs once I've put some usage into it and feel it works as needed. Feel free to download the latest version and give it a whirl.

gmmorris avatar Aug 07 '19 13:08 gmmorris