std.mergePatch() but with hidden object fields?

136 views
Skip to first unread message

Brett Viren

unread,
Jul 6, 2021, 3:27:09 PM7/6/21
to Jsonnet
Hi everyone,

I'd like the following to print "hello":

❯ cat junk.jsonnet
local one = {};
local two = {foo::function() "hello"};
std.mergePatch(one, two).foo()

However, because std.objectHas() and std.objectFields() as used by
std.mergePatch() ignore "hidden" fields, it (v0.17.0) gives instead:

❯ jsonnet junk.jsonnet
RUNTIME ERROR: field does not exist: foo
junk.jsonnet:3:1-29



The best solution I think of is to make a new "mergePatchAll()" which is
identical to std.mergePatch() but internally uses std.objectHasAll() and
std.objectFieldsAll().

I try that locally (attached) and it seems okay. Would it make sense to
have this new function as std.mergePatchAll()?

It renames mergePatch() to mergePatchEx() and that is called by both
mergePatch() and mergePatchAll(). This follows the pattern I see in the
existing "...Ex(..., bool)" family of functions.

BTW, I try also making a test_suite/mergeall.jsonnet equivalent to
test_suite/merge.jsonnet but with all test objects using hidden fields.
However, it seems this will need a "std.assertEqualAll()" to complete
and that gets me into built-in operations which takes me deeper than I'd
like to travel.


-Brett.


mergePatchEx(target, patch, hidden)::
if std.isObject(patch) then
local target_object =
if std.isObject(target) then target else {};

local target_fields =
if std.isObject(target_object) then std.objectFieldsEx(target_object, hidden) else [];

local null_fields = [k for k in std.objectFieldsEx(patch, hidden) if patch[k] == null];
local both_fields = std.setUnion(target_fields, std.objectFieldsEx(patch, hidden));

{
[k]:
if !std.objectHasEx(patch, k, hidden) then
target_object[k]
else if !std.objectHasEx(target_object, k, hidden) then
std.mergePatchEx(null, patch[k], hidden) tailstrict
else
std.mergePatchEx(target_object[k], patch[k], hidden) tailstrict
for k in std.setDiff(both_fields, null_fields)
}
else
patch,

mergePatch(target, patch)::
std.mergePatchEx(target, patch, false),

mergePatchAll(target, patch)::
std.mergePatchEx(target, patch, true),

signature.asc
Reply all
Reply to author
Forward
0 new messages