delegate formatting of compound Bash statements to dedicated classes

this simplifies handling compound statements using _AdviceOutput class.
The necessary statements are exposed as context managers and API for
most common constructs is provided.

https://pagure.io/freeipa/issue/7036

Reviewed-By: Florence Blanc-Renaud <frenaud@redhat.com>
Reviewed-By: Alexander Bokovoy <abokovoy@redhat.com>
This commit is contained in:
Martin Babinsky
2017-06-22 15:02:25 +02:00
committed by Martin Basti
parent dea4b4ca1b
commit 9808395c17

View File

@@ -286,33 +286,53 @@ class _AdviceOutput(object):
) )
def exit_on_predicate(self, predicate, error_message_lines): def exit_on_predicate(self, predicate, error_message_lines):
commands_to_run = [ with self.unbranched_if(predicate):
self._format_error(error_message_line) for error_message_line in error_message_lines:
for error_message_line in error_message_lines] self.command(self._format_error(error_message_line))
commands_to_run.append('exit 1') self.command('exit 1')
self.commands_on_predicate(
predicate, @contextmanager
commands_to_run) def unbranched_if(self, predicate):
with self._compound_statement(UnbranchedIfStatement, predicate):
yield
@contextmanager
def _compound_statement(self, statement_cls, *args):
with statement_cls(self, *args):
yield
def commands_on_predicate(self, predicate, commands_to_run_when_true, def commands_on_predicate(self, predicate, commands_to_run_when_true,
commands_to_run_when_false=None): commands_to_run_when_false=None):
if_command = 'if {}'.format(predicate) if commands_to_run_when_false is not None:
self.command(if_command) if_statement = self.if_branch
self.command('then') else:
if_statement = self.unbranched_if
with self.indented_block(): with if_statement(predicate):
for command_to_run_when_true in commands_to_run_when_true: for command_to_run_when_true in commands_to_run_when_true:
self.command( self.command(
command_to_run_when_true) command_to_run_when_true)
if commands_to_run_when_false is not None: if commands_to_run_when_false is not None:
self.command("else") with self.else_branch():
with self.indented_block():
for command_to_run_when_false in commands_to_run_when_false: for command_to_run_when_false in commands_to_run_when_false:
self.command(command_to_run_when_false) self.command(command_to_run_when_false)
self.command('fi') @contextmanager
def if_branch(self, predicate):
with self._compound_statement(IfBranch, predicate):
yield
@contextmanager
def else_branch(self):
with self._compound_statement(ElseBranch):
yield
@contextmanager
def else_if_branch(self, predicate):
with self._compound_statement(ElseIfBranch, predicate):
yield
class Advice(Plugin): class Advice(Plugin):