reimported.
[catagits/Task-Catalyst.git] / inc / Module / AutoInstall.pm
1 #line 1
2 package Module::AutoInstall;
3
4 use strict;
5 use Cwd                 ();
6 use ExtUtils::MakeMaker ();
7
8 use vars qw{$VERSION};
9 BEGIN {
10         $VERSION = '1.02';
11 }
12
13 # special map on pre-defined feature sets
14 my %FeatureMap = (
15     ''      => 'Core Features',    # XXX: deprecated
16     '-core' => 'Core Features',
17 );
18
19 # various lexical flags
20 my ( @Missing, @Existing,  %DisabledTests, $UnderCPAN,     $HasCPANPLUS );
21 my ( $Config,  $CheckOnly, $SkipInstall,   $AcceptDefault, $TestOnly );
22 my ( $PostambleActions, $PostambleUsed );
23
24 # See if it's a testing or non-interactive session
25 _accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN ); 
26 _init();
27
28 sub _accept_default {
29     $AcceptDefault = shift;
30 }
31
32 sub missing_modules {
33     return @Missing;
34 }
35
36 sub do_install {
37     __PACKAGE__->install(
38         [
39             $Config
40             ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
41             : ()
42         ],
43         @Missing,
44     );
45 }
46
47 # initialize various flags, and/or perform install
48 sub _init {
49     foreach my $arg (
50         @ARGV,
51         split(
52             /[\s\t]+/,
53             $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''
54         )
55       )
56     {
57         if ( $arg =~ /^--config=(.*)$/ ) {
58             $Config = [ split( ',', $1 ) ];
59         }
60         elsif ( $arg =~ /^--installdeps=(.*)$/ ) {
61             __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
62             exit 0;
63         }
64         elsif ( $arg =~ /^--default(?:deps)?$/ ) {
65             $AcceptDefault = 1;
66         }
67         elsif ( $arg =~ /^--check(?:deps)?$/ ) {
68             $CheckOnly = 1;
69         }
70         elsif ( $arg =~ /^--skip(?:deps)?$/ ) {
71             $SkipInstall = 1;
72         }
73         elsif ( $arg =~ /^--test(?:only)?$/ ) {
74             $TestOnly = 1;
75         }
76     }
77 }
78
79 # overrides MakeMaker's prompt() to automatically accept the default choice
80 sub _prompt {
81     goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
82
83     my ( $prompt, $default ) = @_;
84     my $y = ( $default =~ /^[Yy]/ );
85
86     print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] ';
87     print "$default\n";
88     return $default;
89 }
90
91 # the workhorse
92 sub import {
93     my $class = shift;
94     my @args  = @_ or return;
95     my $core_all;
96
97     print "*** $class version " . $class->VERSION . "\n";
98     print "*** Checking for Perl dependencies...\n";
99
100     my $cwd = Cwd::cwd();
101
102     $Config = [];
103
104     my $maxlen = length(
105         (
106             sort   { length($b) <=> length($a) }
107               grep { /^[^\-]/ }
108               map  {
109                 ref($_)
110                   ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} )
111                   : ''
112               }
113               map { +{@args}->{$_} }
114               grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} }
115         )[0]
116     );
117
118     while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) {
119         my ( @required, @tests, @skiptests );
120         my $default  = 1;
121         my $conflict = 0;
122
123         if ( $feature =~ m/^-(\w+)$/ ) {
124             my $option = lc($1);
125
126             # check for a newer version of myself
127             _update_to( $modules, @_ ) and return if $option eq 'version';
128
129             # sets CPAN configuration options
130             $Config = $modules if $option eq 'config';
131
132             # promote every features to core status
133             $core_all = ( $modules =~ /^all$/i ) and next
134               if $option eq 'core';
135
136             next unless $option eq 'core';
137         }
138
139         print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n";
140
141         $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' );
142
143         unshift @$modules, -default => &{ shift(@$modules) }
144           if ( ref( $modules->[0] ) eq 'CODE' );    # XXX: bugward combatability
145
146         while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) {
147             if ( $mod =~ m/^-(\w+)$/ ) {
148                 my $option = lc($1);
149
150                 $default   = $arg    if ( $option eq 'default' );
151                 $conflict  = $arg    if ( $option eq 'conflict' );
152                 @tests     = @{$arg} if ( $option eq 'tests' );
153                 @skiptests = @{$arg} if ( $option eq 'skiptests' );
154
155                 next;
156             }
157
158             printf( "- %-${maxlen}s ...", $mod );
159
160             if ( $arg and $arg =~ /^\D/ ) {
161                 unshift @$modules, $arg;
162                 $arg = 0;
163             }
164
165             # XXX: check for conflicts and uninstalls(!) them.
166             if (
167                 defined( my $cur = _version_check( _load($mod), $arg ||= 0 ) ) )
168             {
169                 print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n";
170                 push @Existing, $mod => $arg;
171                 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
172             }
173             else {
174                 print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n";
175                 push @required, $mod => $arg;
176             }
177         }
178
179         next unless @required;
180
181         my $mandatory = ( $feature eq '-core' or $core_all );
182
183         if (
184             !$SkipInstall
185             and (
186                 $CheckOnly
187                 or _prompt(
188                     qq{==> Auto-install the }
189                       . ( @required / 2 )
190                       . ( $mandatory ? ' mandatory' : ' optional' )
191                       . qq{ module(s) from CPAN?},
192                     $default ? 'y' : 'n',
193                 ) =~ /^[Yy]/
194             )
195           )
196         {
197             push( @Missing, @required );
198             $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
199         }
200
201         elsif ( !$SkipInstall
202             and $default
203             and $mandatory
204             and
205             _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', )
206             =~ /^[Nn]/ )
207         {
208             push( @Missing, @required );
209             $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
210         }
211
212         else {
213             $DisabledTests{$_} = 1 for map { glob($_) } @tests;
214         }
215     }
216
217     _check_lock();    # check for $UnderCPAN
218
219     if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) {
220         require Config;
221         print
222 "*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n";
223
224         # make an educated guess of whether we'll need root permission.
225         print "    (You may need to do that as the 'root' user.)\n"
226           if eval '$>';
227     }
228     print "*** $class configuration finished.\n";
229
230     chdir $cwd;
231
232     # import to main::
233     no strict 'refs';
234     *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
235 }
236
237 # CPAN.pm is non-reentrant, so check if we're under it and have no CPANPLUS
238 sub _check_lock {
239     return unless @Missing;
240     _load_cpan();
241
242     # Find the CPAN lock-file
243     my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
244     return unless -f $lock;
245
246     # Check the lock
247     local *LOCK;
248     return unless open(LOCK, $lock);
249
250     if (
251             ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
252         and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
253     ) {
254         print <<'END_MESSAGE';
255
256 *** Since we're running under CPAN, I'll just let it take care
257     of the dependency's installation later.
258 END_MESSAGE
259         $UnderCPAN = 1;
260     }
261
262     close LOCK;
263 }
264
265 sub install {
266     my $class = shift;
267
268     my $i;    # used below to strip leading '-' from config keys
269     my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
270
271     my ( @modules, @installed );
272     while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) {
273
274         # grep out those already installed
275         if ( defined( _version_check( _load($pkg), $ver ) ) ) {
276             push @installed, $pkg;
277         }
278         else {
279             push @modules, $pkg, $ver;
280         }
281     }
282
283     return @installed unless @modules;    # nothing to do
284
285     print "*** Installing dependencies...\n";
286
287     return unless _connected_to('cpan.org');
288
289     my %args = @config;
290     my %failed;
291     local *FAILED;
292     if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
293         while (<FAILED>) { chomp; $failed{$_}++ }
294         close FAILED;
295
296         my @newmod;
297         while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
298             push @newmod, ( $k => $v ) unless $failed{$k};
299         }
300         @modules = @newmod;
301     }
302
303     if ( ! $UnderCPAN and _has_cpanplus() ) {
304         _install_cpanplus( \@modules, \@config );
305     } else {
306         _install_cpan( \@modules, \@config );
307     }
308
309     print "*** $class installation finished.\n";
310
311     # see if we have successfully installed them
312     while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
313         if ( defined( _version_check( _load($pkg), $ver ) ) ) {
314             push @installed, $pkg;
315         }
316         elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
317             print FAILED "$pkg\n";
318         }
319     }
320
321     close FAILED if $args{do_once};
322
323     return @installed;
324 }
325
326 sub _install_cpanplus {
327     my @modules   = @{ +shift };
328     my @config    = _cpanplus_config( @{ +shift } );
329     my $installed = 0;
330
331     require CPANPLUS::Backend;
332     my $cp   = CPANPLUS::Backend->new;
333     my $conf = $cp->configure_object;
334
335     return unless $conf->can('conf') # 0.05x+ with "sudo" support
336                or _can_write($conf->_get_build('base'));  # 0.04x
337
338     # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
339     my $makeflags = $conf->get_conf('makeflags') || '';
340     if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
341         # 0.03+ uses a hashref here
342         $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
343
344     } else {
345         # 0.02 and below uses a scalar
346         $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
347           if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
348
349     }
350     $conf->set_conf( makeflags => $makeflags );
351     $conf->set_conf( prereqs   => 1 );
352
353     
354
355     while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
356         $conf->set_conf( $key, $val );
357     }
358
359     my $modtree = $cp->module_tree;
360     while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
361         print "*** Installing $pkg...\n";
362
363         MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
364
365         my $success;
366         my $obj = $modtree->{$pkg};
367
368         if ( $obj and defined( _version_check( $obj->{version}, $ver ) ) ) {
369             my $pathname = $pkg;
370             $pathname =~ s/::/\\W/;
371
372             foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
373                 delete $INC{$inc};
374             }
375
376             my $rv = $cp->install( modules => [ $obj->{module} ] );
377
378             if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
379                 print "*** $pkg successfully installed.\n";
380                 $success = 1;
381             } else {
382                 print "*** $pkg installation cancelled.\n";
383                 $success = 0;
384             }
385
386             $installed += $success;
387         } else {
388             print << ".";
389 *** Could not find a version $ver or above for $pkg; skipping.
390 .
391         }
392
393         MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
394     }
395
396     return $installed;
397 }
398
399 sub _cpanplus_config {
400         my @config = ();
401         while ( @_ ) {
402                 my ($key, $value) = (shift(), shift());
403                 if ( $key eq 'prerequisites_policy' ) {
404                         if ( $value eq 'follow' ) {
405                                 $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
406                         } elsif ( $value eq 'ask' ) {
407                                 $value = CPANPLUS::Internals::Constants::PREREQ_ASK();
408                         } elsif ( $value eq 'ignore' ) {
409                                 $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
410                         } else {
411                                 die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
412                         }
413                 } else {
414                         die "*** Cannot convert option $key to CPANPLUS version.\n";
415                 }
416         }
417         return @config;
418 }
419
420 sub _install_cpan {
421     my @modules   = @{ +shift };
422     my @config    = @{ +shift };
423     my $installed = 0;
424     my %args;
425
426     _load_cpan();
427     require Config;
428
429     if (CPAN->VERSION < 1.80) {
430         # no "sudo" support, probe for writableness
431         return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
432                   and _can_write( $Config::Config{sitelib} );
433     }
434
435     # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
436     my $makeflags = $CPAN::Config->{make_install_arg} || '';
437     $CPAN::Config->{make_install_arg} =
438       join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
439       if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
440
441     # don't show start-up info
442     $CPAN::Config->{inhibit_startup_message} = 1;
443
444     # set additional options
445     while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
446         ( $args{$opt} = $arg, next )
447           if $opt =~ /^force$/;    # pseudo-option
448         $CPAN::Config->{$opt} = $arg;
449     }
450
451     local $CPAN::Config->{prerequisites_policy} = 'follow';
452
453     while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
454         MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
455
456         print "*** Installing $pkg...\n";
457
458         my $obj     = CPAN::Shell->expand( Module => $pkg );
459         my $success = 0;
460
461         if ( $obj and defined( _version_check( $obj->cpan_version, $ver ) ) ) {
462             my $pathname = $pkg;
463             $pathname =~ s/::/\\W/;
464
465             foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
466                 delete $INC{$inc};
467             }
468
469             $obj->force('install') if $args{force};
470
471             my $rv = $obj->install || eval {
472                 $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
473                   ->{install}
474                   if $CPAN::META;
475             };
476
477             if ( $rv eq 'YES' ) {
478                 print "*** $pkg successfully installed.\n";
479                 $success = 1;
480             }
481             else {
482                 print "*** $pkg installation failed.\n";
483                 $success = 0;
484             }
485
486             $installed += $success;
487         }
488         else {
489             print << ".";
490 *** Could not find a version $ver or above for $pkg; skipping.
491 .
492         }
493
494         MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
495     }
496
497     return $installed;
498 }
499
500 sub _has_cpanplus {
501     return (
502         $HasCPANPLUS = (
503             $INC{'CPANPLUS/Config.pm'}
504               or _load('CPANPLUS::Shell::Default')
505         )
506     );
507 }
508
509 # make guesses on whether we're under the CPAN installation directory
510 sub _under_cpan {
511     require Cwd;
512     require File::Spec;
513
514     my $cwd  = File::Spec->canonpath( Cwd::cwd() );
515     my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
516
517     return ( index( $cwd, $cpan ) > -1 );
518 }
519
520 sub _update_to {
521     my $class = __PACKAGE__;
522     my $ver   = shift;
523
524     return
525       if defined( _version_check( _load($class), $ver ) );  # no need to upgrade
526
527     if (
528         _prompt( "==> A newer version of $class ($ver) is required. Install?",
529             'y' ) =~ /^[Nn]/
530       )
531     {
532         die "*** Please install $class $ver manually.\n";
533     }
534
535     print << ".";
536 *** Trying to fetch it from CPAN...
537 .
538
539     # install ourselves
540     _load($class) and return $class->import(@_)
541       if $class->install( [], $class, $ver );
542
543     print << '.'; exit 1;
544
545 *** Cannot bootstrap myself. :-( Installation terminated.
546 .
547 }
548
549 # check if we're connected to some host, using inet_aton
550 sub _connected_to {
551     my $site = shift;
552
553     return (
554         ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
555             qq(
556 *** Your host cannot resolve the domain name '$site', which
557     probably means the Internet connections are unavailable.
558 ==> Should we try to install the required module(s) anyway?), 'n'
559           ) =~ /^[Yy]/
560     );
561 }
562
563 # check if a directory is writable; may create it on demand
564 sub _can_write {
565     my $path = shift;
566     mkdir( $path, 0755 ) unless -e $path;
567
568     return 1 if -w $path;
569
570     print << ".";
571 *** You are not allowed to write to the directory '$path';
572     the installation may fail due to insufficient permissions.
573 .
574
575     if (
576         eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
577             qq(
578 ==> Should we try to re-execute the autoinstall process with 'sudo'?),
579             ((-t STDIN) ? 'y' : 'n')
580         ) =~ /^[Yy]/
581       )
582     {
583
584         # try to bootstrap ourselves from sudo
585         print << ".";
586 *** Trying to re-execute the autoinstall process with 'sudo'...
587 .
588         my $missing = join( ',', @Missing );
589         my $config = join( ',',
590             UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
591           if $Config;
592
593         return
594           unless system( 'sudo', $^X, $0, "--config=$config",
595             "--installdeps=$missing" );
596
597         print << ".";
598 *** The 'sudo' command exited with error!  Resuming...
599 .
600     }
601
602     return _prompt(
603         qq(
604 ==> Should we try to install the required module(s) anyway?), 'n'
605     ) =~ /^[Yy]/;
606 }
607
608 # load a module and return the version it reports
609 sub _load {
610     my $mod  = pop;    # class/instance doesn't matter
611     my $file = $mod;
612
613     $file =~ s|::|/|g;
614     $file .= '.pm';
615
616     local $@;
617     return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
618 }
619
620 # Load CPAN.pm and it's configuration
621 sub _load_cpan {
622     return if $CPAN::VERSION;
623     require CPAN;
624     if ( $CPAN::HandleConfig::VERSION ) {
625         # Newer versions of CPAN have a HandleConfig module
626         CPAN::HandleConfig->load;
627     } else {
628         # Older versions had the load method in Config directly
629         CPAN::Config->load;
630     }
631 }
632
633 # compare two versions, either use Sort::Versions or plain comparison
634 sub _version_check {
635     my ( $cur, $min ) = @_;
636     return unless defined $cur;
637
638     $cur =~ s/\s+$//;
639
640     # check for version numbers that are not in decimal format
641     if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
642         if ( $version::VERSION or defined( _load('version') ) ) {
643
644             # use version.pm if it is installed.
645             return (
646                 ( version->new($cur) >= version->new($min) ) ? $cur : undef );
647         }
648         elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
649         {
650
651             # use Sort::Versions as the sorting algorithm for a.b.c versions
652             return ( ( Sort::Versions::versioncmp( $cur, $min ) != -1 )
653                 ? $cur
654                 : undef );
655         }
656
657         warn "Cannot reliably compare non-decimal formatted versions.\n"
658           . "Please install version.pm or Sort::Versions.\n";
659     }
660
661     # plain comparison
662     local $^W = 0;    # shuts off 'not numeric' bugs
663     return ( $cur >= $min ? $cur : undef );
664 }
665
666 # nothing; this usage is deprecated.
667 sub main::PREREQ_PM { return {}; }
668
669 sub _make_args {
670     my %args = @_;
671
672     $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
673       if $UnderCPAN or $TestOnly;
674
675     if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
676         require ExtUtils::Manifest;
677         my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
678
679         $args{EXE_FILES} =
680           [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
681     }
682
683     $args{test}{TESTS} ||= 't/*.t';
684     $args{test}{TESTS} = join( ' ',
685         grep { !exists( $DisabledTests{$_} ) }
686           map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
687
688     my $missing = join( ',', @Missing );
689     my $config =
690       join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
691       if $Config;
692
693     $PostambleActions = (
694         $missing
695         ? "\$(PERL) $0 --config=$config --installdeps=$missing"
696         : "\$(NOECHO) \$(NOOP)"
697     );
698
699     return %args;
700 }
701
702 # a wrapper to ExtUtils::MakeMaker::WriteMakefile
703 sub Write {
704     require Carp;
705     Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
706
707     if ($CheckOnly) {
708         print << ".";
709 *** Makefile not written in check-only mode.
710 .
711         return;
712     }
713
714     my %args = _make_args(@_);
715
716     no strict 'refs';
717
718     $PostambleUsed = 0;
719     local *MY::postamble = \&postamble unless defined &MY::postamble;
720     ExtUtils::MakeMaker::WriteMakefile(%args);
721
722     print << "." unless $PostambleUsed;
723 *** WARNING: Makefile written with customized MY::postamble() without
724     including contents from Module::AutoInstall::postamble() --
725     auto installation features disabled.  Please contact the author.
726 .
727
728     return 1;
729 }
730
731 sub postamble {
732     $PostambleUsed = 1;
733
734     return << ".";
735
736 config :: installdeps
737 \t\$(NOECHO) \$(NOOP)
738
739 checkdeps ::
740 \t\$(PERL) $0 --checkdeps
741
742 installdeps ::
743 \t$PostambleActions
744
745 .
746
747 }
748
749 1;
750
751 __END__
752
753 #line 988