Update CPANPLUS to 0.81_01
[p5sagit/p5-mst-13.2.git] / lib / CPANPLUS / Shell / Default.pm
1 package CPANPLUS::Shell::Default;
2
3 use strict;
4
5
6 use CPANPLUS::Error;
7 use CPANPLUS::Backend;
8 use CPANPLUS::Configure::Setup;
9 use CPANPLUS::Internals::Constants;
10 use CPANPLUS::Internals::Constants::Report qw[GRADE_FAIL];
11
12 use Cwd;
13 use IPC::Cmd;
14 use Term::UI;
15 use Data::Dumper;
16 use Term::ReadLine;
17
18 use Module::Load                qw[load];
19 use Params::Check               qw[check];
20 use Module::Load::Conditional   qw[can_load check_install];
21 use Locale::Maketext::Simple    Class => 'CPANPLUS', Style => 'gettext';
22
23 local $Params::Check::VERBOSE   = 1;
24 local $Data::Dumper::Indent     = 1; # for dumpering from !
25
26 BEGIN {
27     use vars        qw[ $VERSION @ISA ];
28     @ISA        =   qw[ CPANPLUS::Shell::_Base::ReadLine ];
29     $VERSION = "0.81_01";
30 }
31
32 load CPANPLUS::Shell;
33
34
35 my $map = {
36     'm'     => '_search_module',
37     'a'     => '_search_author',
38     '!'     => '_bang',
39     '?'     => '_help',
40     'h'     => '_help',
41     'q'     => '_quit',
42     'r'     => '_readme',
43     'v'     => '_show_banner',
44     'w'     => '__display_results',
45     'd'     => '_fetch',
46     'z'     => '_shell',
47     'f'     => '_distributions',
48     'x'     => '_reload_indices',
49     'i'     => '_install',
50     't'     => '_install',
51     'l'     => '_details',
52     'p'     => '_print',
53     's'     => '_set_conf',
54     'o'     => '_uptodate',
55     'b'     => '_autobundle',
56     'u'     => '_uninstall',
57     '/'     => '_meta',         # undocumented for now
58     'c'     => '_reports',
59 };
60 ### free letters: e g j k n y ###
61
62
63 ### will be filled if you have a .default-shell.rc and
64 ### Config::Auto installed
65 my $rc = {};
66
67 ### the shell object, scoped to the file ###
68 my $Shell;
69 my $Brand   = loc('CPAN Terminal');
70 my $Prompt  = $Brand . '> ';
71
72 =pod
73
74 =head1 NAME
75
76 CPANPLUS::Shell::Default
77
78 =head1 SYNOPSIS
79
80     ### loading the shell:
81     $ cpanp                     # run 'cpanp' from the command line
82     $ perl -MCPANPLUS -eshell   # load the shell from the command line
83
84
85     use CPANPLUS::Shell qw[Default];        # load this shell via the API
86                                             # always done via CPANPLUS::Shell
87
88     my $ui = CPANPLUS::Shell->new;
89     $ui->shell;                             # run the shell
90     $ui->dispatch_on_input( input => 'x');  # update the source using the
91                                             # dispatch method
92
93     ### when in the shell:
94     ### Note that all commands can also take options.
95     ### Look at their underlying CPANPLUS::Backend methods to see
96     ### what options those are.
97     cpanp> h                 # show help messages
98     cpanp> ?                 # show help messages
99
100     cpanp> m Acme            # find acme modules, allows regexes
101     cpanp> a KANE            # find modules by kane, allows regexes
102     cpanp> f Acme::Foo       # get a list of all releases of Acme::Foo
103
104     cpanp> i Acme::Foo       # install Acme::Foo
105     cpanp> i Acme-Foo-1.3    # install version 1.3 of Acme::Foo
106     cpanp> i <URI>           # install from URI, like ftp://foo.com/X.tgz
107     cpanp> i 1 3..5          # install search results 1, 3, 4 and 5
108     cpanp> i *               # install all search results
109     cpanp> a KANE; i *;      # find modules by kane, install all results
110     cpanp> t Acme::Foo       # test Acme::Foo, without installing it
111     cpanp> u Acme::Foo       # uninstall Acme::Foo
112     cpanp> d Acme::Foo       # download Acme::Foo
113     cpanp> z Acme::Foo       # download & extract Acme::Foo, then open a
114                              # shell in the extraction directory
115
116     cpanp> c Acme::Foo       # get a list of test results for Acme::Foo
117     cpanp> l Acme::Foo       # view details about the Acme::Foo package
118     cpanp> r Acme::Foo       # view Acme::Foo's README file
119     cpanp> o                 # get a list of all installed modules that
120                              # are out of date
121     cpanp> o 1..3            # list uptodateness from a previous search 
122                             
123     cpanp> s conf            # show config settings
124     cpanp> s conf md5 1      # enable md5 checks
125     cpanp> s program         # show program settings
126     cpanp> s edit            # edit config file
127     cpanp> s reconfigure     # go through initial configuration again
128     cpanp> s selfupdate      # update your CPANPLUS install
129     cpanp> s save            # save config to disk
130     cpanp> s mirrors         # show currently selected mirrors
131
132     cpanp> ! [PERL CODE]     # execute the following perl code
133
134     cpanp> b                 # create an autobundle for this computers
135                              # perl installation
136     cpanp> x                 # reload index files (purges cache)
137     cpanp> x --update_source # reload index files, get fresh source files
138     cpanp> p [FILE]          # print error stack (to a file)
139     cpanp> v                 # show the banner
140     cpanp> w                 # show last search results again
141
142     cpanp> q                 # quit the shell
143
144     cpanp> /plugins          # list avialable plugins
145     cpanp> /? PLUGIN         # list help test of <PLUGIN>                  
146
147     ### common options:
148     cpanp> i ... --skiptest # skip tests
149     cpanp> i ... --force    # force all operations
150     cpanp> i ... --verbose  # run in verbose mode
151
152 =head1 DESCRIPTION
153
154 This module provides the default user interface to C<CPANPLUS>. You
155 can start it via the C<cpanp> binary, or as detailed in the L<SYNOPSIS>.
156
157 =cut
158
159 sub new {
160     my $class   = shift;
161
162     my $cb      = new CPANPLUS::Backend;
163     my $self    = $class->SUPER::_init(
164                             brand       => $Brand,
165                             term        => Term::ReadLine->new( $Brand ),
166                             prompt      => $Prompt,
167                             backend     => $cb,
168                             format      => "%4s %-55s %8s %-10s\n",
169                             dist_format => "%4s %-42s %-12s %8s %-10s\n",
170                         );
171     ### make it available package wide ###
172     $Shell = $self;
173
174     my $rc_file = File::Spec->catfile(
175                         $cb->configure_object->get_conf('base'),
176                         DOT_SHELL_DEFAULT_RC,
177                     );
178
179
180     if( -e $rc_file && -r _ ) {
181         $rc = _read_configuration_from_rc( $rc_file );
182     }
183
184     ### register install callback ###
185     $cb->_register_callback(
186             name    => 'install_prerequisite',
187             code    => \&__ask_about_install,
188     );
189
190     ### execute any login commands specified ###
191     $self->dispatch_on_input( input => $rc->{'login'} )
192             if defined $rc->{'login'};
193
194     ### register test report callbacks ###
195     $cb->_register_callback(
196             name    => 'edit_test_report',
197             code    => \&__ask_about_edit_test_report,
198     );
199
200     $cb->_register_callback(
201             name    => 'send_test_report',
202             code    => \&__ask_about_send_test_report,
203     );
204
205     $cb->_register_callback(
206             name    => 'proceed_on_test_failure',
207             code    => \&__ask_about_test_failure,
208     );
209
210
211     return $self;
212 }
213
214 sub shell {
215     my $self = shift;
216     my $term = $self->term;
217     my $conf = $self->backend->configure_object;
218
219     $self->_show_banner;
220     print "*** Type 'p' now to show start up log\n"; # XXX add to banner?
221     $self->_show_random_tip if $conf->get_conf('show_startup_tip');
222     $self->_input_loop && print "\n";
223     $self->_quit;
224 }
225
226 sub _input_loop {
227     my $self    = shift;
228     my $term    = $self->term;
229     my $cb      = $self->backend;
230
231     my $normal_quit = 0;
232     while (
233         defined (my $input = eval { $term->readline($self->prompt) } )
234         or $self->_signals->{INT}{count} == 1
235     ) {
236         ### re-initiate all signal handlers
237         while (my ($sig, $entry) = each %{$self->_signals} ) {
238             $SIG{$sig} = $entry->{handler} if exists($entry->{handler});
239         }
240
241         print "\n";
242         last if $self->dispatch_on_input( input => $input );
243
244         ### flush the lib cache ###
245         $cb->_flush( list => [qw|lib load|] );
246
247     } continue {
248         $self->_signals->{INT}{count}--
249             if $self->_signals->{INT}{count}; # clear the sigint count
250     }
251
252     return 1;
253 }
254
255 ### return 1 to quit ###
256 sub dispatch_on_input {
257     my $self = shift;
258     my $conf = $self->backend->configure_object();
259     my $term = $self->term;
260     my %hash = @_;
261
262     my($string, $noninteractive);
263     my $tmpl = {
264         input          => { required => 1, store => \$string },
265         noninteractive => { required => 0, store => \$noninteractive },
266     };
267
268     check( $tmpl, \%hash ) or return;
269
270     ### indicates whether or not the user will receive a shell
271     ### prompt after the command has finished.
272     $self->noninteractive($noninteractive) if defined $noninteractive;
273
274     my @cmds =  split ';', $string;
275     while( my $input = shift @cmds ) {
276
277         ### to send over the socket ###
278         my $org_input = $input;
279
280         my $key; my $options;
281         {   ### make whitespace not count when using special chars
282             { $input =~ s|^\s*([!?/])|$1 |; }
283
284             ### get the first letter of the input
285             $input =~ s|^\s*([\w\?\!/])\w*||;
286
287             chomp $input;
288             $key =  lc($1);
289
290             ### we figured out what the command was...
291             ### if we have more input, that DOES NOT start with a white
292             ### space char, we misparsed.. like 'Test::Foo::Bar', which
293             ### would turn into 't', '::Foo::Bar'...
294             if( $input and $input !~ s/^\s+// ) {
295                 print loc("Could not understand command: %1\n".
296                           "Possibly missing command before argument(s)?\n",
297                           $org_input); 
298                 return;
299             }     
300
301             ### allow overrides from the config file ###
302             if( defined $rc->{$key} ) {
303                 $input = $rc->{$key} . $input;
304             }
305
306             ### grab command line options like --no-force and --verbose ###
307             ($options,$input) = $term->parse_options($input)
308                 unless $key eq '!';
309         }
310
311         ### emtpy line? ###
312         return unless $key;
313
314         ### time to quit ###
315         return 1 if $key eq 'q';
316
317         my $method = $map->{$key};
318
319         ### dispatch meta locally at all times ###
320         $self->$method(input => $input, options => $options), next
321             if $key eq '/';
322
323         ### flush unless we're trying to print the stack
324         CPANPLUS::Error->flush unless $key eq 'p';
325
326         ### connected over a socket? ###
327         if( $self->remote ) {
328
329             ### unsupported commands ###
330             if( $key eq 'z' or
331                 ($key eq 's' and $input =~ /^\s*edit/)
332             ) {
333                 print "\n", loc("Command not supported over remote connection"),
334                         "\n\n";
335
336             } else {
337                 my($status,$buff) = $self->__send_remote_command($org_input);
338
339                 print "\n", loc("Command failed!"), "\n\n" unless $status;
340
341                 $self->_pager_open if $buff =~ tr/\n// > $self->_term_rowcount;
342                 print $buff;
343                 $self->_pager_close;
344             }
345
346         ### or just a plain local shell? ###
347         } else {
348
349             unless( $self->can($method) ) {
350                 print loc("Unknown command '%1'. Usage:", $key), "\n";
351                 $self->_help;
352
353             } else {
354
355                 ### some methods don't need modules ###
356                 my @mods;
357                 @mods = $self->_select_modules($input)
358                         unless grep {$key eq $_} qw[! m a v w x p s b / ? h];
359
360                 eval { $self->$method(  modules => \@mods,
361                                         options => $options,
362                                         input   => $input,
363                                         choice  => $key )
364                 };
365                 error( $@ ) if $@;
366             }
367         }
368     }
369
370     return;
371 }
372
373 sub _select_modules {
374     my $self    = shift;
375     my $input   = shift or return;
376     my $cache   = $self->cache;
377     my $cb      = $self->backend;
378
379     ### expand .. in $input
380     $input =~ s{\b(\d+)\s*\.\.\s*(\d+)\b}
381                {join(' ', ($1 < 1 ? 1 : $1) .. ($2 > $#{$cache} ? $#{$cache} : $2))}eg;
382
383     $input = join(' ', 1 .. $#{$cache}) if $input eq '*';
384     $input =~ s/'/::/g; # perl 4 convention
385
386     my @rv;
387     for my $mod (split /\s+/, $input) {
388
389         ### it's a cache look up ###
390         if( $mod =~ /^\d+/ and $mod > 0 ) {
391             unless( scalar @$cache ) {
392                 print loc("No search was done yet!"), "\n";
393
394             } elsif ( my $obj = $cache->[$mod] ) {
395                 push @rv, $obj;
396
397             } else {
398                 print loc("No such module: %1", $mod), "\n";
399             }
400
401         } else {
402             my $obj = $cb->parse_module( module => $mod );
403
404             unless( $obj ) {
405                 print loc("No such module: %1", $mod), "\n";
406
407             } else {
408                 push @rv, $obj;
409             }
410         }
411     }
412
413     unless( scalar @rv ) {
414         print loc("No modules found to operate on!\n");
415         return;
416     } else {
417         return @rv;
418     }
419 }
420
421 sub _format_version {
422     my $self    = shift;
423     my $version = shift;
424
425     ### fudge $version into the 'optimal' format
426     $version = 0 if $version eq 'undef';
427     $version =~ s/_//g; # everything after gets stripped off otherwise
428
429     ### allow 6 digits after the dot, as that's how perl stringifies
430     ### x.y.z numbers.
431     $version = sprintf('%3.6f', $version);
432     $version = '' if $version == '0.00';
433     $version =~ s/(00{0,3})$/' ' x (length $1)/e;
434
435     return $version;
436 }
437
438 sub __display_results {
439     my $self    = shift;
440     my $cache   = $self->cache;
441
442     my @rv = @$cache;
443
444     if( scalar @rv ) {
445
446         $self->_pager_open if $#{$cache} >= $self->_term_rowcount;
447
448         my $i = 1;
449         for my $mod (@rv) {
450             next unless $mod;   # first one is undef
451                                 # humans start counting at 1
452
453             ### for dists only -- we have checksum info
454             if( $mod->mtime ) {
455                 printf $self->dist_format,
456                             $i,
457                             $mod->module,
458                             $mod->mtime,
459                             $self->_format_version($mod->version),
460                             $mod->author->cpanid();
461
462             } else {
463                 printf $self->format,
464                             $i,
465                             $mod->module,
466                             $self->_format_version($mod->version),
467                             $mod->author->cpanid();
468             }
469             $i++;
470         }
471
472         $self->_pager_close;
473
474     } else {
475         print loc("No results to display"), "\n";
476     }
477 }
478
479
480 sub _quit {
481     my $self = shift;
482
483     $self->dispatch_on_input( input => $rc->{'logout'} )
484             if defined $rc->{'logout'};
485
486     print loc("Exiting CPANPLUS shell"), "\n";
487 }
488
489 ###########################
490 ### actual command subs ###
491 ###########################
492
493
494 ### print out the help message ###
495 ### perhaps, '?' should be a slightly different version ###
496 {   my @help;
497     sub _help {
498         my $self = shift;
499         my %hash    = @_;
500     
501         my $input;
502         {   local $Params::Check::ALLOW_UNKNOWN = 1;
503     
504             my $tmpl = {
505                 input   => { required => 0, store => \$input }
506             };
507     
508             my $args = check( $tmpl, \%hash ) or return;
509         }
510     
511         @help = (
512 loc('[General]'                                                                     ),
513 loc('    h | ?                  # display help'                                     ),
514 loc('    q                      # exit'                                             ),
515 loc('    v                      # version information'                              ),
516 loc('[Search]'                                                                      ),
517 loc('    a AUTHOR ...           # search by author(s)'                              ),
518 loc('    m MODULE ...           # search by module(s)'                              ),
519 loc('    f MODULE ...           # list all releases of a module'                    ),
520 loc("    o [ MODULE ... ]       # list installed module(s) that aren't up to date"  ),
521 loc('    w                      # display the result of your last search again'     ),
522 loc('[Operations]'                                                                  ),
523 loc('    i MODULE | NUMBER ...  # install module(s), by name or by search number'   ),
524 loc('    i URI | ...            # install module(s), by URI (ie http://foo.com/X.tgz)'   ),
525 loc('    t MODULE | NUMBER ...  # test module(s), by name or by search number'      ),
526 loc('    u MODULE | NUMBER ...  # uninstall module(s), by name or by search number' ),
527 loc('    d MODULE | NUMBER ...  # download module(s)'                               ),
528 loc('    l MODULE | NUMBER ...  # display detailed information about module(s)'     ),
529 loc('    r MODULE | NUMBER ...  # display README files of module(s)'                ),
530 loc('    c MODULE | NUMBER ...  # check for module report(s) from cpan-testers'     ),
531 loc('    z MODULE | NUMBER ...  # extract module(s) and open command prompt in it'  ),
532 loc('[Local Administration]'                                                        ),
533 loc('    b                      # write a bundle file for your configuration'       ),
534 loc('    s program [OPT VALUE]  # set program locations for this session'           ),
535 loc('    s conf    [OPT VALUE]  # set config options for this session'              ),
536 loc('    s mirrors              # show currently selected mirrors' ),
537 loc('    s reconfigure          # reconfigure settings ' ),
538 loc('    s selfupdate           # update your CPANPLUS install '),
539 loc('    s save [user|system]   # save settings for this user or systemwide' ),
540 loc('    s edit [user|system]   # open configuration file in editor and reload'     ),
541 loc('    ! EXPR                 # evaluate a perl statement'                        ),
542 loc('    p [FILE]               # print the error stack (optionally to a file)'     ),
543 loc('    x                      # reload CPAN indices (purges cache)'                              ),
544 loc('    x --update_source      # reload CPAN indices, get fresh source files' ),
545 loc('[Common Options]'                                  ),
546 loc('   i ... --skiptest        # skip tests'           ),
547 loc('   i ... --force           # force all operations' ),
548 loc('   i ... --verbose         # run in verbose mode'  ),
549 loc('[Plugins]'                                                             ),
550 loc('   /plugins                # list available plugins'                   ),
551 loc('   /? [PLUGIN NAME]        # show usage for (a particular) plugin(s)'  ),
552
553         ) unless @help;
554     
555         $self->_pager_open if (@help >= $self->_term_rowcount);
556         ### XXX: functional placeholder for actual 'detailed' help.
557         print "Detailed help for the command '$input' is not available.\n\n"
558           if length $input;
559         print map {"$_\n"} @help;
560         print $/;
561         $self->_pager_close;
562     }
563 }
564
565 ### eval some code ###
566 sub _bang {
567     my $self    = shift;
568     my $cb      = $self->backend;
569     my %hash    = @_;
570
571
572     my $input;
573     {   local $Params::Check::ALLOW_UNKNOWN = 1;
574
575         my $tmpl = {
576             input   => { required => 1, store => \$input }
577         };
578
579         my $args = check( $tmpl, \%hash ) or return;
580     }
581
582     local $Data::Dumper::Indent     = 1; # for dumpering from !
583     eval $input;
584     error( $@ ) if $@;
585     print "\n";
586     return;
587 }
588
589 sub _search_module {
590     my $self    = shift;
591     my $cb      = $self->backend;
592     my %hash    = @_;
593
594     my $args;
595     {   local $Params::Check::ALLOW_UNKNOWN = 1;
596
597         my $tmpl = {
598             input   => { required => 1, },
599             options => { default => { } },
600         };
601
602         $args = check( $tmpl, \%hash ) or return;
603     }
604
605     my @regexes = map { qr/$_/i } split /\s+/, $args->{'input'};
606
607     ### XXX this is rather slow, because (probably)
608     ### of the many method calls
609     ### XXX need to profile to speed it up =/
610
611     ### find the modules ###
612     my @rv = sort { $a->module cmp $b->module }
613                     $cb->search(
614                         %{$args->{'options'}},
615                         type    => 'module',
616                         allow   => \@regexes,
617                     );
618
619     ### store the result in the cache ###
620     $self->cache([undef,@rv]);
621
622     $self->__display_results;
623
624     return 1;
625 }
626
627 sub _search_author {
628     my $self    = shift;
629     my $cb      = $self->backend;
630     my %hash    = @_;
631
632     my $args;
633     {   local $Params::Check::ALLOW_UNKNOWN = 1;
634
635         my $tmpl = {
636             input   => { required => 1, },
637             options => { default => { } },
638         };
639
640         $args = check( $tmpl, \%hash ) or return;
641     }
642
643     my @regexes = map { qr/$_/i } split /\s+/, $args->{'input'};
644
645     my @rv;
646     for my $type (qw[author cpanid]) {
647         push @rv, $cb->search(
648                         %{$args->{'options'}},
649                         type    => $type,
650                         allow   => \@regexes,
651                     );
652     }
653
654     my %seen;
655     my @list =  sort { $a->module cmp $b->module }
656                 grep { defined }
657                 map  { $_->modules }
658                 grep { not $seen{$_}++ } @rv;
659
660     $self->cache([undef,@list]);
661
662     $self->__display_results;
663     return 1;
664 }
665
666 sub _readme {
667     my $self    = shift;
668     my $cb      = $self->backend;
669     my %hash    = @_;
670
671     my $args; my $mods; my $opts;
672     {   local $Params::Check::ALLOW_UNKNOWN = 1;
673
674         my $tmpl = {
675             modules => { required => 1,  store => \$mods },
676             options => { default => { }, store => \$opts },
677         };
678
679         $args = check( $tmpl, \%hash ) or return;
680     }
681
682     return unless scalar @$mods;
683
684     $self->_pager_open;
685     for my $mod ( @$mods ) {
686         print $mod->readme( %$opts );
687     }
688
689     $self->_pager_close;
690
691     return 1;
692 }
693
694 sub _fetch {
695     my $self    = shift;
696     my $cb      = $self->backend;
697     my %hash    = @_;
698
699     my $args; my $mods; my $opts;
700     {   local $Params::Check::ALLOW_UNKNOWN = 1;
701
702         my $tmpl = {
703             modules => { required => 1,  store => \$mods },
704             options => { default => { }, store => \$opts },
705         };
706
707         $args = check( $tmpl, \%hash ) or return;
708     }
709
710     $self->_pager_open if @$mods >= $self->_term_rowcount;
711     for my $mod (@$mods) {
712         my $where = $mod->fetch( %$opts );
713
714         print $where
715                 ? loc("Successfully fetched '%1' to '%2'",
716                         $mod->module, $where )
717                 : loc("Failed to fetch '%1'", $mod->module);
718         print "\n";
719     }
720     $self->_pager_close;
721
722 }
723
724 sub _shell {
725     my $self    = shift;
726     my $cb      = $self->backend;
727     my $conf    = $cb->configure_object;
728     my %hash    = @_;
729
730     my $shell = $conf->get_program('shell');
731     unless( $shell ) {
732         print   loc("Your config does not specify a subshell!"), "\n",
733                 loc("Perhaps you need to re-run your setup?"), "\n";
734         return;
735     }
736
737     my $args; my $mods; my $opts;
738     {   local $Params::Check::ALLOW_UNKNOWN = 1;
739
740         my $tmpl = {
741             modules => { required => 1,  store => \$mods },
742             options => { default => { }, store => \$opts },
743         };
744
745         $args = check( $tmpl, \%hash ) or return;
746     }
747
748     my $cwd = Cwd::cwd();
749     for my $mod (@$mods) {
750         $mod->fetch(    %$opts )    or next;
751         $mod->extract(  %$opts )    or next;
752
753         $cb->_chdir( dir => $mod->status->extract() )   or next;
754
755         #local $ENV{PERL5OPT} = CPANPLUS::inc->original_perl5opt;
756
757         if( system($shell) and $! ) {
758             print loc("Error executing your subshell '%1': %2",
759                         $shell, $!),"\n";
760             next;
761         }
762     }
763     $cb->_chdir( dir => $cwd );
764
765     return 1;
766 }
767
768 sub _distributions {
769     my $self    = shift;
770     my $cb      = $self->backend;
771     my $conf    = $cb->configure_object;
772     my %hash    = @_;
773
774     my $args; my $mods; my $opts;
775     {   local $Params::Check::ALLOW_UNKNOWN = 1;
776
777         my $tmpl = {
778             modules => { required => 1,  store => \$mods },
779             options => { default => { }, store => \$opts },
780         };
781
782         $args = check( $tmpl, \%hash ) or return;
783     }
784
785     my @list;
786     for my $mod (@$mods) {
787         push @list, sort { $a->version <=> $b->version }
788                     grep { defined } $mod->distributions( %$opts );
789     }
790
791     my @rv = sort { $a->module cmp $b->module } @list;
792
793     $self->cache([undef,@rv]);
794     $self->__display_results;
795
796     return; 1;
797 }
798
799 sub _reload_indices {
800     my $self = shift;
801     my $cb   = $self->backend;
802     my %hash = @_;
803
804     my $args; my $opts;
805     {   local $Params::Check::ALLOW_UNKNOWN = 1;
806
807         my $tmpl = {
808             options => { default => { }, store => \$opts },
809         };
810
811         $args = check( $tmpl, \%hash ) or return;
812     }
813
814     my $rv = $cb->reload_indices( %$opts );
815     
816     ### so the update failed, but you didnt give it any options either
817     if( !$rv and !(keys %$opts) ) {
818         print   "\nFailure may be due to corrupt source files\n" .
819                 "Try this:\n\tx --update_source\n\n";
820     }
821     
822     return $rv;
823     
824 }
825
826 sub _install {
827     my $self    = shift;
828     my $cb      = $self->backend;
829     my $conf    = $cb->configure_object;
830     my %hash    = @_;
831
832     my $args; my $mods; my $opts; my $choice;
833     {   local $Params::Check::ALLOW_UNKNOWN = 1;
834
835         my $tmpl = {
836             modules => { required => 1,     store => \$mods },
837             options => { default  => { },   store => \$opts },
838             choice  => { required => 1,     store => \$choice,
839                          allow    => [qw|i t|] },
840         };
841
842         $args = check( $tmpl, \%hash ) or return;
843     }
844
845     unless( scalar @$mods ) {
846         print loc("Nothing done\n");
847         return;
848     }
849
850     my $target = $choice eq 'i' ? TARGET_INSTALL : TARGET_CREATE;
851     my $prompt = $choice eq 'i' ? loc('Installing ') : loc('Testing ');
852     my $action = $choice eq 'i' ? 'install' : 'test';
853
854     my $status = {};
855     ### first loop over the mods to install them ###
856     for my $mod (@$mods) {
857         print $prompt, $mod->module, " (".$mod->version.")", "\n";
858
859         my $log_length = length CPANPLUS::Error->stack_as_string;
860     
861         ### store the status for look up when we're done with all
862         ### install calls
863         $status->{$mod} = $mod->install( %$opts, target => $target );
864         
865         ### would you like a log file of what happened?
866         if( $conf->get_conf('write_install_logs') ) {
867
868             my $dir = File::Spec->catdir(
869                             $conf->get_conf('base'),
870                             $conf->_get_build('install_log_dir'),
871                         );
872             ### create the dir if it doesn't exit yet
873             $cb->_mkdir( dir => $dir ) unless -d $dir;
874
875             my $file = File::Spec->catfile( 
876                             $dir,
877                             INSTALL_LOG_FILE->( $mod ) 
878                         );
879             if ( open my $fh, ">$file" ) {
880                 my $stack = CPANPLUS::Error->stack_as_string;
881                 ### remove everything in the log that was there *before*
882                 ### we started this install
883                 substr( $stack, 0, $log_length, '' );
884                 
885                 print $fh $stack;
886                 close $fh;
887                 
888                 print loc("*** Install log written to:\n  %1\n\n", $file);
889             } else {                
890                 warn "Could not open '$file': $!\n";
891                 next;
892             }                
893         }
894     }
895
896     my $flag;
897     ### then report whether all this went ok or not ###
898     for my $mod (@$mods) {
899     #    if( $mod->status->installed ) {
900         if( $status->{$mod} ) {
901             print loc("Module '%1' %tense(%2,past) successfully\n",
902                         $mod->module, $action)
903         } else {
904             $flag++;
905             print loc("Error %tense(%1,present) '%2'\n",
906                         $action, $mod->module);
907         }
908     }
909
910
911
912     if( !$flag ) {
913         print loc("No errors %tense(%1,present) all modules", $action), "\n";
914     } else {
915         print loc("Problem %tense(%1,present) one or more modules", $action);
916         print "\n";
917         print loc("*** You can view the complete error buffer by pressing '%1' ***\n", 'p')
918                 unless $conf->get_conf('verbose') || $self->noninteractive;
919     }
920     print "\n";
921
922     return !$flag;
923 }
924
925 sub __ask_about_install {
926     my $mod     = shift or return;
927     my $prereq  = shift or return;
928     my $term    = $Shell->term;
929
930     print "\n";
931     print loc(  "Module '%1' requires '%2' to be installed",
932                 $mod->module, $prereq->module );
933     print "\n\n";
934     print loc(  "If you don't wish to see this question anymore\n".
935                 "you can disable it by entering the following ".
936                 "commands on the prompt:\n    '%1'",
937                 's conf prereqs 1; s save' );
938     print "\n\n";
939
940     my $bool =  $term->ask_yn(
941                     prompt  => loc("Should I install this module?"),
942                     default => 'y'
943                 );
944
945     return $bool;
946 }
947
948 sub __ask_about_send_test_report {
949     my($mod, $grade) = @_;
950     return 1 unless $grade eq GRADE_FAIL;
951
952     my $term    = $Shell->term;
953
954     print "\n";
955     print loc(  "Test report prepared for module '%1'.\n Would you like to ".
956                 "send it? (You can edit it if you like)", $mod->module );
957     print "\n\n";
958     my $bool =  $term->ask_yn(
959                     prompt  => loc("Would you like to send the test report?"),
960                     default => 'n'
961                 );
962
963     return $bool;
964 }
965
966 sub __ask_about_edit_test_report {
967     my($mod, $grade) = @_;
968     return 0 unless $grade eq GRADE_FAIL;
969
970     my $term    = $Shell->term;
971
972     print "\n";
973     print loc(  "Test report prepared for module '%1'. You can edit this ".
974                 "report if you would like", $mod->module );
975     print "\n\n";
976     my $bool =  $term->ask_yn(
977                     prompt  => loc("Would you like to edit the test report?"),
978                     default => 'y'
979                 );
980
981     return $bool;
982 }
983
984 sub __ask_about_test_failure {
985     my $mod         = shift;
986     my $captured    = shift || '';
987     my $term        = $Shell->term;
988
989     print "\n";
990     print loc(  "The tests for '%1' failed. Would you like me to proceed ".
991                 "anyway or should we abort?", $mod->module );
992     print "\n\n";
993     
994     my $bool =  $term->ask_yn(
995                     prompt  => loc("Proceed anyway?"),
996                     default => 'n',
997                 );
998
999     return $bool;
1000 }
1001
1002
1003 sub _details {
1004     my $self    = shift;
1005     my $cb      = $self->backend;
1006     my $conf    = $cb->configure_object;
1007     my %hash    = @_;
1008
1009     my $args; my $mods; my $opts;
1010     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1011
1012         my $tmpl = {
1013             modules => { required => 1,  store => \$mods },
1014             options => { default => { }, store => \$opts },
1015         };
1016
1017         $args = check( $tmpl, \%hash ) or return;
1018     }
1019
1020     ### every module has about 10 lines of details
1021     ### maybe more later with Module::CPANTS etc
1022     $self->_pager_open if scalar @$mods * 10 > $self->_term_rowcount;
1023
1024
1025     my $format = "%-30s %-30s\n";
1026     for my $mod (@$mods) {
1027         my $href = $mod->details( %$opts );
1028         my @list = sort { $a->module cmp $b->module } $mod->contains;
1029
1030         unless( $href ) {
1031             print loc("No details for %1 - it might be outdated.",
1032                         $mod->module), "\n";
1033             next;
1034
1035         } else {
1036             print loc( "Details for '%1'\n", $mod->module );
1037             for my $item ( sort keys %$href ) {
1038                 printf $format, $item, $href->{$item};
1039             }
1040             
1041             my $showed;
1042             for my $item ( @list ) {
1043                 printf $format, ($showed ? '' : 'Contains:'), $item->module;
1044                 $showed++;
1045             }
1046             print "\n";
1047         }
1048     }
1049     $self->_pager_close;
1050     print "\n";
1051
1052     return 1;
1053 }
1054
1055 sub _print {
1056     my $self = shift;
1057     my %hash = @_;
1058
1059     my $args; my $opts; my $file;
1060     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1061
1062         my $tmpl = {
1063             options => { default => { }, store => \$opts },
1064             input   => { default => '',  store => \$file },
1065         };
1066
1067         $args = check( $tmpl, \%hash ) or return;
1068     }
1069
1070     my $old; my $fh;
1071     if( $file ) {
1072         $fh = FileHandle->new( ">$file" )
1073                     or( warn loc("Could not open '%1': '%2'", $file, $!),
1074                         return
1075                     );
1076         $old = select $fh;
1077     }
1078
1079
1080     $self->_pager_open if !$file;
1081
1082     print CPANPLUS::Error->stack_as_string;
1083
1084     $self->_pager_close;
1085
1086     select $old if $old;
1087     print "\n";
1088
1089     return 1;
1090 }
1091
1092 sub _set_conf {
1093     my $self    = shift;
1094     my %hash    = @_;
1095     my $cb      = $self->backend;
1096     my $conf    = $cb->configure_object;
1097
1098     ### possible options
1099     ### XXX hard coded, not optimal :(
1100     my %types   = (
1101         reconfigure => '', 
1102         save        => q([user | system | boxed]),
1103         edit        => '',
1104         program     => q([key => val]),
1105         conf        => q([key => val]),
1106         mirrors     => '',
1107         selfupdate  => '',  # XXX add all opts here?
1108     );
1109
1110
1111     my $args; my $opts; my $input;
1112     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1113
1114         my $tmpl = {
1115             options => { default => { }, store => \$opts },
1116             input   => { default => '',  store => \$input },
1117         };
1118
1119         $args = check( $tmpl, \%hash ) or return;
1120     }
1121
1122     my ($type,$key,$value) = $input =~ m/(\w+)\s*(\w*)\s*(.*?)\s*$/;
1123     $type = lc $type;
1124
1125     if( $type eq 'reconfigure' ) {
1126         my $setup = CPANPLUS::Configure::Setup->new(
1127                         configure_object    => $conf,
1128                         term                => $self->term,
1129                         backend             => $cb,
1130                     );
1131         return $setup->init;
1132
1133     } elsif ( $type eq 'save' ) {
1134         my $where = {
1135             user    => CONFIG_USER,
1136             system  => CONFIG_SYSTEM,
1137             boxed   => CONFIG_BOXED,
1138         }->{ $key } || CONFIG_USER;      
1139         
1140         ### boxed is special, so let's get it's value from %INC
1141         ### so we can tell it where to save
1142         ### XXX perhaps this logic should be generic for all
1143         ### types, and put in the ->save() routine
1144         my $dir;
1145         if( $where eq CONFIG_BOXED ) {
1146             my $file    = join( '/', split( '::', CONFIG_BOXED ) ) . '.pm';
1147             my $file_re = quotemeta($file);
1148             
1149             my $path    = $INC{$file} || '';
1150             $path       =~ s/$file_re$//;        
1151             $dir        = $path;
1152         }     
1153         
1154         my $rv = $cb->configure_object->save( $where => $dir );
1155
1156         print $rv
1157                 ? loc("Configuration successfully saved to %1\n    (%2)\n",
1158                        $where, $rv)
1159                 : loc("Failed to save configuration\n" );
1160         return $rv;
1161
1162     } elsif ( $type eq 'edit' ) {
1163
1164         my $editor  = $conf->get_program('editor')
1165                         or( print(loc("No editor specified")), return );
1166
1167         my $where = {
1168             user    => CONFIG_USER,
1169             system  => CONFIG_SYSTEM,
1170         }->{ $key } || CONFIG_USER;      
1171         
1172         my $file = $conf->_config_pm_to_file( $where );
1173         system("$editor $file");
1174
1175         ### now reload it
1176         ### disable warnings for this
1177         {   require Module::Loaded;
1178             Module::Loaded::mark_as_unloaded( $_ ) for $conf->configs;
1179
1180             ### reinitialize the config
1181             local $^W;
1182             $conf->init;
1183         }
1184
1185         return 1;
1186
1187     } elsif ( $type eq 'mirrors' ) {
1188     
1189         print loc("Readonly list of mirrors (in order of preference):\n\n" );
1190         
1191         my $i;
1192         for my $host ( @{$conf->get_conf('hosts')} ) {
1193             my $uri = $cb->_host_to_uri( %$host );
1194             
1195             $i++;
1196             print "\t[$i] $uri\n";
1197         }
1198
1199     } elsif ( $type eq 'selfupdate' ) {
1200         my %valid = map { $_ => $_ } 
1201                         $cb->selfupdate_object->list_categories;    
1202
1203         unless( $valid{$key} ) {
1204             print loc( "To update your current CPANPLUS installation, ".
1205                         "choose one of the these options:\n%1",
1206                         ( join $/, map { 
1207                              sprintf "\ts selfupdate %-17s " .
1208                                      "[--latest=0] [--dryrun]", $_ 
1209                           } sort keys %valid ) 
1210                     );          
1211         } else {
1212             my %update_args = (
1213                 update  => $key,
1214                 latest  => 1,
1215                 %$opts
1216             );
1217
1218
1219             my %list = $cb->selfupdate_object
1220                             ->list_modules_to_update( %update_args );
1221
1222             print loc( "The following updates will take place:" ), $/.$/;
1223             
1224             for my $feature ( sort keys %list ) {
1225                 my $aref = $list{$feature};
1226                 
1227                 ### is it a 'feature' or a built in?
1228                 print $valid{$feature} 
1229                     ? "  " . ucfirst($feature) . ":\n"
1230                     : "  Modules for '$feature' support:\n";
1231                     
1232                 ### show what modules would be installed    
1233                 print scalar @$aref
1234                     ? map { sprintf "    %-42s %-6s -> %-6s \n", 
1235                             $_->name, $_->installed_version, $_->version
1236                       } @$aref      
1237                     : "    No upgrades required\n";                                                  
1238                 print $/;
1239             }
1240             
1241         
1242             unless( $opts->{'dryrun'} ) { 
1243                 print loc( "Updating your CPANPLUS installation\n" );
1244                 $cb->selfupdate_object->selfupdate( %update_args );
1245             }
1246         }
1247         
1248     } else {
1249
1250         if ( $type eq 'program' or $type eq 'conf' ) {
1251
1252             my $format = {
1253                 conf    => '%-25s %s',
1254                 program => '%-12s %s',
1255             }->{ $type };      
1256
1257             unless( $key ) {
1258                 my @list =  grep { $_ ne 'hosts' }
1259                             $conf->options( type => $type );
1260
1261                 my $method = 'get_' . $type;
1262
1263                 local $Data::Dumper::Indent = 0;
1264                 for my $name ( @list ) {
1265                     my $val = $conf->$method($name) || '';
1266                     ($val)  = ref($val)
1267                                 ? (Data::Dumper::Dumper($val) =~ /= (.*);$/)
1268                                 : "'$val'";
1269                     printf  "    $format\n", $name, $val;
1270                 }
1271
1272             } elsif ( $key eq 'hosts' ) {
1273                 print loc(  "Setting hosts is not trivial.\n" .
1274                             "It is suggested you use '%1' and edit the " .
1275                             "configuration file manually", 's edit');
1276             } else {
1277                 my $method = 'set_' . $type;
1278                 $conf->$method( $key => defined $value ? $value : '' )
1279                     and print loc("Key '%1' was set to '%2'", $key,
1280                                   defined $value ? $value : 'EMPTY STRING');
1281             }
1282
1283         } else {
1284             print loc("Unknown type '%1'",$type || 'EMPTY' );
1285             print $/;
1286             print loc("Try one of the following:");
1287             print $/, join $/, 
1288                       map { sprintf "\t%-11s %s", $_, $types{$_} } 
1289                       sort keys %types;
1290         }
1291     }
1292     print "\n";
1293     return 1;
1294 }
1295
1296 sub _uptodate {
1297     my $self = shift;
1298     my %hash = @_;
1299     my $cb   = $self->backend;
1300     my $conf = $cb->configure_object;
1301
1302     my $opts; my $mods;
1303     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1304
1305         my $tmpl = {
1306             options => { default => { }, store => \$opts },
1307             modules => { required => 1,  store => \$mods },
1308         };
1309
1310         check( $tmpl, \%hash ) or return;
1311     }
1312
1313     ### long listing? short is default ###
1314     my $long = $opts->{'long'} ? 1 : 0;
1315
1316     my @list = scalar @$mods ? @$mods : @{$cb->_all_installed};
1317
1318     my @rv; my %seen;
1319     for my $mod (@list) {
1320         ### skip this mod if it's up to date ###
1321         next if $mod->is_uptodate;
1322         ### skip this mod if it's core ###
1323         next if $mod->package_is_perl_core;
1324
1325         if( $long or !$seen{$mod->package}++ ) {
1326             push @rv, $mod;
1327         }
1328     }
1329
1330     @rv = sort { $a->module cmp $b->module } @rv;
1331
1332     $self->cache([undef,@rv]);
1333
1334     $self->_pager_open if scalar @rv >= $self->_term_rowcount;
1335
1336     my $format = "%5s %12s %12s %-36s %-10s\n";
1337
1338     my $i = 1;
1339     for my $mod ( @rv ) {
1340         printf $format,
1341                 $i,
1342                 $self->_format_version($mod->installed_version) || 'Unparsable',
1343                 $self->_format_version( $mod->version ),
1344                 $mod->module,
1345                 $mod->author->cpanid();
1346         $i++;
1347     }
1348     $self->_pager_close;
1349
1350     return 1;
1351 }
1352
1353 sub _autobundle {
1354     my $self = shift;
1355     my %hash = @_;
1356     my $cb   = $self->backend;
1357     my $conf = $cb->configure_object;
1358
1359     my $opts; my $input;
1360     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1361
1362         my $tmpl = {
1363             options => { default => { }, store => \$opts },
1364             input   => { default => '',  store => \$input },
1365         };
1366
1367          check( $tmpl, \%hash ) or return;
1368     }
1369
1370     $opts->{'path'} = $input if $input;
1371
1372     my $where = $cb->autobundle( %$opts );
1373
1374     print $where
1375             ? loc("Wrote autobundle to '%1'", $where)
1376             : loc("Could not create autobundle" );
1377     print "\n";
1378
1379     return $where ? 1 : 0;
1380 }
1381
1382 sub _uninstall {
1383     my $self = shift;
1384     my %hash = @_;
1385     my $cb   = $self->backend;
1386     my $term = $self->term;
1387     my $conf = $cb->configure_object;
1388
1389     my $opts; my $mods;
1390     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1391
1392         my $tmpl = {
1393             options => { default => { }, store => \$opts },
1394             modules => { default => [],  store => \$mods },
1395         };
1396
1397          check( $tmpl, \%hash ) or return;
1398     }
1399
1400     my $force = $opts->{'force'} || $conf->get_conf('force');
1401
1402     unless( $force ) {
1403         my $list = join "\n", map { '    ' . $_->module } @$mods;
1404
1405         print loc("
1406 This will uninstall the following modules:
1407 %1
1408
1409 Note that if you installed them via a package manager, you probably
1410 should use the same package manager to uninstall them
1411
1412 ", $list);
1413
1414         return unless $term->ask_yn(
1415                         prompt  => loc("Are you sure you want to continue?"),
1416                         default => 'n',
1417                     );
1418     }
1419
1420     ### first loop over all the modules to uninstall them ###
1421     for my $mod (@$mods) {
1422         print loc("Uninstalling '%1'", $mod->module), "\n";
1423
1424         $mod->uninstall( %$opts );
1425     }
1426
1427     my $flag;
1428     ### then report whether all this went ok or not ###
1429     for my $mod (@$mods) {
1430         if( $mod->status->uninstall ) {
1431             print loc("Module '%1' %tense(uninstall,past) successfully\n",
1432                        $mod->module )
1433         } else {
1434             $flag++;
1435             print loc("Error %tense(uninstall,present) '%1'\n", $mod->module);
1436         }
1437     }
1438
1439     if( !$flag ) {
1440         print loc("All modules %tense(uninstall,past) successfully"), "\n";
1441     } else {
1442         print loc("Problem %tense(uninstalling,present) one or more modules" ),
1443                     "\n";
1444         print loc("*** You can view the complete error buffer by pressing '%1'".
1445                     "***\n", 'p') unless $conf->get_conf('verbose');
1446     }
1447     print "\n";
1448
1449     return !$flag;
1450 }
1451
1452 sub _reports {
1453    my $self = shift;
1454     my %hash = @_;
1455     my $cb   = $self->backend;
1456     my $term = $self->term;
1457     my $conf = $cb->configure_object;
1458
1459     my $opts; my $mods;
1460     {   local $Params::Check::ALLOW_UNKNOWN = 1;
1461
1462         my $tmpl = {
1463             options => { default => { }, store => \$opts },
1464             modules => { default => '',  store => \$mods },
1465         };
1466
1467          check( $tmpl, \%hash ) or return;
1468     }
1469
1470     ### XXX might need to be conditional ###
1471     $self->_pager_open;
1472
1473     for my $mod (@$mods) {
1474         my @list = $mod->fetch_report( %$opts )
1475                     or( print(loc("No reports available for this distribution.")),
1476                         next
1477                     );
1478
1479         @list = reverse
1480                 map  { $_->[0] }
1481                 sort { $a->[1] cmp $b->[1] }
1482                 map  { [$_, $_->{'dist'}.':'.$_->{'platform'}] } @list;
1483
1484
1485
1486         ### XXX this may need to be sorted better somehow ###
1487         my $url;
1488         my $format = "%8s %s %s\n";
1489
1490         my %seen;
1491         for my $href (@list ) {
1492             print "[" . $mod->author->cpanid .'/'. $href->{'dist'} . "]\n"
1493                 unless $seen{ $href->{'dist'} }++;
1494
1495             printf $format, $href->{'grade'}, $href->{'platform'},
1496                             ($href->{'details'} ? '(*)' : '');
1497
1498             $url ||= $href->{'details'};
1499         }
1500
1501         print "\n==> $url\n" if $url;
1502         print "\n";
1503     }
1504     $self->_pager_close;
1505
1506     return 1;
1507 }
1508
1509
1510 ### Load plugins
1511 {   my @PluginModules;
1512     my %Dispatch = ( 
1513         showtip => [ __PACKAGE__, '_show_random_tip'], 
1514         plugins => [ __PACKAGE__, '_list_plugins'   ], 
1515         '?'     => [ __PACKAGE__, '_plugins_usage'  ],
1516     );        
1517
1518     sub plugin_modules  { return @PluginModules }
1519     sub plugin_table    { return %Dispatch }
1520     
1521     ### find all plugins first
1522     if( check_install(  module  => 'Module::Pluggable', version => '2.4') ) {
1523         require Module::Pluggable;
1524
1525         my $only_re = __PACKAGE__ . '::Plugins::\w+$';
1526
1527         Module::Pluggable->import(
1528                         sub_name    => '_plugins',
1529                         search_path => __PACKAGE__,
1530                         only        => qr/$only_re/,
1531                         #except      => [ INSTALLER_MM, INSTALLER_SAMPLE ]
1532                     );
1533                     
1534         push @PluginModules, __PACKAGE__->_plugins;
1535     }
1536
1537     ### now try to load them
1538     for my $p ( __PACKAGE__->plugin_modules ) {
1539         my %map = eval { load $p; $p->import; $p->plugins };
1540         error(loc("Could not load plugin '$p': $@")), next if $@;
1541     
1542         ### register each plugin
1543         while( my($name, $func) = each %map ) {
1544             
1545             if( not length $name or not length $func ) {
1546                 error(loc("Empty plugin name or dispatch function detected"));
1547                 next;
1548             }                
1549             
1550             if( exists( $Dispatch{$name} ) ) {
1551                 error(loc("'%1' is already registered by '%2'", 
1552                     $name, $Dispatch{$name}->[0]));
1553                 next;                    
1554             }
1555     
1556             ### register name, package and function
1557             $Dispatch{$name} = [ $p, $func ];
1558         }
1559     }
1560
1561     ### dispatch a plugin command to it's function
1562     sub _meta {
1563         my $self = shift;
1564         my %hash = @_;
1565         my $cb   = $self->backend;
1566         my $term = $self->term;
1567         my $conf = $cb->configure_object;
1568     
1569         my $opts; my $input;
1570         {   local $Params::Check::ALLOW_UNKNOWN = 1;
1571     
1572             my $tmpl = {
1573                 options => { default => { }, store => \$opts },
1574                 input   => { default => '',  store => \$input },
1575             };
1576     
1577              check( $tmpl, \%hash ) or return;
1578         }
1579     
1580         $input =~ s/\s*(\S+)\s*//;
1581         my $cmd = $1;
1582     
1583         ### look up the command, or go to the default
1584         my $aref = $Dispatch{ $cmd } || [ __PACKAGE__, '_plugin_default' ];
1585         
1586         my($pkg,$func) = @$aref;
1587         
1588         my $rv = eval { $pkg->$func( $self, $cb, $cmd, $input, $opts ) };
1589         
1590         error( $@ ) if $@;
1591
1592         ### return $rv instead, so input loop can be terminated?
1593         return 1;
1594     }
1595     
1596     sub _plugin_default { error(loc("No such plugin command")) }
1597 }
1598
1599 ### plugin commands 
1600 {   my $help_format = "    /%-20s # %s\n"; 
1601     
1602     sub _list_plugins   {
1603         print loc("Available plugins:\n");
1604         print loc("    List usage by using: /? PLUGIN_NAME\n" );
1605         print $/;
1606         
1607         my %table = __PACKAGE__->plugin_table;
1608         for my $name( sort keys %table ) {
1609             my $pkg     = $table{$name}->[0];
1610             my $this    = __PACKAGE__;
1611             
1612             my $who = $pkg eq $this
1613                 ? "Standard Plugin"
1614                 : do { $pkg =~ s/^$this/../; "Provided by: $pkg" };
1615             
1616             printf $help_format, $name, $who;
1617         }          
1618     
1619         print $/.$/;
1620         
1621         print   "    Write your own plugins? Read the documentation of:\n" .
1622                 "        CPANPLUS::Shell::Default::Plugins::HOWTO\n";
1623                 
1624         print $/;        
1625     }
1626
1627     sub _list_plugins_help {
1628         return sprintf $help_format, 'plugins', loc("lists available plugins");
1629     }
1630
1631     ### registered as a plugin too
1632     sub _show_random_tip_help {
1633         return sprintf $help_format, 'showtip', loc("show usage tips" );
1634     }   
1635
1636     sub _plugins_usage {
1637         my $pkg     = shift;
1638         my $shell   = shift;
1639         my $cb      = shift;
1640         my $cmd     = shift;
1641         my $input   = shift;
1642         my %table   = __PACKAGE__->plugin_table;
1643         
1644         my @list = length $input ? split /\s+/, $input : sort keys %table;
1645         
1646         for my $name( @list ) {
1647
1648             ### no such plugin? skip
1649             error(loc("No such plugin '$name'")), next unless $table{$name};
1650
1651             my $pkg     = $table{$name}->[0];
1652             my $func    = $table{$name}->[1] . '_help';
1653             
1654             if ( my $sub = $pkg->can( $func ) ) {
1655                 eval { print $sub->() };
1656                 error( $@ ) if $@;
1657             
1658             } else {
1659                 print "    No usage for '$name' -- try perldoc $pkg";
1660             }
1661             
1662             print $/;
1663         }          
1664     
1665         print $/.$/;      
1666     }
1667     
1668     sub _plugins_usage_help {
1669         return sprintf $help_format, '? [NAME ...]',
1670                                      loc("show usage for plugins");
1671     }
1672 }
1673
1674 ### send a command to a remote host, retrieve the answer;
1675 sub __send_remote_command {
1676     my $self    = shift;
1677     my $cmd     = shift;
1678     my $remote  = $self->remote or return;
1679     my $user    = $remote->{'username'};
1680     my $pass    = $remote->{'password'};
1681     my $conn    = $remote->{'connection'};
1682     my $end     = "\015\012";
1683     my $answer;
1684
1685     my $send = join "\0", $user, $pass, $cmd;
1686
1687     print $conn $send . $end;
1688
1689     ### XXX why doesn't something like this just work?
1690     #1 while recv($conn, $answer, 1024, 0);
1691     while(1) {
1692         my $buff;
1693         $conn->recv( $buff, 1024, 0 );
1694         $answer .= $buff;
1695         last if $buff =~ /$end$/;
1696     }
1697
1698     my($status,$buffer) = split "\0", $answer;
1699
1700     return ($status, $buffer);
1701 }
1702
1703
1704 sub _read_configuration_from_rc {
1705     my $rc_file = shift;
1706
1707     my $href;
1708     if( can_load( modules => { 'Config::Auto' => '0.0' } ) ) {
1709         $Config::Auto::DisablePerl = 1;
1710
1711         eval { $href = Config::Auto::parse( $rc_file, format => 'space' ) };
1712
1713         print loc(  "Unable to read in config file '%1': %2",
1714                     $rc_file, $@ ) if $@;
1715     }
1716
1717     return $href || {};
1718 }
1719
1720 {   my @tips = (
1721         loc( "You can update CPANPLUS by running: '%1'", 's selfupdate' ),
1722         loc( "You can install modules by URL using '%1'", 'i URL' ),
1723         loc( "You can turn off these tips using '%1'", 
1724              's conf show_startup_tip 0' ),
1725         loc( "You can use wildcards like '%1' and '%2' on search results",
1726              '*', '2..5' ) ,
1727         loc( "You can use plugins. Type '%1' to list available plugins",
1728              '/plugins' ),
1729         loc( "You can show all your out of date modules using '%1'", 'o' ),  
1730         loc( "Many operations take options, like '%1', '%2' or '%3'",
1731              '--verbose', '--force', '--skiptest' ),
1732         loc( "The documentation in %1 and %2 is very useful",
1733              "CPANPLUS::Module", "CPANPLUS::Backend" ),
1734         loc( "You can type '%1' for help and '%2' to exit", 'h', 'q' ),
1735         loc( "You can run an interactive setup using '%1'", 's reconfigure' ),          
1736     );
1737     
1738     sub _show_random_tip {
1739         my $self = shift;
1740         print $/, "Did you know...\n    ", $tips[ int rand scalar @tips ], $/;
1741         return 1;
1742     }
1743 }    
1744
1745 1;
1746
1747 __END__
1748
1749 =pod
1750
1751 =head1 BUG REPORTS
1752
1753 Please report bugs or other issues to E<lt>bug-cpanplus@rt.cpan.org<gt>.
1754
1755 =head1 AUTHOR
1756
1757 This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
1758
1759 =head1 COPYRIGHT
1760
1761 The CPAN++ interface (of which this module is a part of) is copyright (c) 
1762 2001 - 2007, Jos Boumans E<lt>kane@cpan.orgE<gt>. All rights reserved.
1763
1764 This library is free software; you may redistribute and/or modify it 
1765 under the same terms as Perl itself.
1766
1767 =head1 SEE ALSO
1768
1769 L<CPANPLUS::Shell::Classic>, L<CPANPLUS::Shell>, L<cpanp>
1770
1771 =cut
1772
1773 # Local variables:
1774 # c-indentation-style: bsd
1775 # c-basic-offset: 4
1776 # indent-tabs-mode: nil
1777 # End:
1778 # vim: expandtab shiftwidth=4:
1779
1780 __END__
1781
1782 TODO:
1783     e   => "_expand_inc", # scratch it, imho -- not used enough
1784
1785 ### free letters: g j k n y ###