| 1 | package App::SD::CLI::Command; | ||
| 2 | use Any::Moose 'Role'; | ||
| 3 | use Params::Validate qw(validate); | ||
| 4 | |||
| 5 | =head2 get_content %args | ||
| 6 | |||
| 7 | This is a helper routine for use in SD commands to enable getting records | ||
| 8 | in different ways such as from a file, on the commandline, or from an | ||
| 9 | editor. Returns the record content. | ||
| 10 | |||
| 11 | Valid keys in %args are type => str, default_edit => bool, and | ||
| 12 | prefill_props => $props_hash_ref, props_order => $order_array_ref, | ||
| 13 | footer => str, header => str. | ||
| 14 | |||
| 15 | Specifying props with prefill_props allows you to present lists of | ||
| 16 | key/value pairs (with possible default values) for a user to fill in. | ||
| 17 | If you need a specific ordering of props, specify it with | ||
| 18 | C<props_order>. Specifying C<header> and/or C<footer> allows you to | ||
| 19 | print some optional text before and/or after the list of props. | ||
| 20 | |||
| 21 | Note that you will have to post-process C<$content> from the routine | ||
| 22 | calling C<get_content> in order to extract the keys and values from | ||
| 23 | the returned text. | ||
| 24 | |||
| 25 | =cut | ||
| 26 | |||
| 27 | sub get_content { | ||
| 28 | my $self = shift; | ||
| 29 | my %args = @_; | ||
| 30 | |||
| 31 | Prophet::CLI->end_pager(); | ||
| 32 | |||
| 33 | my $content; | ||
| 34 | if (my $file = $self->delete_arg('file')) { | ||
| 35 | my ( $vol, $dir, $name ) = File::Spec->splitpath( $file ); | ||
| 36 | $content = Prophet::Util->slurp( $file ); | ||
| 37 | $self->set_prop(name => $name); | ||
| 38 | } elsif ($content = $self->delete_arg('content')) { | ||
| 39 | |||
| 40 | } elsif ($args{default_edit} || $self->has_arg('edit')) { | ||
| 41 | my $text = ''; | ||
| 42 | if (my $header = $args{header}) { | ||
| 43 | $text .= $header; | ||
| 44 | } | ||
| 45 | if (my $props = $args{prefill_props}) { | ||
| 46 | my $props_order; | ||
| 47 | my @ordering = ($props_order = $args{props_order}) ? | ||
| 48 | @$props_order : keys %$props; | ||
| 49 | $text .= join "\n", map { "$_: $props->{$_}" } @ordering; | ||
| 50 | } | ||
| 51 | if (my $footer = $args{footer}) { | ||
| 52 | $text .= $footer; | ||
| 53 | } | ||
| 54 | |||
| 55 | $content = $self->edit_text($text); | ||
| 56 | # user aborted their text editor without changing anything; signify | ||
| 57 | # this to the caller by returning nothing | ||
| 58 | $content = '' if $content eq $text; | ||
| 59 | } elsif ($ENV{IN_PROPHET_TEST_COMMAND}) { | ||
| 60 | die "Tried to invoke an editor in a test script!"; | ||
| 61 | } else { | ||
| 62 | print "Please type your $args{type} and press ctrl-d.\n"; | ||
| 63 | $content = do { local $/; <STDIN> }; | ||
| 64 | } | ||
| 65 | |||
| 66 | chomp $content; | ||
| 67 | return $content; | ||
| 68 | } | ||
| 69 | |||
| 70 | no Any::Moose; | ||
| 71 | |||
| 72 | 1; | ||
| 73 |