| 1 | package HPCI::ScriptSource; | ||
| 2 | |||
| 3 | # safe Perl | ||
| 4 | use warnings; | ||
| 5 | use strict; | ||
| 6 | use Carp; | ||
| 7 | |||
| 8 | use Moose::Role; | ||
| 9 | |||
| 10 | our @source_commands; | ||
| 11 | |||
| 12 | our @pre_commands; | ||
| 13 | our @post_success_commands; | ||
| 14 | our @post_failure_commands; | ||
| 15 | our @post_always_commands; | ||
| 16 | |||
| 17 | has 'source_command' => ( | ||
| 18 | is => 'ro', | ||
| 19 | isa => 'Str|ArrayRef[Str]', | ||
| 20 | predicate => '_has_source_command' | ||
| 21 | ); | ||
| 22 | |||
| 23 | before 'BUILD' => sub { | ||
| 24 | my $self = shift; | ||
| 25 | |||
| 26 | my $cmds = $self->_command_expansion_methods; | ||
| 27 | unshift @$cmds, 'print_script_source'; | ||
| 28 | }; | ||
| 29 | |||
| 30 | sub print_list { | ||
| 31 | my $self = shift; | ||
| 32 | my $fh = shift; | ||
| 33 | my $list = shift; | ||
| 34 | my $indent = shift // ''; | ||
| 35 | for my $elem (@$list) { | ||
| 36 | print $fh "$indent$_\n" for ref $elem ? @$elem : $elem; | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | sub print_script_source { | ||
| 41 | my $self = shift; | ||
| 42 | my $fh = shift; | ||
| 43 | $self->print_list( $fh, \@source_commands ); | ||
| 44 | $self->print_list( $fh, $self->source_command ) if $self->_has_source_command; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub print_pre_commands { | ||
| 48 | my $self = shift; | ||
| 49 | my $fh = shift; | ||
| 50 | $self->print_list( $fh, \@pre_commands ) | ||
| 51 | if @pre_commands; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub print_post_commands { | ||
| 55 | my $self = shift; | ||
| 56 | my $fh = shift; | ||
| 57 | if (@post_success_commands or @post_failure_commands or @post_always_commands) { | ||
| 58 | print $fh "__STAGE_STATUS__=\$?\n"; | ||
| 59 | print $fh "if [[ \$__STAGE_STATUS__ -eq 0 ]]\n"; | ||
| 60 | print $fh "then\n"; | ||
| 61 | |||
| 62 | my $indent = ' '; | ||
| 63 | |||
| 64 | if (@post_success_commands) { | ||
| 65 | $self->print_list( $fh, \@post_success_commands, $indent ); | ||
| 66 | } | ||
| 67 | else { | ||
| 68 | print $fh "${indent}__IGNORE_ME_=0\n"; | ||
| 69 | } | ||
| 70 | |||
| 71 | if (@post_failure_commands) { | ||
| 72 | print $fh "else\n"; | ||
| 73 | $self->print_list( $fh, \@post_failure_commands, $indent ); | ||
| 74 | } | ||
| 75 | |||
| 76 | print $fh "fi\n"; | ||
| 77 | |||
| 78 | $self->print_list( $fh, \@post_always_commands, $indent ) | ||
| 79 | if @post_always_commands; | ||
| 80 | |||
| 81 | print $fh "exit \$__STAGE_STATUS__\n"; | ||
| 82 | } | ||
| 83 | } | ||
| 84 | |||
| 85 | 1; |