2 package Module::AutoInstall;
6 use ExtUtils::MakeMaker ();
13 # special map on pre-defined feature sets
15 '' => 'Core Features', # XXX: deprecated
16 '-core' => 'Core Features',
19 # various lexical flags
20 my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS );
22 $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly, $AllDeps
24 my ( $PostambleActions, $PostambleUsed );
26 # See if it's a testing or non-interactive session
27 _accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN );
31 $AcceptDefault = shift;
42 ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
49 # initialize various flags, and/or perform install
55 $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''
59 if ( $arg =~ /^--config=(.*)$/ ) {
60 $Config = [ split( ',', $1 ) ];
62 elsif ( $arg =~ /^--installdeps=(.*)$/ ) {
63 __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
66 elsif ( $arg =~ /^--default(?:deps)?$/ ) {
69 elsif ( $arg =~ /^--check(?:deps)?$/ ) {
72 elsif ( $arg =~ /^--skip(?:deps)?$/ ) {
75 elsif ( $arg =~ /^--test(?:only)?$/ ) {
78 elsif ( $arg =~ /^--all(?:deps)?$/ ) {
84 # overrides MakeMaker's prompt() to automatically accept the default choice
86 goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
88 my ( $prompt, $default ) = @_;
89 my $y = ( $default =~ /^[Yy]/ );
91 print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] ';
99 my @args = @_ or return;
102 print "*** $class version " . $class->VERSION . "\n";
103 print "*** Checking for Perl dependencies...\n";
105 my $cwd = Cwd::cwd();
111 sort { length($b) <=> length($a) }
115 ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} )
118 map { +{@args}->{$_} }
119 grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} }
123 # We want to know if we're under CPAN early to avoid prompting, but
124 # if we aren't going to try and install anything anyway then skip the
125 # check entirely since we don't want to have to load (and configure)
126 # an old CPAN just for a cosmetic message
128 $UnderCPAN = _check_lock(1) unless $SkipInstall;
130 while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) {
131 my ( @required, @tests, @skiptests );
135 if ( $feature =~ m/^-(\w+)$/ ) {
138 # check for a newer version of myself
139 _update_to( $modules, @_ ) and return if $option eq 'version';
141 # sets CPAN configuration options
142 $Config = $modules if $option eq 'config';
144 # promote every features to core status
145 $core_all = ( $modules =~ /^all$/i ) and next
146 if $option eq 'core';
148 next unless $option eq 'core';
151 print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n";
153 $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' );
155 unshift @$modules, -default => &{ shift(@$modules) }
156 if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability
158 while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) {
159 if ( $mod =~ m/^-(\w+)$/ ) {
162 $default = $arg if ( $option eq 'default' );
163 $conflict = $arg if ( $option eq 'conflict' );
164 @tests = @{$arg} if ( $option eq 'tests' );
165 @skiptests = @{$arg} if ( $option eq 'skiptests' );
170 printf( "- %-${maxlen}s ...", $mod );
172 if ( $arg and $arg =~ /^\D/ ) {
173 unshift @$modules, $arg;
177 # XXX: check for conflicts and uninstalls(!) them.
178 my $cur = _load($mod);
179 if (_version_cmp ($cur, $arg) >= 0)
181 print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n";
182 push @Existing, $mod => $arg;
183 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
186 if (not defined $cur) # indeed missing
188 print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n";
192 # no need to check $arg as _version_cmp ($cur, undef) would satisfy >= above
193 print "too old. ($cur < $arg)\n";
196 push @required, $mod => $arg;
200 next unless @required;
202 my $mandatory = ( $feature eq '-core' or $core_all );
208 or ($mandatory and $UnderCPAN)
211 qq{==> Auto-install the }
213 . ( $mandatory ? ' mandatory' : ' optional' )
214 . qq{ module(s) from CPAN?},
215 $default ? 'y' : 'n',
220 push( @Missing, @required );
221 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
224 elsif ( !$SkipInstall
228 _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', )
231 push( @Missing, @required );
232 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
236 $DisabledTests{$_} = 1 for map { glob($_) } @tests;
240 if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) {
243 "*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n";
245 # make an educated guess of whether we'll need root permission.
246 print " (You may need to do that as the 'root' user.)\n"
249 print "*** $class configuration finished.\n";
255 *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
260 print <<"END_MESSAGE";
261 *** Since we're running under ${thing}, I'll just let it take care
262 of the dependency's installation later.
267 # Check to see if we are currently running under CPAN.pm and/or CPANPLUS;
268 # if we are, then we simply let it taking care of our dependencies
270 return unless @Missing or @_;
272 my $cpan_env = $ENV{PERL5_CPAN_IS_RUNNING};
274 if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) {
275 return _running_under($cpan_env ? 'CPAN' : 'CPANPLUS');
280 if ($CPAN::VERSION > '1.89') {
282 return _running_under('CPAN');
284 return; # CPAN.pm new enough, don't need to check further
287 # last ditch attempt, this -will- configure CPAN, very sorry
289 _load_cpan(1); # force initialize even though it's already loaded
291 # Find the CPAN lock-file
292 my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
293 return unless -f $lock;
297 return unless open(LOCK, $lock);
300 ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
301 and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
303 print <<'END_MESSAGE';
305 *** Since we're running under CPAN, I'll just let it take care
306 of the dependency's installation later.
318 my $i; # used below to strip leading '-' from config keys
319 my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
321 my ( @modules, @installed );
322 while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) {
324 # grep out those already installed
325 if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
326 push @installed, $pkg;
329 push @modules, $pkg, $ver;
333 return @installed unless @modules; # nothing to do
334 return @installed if _check_lock(); # defer to the CPAN shell
336 print "*** Installing dependencies...\n";
338 return unless _connected_to('cpan.org');
343 if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
344 while (<FAILED>) { chomp; $failed{$_}++ }
348 while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
349 push @newmod, ( $k => $v ) unless $failed{$k};
354 if ( _has_cpanplus() and not $ENV{PERL_AUTOINSTALL_PREFER_CPAN} ) {
355 _install_cpanplus( \@modules, \@config );
357 _install_cpan( \@modules, \@config );
360 print "*** $class installation finished.\n";
362 # see if we have successfully installed them
363 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
364 if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
365 push @installed, $pkg;
367 elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
368 print FAILED "$pkg\n";
372 close FAILED if $args{do_once};
377 sub _install_cpanplus {
378 my @modules = @{ +shift };
379 my @config = _cpanplus_config( @{ +shift } );
382 require CPANPLUS::Backend;
383 my $cp = CPANPLUS::Backend->new;
384 my $conf = $cp->configure_object;
386 return unless $conf->can('conf') # 0.05x+ with "sudo" support
387 or _can_write($conf->_get_build('base')); # 0.04x
389 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
390 my $makeflags = $conf->get_conf('makeflags') || '';
391 if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
392 # 0.03+ uses a hashref here
393 $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
396 # 0.02 and below uses a scalar
397 $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
398 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
401 $conf->set_conf( makeflags => $makeflags );
402 $conf->set_conf( prereqs => 1 );
406 while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
407 $conf->set_conf( $key, $val );
410 my $modtree = $cp->module_tree;
411 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
412 print "*** Installing $pkg...\n";
414 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
417 my $obj = $modtree->{$pkg};
419 if ( $obj and _version_cmp( $obj->{version}, $ver ) >= 0 ) {
421 $pathname =~ s/::/\\W/;
423 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
427 my $rv = $cp->install( modules => [ $obj->{module} ] );
429 if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
430 print "*** $pkg successfully installed.\n";
433 print "*** $pkg installation cancelled.\n";
437 $installed += $success;
440 *** Could not find a version $ver or above for $pkg; skipping.
444 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
450 sub _cpanplus_config {
453 my ($key, $value) = (shift(), shift());
454 if ( $key eq 'prerequisites_policy' ) {
455 if ( $value eq 'follow' ) {
456 $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
457 } elsif ( $value eq 'ask' ) {
458 $value = CPANPLUS::Internals::Constants::PREREQ_ASK();
459 } elsif ( $value eq 'ignore' ) {
460 $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
462 die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
465 die "*** Cannot convert option $key to CPANPLUS version.\n";
472 my @modules = @{ +shift };
473 my @config = @{ +shift };
480 if (CPAN->VERSION < 1.80) {
481 # no "sudo" support, probe for writableness
482 return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
483 and _can_write( $Config::Config{sitelib} );
486 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
487 my $makeflags = $CPAN::Config->{make_install_arg} || '';
488 $CPAN::Config->{make_install_arg} =
489 join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
490 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
492 # don't show start-up info
493 $CPAN::Config->{inhibit_startup_message} = 1;
495 # set additional options
496 while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
497 ( $args{$opt} = $arg, next )
498 if $opt =~ /^force$/; # pseudo-option
499 $CPAN::Config->{$opt} = $arg;
502 local $CPAN::Config->{prerequisites_policy} = 'follow';
504 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
505 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
507 print "*** Installing $pkg...\n";
509 my $obj = CPAN::Shell->expand( Module => $pkg );
512 if ( $obj and _version_cmp( $obj->cpan_version, $ver ) >= 0 ) {
514 $pathname =~ s/::/\\W/;
516 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
520 my $rv = $args{force} ? CPAN::Shell->force( install => $pkg )
521 : CPAN::Shell->install($pkg);
523 $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
528 if ( $rv eq 'YES' ) {
529 print "*** $pkg successfully installed.\n";
533 print "*** $pkg installation failed.\n";
537 $installed += $success;
541 *** Could not find a version $ver or above for $pkg; skipping.
545 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
554 $INC{'CPANPLUS/Config.pm'}
555 or _load('CPANPLUS::Shell::Default')
560 # make guesses on whether we're under the CPAN installation directory
565 my $cwd = File::Spec->canonpath( Cwd::cwd() );
566 my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
568 return ( index( $cwd, $cpan ) > -1 );
572 my $class = __PACKAGE__;
576 if _version_cmp( _load($class), $ver ) >= 0; # no need to upgrade
579 _prompt( "==> A newer version of $class ($ver) is required. Install?",
583 die "*** Please install $class $ver manually.\n";
587 *** Trying to fetch it from CPAN...
591 _load($class) and return $class->import(@_)
592 if $class->install( [], $class, $ver );
594 print << '.'; exit 1;
596 *** Cannot bootstrap myself. :-( Installation terminated.
600 # check if we're connected to some host, using inet_aton
605 ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
607 *** Your host cannot resolve the domain name '$site', which
608 probably means the Internet connections are unavailable.
609 ==> Should we try to install the required module(s) anyway?), 'n'
614 # check if a directory is writable; may create it on demand
617 mkdir( $path, 0755 ) unless -e $path;
619 return 1 if -w $path;
622 *** You are not allowed to write to the directory '$path';
623 the installation may fail due to insufficient permissions.
627 eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
629 ==> Should we try to re-execute the autoinstall process with 'sudo'?),
630 ((-t STDIN) ? 'y' : 'n')
635 # try to bootstrap ourselves from sudo
637 *** Trying to re-execute the autoinstall process with 'sudo'...
639 my $missing = join( ',', @Missing );
640 my $config = join( ',',
641 UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
645 unless system( 'sudo', $^X, $0, "--config=$config",
646 "--installdeps=$missing" );
649 *** The 'sudo' command exited with error! Resuming...
655 ==> Should we try to install the required module(s) anyway?), 'n'
659 # load a module and return the version it reports
661 my $mod = pop; # class/instance doesn't matter
668 return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
671 # Load CPAN.pm and it's configuration
673 return if $CPAN::VERSION and $CPAN::Config and not @_;
676 # CPAN-1.82+ adds CPAN::Config::AUTOLOAD to redirect to
677 # CPAN::HandleConfig->load. CPAN reports that the redirection
678 # is deprecated in a warning printed at the user.
680 # CPAN-1.81 expects CPAN::HandleConfig->load, does not have
681 # $CPAN::HandleConfig::VERSION but cannot handle
684 # Which "versions expect CPAN::Config->load?
686 if ( $CPAN::HandleConfig::VERSION
687 || CPAN::HandleConfig->can('load')
689 # Newer versions of CPAN have a HandleConfig module
690 CPAN::HandleConfig->load;
692 # Older versions had the load method in Config directly
697 # compare two versions, either use Sort::Versions or plain comparison
698 # return values same as <=>
700 my ( $cur, $min ) = @_;
701 return -1 unless defined $cur; # if 0 keep comparing
702 return 1 unless $min;
706 # check for version numbers that are not in decimal format
707 if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
708 if ( ( $version::VERSION or defined( _load('version') )) and
712 # use version.pm if it is installed.
713 return version->new($cur) <=> version->new($min);
715 elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
718 # use Sort::Versions as the sorting algorithm for a.b.c versions
719 return Sort::Versions::versioncmp( $cur, $min );
722 warn "Cannot reliably compare non-decimal formatted versions.\n"
723 . "Please install version.pm or Sort::Versions.\n";
727 local $^W = 0; # shuts off 'not numeric' bugs
728 return $cur <=> $min;
731 # nothing; this usage is deprecated.
732 sub main::PREREQ_PM { return {}; }
737 $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
738 if $UnderCPAN or $TestOnly;
740 if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
741 require ExtUtils::Manifest;
742 my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
745 [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
748 $args{test}{TESTS} ||= 't/*.t';
749 $args{test}{TESTS} = join( ' ',
750 grep { !exists( $DisabledTests{$_} ) }
751 map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
753 my $missing = join( ',', @Missing );
755 join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
758 $PostambleActions = (
759 ($missing and not $UnderCPAN)
760 ? "\$(PERL) $0 --config=$config --installdeps=$missing"
761 : "\$(NOECHO) \$(NOOP)"
767 # a wrapper to ExtUtils::MakeMaker::WriteMakefile
770 Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
774 *** Makefile not written in check-only mode.
779 my %args = _make_args(@_);
784 local *MY::postamble = \&postamble unless defined &MY::postamble;
785 ExtUtils::MakeMaker::WriteMakefile(%args);
787 print << "." unless $PostambleUsed;
788 *** WARNING: Makefile written with customized MY::postamble() without
789 including contents from Module::AutoInstall::postamble() --
790 auto installation features disabled. Please contact the author.
801 config :: installdeps
802 \t\$(NOECHO) \$(NOOP)
805 \t\$(PERL) $0 --checkdeps