Skip to content

Commit

Permalink
Add if-defined conditional
Browse files Browse the repository at this point in the history
This fixes gstein#18
  • Loading branch information
sebbASF committed Jul 30, 2023
1 parent 943d7b2 commit 939f5f3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
17 changes: 15 additions & 2 deletions ezt.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,11 +286,11 @@ def _parse(self, reader, for_names=None, file_args=(), base_printer=None):
program.append((cmd,
(_prepare_ref(args[1], for_names, file_args),
reader, printers[-1]), filename, line_number))
elif cmd == 'if-any':
elif cmd == 'if-any' or cmd == 'if-defined':
f_args = [ ]
for arg in args[1:]:
f_args.append(_prepare_ref(arg, for_names, file_args))
stack.append(['if-any', len(program), f_args, None, line_number])
stack.append([cmd, len(program), f_args, None, line_number])
else:
# implied PRINT command
if len(args) > 1:
Expand Down Expand Up @@ -390,6 +390,18 @@ def _cmd_if_any(self, args, fp, ctx, filename, line_number):
break
self._do_if(value, t_section, f_section, fp, ctx)

def _cmd_if_defined(self, args, fp, ctx, filename, line_number):
"If all values are defined, then T else F."
(valrefs, t_section, f_section) = args
value = 0
try:
for valref in valrefs:
if _get_value(valref, ctx, filename, line_number):
value = 1
except UnknownReference as e:
value = 0
self._do_if(value, t_section, f_section, fp, ctx)

def _cmd_if_index(self, args, fp, ctx, _filename, _line_number):
((valref, value), t_section, f_section) = args
items, idx = ctx.for_index[valref[0]]
Expand Down Expand Up @@ -505,6 +517,7 @@ def _get_value(refname_start_rest, ctx, filename, line_number):
for blocks take precedence over data dictionary members with the
same name.
"""
# print('\nrsr',refname_start_rest,'\n',file=sys.stderr)
(refname, start, rest) = refname_start_rest
if rest is None:
# it was a string constant
Expand Down
12 changes: 12 additions & 0 deletions tests/ezt_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,18 @@ def testIsAny(self):
d = self._runTemplate(t, {'O1': [], 'O2': None, 'O3': 0, 'O4': 'hi'})
self.assertEqual('\n!O1\n!O2\nO3\nO4\n!O1O2\nO1O4\n', d)

def testIfDefined(self):
t = """
[if-defined O1]O1[else]!O1[end]
[if-defined O2]O2[else]!O2[end]
[if-defined O3]O3[else]!O3[end]
[if-defined O4]O4[else]!O4[end]
[if-defined O1 O2 O3 O4]O1O2O3O4[else]!O1O2O3O4[end]
[if-defined O3 O4]O3O4[else]!O3O4[end]
"""
d = self._runTemplate(t, {'O3': 0, 'O4': 'hi'})
self.assertEqual('\n!O1\n!O2\nO3\nO4\n!O1O2O3O4\nO3O4\n', d)

def testIfIndex(self):
o = [1, 4, 9, 16, 25]
t = """
Expand Down

0 comments on commit 939f5f3

Please sign in to comment.