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';
257 return (@Existing, @Missing);
262 print <<"END_MESSAGE";
263 *** Since we're running under ${thing}, I'll just let it take care
264 of the dependency's installation later.
269 # Check to see if we are currently running under CPAN.pm and/or CPANPLUS;
270 # if we are, then we simply let it taking care of our dependencies
272 return unless @Missing or @_;
274 my $cpan_env = $ENV{PERL5_CPAN_IS_RUNNING};
276 if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) {
277 return _running_under($cpan_env ? 'CPAN' : 'CPANPLUS');
282 if ($CPAN::VERSION > '1.89') {
284 return _running_under('CPAN');
286 return; # CPAN.pm new enough, don't need to check further
289 # last ditch attempt, this -will- configure CPAN, very sorry
291 _load_cpan(1); # force initialize even though it's already loaded
293 # Find the CPAN lock-file
294 my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
295 return unless -f $lock;
299 return unless open(LOCK, $lock);
302 ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
303 and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
305 print <<'END_MESSAGE';
307 *** Since we're running under CPAN, I'll just let it take care
308 of the dependency's installation later.
320 my $i; # used below to strip leading '-' from config keys
321 my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
323 my ( @modules, @installed );
324 while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) {
326 # grep out those already installed
327 if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
328 push @installed, $pkg;
331 push @modules, $pkg, $ver;
335 return @installed unless @modules; # nothing to do
336 return @installed if _check_lock(); # defer to the CPAN shell
338 print "*** Installing dependencies...\n";
340 return unless _connected_to('cpan.org');
345 if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
346 while (<FAILED>) { chomp; $failed{$_}++ }
350 while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
351 push @newmod, ( $k => $v ) unless $failed{$k};
356 if ( _has_cpanplus() and not $ENV{PERL_AUTOINSTALL_PREFER_CPAN} ) {
357 _install_cpanplus( \@modules, \@config );
359 _install_cpan( \@modules, \@config );
362 print "*** $class installation finished.\n";
364 # see if we have successfully installed them
365 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
366 if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
367 push @installed, $pkg;
369 elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
370 print FAILED "$pkg\n";
374 close FAILED if $args{do_once};
379 sub _install_cpanplus {
380 my @modules = @{ +shift };
381 my @config = _cpanplus_config( @{ +shift } );
384 require CPANPLUS::Backend;
385 my $cp = CPANPLUS::Backend->new;
386 my $conf = $cp->configure_object;
388 return unless $conf->can('conf') # 0.05x+ with "sudo" support
389 or _can_write($conf->_get_build('base')); # 0.04x
391 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
392 my $makeflags = $conf->get_conf('makeflags') || '';
393 if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
394 # 0.03+ uses a hashref here
395 $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
398 # 0.02 and below uses a scalar
399 $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
400 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
403 $conf->set_conf( makeflags => $makeflags );
404 $conf->set_conf( prereqs => 1 );
408 while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
409 $conf->set_conf( $key, $val );
412 my $modtree = $cp->module_tree;
413 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
414 print "*** Installing $pkg...\n";
416 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
419 my $obj = $modtree->{$pkg};
421 if ( $obj and _version_cmp( $obj->{version}, $ver ) >= 0 ) {
423 $pathname =~ s/::/\\W/;
425 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
429 my $rv = $cp->install( modules => [ $obj->{module} ] );
431 if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
432 print "*** $pkg successfully installed.\n";
435 print "*** $pkg installation cancelled.\n";
439 $installed += $success;
442 *** Could not find a version $ver or above for $pkg; skipping.
446 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
452 sub _cpanplus_config {
455 my ($key, $value) = (shift(), shift());
456 if ( $key eq 'prerequisites_policy' ) {
457 if ( $value eq 'follow' ) {
458 $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
459 } elsif ( $value eq 'ask' ) {
460 $value = CPANPLUS::Internals::Constants::PREREQ_ASK();
461 } elsif ( $value eq 'ignore' ) {
462 $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
464 die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
467 die "*** Cannot convert option $key to CPANPLUS version.\n";
474 my @modules = @{ +shift };
475 my @config = @{ +shift };
482 if (CPAN->VERSION < 1.80) {
483 # no "sudo" support, probe for writableness
484 return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
485 and _can_write( $Config::Config{sitelib} );
488 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
489 my $makeflags = $CPAN::Config->{make_install_arg} || '';
490 $CPAN::Config->{make_install_arg} =
491 join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
492 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
494 # don't show start-up info
495 $CPAN::Config->{inhibit_startup_message} = 1;
497 # set additional options
498 while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
499 ( $args{$opt} = $arg, next )
500 if $opt =~ /^force$/; # pseudo-option
501 $CPAN::Config->{$opt} = $arg;
504 local $CPAN::Config->{prerequisites_policy} = 'follow';
506 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
507 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
509 print "*** Installing $pkg...\n";
511 my $obj = CPAN::Shell->expand( Module => $pkg );
514 if ( $obj and _version_cmp( $obj->cpan_version, $ver ) >= 0 ) {
516 $pathname =~ s/::/\\W/;
518 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
522 my $rv = $args{force} ? CPAN::Shell->force( install => $pkg )
523 : CPAN::Shell->install($pkg);
525 $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
530 if ( $rv eq 'YES' ) {
531 print "*** $pkg successfully installed.\n";
535 print "*** $pkg installation failed.\n";
539 $installed += $success;
543 *** Could not find a version $ver or above for $pkg; skipping.
547 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
556 $INC{'CPANPLUS/Config.pm'}
557 or _load('CPANPLUS::Shell::Default')
562 # make guesses on whether we're under the CPAN installation directory
567 my $cwd = File::Spec->canonpath( Cwd::cwd() );
568 my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
570 return ( index( $cwd, $cpan ) > -1 );
574 my $class = __PACKAGE__;
578 if _version_cmp( _load($class), $ver ) >= 0; # no need to upgrade
581 _prompt( "==> A newer version of $class ($ver) is required. Install?",
585 die "*** Please install $class $ver manually.\n";
589 *** Trying to fetch it from CPAN...
593 _load($class) and return $class->import(@_)
594 if $class->install( [], $class, $ver );
596 print << '.'; exit 1;
598 *** Cannot bootstrap myself. :-( Installation terminated.
602 # check if we're connected to some host, using inet_aton
607 ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
609 *** Your host cannot resolve the domain name '$site', which
610 probably means the Internet connections are unavailable.
611 ==> Should we try to install the required module(s) anyway?), 'n'
616 # check if a directory is writable; may create it on demand
619 mkdir( $path, 0755 ) unless -e $path;
621 return 1 if -w $path;
624 *** You are not allowed to write to the directory '$path';
625 the installation may fail due to insufficient permissions.
629 eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
631 ==> Should we try to re-execute the autoinstall process with 'sudo'?),
632 ((-t STDIN) ? 'y' : 'n')
637 # try to bootstrap ourselves from sudo
639 *** Trying to re-execute the autoinstall process with 'sudo'...
641 my $missing = join( ',', @Missing );
642 my $config = join( ',',
643 UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
647 unless system( 'sudo', $^X, $0, "--config=$config",
648 "--installdeps=$missing" );
651 *** The 'sudo' command exited with error! Resuming...
657 ==> Should we try to install the required module(s) anyway?), 'n'
661 # load a module and return the version it reports
663 my $mod = pop; # class/instance doesn't matter
670 return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
673 # Load CPAN.pm and it's configuration
675 return if $CPAN::VERSION and $CPAN::Config and not @_;
678 # CPAN-1.82+ adds CPAN::Config::AUTOLOAD to redirect to
679 # CPAN::HandleConfig->load. CPAN reports that the redirection
680 # is deprecated in a warning printed at the user.
682 # CPAN-1.81 expects CPAN::HandleConfig->load, does not have
683 # $CPAN::HandleConfig::VERSION but cannot handle
686 # Which "versions expect CPAN::Config->load?
688 if ( $CPAN::HandleConfig::VERSION
689 || CPAN::HandleConfig->can('load')
691 # Newer versions of CPAN have a HandleConfig module
692 CPAN::HandleConfig->load;
694 # Older versions had the load method in Config directly
699 # compare two versions, either use Sort::Versions or plain comparison
700 # return values same as <=>
702 my ( $cur, $min ) = @_;
703 return -1 unless defined $cur; # if 0 keep comparing
704 return 1 unless $min;
708 # check for version numbers that are not in decimal format
709 if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
710 if ( ( $version::VERSION or defined( _load('version') )) and
714 # use version.pm if it is installed.
715 return version->new($cur) <=> version->new($min);
717 elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
720 # use Sort::Versions as the sorting algorithm for a.b.c versions
721 return Sort::Versions::versioncmp( $cur, $min );
724 warn "Cannot reliably compare non-decimal formatted versions.\n"
725 . "Please install version.pm or Sort::Versions.\n";
729 local $^W = 0; # shuts off 'not numeric' bugs
730 return $cur <=> $min;
733 # nothing; this usage is deprecated.
734 sub main::PREREQ_PM { return {}; }
739 $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
740 if $UnderCPAN or $TestOnly;
742 if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
743 require ExtUtils::Manifest;
744 my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
747 [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
750 $args{test}{TESTS} ||= 't/*.t';
751 $args{test}{TESTS} = join( ' ',
752 grep { !exists( $DisabledTests{$_} ) }
753 map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
755 my $missing = join( ',', @Missing );
757 join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
760 $PostambleActions = (
761 ($missing and not $UnderCPAN)
762 ? "\$(PERL) $0 --config=$config --installdeps=$missing"
763 : "\$(NOECHO) \$(NOOP)"
769 # a wrapper to ExtUtils::MakeMaker::WriteMakefile
772 Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
776 *** Makefile not written in check-only mode.
781 my %args = _make_args(@_);
786 local *MY::postamble = \&postamble unless defined &MY::postamble;
787 ExtUtils::MakeMaker::WriteMakefile(%args);
789 print << "." unless $PostambleUsed;
790 *** WARNING: Makefile written with customized MY::postamble() without
791 including contents from Module::AutoInstall::postamble() --
792 auto installation features disabled. Please contact the author.
803 config :: installdeps
804 \t\$(NOECHO) \$(NOOP)
807 \t\$(PERL) $0 --checkdeps