Skip to content

Commit 33f11a1

Browse files
authored
Merge pull request #497 from reubenmiller/fix-jsonnet-template-helpers-get-has
fix(jsonnet): check if value is an object before accessing nested properties
2 parents de8ab7e + db8c0ce commit 33f11a1

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

pkg/mapbuilder/mapbuilder.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,9 @@ func evaluateJsonnet(imports string, snippets ...string) (string, error) {
500500
},
501501
Get(o, f, default=null)::
502502
local get_(o, ks) =
503-
if ! std.objectHas(o, ks[0]) then
503+
if std.type(o) != 'object' then
504+
default
505+
else if ! std.objectHas(o, ks[0]) then
504506
default
505507
else if std.length(ks) == 1 then
506508
o[ks[0]]
@@ -509,7 +511,9 @@ func evaluateJsonnet(imports string, snippets ...string) (string, error) {
509511
get_(o, std.split(f, '.')),
510512
Has(o, f)::
511513
local has_(o, ks) =
512-
if ! std.objectHas(o, ks[0]) then
514+
if std.type(o) != 'object' then
515+
false
516+
else if ! std.objectHas(o, ks[0]) then
513517
false
514518
else if std.length(ks) == 1 then
515519
true

tests/manual/template/template_get.yml

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,50 @@ tests:
4141
"dummy": 2
4242
}
4343
}
44+
45+
It safely access input if when there is no piped input:
46+
command: |
47+
c8y template execute --template "_.Get(input.value, 'nestedProp2', {dummy: 2})" -c=false -o json
48+
stdout:
49+
exactly: |
50+
{
51+
"dummy": 2
52+
}
53+
54+
It safely access nested properties of input if when there is no piped input:
55+
command: |
56+
c8y template execute --template "_.Get(input, 'value.nestedProp2', {dummy: 2})" -c=false -o json
57+
stdout:
58+
exactly: |
59+
{
60+
"dummy": 2
61+
}
62+
63+
It safely access nested properties of input if when there is piped input:
64+
command: |
65+
c8y template execute --template "{nestedProp2: 1}" \
66+
| c8y template execute --template "{output: _.Get(input, 'value.nestedProp2', {dummy: 2})}" -c=false -o json
67+
stdout:
68+
exactly: |
69+
{
70+
"output": 1
71+
}
72+
73+
It safely checks for nested properties when there is piped input:
74+
command: |
75+
c8y template execute --template "{nestedProp2: 1}" \
76+
| c8y template execute --template "{output: _.Has(input, 'value.nestedProp2')}" -c=false -o json
77+
stdout:
78+
exactly: |
79+
{
80+
"output": true
81+
}
82+
83+
It safely checks for nested properties when there is no piped input:
84+
command: |
85+
c8y template execute --template "{output: _.Has(input, 'value.nestedProp2')}" -c=false -o json
86+
stdout:
87+
exactly: |
88+
{
89+
"output": false
90+
}

0 commit comments

Comments
 (0)