sbarzowski / jsonnet-modifiers

Jsonnet library for modifying nested structures
Apache License 2.0
21 stars 0 forks source link

Support for checking existence of objects #1

Open sbarzowski opened 5 years ago

sbarzowski commented 5 years ago

The need for this was mentioned here: https://groups.google.com/d/msg/jsonnet/4gaCg_l3ZsA/NeGpAgIGCAAJ

And here: https://groups.google.com/forum/#!topic/jsonnet/1nEJOYmS78I

Related:

sbarzowski commented 5 years ago

Checking the existence of fields can be done following the same pattern, even the same API. It's a tiny bit awkward, though.

We can have a "checking selector" which returns false if the field doesn't exist or modifier applied to it, if it does.

local checkField(name) = function(modifier) function(obj)
    if std.objectHas(obj, name) then modifier(obj.field) else false

Ofc. something similar applied to arrays is also possible.

Then it could be used as:

    m.change([checkField("foo"), checkField("bar")], true)(obj)

It's (expectedly) awkward to use change interface for checking if fields exist - there's this true value at the end, and obvious indexing needs to be spelled out as checkField ("foo" means m.override(foo) by default for change function). So we would need a different wrapper function which presents an interface more like this:

m.check(["foo", "bar"])(obj)

In this case strings would mean to checkField and not m.override.

sbarzowski commented 5 years ago

Currently I see the following kinds of operations besides current "strict modification".

Each of them can follow the same selector/modifier pattern, but it potentially warrants its own default meaning of strings and numbers.

I'm also afraid they don't necessarily need to play together very well, i.e. it's not immediately clear to me what is going to happen when checking selectors and modifying selectors are mixed and if it makes sense at all. Perhaps we could check and prohibit that or perhaps it is actually useful. Well, mixing just strict and nonstrict variants of the same thing, e.g. strict getting of one field and safe getting of another definitely makes sense.

So another classification is that we have strict and non-strict versions of:

Perhaps checking can be eliminated (or reduced to a convenience method) by checking if safe indexing found any values.