2 package Module::AutoInstall;
7 use ExtUtils::MakeMaker ();
14 # special map on pre-defined feature sets
16 '' => 'Core Features', # XXX: deprecated
17 '-core' => 'Core Features',
20 # various lexical flags
21 my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $InstallDepsTarget, $HasCPANPLUS );
23 $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly, $AllDeps,
26 my ( $PostambleActions, $PostambleActionsNoTest, $PostambleActionsUpgradeDeps,
27 $PostambleActionsUpgradeDepsNoTest, $PostambleActionsListDeps,
28 $PostambleActionsListAllDeps, $PostambleUsed, $NoTest);
30 # See if it's a testing or non-interactive session
31 _accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN );
35 $AcceptDefault = shift;
38 sub _installdeps_target {
39 $InstallDepsTarget = shift;
50 ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
57 # initialize various flags, and/or perform install
63 $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''
67 if ( $arg =~ /^--config=(.*)$/ ) {
68 $Config = [ split( ',', $1 ) ];
70 elsif ( $arg =~ /^--installdeps=(.*)$/ ) {
71 __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
74 elsif ( $arg =~ /^--upgradedeps=(.*)$/ ) {
76 __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
79 elsif ( $arg =~ /^--default(?:deps)?$/ ) {
82 elsif ( $arg =~ /^--check(?:deps)?$/ ) {
85 elsif ( $arg =~ /^--skip(?:deps)?$/ ) {
88 elsif ( $arg =~ /^--test(?:only)?$/ ) {
91 elsif ( $arg =~ /^--all(?:deps)?$/ ) {
97 # overrides MakeMaker's prompt() to automatically accept the default choice
99 goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
101 my ( $prompt, $default ) = @_;
102 my $y = ( $default =~ /^[Yy]/ );
104 print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] ';
112 my @args = @_ or return;
115 print "*** $class version " . $class->VERSION . "\n";
116 print "*** Checking for Perl dependencies...\n";
118 my $cwd = Cwd::getcwd();
124 sort { length($b) <=> length($a) }
128 ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} )
131 map { +{@args}->{$_} }
132 grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} }
136 # We want to know if we're under CPAN early to avoid prompting, but
137 # if we aren't going to try and install anything anyway then skip the
138 # check entirely since we don't want to have to load (and configure)
139 # an old CPAN just for a cosmetic message
141 $UnderCPAN = _check_lock(1) unless $SkipInstall || $InstallDepsTarget;
143 while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) {
144 my ( @required, @tests, @skiptests );
148 if ( $feature =~ m/^-(\w+)$/ ) {
151 # check for a newer version of myself
152 _update_to( $modules, @_ ) and return if $option eq 'version';
154 # sets CPAN configuration options
155 $Config = $modules if $option eq 'config';
157 # promote every features to core status
158 $core_all = ( $modules =~ /^all$/i ) and next
159 if $option eq 'core';
161 next unless $option eq 'core';
164 print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n";
166 $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' );
168 unshift @$modules, -default => &{ shift(@$modules) }
169 if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward compatibility
171 while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) {
172 if ( $mod =~ m/^-(\w+)$/ ) {
175 $default = $arg if ( $option eq 'default' );
176 $conflict = $arg if ( $option eq 'conflict' );
177 @tests = @{$arg} if ( $option eq 'tests' );
178 @skiptests = @{$arg} if ( $option eq 'skiptests' );
183 printf( "- %-${maxlen}s ...", $mod );
185 if ( $arg and $arg =~ /^\D/ ) {
186 unshift @$modules, $arg;
190 # XXX: check for conflicts and uninstalls(!) them.
191 my $cur = _version_of($mod);
192 if (_version_cmp ($cur, $arg) >= 0)
194 print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n";
195 push @Existing, $mod => $arg;
196 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
199 if (not defined $cur) # indeed missing
201 print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n";
205 # no need to check $arg as _version_cmp ($cur, undef) would satisfy >= above
206 print "too old. ($cur < $arg)\n";
209 push @required, $mod => $arg;
213 next unless @required;
215 my $mandatory = ( $feature eq '-core' or $core_all );
221 or ($mandatory and $UnderCPAN)
223 or $InstallDepsTarget
225 qq{==> Auto-install the }
227 . ( $mandatory ? ' mandatory' : ' optional' )
228 . qq{ module(s) from CPAN?},
229 $default ? 'y' : 'n',
234 push( @Missing, @required );
235 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
238 elsif ( !$SkipInstall
242 _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', )
245 push( @Missing, @required );
246 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
250 $DisabledTests{$_} = 1 for map { glob($_) } @tests;
254 if ( @Missing and not( $CheckOnly or $UnderCPAN) ) {
256 my $make = $Config::Config{make};
257 if ($InstallDepsTarget) {
259 "*** To install dependencies type '$make installdeps' or '$make installdeps_notest'.\n";
263 "*** Dependencies will be installed the next time you type '$make'.\n";
266 # make an educated guess of whether we'll need root permission.
267 print " (You may need to do that as the 'root' user.)\n"
270 print "*** $class configuration finished.\n";
276 *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
278 return (@Existing, @Missing);
283 print <<"END_MESSAGE";
284 *** Since we're running under ${thing}, I'll just let it take care
285 of the dependency's installation later.
290 # Check to see if we are currently running under CPAN.pm and/or CPANPLUS;
291 # if we are, then we simply let it taking care of our dependencies
293 return unless @Missing or @_;
295 if ($ENV{PERL5_CPANM_IS_RUNNING}) {
296 return _running_under('cpanminus');
299 my $cpan_env = $ENV{PERL5_CPAN_IS_RUNNING};
301 if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) {
302 return _running_under($cpan_env ? 'CPAN' : 'CPANPLUS');
307 if ($CPAN::VERSION > '1.89') {
309 return _running_under('CPAN');
311 return; # CPAN.pm new enough, don't need to check further
314 # last ditch attempt, this -will- configure CPAN, very sorry
316 _load_cpan(1); # force initialize even though it's already loaded
318 # Find the CPAN lock-file
319 my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
320 return unless -f $lock;
324 return unless open(LOCK, $lock);
327 ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
328 and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
330 print <<'END_MESSAGE';
332 *** Since we're running under CPAN, I'll just let it take care
333 of the dependency's installation later.
345 my $i; # used below to strip leading '-' from config keys
346 my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
348 my ( @modules, @installed, @modules_to_upgrade );
349 while (my ($pkg, $ver) = splice(@_, 0, 2)) {
351 # grep out those already installed
352 if (_version_cmp(_version_of($pkg), $ver) >= 0) {
353 push @installed, $pkg;
355 push @modules_to_upgrade, $pkg, $ver;
359 push @modules, $pkg, $ver;
364 push @modules, @modules_to_upgrade;
366 @modules_to_upgrade = ();
369 return @installed unless @modules; # nothing to do
370 return @installed if _check_lock(); # defer to the CPAN shell
372 print "*** Installing dependencies...\n";
374 return unless _connected_to('cpan.org');
379 if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
380 while (<FAILED>) { chomp; $failed{$_}++ }
384 while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
385 push @newmod, ( $k => $v ) unless $failed{$k};
390 if ( _has_cpanplus() and not $ENV{PERL_AUTOINSTALL_PREFER_CPAN} ) {
391 _install_cpanplus( \@modules, \@config );
393 _install_cpan( \@modules, \@config );
396 print "*** $class installation finished.\n";
398 # see if we have successfully installed them
399 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
400 if ( _version_cmp( _version_of($pkg), $ver ) >= 0 ) {
401 push @installed, $pkg;
403 elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
404 print FAILED "$pkg\n";
408 close FAILED if $args{do_once};
413 sub _install_cpanplus {
414 my @modules = @{ +shift };
415 my @config = _cpanplus_config( @{ +shift } );
418 require CPANPLUS::Backend;
419 my $cp = CPANPLUS::Backend->new;
420 my $conf = $cp->configure_object;
422 return unless $conf->can('conf') # 0.05x+ with "sudo" support
423 or _can_write($conf->_get_build('base')); # 0.04x
425 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
426 my $makeflags = $conf->get_conf('makeflags') || '';
427 if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
428 # 0.03+ uses a hashref here
429 $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
432 # 0.02 and below uses a scalar
433 $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
434 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
437 $conf->set_conf( makeflags => $makeflags );
438 $conf->set_conf( prereqs => 1 );
442 while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
443 $conf->set_conf( $key, $val );
446 my $modtree = $cp->module_tree;
447 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
448 print "*** Installing $pkg...\n";
450 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
453 my $obj = $modtree->{$pkg};
455 if ( $obj and _version_cmp( $obj->{version}, $ver ) >= 0 ) {
457 $pathname =~ s/::/\\W/;
459 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
463 my $rv = $cp->install( modules => [ $obj->{module} ] );
465 if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
466 print "*** $pkg successfully installed.\n";
469 print "*** $pkg installation cancelled.\n";
473 $installed += $success;
476 *** Could not find a version $ver or above for $pkg; skipping.
480 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
486 sub _cpanplus_config {
489 my ($key, $value) = (shift(), shift());
490 if ( $key eq 'prerequisites_policy' ) {
491 if ( $value eq 'follow' ) {
492 $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
493 } elsif ( $value eq 'ask' ) {
494 $value = CPANPLUS::Internals::Constants::PREREQ_ASK();
495 } elsif ( $value eq 'ignore' ) {
496 $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
498 die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
500 push @config, 'prereqs', $value;
501 } elsif ( $key eq 'force' ) {
502 push @config, $key, $value;
503 } elsif ( $key eq 'notest' ) {
504 push @config, 'skiptest', $value;
506 die "*** Cannot convert option $key to CPANPLUS version.\n";
513 my @modules = @{ +shift };
514 my @config = @{ +shift };
521 if (CPAN->VERSION < 1.80) {
522 # no "sudo" support, probe for writableness
523 return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
524 and _can_write( $Config::Config{sitelib} );
527 # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
528 my $makeflags = $CPAN::Config->{make_install_arg} || '';
529 $CPAN::Config->{make_install_arg} =
530 join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
531 if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
533 # don't show start-up info
534 $CPAN::Config->{inhibit_startup_message} = 1;
536 # set additional options
537 while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
538 ( $args{$opt} = $arg, next )
539 if $opt =~ /^(?:force|notest)$/; # pseudo-option
540 $CPAN::Config->{$opt} = $opt eq 'urllist' ? [$arg] : $arg;
543 if ($args{notest} && (not CPAN::Shell->can('notest'))) {
544 die "Your version of CPAN is too old to support the 'notest' pragma";
547 local $CPAN::Config->{prerequisites_policy} = 'follow';
549 while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
550 MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
552 print "*** Installing $pkg...\n";
554 my $obj = CPAN::Shell->expand( Module => $pkg );
557 if ( $obj and _version_cmp( $obj->cpan_version, $ver ) >= 0 ) {
559 $pathname =~ s/::/\\W/;
561 foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
567 CPAN::Shell->force( install => $pkg )
568 } elsif ($args{notest}) {
569 CPAN::Shell->notest( install => $pkg )
571 CPAN::Shell->install($pkg)
576 $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
581 if ( $rv eq 'YES' ) {
582 print "*** $pkg successfully installed.\n";
586 print "*** $pkg installation failed.\n";
590 $installed += $success;
594 *** Could not find a version $ver or above for $pkg; skipping.
598 MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
607 $INC{'CPANPLUS/Config.pm'}
608 or _load('CPANPLUS::Shell::Default')
613 # make guesses on whether we're under the CPAN installation directory
618 my $cwd = File::Spec->canonpath( Cwd::getcwd() );
619 my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
621 return ( index( $cwd, $cpan ) > -1 );
625 my $class = __PACKAGE__;
629 if _version_cmp( _version_of($class), $ver ) >= 0; # no need to upgrade
632 _prompt( "==> A newer version of $class ($ver) is required. Install?",
636 die "*** Please install $class $ver manually.\n";
640 *** Trying to fetch it from CPAN...
644 _load($class) and return $class->import(@_)
645 if $class->install( [], $class, $ver );
647 print << '.'; exit 1;
649 *** Cannot bootstrap myself. :-( Installation terminated.
653 # check if we're connected to some host, using inet_aton
658 ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
660 *** Your host cannot resolve the domain name '$site', which
661 probably means the Internet connections are unavailable.
662 ==> Should we try to install the required module(s) anyway?), 'n'
667 # check if a directory is writable; may create it on demand
670 mkdir( $path, 0755 ) unless -e $path;
672 return 1 if -w $path;
675 *** You are not allowed to write to the directory '$path';
676 the installation may fail due to insufficient permissions.
680 eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
682 ==> Should we try to re-execute the autoinstall process with 'sudo'?),
683 ((-t STDIN) ? 'y' : 'n')
688 # try to bootstrap ourselves from sudo
690 *** Trying to re-execute the autoinstall process with 'sudo'...
692 my $missing = join( ',', @Missing );
693 my $config = join( ',',
694 UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
698 unless system( 'sudo', $^X, $0, "--config=$config",
699 "--installdeps=$missing" );
702 *** The 'sudo' command exited with error! Resuming...
708 ==> Should we try to install the required module(s) anyway?), 'n'
712 # load a module and return the version it reports
714 my $mod = pop; # method/function doesn't matter
719 return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
722 # report version without loading a module
724 my $mod = pop; # method/function doesn't matter
728 foreach my $dir ( @INC ) {
730 my $path = File::Spec->catfile($dir, $file);
731 next unless -e $path;
732 require ExtUtils::MM_Unix;
733 return ExtUtils::MM_Unix->parse_version($path);
738 # Load CPAN.pm and it's configuration
740 return if $CPAN::VERSION and $CPAN::Config and not @_;
743 # CPAN-1.82+ adds CPAN::Config::AUTOLOAD to redirect to
744 # CPAN::HandleConfig->load. CPAN reports that the redirection
745 # is deprecated in a warning printed at the user.
747 # CPAN-1.81 expects CPAN::HandleConfig->load, does not have
748 # $CPAN::HandleConfig::VERSION but cannot handle
751 # Which "versions expect CPAN::Config->load?
753 if ( $CPAN::HandleConfig::VERSION
754 || CPAN::HandleConfig->can('load')
756 # Newer versions of CPAN have a HandleConfig module
757 CPAN::HandleConfig->load;
759 # Older versions had the load method in Config directly
764 # compare two versions, either use Sort::Versions or plain comparison
765 # return values same as <=>
767 my ( $cur, $min ) = @_;
768 return -1 unless defined $cur; # if 0 keep comparing
769 return 1 unless $min;
773 # check for version numbers that are not in decimal format
774 if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
775 if ( ( $version::VERSION or defined( _load('version') )) and
779 # use version.pm if it is installed.
780 return version->new($cur) <=> version->new($min);
782 elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
785 # use Sort::Versions as the sorting algorithm for a.b.c versions
786 return Sort::Versions::versioncmp( $cur, $min );
789 warn "Cannot reliably compare non-decimal formatted versions.\n"
790 . "Please install version.pm or Sort::Versions.\n";
794 local $^W = 0; # shuts off 'not numeric' bugs
795 return $cur <=> $min;
798 # nothing; this usage is deprecated.
799 sub main::PREREQ_PM { return {}; }
804 $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
805 if $UnderCPAN or $TestOnly;
807 if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
808 require ExtUtils::Manifest;
809 my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
812 [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
815 $args{test}{TESTS} ||= 't/*.t';
816 $args{test}{TESTS} = join( ' ',
817 grep { !exists( $DisabledTests{$_} ) }
818 map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
820 my $missing = join( ',', @Missing );
822 join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
825 $PostambleActions = (
826 ($missing and not $UnderCPAN)
827 ? "\$(PERL) $0 --config=$config --installdeps=$missing"
828 : "\$(NOECHO) \$(NOOP)"
831 my $deps_list = join( ',', @Missing, @Existing );
833 $PostambleActionsUpgradeDeps =
834 "\$(PERL) $0 --config=$config --upgradedeps=$deps_list";
837 join( ',', (UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config}),
841 $PostambleActionsNoTest = (
842 ($missing and not $UnderCPAN)
843 ? "\$(PERL) $0 --config=$config_notest --installdeps=$missing"
844 : "\$(NOECHO) \$(NOOP)"
847 $PostambleActionsUpgradeDepsNoTest =
848 "\$(PERL) $0 --config=$config_notest --upgradedeps=$deps_list";
850 $PostambleActionsListDeps =
851 '@$(PERL) -le "print for @ARGV" '
852 . join(' ', map $Missing[$_], grep $_ % 2 == 0, 0..$#Missing);
854 my @all = (@Missing, @Existing);
856 $PostambleActionsListAllDeps =
857 '@$(PERL) -le "print for @ARGV" '
858 . join(' ', map $all[$_], grep $_ % 2 == 0, 0..$#all);
863 # a wrapper to ExtUtils::MakeMaker::WriteMakefile
866 Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
870 *** Makefile not written in check-only mode.
875 my %args = _make_args(@_);
880 local *MY::postamble = \&postamble unless defined &MY::postamble;
881 ExtUtils::MakeMaker::WriteMakefile(%args);
883 print << "." unless $PostambleUsed;
884 *** WARNING: Makefile written with customized MY::postamble() without
885 including contents from Module::AutoInstall::postamble() --
886 auto installation features disabled. Please contact the author.
896 $fragment .= <<"AUTO_INSTALL" if !$InstallDepsTarget;
898 config :: installdeps
899 \t\$(NOECHO) \$(NOOP)
902 $fragment .= <<"END_MAKE";
905 \t\$(PERL) $0 --checkdeps
910 installdeps_notest ::
911 \t$PostambleActionsNoTest
914 \t$PostambleActionsUpgradeDeps
916 upgradedeps_notest ::
917 \t$PostambleActionsUpgradeDepsNoTest
920 \t$PostambleActionsListDeps
923 \t$PostambleActionsListAllDeps