Get useful help about which option you fucked up back
[catagits/Catalyst-Runtime.git] / lib / Catalyst / ScriptRole.pm
1 package Catalyst::ScriptRole;
2 use Moose::Role;
3 use MooseX::Types::Moose qw/Str Bool/;
4 use Pod::Usage;
5 use MooseX::Getopt;
6 use namespace::autoclean;
7
8 with 'MooseX::Getopt' => {
9     excludes => [qw/
10         _getopt_spec_warnings
11         _getopt_spec_exception
12     /],
13 };
14
15 has application_name => (
16     traits => ['NoGetopt'],
17     isa => Str,
18     is => 'ro',
19     required => 1,
20 );
21
22 has help => (
23     traits => ['Getopt'],
24     isa => Bool,
25     is => 'ro',
26     documentation => q{Display this help and exit},
27 );
28
29 sub _getopt_spec_exception {}
30
31 sub _getopt_spec_warnings {
32     shift;
33     warn @_;
34 }
35
36 sub _exit_with_usage {
37     my $self = shift;
38     pod2usage();
39     exit 0;
40 }
41
42 before run => sub {
43     my $self = shift;
44     $self->_exit_with_usage if $self->help;
45 };
46
47 sub run {
48     my $self = shift;
49     $self->_run_application;
50 }
51
52 sub _application_args {
53     ()
54 }
55
56 sub _run_application {
57     my $self = shift;
58     my $app = $self->application_name;
59     Class::MOP::load_class($app);
60     $app->run($self->_application_args);
61 }
62
63 # GROSS HACK, temporary until MX::Getopt gets some proper refactoring and unfucking..
64 around '_parse_argv' => sub {
65     my ($orig, $self, @args) = @_;
66     my %data = eval { $self->$orig(@args) };
67     $self->_exit_with_usage($@) if $@;
68     $data{usage} = Catalyst::ScriptRole::Useage->new(code => sub { shift; $self->_exit_with_usage(@_) });
69     return %data;
70 };
71
72 # This package is going away.
73 package # Hide from PAUSE
74     Catalyst::ScriptRole::Useage;
75 use Moose;
76 use namespace::autoclean;
77
78 has code => ( is => 'ro', required => 1 );
79
80 sub die { shift->code->(@_) }
81
82 1;
83
84 =head1 NAME
85
86 Catalyst::ScriptRole - Common functionality for Catalyst scripts.
87
88 =head1 SYNOPSIS
89
90     package MyApp::Script::Foo;
91     use Moose;
92     use namespace::autoclean;
93
94     with 'Catalyst::Script::Role';
95
96      sub _application_args { ... }
97
98 =head1 DESCRIPTION
99
100 Role with the common functionality of Catalyst scripts.
101
102 =head1 METHODS
103
104 =head2 run
105
106 The method invoked to run the application.
107
108 =head1 ATTRIBUTES
109
110 =head2 application_name
111
112 The name of the application class, e.g. MyApp
113
114 =head1 SEE ALSO
115
116 L<Catalyst>
117
118 L<MooseX::Getopt>
119
120 =head1 AUTHORS
121
122 Catalyst Contributors, see Catalyst.pm
123
124 =head1 COPYRIGHT
125
126 This library is free software, you can redistribute it and/or modify
127 it under the same terms as Perl itself.
128
129 =cut
130