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