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 );
21 my ( $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly );
22 my ( $PostambleActions, $PostambleUsed );
24 # See if it's a testing or non-interactive session
25 _accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN );
29 $AcceptDefault = shift;
40 ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
47 # initialize various flags, and/or perform install
53 $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''
57 if ( $arg =~ /^--config=(.*)$/ ) {
58 $Config = [ split( ',', $1 ) ];
60 elsif ( $arg =~ /^--installdeps=(.*)$/ ) {
61 __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
64 elsif ( $arg =~ /^--default(?:deps)?$/ ) {
67 elsif ( $arg =~ /^--check(?:deps)?$/ ) {
70 elsif ( $arg =~ /^--skip(?:deps)?$/ ) {
73 elsif ( $arg =~ /^--test(?:only)?$/ ) {
79 # overrides MakeMaker's prompt() to automatically accept the default choice
81 goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
83 my ( $prompt, $default ) = @_;
84 my $y = ( $default =~ /^[Yy]/ );
86 print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] ';
94 my @args = @_ or return;
97 print "*** $class version " . $class->VERSION . "\n";
98 print "*** Checking for Perl dependencies...\n";
100 my $cwd = Cwd::cwd();
106 sort { length($b) <=> length($a) }
110 ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} )
113 map { +{@args}->{$_} }
114 grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} }
118 while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) {
119 my ( @required, @tests, @skiptests );
123 if ( $feature =~ m/^-(\w+)$/ ) {
126 # check for a newer version of myself
127 _update_to( $modules, @_ ) and return if $option eq 'version';
129 # sets CPAN configuration options
130 $Config = $modules if $option eq 'config';
132 # promote every features to core status
133 $core_all = ( $modules =~ /^all$/i ) and next
134 if $option eq 'core';
136 next unless $option eq 'core';
139 print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n";
141 $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' );
143 unshift @$modules, -default => &{ shift(@$modules) }
144 if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability
146 while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) {
147 if ( $mod =~ m/^-(\w+)$/ ) {
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' );
158 printf( "- %-${maxlen}s ...", $mod );
160 if ( $arg and $arg =~ /^\D/ ) {
161 unshift @$modules, $arg;
165 # XXX: check for conflicts and uninstalls(!) them.
167 defined( my $cur = _version_check( _load($mod), $arg ||= 0 ) ) )
169 print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n";
170 push @Existing, $mod => $arg;
171 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
174 print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n";
175 push @required, $mod => $arg;
179 next unless @required;
181 my $mandatory = ( $feature eq '-core' or $core_all );
188 qq{==> Auto-install the }
190 . ( $mandatory ? ' mandatory' : ' optional' )
191 . qq{ module(s) from CPAN?},
192 $default ? 'y' : 'n',
197 push( @Missing, @required );
198 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
201 elsif ( !$SkipInstall
205 _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', )
208 push( @Missing, @required );
209 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
213 $DisabledTests{$_} = 1 for map { glob($_) } @tests;
217 $UnderCPAN = _check_lock(); # check for $UnderCPAN
219 if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) {
222 "*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n";
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"
228 print "*** $class configuration finished.\n";
234 *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
237 # Check to see if we are currently running under CPAN.pm and/or CPANPLUS;
238 # if we are, then we simply let it taking care of our dependencies
240 return unless @Missing;
242 if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) {
243 print <<'END_MESSAGE';
245 *** Since we're running under CPANPLUS, I'll just let it take care
246 of the dependency's installation later.
253 # Find the CPAN lock-file
254 my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
255 return unless -f $lock;
259 return unless open(LOCK, $lock);
262 ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
263 and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
265 print <<'END_MESSAGE';
267 *** Since we're running under CPAN, I'll just let it take care
268 of the dependency's installation later.
280 my $i; # used below to strip leading '-' from config keys
281 my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
283 my ( @modules, @installed );
284 while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) {
286 # grep out those already installed
287 if ( defined( _version_check( _load($pkg), $ver ) ) ) {
288 push @installed, $pkg;
291 push @modules, $pkg, $ver;
295 return @installed unless @modules; # nothing to do
296 return @installed if _check_lock(); # defer to the CPAN shell
298 print "*** Installing dependencies...\n";
300 return unless _connected_to('cpan.org');
305 if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
306 while (<FAILED>) { chomp; $failed{$_}++ }
310 while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
311 push @newmod, ( $k => $v ) unless $failed{$k};
316 if ( _has_cpanplus() ) {
317 _install_cpanplus( \@modules, \@config );
319 _install_cpan( \@modules, \@config );
322 print "*** $class installation finished.\n";
324 # see if we have successfully installed them
325 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
326 if ( defined( _version_check( _load($pkg), $ver ) ) ) {
327 push @installed, $pkg;
329 elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
330 print FAILED "$pkg\n";
334 close FAILED if $args{do_once};
339 sub _install_cpanplus {
340 my @modules = @{ +shift };
341 my @config = _cpanplus_config( @{ +shift } );
344 require CPANPLUS::Backend;
345 my $cp = CPANPLUS::Backend->new;
346 my $conf = $cp->configure_object;
348 return unless $conf->can('conf') # 0.05x+ with "sudo" support
349 or _can_write($conf->_get_build('base')); # 0.04x
351 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
352 my $makeflags = $conf->get_conf('makeflags') || '';
353 if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
354 # 0.03+ uses a hashref here
355 $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
358 # 0.02 and below uses a scalar
359 $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
360 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
363 $conf->set_conf( makeflags => $makeflags );
364 $conf->set_conf( prereqs => 1 );
368 while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
369 $conf->set_conf( $key, $val );
372 my $modtree = $cp->module_tree;
373 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
374 print "*** Installing $pkg...\n";
376 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
379 my $obj = $modtree->{$pkg};
381 if ( $obj and defined( _version_check( $obj->{version}, $ver ) ) ) {
383 $pathname =~ s/::/\\W/;
385 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
389 my $rv = $cp->install( modules => [ $obj->{module} ] );
391 if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
392 print "*** $pkg successfully installed.\n";
395 print "*** $pkg installation cancelled.\n";
399 $installed += $success;
402 *** Could not find a version $ver or above for $pkg; skipping.
406 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
412 sub _cpanplus_config {
415 my ($key, $value) = (shift(), shift());
416 if ( $key eq 'prerequisites_policy' ) {
417 if ( $value eq 'follow' ) {
418 $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
419 } elsif ( $value eq 'ask' ) {
420 $value = CPANPLUS::Internals::Constants::PREREQ_ASK();
421 } elsif ( $value eq 'ignore' ) {
422 $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
424 die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
427 die "*** Cannot convert option $key to CPANPLUS version.\n";
434 my @modules = @{ +shift };
435 my @config = @{ +shift };
442 if (CPAN->VERSION < 1.80) {
443 # no "sudo" support, probe for writableness
444 return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
445 and _can_write( $Config::Config{sitelib} );
448 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
449 my $makeflags = $CPAN::Config->{make_install_arg} || '';
450 $CPAN::Config->{make_install_arg} =
451 join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
452 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
454 # don't show start-up info
455 $CPAN::Config->{inhibit_startup_message} = 1;
457 # set additional options
458 while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
459 ( $args{$opt} = $arg, next )
460 if $opt =~ /^force$/; # pseudo-option
461 $CPAN::Config->{$opt} = $arg;
464 local $CPAN::Config->{prerequisites_policy} = 'follow';
466 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
467 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
469 print "*** Installing $pkg...\n";
471 my $obj = CPAN::Shell->expand( Module => $pkg );
474 if ( $obj and defined( _version_check( $obj->cpan_version, $ver ) ) ) {
476 $pathname =~ s/::/\\W/;
478 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
482 my $rv = $args{force} ? CPAN::Shell->force( install => $pkg )
483 : CPAN::Shell->install($pkg);
485 $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
490 if ( $rv eq 'YES' ) {
491 print "*** $pkg successfully installed.\n";
495 print "*** $pkg installation failed.\n";
499 $installed += $success;
503 *** Could not find a version $ver or above for $pkg; skipping.
507 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
516 $INC{'CPANPLUS/Config.pm'}
517 or _load('CPANPLUS::Shell::Default')
522 # make guesses on whether we're under the CPAN installation directory
527 my $cwd = File::Spec->canonpath( Cwd::cwd() );
528 my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
530 return ( index( $cwd, $cpan ) > -1 );
534 my $class = __PACKAGE__;
538 if defined( _version_check( _load($class), $ver ) ); # no need to upgrade
541 _prompt( "==> A newer version of $class ($ver) is required. Install?",
545 die "*** Please install $class $ver manually.\n";
549 *** Trying to fetch it from CPAN...
553 _load($class) and return $class->import(@_)
554 if $class->install( [], $class, $ver );
556 print << '.'; exit 1;
558 *** Cannot bootstrap myself. :-( Installation terminated.
562 # check if we're connected to some host, using inet_aton
567 ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
569 *** Your host cannot resolve the domain name '$site', which
570 probably means the Internet connections are unavailable.
571 ==> Should we try to install the required module(s) anyway?), 'n'
576 # check if a directory is writable; may create it on demand
579 mkdir( $path, 0755 ) unless -e $path;
581 return 1 if -w $path;
584 *** You are not allowed to write to the directory '$path';
585 the installation may fail due to insufficient permissions.
589 eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
591 ==> Should we try to re-execute the autoinstall process with 'sudo'?),
592 ((-t STDIN) ? 'y' : 'n')
597 # try to bootstrap ourselves from sudo
599 *** Trying to re-execute the autoinstall process with 'sudo'...
601 my $missing = join( ',', @Missing );
602 my $config = join( ',',
603 UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
607 unless system( 'sudo', $^X, $0, "--config=$config",
608 "--installdeps=$missing" );
611 *** The 'sudo' command exited with error! Resuming...
617 ==> Should we try to install the required module(s) anyway?), 'n'
621 # load a module and return the version it reports
623 my $mod = pop; # class/instance doesn't matter
630 return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
633 # Load CPAN.pm and it's configuration
635 return if $CPAN::VERSION;
637 if ( $CPAN::HandleConfig::VERSION ) {
638 # Newer versions of CPAN have a HandleConfig module
639 CPAN::HandleConfig->load;
641 # Older versions had the load method in Config directly
646 # compare two versions, either use Sort::Versions or plain comparison
648 my ( $cur, $min ) = @_;
649 return unless defined $cur;
653 # check for version numbers that are not in decimal format
654 if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
655 if ( ( $version::VERSION or defined( _load('version') )) and
659 # use version.pm if it is installed.
661 ( version->new($cur) >= version->new($min) ) ? $cur : undef );
663 elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
666 # use Sort::Versions as the sorting algorithm for a.b.c versions
667 return ( ( Sort::Versions::versioncmp( $cur, $min ) != -1 )
672 warn "Cannot reliably compare non-decimal formatted versions.\n"
673 . "Please install version.pm or Sort::Versions.\n";
677 local $^W = 0; # shuts off 'not numeric' bugs
678 return ( $cur >= $min ? $cur : undef );
681 # nothing; this usage is deprecated.
682 sub main::PREREQ_PM { return {}; }
687 $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
688 if $UnderCPAN or $TestOnly;
690 if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
691 require ExtUtils::Manifest;
692 my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
695 [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
698 $args{test}{TESTS} ||= 't/*.t';
699 $args{test}{TESTS} = join( ' ',
700 grep { !exists( $DisabledTests{$_} ) }
701 map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
703 my $missing = join( ',', @Missing );
705 join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
708 $PostambleActions = (
710 ? "\$(PERL) $0 --config=$config --installdeps=$missing"
711 : "\$(NOECHO) \$(NOOP)"
717 # a wrapper to ExtUtils::MakeMaker::WriteMakefile
720 Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
724 *** Makefile not written in check-only mode.
729 my %args = _make_args(@_);
734 local *MY::postamble = \&postamble unless defined &MY::postamble;
735 ExtUtils::MakeMaker::WriteMakefile(%args);
737 print << "." unless $PostambleUsed;
738 *** WARNING: Makefile written with customized MY::postamble() without
739 including contents from Module::AutoInstall::postamble() --
740 auto installation features disabled. Please contact the author.
751 config :: installdeps
752 \t\$(NOECHO) \$(NOOP)
755 \t\$(PERL) $0 --checkdeps