jsonnet-modifiers
jsonnet-modifiers copied to clipboard
Support for checking existence of objects
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:
- Deep indexing, i.e. just extracting the parts of deeply nested data
- Safe indexing/changing (ignoring/creating fields that don't exist.
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
.
Currently I see the following kinds of operations besides current "strict modification".
- checking if a deep field exists
- deep safe indexing (ignoring parts that don't exist)
- deep strict indexing (strict, i.e. causing errors when things don't exist)
- implicit creating of nonexistent fields when modifying
- implicit ignoring of nonexistent fields when modifying
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:
- modification
- indexing (just getting the value out)
- checking
Perhaps checking can be eliminated (or reduced to a convenience method) by checking if safe indexing found any values.