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 4 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
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
2 changes: 2 additions & 0 deletions reclass/values/refitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ def _resolve(self, ref, context):
try:
return path.get_value(context)
except (KeyError, TypeError) as e:
if path.default:
return path.default
raise ResolveError(ref)

def render(self, context, inventory):
Expand Down
5 changes: 5 additions & 0 deletions reclass/values/tests/test_refitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ 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__resolve_fails(self):
refitem = RefItem('', Settings({'delimiter': ':'}))
context = {'foo':{'bar': 1}}
Expand Down