1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025-2026 Benjamin Abendroth <braph93@gmx.de>
'''Code for creating when conditions in Bash.'''
from . import when
from . import shell
class ConditionGenerator:
'''Class for generating conditions.'''
def __init__(self, commandline, variable_manager):
self.commandline = commandline
self.variable_manager = variable_manager
def generate(self, tokens):
'''Turn tokens/objects into condition code.'''
r = []
for obj in tokens:
if isinstance(obj, when.OptionIs):
r.append(self._gen_option_is(obj))
elif isinstance(obj, when.HasOption):
r.append(self._gen_has_option(obj))
elif obj in ('&&', '||', '!'):
r.append(obj)
elif obj == '(':
r.append('{')
elif obj == ')':
r.append(';}')
else:
raise AssertionError("Not reached")
if when.needs_braces(tokens):
return '{ %s; }' % ' '.join(r)
return ' '.join(r)
def _gen_option_is(self, obj):
conditions = []
for o in self.commandline.get_options_by_option_strings(obj.options):
have_option = '(( ${#%s[@]} ))' % self.variable_manager.capture_variable(o)
value_equals = []
for value in obj.values:
value_equals.append('[[ "${%s[-1]}" == %s ]]' % (
self.variable_manager.capture_variable(o),
shell.quote(value)
))
if len(value_equals) == 1:
cond = '{ %s && %s; }' % (have_option, value_equals[0])
else:
cond = '{ %s && { %s; } }' % (have_option, ' || '.join(value_equals))
conditions.append(cond)
if len(conditions) == 1:
return conditions[0]
return '{ %s; }' % ' || '.join(conditions)
def _gen_has_option(self, obj):
conditions = []
for o in self.commandline.get_options_by_option_strings(obj.options):
cond = '(( ${#%s[@]} ))' % self.variable_manager.capture_variable(o)
conditions.append(cond)
if len(conditions) == 1:
return conditions[0]
return '{ %s; }' % ' || '.join(conditions)
def generate_when_conditions(commandline, variable_manager, when_):
'''Generate when condition code.'''
tokens = when.parse_when(when_)
generator = ConditionGenerator(commandline, variable_manager)
return generator.generate(tokens)
|