1 package MooseX::Runnable::Util::ArgParser;
3 use MooseX::Types::Moose qw(HashRef ArrayRef Str Bool);
4 use MooseX::Types::Path::Class qw(Dir);
5 use List::MoreUtils qw(first_index);
7 use namespace::autoclean -also => ['_look_for_dash_something', '_delete_first'];
29 has 'include_paths' => (
38 isa => HashRef[ArrayRef[Str]],
56 sub _build_class_name {
58 my @args = $self->argv;
61 my $need_dash_dash = 0;
74 next ARG if $arg =~ /^-[A-Za-z]/;
81 return $arg unless $need_dash_dash;
85 confess 'Parse error: expecting ClassName, got EOF';
88 confess 'Parse error: expecting --, got EOF';
91 confess "Parse error: looking for ClassName, but can't find it; perhaps you meant '--help' ?";
94 sub _look_for_dash_something($@) {
95 my ($something, @args) = @_;
98 my $rx = qr/^-$something(.*)$/;
100 for my $arg (@args) {
101 last ARG if $arg eq '--';
102 last ARG unless $arg =~ /^-/;
113 my @args = $self->argv;
114 return [ _look_for_dash_something 'M', @args ];
117 sub _build_include_paths {
119 my @args = $self->argv;
120 return [ map { Path::Class::dir($_) } _look_for_dash_something 'I', @args ];
125 my @args = $self->argv;
127 (_look_for_dash_something 'h', @args) ||
128 (_look_for_dash_something '\\?', @args) ||
129 (_look_for_dash_something '-help', @args) ;;
134 my @args = $self->argv;
135 $self->class_name; # causes death when plugin syntax is wrong
139 my $in_plugin = undef;
142 for my $arg (@args) {
143 if(defined $in_plugin){
145 $plugins{$in_plugin} = [@accumulator];
149 elsif($arg =~ /^[+](.+)$/){
150 $plugins{$in_plugin} = [@accumulator];
156 push @accumulator, $arg;
159 else { # once we are $in_plugin, we can never be out again
163 elsif($arg =~ /^[+](.+)$/){
171 confess "Parse error: expecting arguments for plugin $in_plugin, but got EOF. ".
172 "Perhaps you forgot '--' ?";
178 sub _delete_first($\@) {
179 my ($to_delete, $list) = @_;
180 my $idx = first_index { $_ eq $to_delete } @$list;
181 splice @$list, $idx, 1;
185 # this is a dumb way to do it, but i forgot about it until just now,
186 # and don't want to rewrite the whole class ;) ;)
187 sub _build_app_args {
189 my @args = $self->argv;
191 return [] if $self->is_help; # LIES!!11!, but who cares
193 # functional programmers may wish to avert their eyes
194 _delete_first $_, @args for map { "-M$_" } $self->modules;
195 _delete_first $_, @args for map { "-I$_" } $self->include_paths;
197 my %plugins = %{ $self->plugins };
200 for my $p (keys %plugins){
201 my $vl = scalar @{ $plugins{$p} };
202 my $idx = first_index { $_ eq "+$p" } @args;
203 next PLUGIN if $idx == -1; # HORRIBLE API!
205 splice @args, $idx, $vl + 1;
208 if($args[0] eq '--'){
212 if($args[0] eq $self->class_name){
216 confess 'Parse error: Some residual crud was found before the app name: '.
229 MooseX::Runnable::Util::ArgParser - parse @ARGV for mx-run
233 my $parser = MooseX::Runnable::Util::ArgParser->new(
239 $parser->include_paths;