Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(parser): support ref-tags with default values #13

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions README-extensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,46 @@ The ``${beta:${alpha:two}}`` construct first resolves the ``${alpha:two}`` refer
the reference ``${beta:a}`` to the value 99.


Default values
-----------------

References can now have a default value, if the reference couldn't get resolved, for example:

.. code-block:: yaml

# nodes/node1.yml
parameters:
myvalue: ${not:existing:ref||default}

``reclass.py --nodeinfo node1`` then gives:

.. code-block:: yaml

parameters:
myvalue: default

The ``${not:existing:ref||default}`` construct searches for a value at ``not:existing:ref``, and then because it can't find any, it will take the default value.

This works for nested references as well:

.. code-block:: yaml

# nodes/node1.yml
parameters:
default: 123
a: ${not:existing:ref||${default}}
b: ${not:existing:ref||${not:existing:default||fallback}}

``reclass.py --nodeinfo node1`` then gives:

.. code-block:: yaml

parameters:
default: 123
a: 123
b: fallback


Ignore overwritten missing references
-------------------------------------

Expand Down
14 changes: 14 additions & 0 deletions reclass/datatypes/tests/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,20 @@ def test_nested_deep_references(self):
p.interpolate()
self.assertEqual(p.as_dict(), r)

def test_nested_references_default_exists(self):
values = {"a": "value", "b": "${not:existing||${a}}"}
reference = {"a": "value", "b": "value"}
parameters = Parameters(values, SETTINGS, '')
parameters.interpolate()
self.assertEqual(parameters.as_dict(), reference)

def test_nested_references_default_exists(self):
values = {"a": "value", "b": "${not:existing||${again||fallback}}"}
reference = {"a": "value", "b": "fallback"}
parameters = Parameters(values, SETTINGS, '')
parameters.interpolate()
self.assertEqual(parameters.as_dict(), reference)

def test_stray_occurrence_overwrites_during_interpolation(self):
p1 = Parameters({'r' : 1, 'b': '${r}'}, SETTINGS, '')
p2 = Parameters({'b' : 2}, SETTINGS, '')
Expand Down
14 changes: 14 additions & 0 deletions reclass/utils/dictpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ def __init__(self, delim, contents=None):
elif isinstance(contents, list):
self._parts = contents
elif isinstance(contents, six.string_types):
# parse the default value from contents, strip default section (||...) from parts
contents, self.default = self._split_default(contents)
self._parts = self._split_string(contents)
elif isinstance(contents, tuple):
self._parts = list(contents)
Expand Down Expand Up @@ -115,6 +117,18 @@ def _get_innermost_container(self, base):
def _split_string(self, string):
return re.split(r'(?<!\\)' + re.escape(self._delim), string)

def _split_default(self, string):
"""
splits reference tag 'my:tag||default-value' into two parts
"""
parts = string.split("||")
if not parts:
return None # no contents at all
elif len(parts) == 1:
return parts[0], None # no default
else:
return parts[:-1][0], parts[-1] # contain '||' in contents and use just the last '||'

def key_parts(self):
return self._parts[:-1]

Expand Down
4 changes: 4 additions & 0 deletions reclass/values/refitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ def _resolve(self, ref, context):
try:
return path.get_value(context)
except (KeyError, TypeError) as e:
if refpath.default is not None:
if refpath.default == '':
refpath.default = None
return refpath.default
raise ResolveError(ref)

def render(self, context, inventory):
Expand Down
10 changes: 10 additions & 0 deletions reclass/values/tests/test_refitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ def test__resolve_ok(self):

self.assertEquals(result, 1)

def test_default_resolve_ok(self):
reference = RefItem('', Settings({'delimiter': ':'}))
result = reference._resolve('non:existing||default', {'foo':'bar'})
self.assertEquals(result, 'default')

def test_default_exists_resolve_ok(self):
reference = RefItem('', Settings({'delimiter': ':'}))
result = reference._resolve('foo||default', {'foo':'bar'})
self.assertEquals(result, 'bar')

def test__resolve_fails(self):
refitem = RefItem('', Settings({'delimiter': ':'}))
context = {'foo':{'bar': 1}}
Expand Down