root/XML-Atom-0.22/inc/ExtUtils/AutoInstall.pm

Revision 397, 17.7 kB (checked in by miya, 2 years ago)

--

Line 
1 #line 1
2 # $File: //member/autrijus/ExtUtils-AutoInstall/lib/ExtUtils/AutoInstall.pm $
3 # $Revision: #14 $ $Change: 10538 $ $DateTime: 2004/04/29 17:55:36 $ vim: expandtab shiftwidth=4
4
5 package ExtUtils::AutoInstall;
6 $ExtUtils::AutoInstall::VERSION = '0.59';
7
8 use strict;
9 use Cwd ();
10 use ExtUtils::MakeMaker ();
11
12 #line 307
13
14 # special map on pre-defined feature sets
15 my %FeatureMap = (
16     ''      => 'Core Features', # XXX: deprecated
17     '-core' => 'Core Features',
18 );
19
20 # various lexical flags
21 my (@Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS);
22 my ($Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly);
23 my ($PostambleActions, $PostambleUsed);
24
25 _accept_default(!-t STDIN); # see if it's a non-interactive session
26 _init();
27
28 sub _accept_default {
29     $AcceptDefault = shift;
30 }
31
32 sub missing_modules {
33     return @Missing;
34 }
35
36 sub do_install {
37     __PACKAGE__->install(
38         [ UNIVERSAL::isa($Config, 'HASH') ? %{$Config} : @{$Config}],
39         @Missing,
40     );
41 }
42
43 # initialize various flags, and/or perform install
44 sub _init {
45     foreach my $arg (@ARGV, split(/[\s\t]+/, $ENV{PERL_EXTUTILS_AUTOINSTALL} || '')) {
46         if ($arg =~ /^--config=(.*)$/) {
47             $Config = [ split(',', $1) ];
48         }
49         elsif ($arg =~ /^--installdeps=(.*)$/) {
50             __PACKAGE__->install($Config, @Missing = split(/,/, $1));
51             exit 0;
52         }
53         elsif ($arg =~ /^--default(?:deps)?$/) {
54             $AcceptDefault = 1;
55         }
56         elsif ($arg =~ /^--check(?:deps)?$/) {
57             $CheckOnly = 1;
58         }
59         elsif ($arg =~ /^--skip(?:deps)?$/) {
60             $SkipInstall = 1;
61         }
62         elsif ($arg =~ /^--test(?:only)?$/) {
63             $TestOnly = 1;
64         }
65     }
66 }
67
68 # overrides MakeMaker's prompt() to automatically accept the default choice
69 sub _prompt {
70     goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
71
72     my ($prompt, $default) = @_;
73     my $y = ($default =~ /^[Yy]/);
74
75     print $prompt, ' [', ($y ? 'Y' : 'y'), '/', ($y ? 'n' : 'N'), '] ';
76     print "$default\n";
77     return $default;
78 }
79
80 # the workhorse
81 sub import {
82     my $class = shift;
83     my @args  = @_ or return;
84     my $core_all;
85
86     print "*** $class version ".$class->VERSION."\n";
87     print "*** Checking for dependencies...\n";
88
89     my $cwd = Cwd::cwd();
90
91     $Config  = [];
92
93     my $maxlen = length((sort { length($b) <=> length($a) }
94         grep { /^[^\-]/ }
95         map { ref($_) ? keys %{ref($_) eq 'HASH' ? $_ : +{@{$_}}} : '' }
96         map { +{@args}->{$_} }
97         grep { /^[^\-]/ or /^-core$/i } keys %{+{@args}})[0]);
98
99     while (my ($feature, $modules) = splice(@args, 0, 2)) {
100         my (@required, @tests, @skiptests);
101         my $default  = 1;
102         my $conflict = 0;
103
104         if ($feature =~ m/^-(\w+)$/) {
105             my $option = lc($1);
106
107             # check for a newer version of myself
108             _update_to($modules, @_) and return if $option eq 'version';
109
110             # sets CPAN configuration options
111             $Config = $modules                  if $option eq 'config';
112
113             # promote every features to core status
114             $core_all = ($modules =~ /^all$/i) and next
115                 if $option eq 'core';
116
117             next unless $option eq 'core';
118         }
119
120         print "[".($FeatureMap{lc($feature)} || $feature)."]\n";
121
122         $modules = [ %{$modules} ] if UNIVERSAL::isa($modules, 'HASH');
123
124         unshift @$modules, -default => &{shift(@$modules)}
125             if (ref($modules->[0]) eq 'CODE'); # XXX: bugward combatability
126
127         while (my ($mod, $arg) = splice(@$modules, 0, 2)) {
128             if ($mod =~ m/^-(\w+)$/) {
129                 my $option = lc($1);
130
131                 $default   = $arg    if ($option eq 'default');
132                 $conflict  = $arg    if ($option eq 'conflict');
133                 @tests     = @{$arg} if ($option eq 'tests');
134                 @skiptests = @{$arg} if ($option eq 'skiptests');
135
136                 next;
137             }
138
139             printf("- %-${maxlen}s ...", $mod);
140
141             # XXX: check for conflicts and uninstalls(!) them.
142             if (defined(my $cur = _version_check(_load($mod), $arg ||= 0))) {
143                 print "loaded. ($cur".($arg ? " >= $arg" : '').")\n";
144                 push @Existing, $mod => $arg;
145                 $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
146             }
147             else {
148                 print "missing." . ($arg ? " (would need $arg)" : '') . "\n";
149                 push @required, $mod => $arg;
150             }
151         }
152
153         next unless @required;
154
155         my $mandatory = ($feature eq '-core' or $core_all);
156
157         if (!$SkipInstall and ($CheckOnly or _prompt(
158             qq{==> Auto-install the }. (@required / 2).
159             ($mandatory ? ' mandatory' : ' optional').
160             qq{ module(s) from CPAN?}, $default ? 'y' : 'n',
161         ) =~ /^[Yy]/)) {
162             push (@Missing, @required);
163             $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
164         }
165
166         elsif (!$SkipInstall and $default and $mandatory and _prompt(
167             qq{==> The module(s) are mandatory! Really skip?}, 'n',
168         ) =~ /^[Nn]/) {
169             push (@Missing, @required);
170             $DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
171         }
172
173         else {
174             $DisabledTests{$_} = 1 for map { glob($_) } @tests;
175         }
176     }
177
178     _check_lock(); # check for $UnderCPAN
179
180     if (@Missing and not ($CheckOnly or $UnderCPAN)) {
181         require Config;
182         print "*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n";
183         # make an educated guess of whether we'll need root permission.
184         print "    (You may need to do that as the 'root' user.)\n" if eval '$>';
185     }
186     print "*** $class configuration finished.\n";
187
188     chdir $cwd;
189
190     # import to main::
191     no strict 'refs';
192     *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
193 }
194
195 # CPAN.pm is non-reentrant, so check if we're under it and have no CPANPLUS
196 sub _check_lock {
197     return unless @Missing;
198     return if _has_cpanplus();
199
200     require CPAN; CPAN::Config->load;
201     my $lock = MM->catfile($CPAN::Config->{cpan_home}, ".lock");
202
203     if (-f $lock and open(LOCK, $lock)
204         and ($^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid())
205         and ($CPAN::Config->{prerequisites_policy} || '') ne 'ignore'
206     ) {
207         print << '.';
208
209 *** Since we're running under CPAN, I'll just let it take care
210     of the dependency's installation later.
211 .
212         $UnderCPAN = 1;
213     }
214
215     close LOCK;
216 }
217
218 sub install {
219     my $class  = shift;
220
221     my $i; # used below to strip leading '-' from config keys
222     my @config = (map { s/^-// if ++$i; $_ } @{+shift});
223
224     my (@modules, @installed);
225     while (my ($pkg, $ver) = splice(@_, 0, 2)) {
226         # grep out those already installed
227         if (defined(_version_check(_load($pkg), $ver))) {
228             push @installed, $pkg;
229         }
230         else {
231             push @modules, $pkg, $ver;
232         }
233     }
234
235     return @installed unless @modules; # nothing to do
236
237     print "*** Installing dependencies...\n";
238
239     return unless _connected_to('cpan.org');
240
241     my %args = @config;
242     my %failed;
243     local *FAILED;
244     if ($args{do_once} and open(FAILED, '.#autoinstall.failed')) {
245         while (<FAILED>) { chomp; $failed{$_}++ }
246         close FAILED;
247
248         my @newmod;
249         while (my ($k, $v) = splice(@modules, 0, 2)) {
250             push @newmod, ($k => $v) unless $failed{$k};
251         }
252         @modules = @newmod;
253     }
254
255     if (_has_cpanplus()) {
256         _install_cpanplus(\@modules, \@config);
257     }
258     else {
259         _install_cpan(\@modules, \@config);
260     }
261
262     print "*** $class installation finished.\n";
263
264     # see if we have successfully installed them
265     while (my ($pkg, $ver) = splice(@modules, 0, 2)) {
266         if (defined(_version_check(_load($pkg), $ver))) {
267             push @installed, $pkg;
268         }
269         elsif ($args{do_once} and open(FAILED, '>> .#autoinstall.failed')) {
270             print FAILED "$pkg\n";
271         }
272     }
273
274     close FAILED if $args{do_once};
275
276     return @installed;
277 }
278
279 sub _install_cpanplus {
280     my @modules = @{+shift};
281     my @config  = @{+shift};
282     my $installed = 0;
283
284     require CPANPLUS::Backend;
285     my $cp   = CPANPLUS::Backend->new;
286     my $conf = $cp->configure_object;
287
288     return unless _can_write($conf->_get_build('base'));
289
290     # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
291     my $makeflags = $conf->get_conf('makeflags') || '';
292     if (UNIVERSAL::isa($makeflags, 'HASH')) {
293         # 0.03+ uses a hashref here
294         $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
295     }
296     else {
297         # 0.02 and below uses a scalar
298         $makeflags = join(' ', split(' ', $makeflags), 'UNINST=1')
299             if ($makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' });
300     }
301     $conf->set_conf(makeflags => $makeflags);
302     $conf->set_conf(prereqs => 1);
303
304     while (my ($key, $val) = splice(@config, 0, 2)) {
305         eval { $conf->set_conf($key, $val) };
306     }
307
308     my $modtree = $cp->module_tree;
309     while (my ($pkg, $ver) = splice(@modules, 0, 2)) {
310         print "*** Installing $pkg...\n";
311
312         MY::preinstall($pkg, $ver) or next if defined &MY::preinstall;
313
314         my $success;
315         my $obj = $modtree->{$pkg};
316
317         if ($obj and defined(_version_check($obj->{version}, $ver))) {
318             my $pathname = $pkg; $pathname =~ s/::/\\W/;
319
320             foreach my $inc (grep { m/$pathname.pm/i } keys(%INC)) {
321                 delete $INC{$inc};
322             }
323
324             my $rv = $cp->install( modules => [ $obj->{module} ]);
325
326             if ($rv and ($rv->{$obj->{module}} or $rv->{ok})) {
327                 print "*** $pkg successfully installed.\n";
328                 $success = 1;
329             }
330             else {
331                 print "*** $pkg installation cancelled.\n";
332                 $success = 0;
333             }
334
335             $installed += $success;
336         }
337         else {
338             print << ".";
339 *** Could not find a version $ver or above for $pkg; skipping.
340 .
341         }
342
343         MY::postinstall($pkg, $ver, $success) if defined &MY::postinstall;
344     }
345
346     return $installed;
347 }
348
349 sub _install_cpan {
350     my @modules = @{+shift};
351     my @config  = @{+shift};
352     my $installed = 0;
353     my %args;
354
355     require CPAN; CPAN::Config->load;
356
357     return unless _can_write(MM->catfile($CPAN::Config->{cpan_home}, 'sources'));
358
359     # if we're root, set UNINST=1 to avoid trouble unless user asked for it.
360     my $makeflags = $CPAN::Config->{make_install_arg} || '';
361     $CPAN::Config->{make_install_arg} = join(' ', split(' ', $makeflags), 'UNINST=1')
362         if ($makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' });
363
364     # don't show start-up info
365     $CPAN::Config->{inhibit_startup_message} = 1;
366
367     # set additional options
368     while (my ($opt, $arg) = splice(@config, 0, 2)) {
369         ($args{$opt} = $arg, next)
370             if $opt =~ /^force$/; # pseudo-option
371         $CPAN::Config->{$opt} = $arg;
372     }
373
374     local $CPAN::Config->{prerequisites_policy} = 'follow';
375
376     while (my ($pkg, $ver) = splice(@modules, 0, 2)) {
377         MY::preinstall($pkg, $ver) or next if defined &MY::preinstall;
378
379         print "*** Installing $pkg...\n";
380
381         my $obj = CPAN::Shell->expand(Module => $pkg);
382         my $success = 0;
383
384         if ($obj and defined(_version_check($obj->cpan_version, $ver))) {
385             my $pathname = $pkg; $pathname =~ s/::/\\W/;
386
387             foreach my $inc (grep { m/$pathname.pm/i } keys(%INC)) {
388                 delete $INC{$inc};
389             }
390
391             $obj->force('install') if $args{force};
392
393             my $rv = $obj->install || eval {
394                 $CPAN::META->instance(
395                     'CPAN::Distribution',
396                     $obj->cpan_file,
397                 )->{install}
398             };
399
400             if ($rv eq 'YES') {
401                 print "*** $pkg successfully installed.\n";
402                 $success = 1;
403             }
404             else {
405                 print "*** $pkg installation failed.\n";
406                 $success = 0;
407             }
408
409             $installed += $success;
410         }
411         else {
412             print << ".";
413 *** Could not find a version $ver or above for $pkg; skipping.
414 .
415         }
416
417         MY::postinstall($pkg, $ver, $success) if defined &MY::postinstall;
418     }
419
420     return $installed;
421 }
422
423 sub _has_cpanplus {
424     return (
425         $HasCPANPLUS = (
426             $INC{'CPANPLUS/Config.pm'} or
427             _load('CPANPLUS::Shell::Default')
428         )
429     );
430 }
431
432 # make guesses on whether we're under the CPAN installation directory
433 sub _under_cpan {
434     require Cwd;
435     require File::Spec;
436
437     my $cwd  = File::Spec->canonpath(Cwd::cwd());
438     my $cpan = File::Spec->canonpath($CPAN::Config->{cpan_home});
439
440     return (index($cwd, $cpan) > -1);
441 }
442
443 sub _update_to {
444     my $class = __PACKAGE__;
445     my $ver   = shift;
446
447     return if defined(_version_check(_load($class), $ver)); # no need to upgrade
448
449     if (_prompt(
450         "==> A newer version of $class ($ver) is required. Install?", 'y'
451     ) =~ /^[Nn]/) {
452         die "*** Please install $class $ver manually.\n";
453     }
454
455     print << ".";
456 *** Trying to fetch it from CPAN...
457 .
458
459     # install ourselves
460     _load($class) and return $class->import(@_)
461         if $class->install([], $class, $ver);
462
463     print << '.'; exit 1;
464
465 *** Cannot bootstrap myself. :-( Installation terminated.
466 .
467 }
468
469 # check if we're connected to some host, using inet_aton
470 sub _connected_to {
471     my $site = shift;
472
473     return (
474         ( _load('Socket') and Socket::inet_aton($site) ) or _prompt(qq(
475 *** Your host cannot resolve the domain name '$site', which
476     probably means the Internet connections are unavailable.
477 ==> Should we try to install the required module(s) anyway?), 'n'
478         ) =~ /^[Yy]/
479     );
480 }
481
482 # check if a directory is writable; may create it on demand
483 sub _can_write {
484     my $path = shift;
485     mkdir ($path, 0755) unless -e $path;
486
487     require Config;
488     return 1 if -w $path and -w $Config::Config{sitelib};
489
490     print << ".";
491 *** You are not allowed to write to the directory '$path';
492     the installation may fail due to insufficient permissions.
493 .
494
495     if (eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(qq(
496 ==> Should we try to re-execute the autoinstall process with 'sudo'?), 'y'
497     ) =~ /^[Yy]/) {
498         # try to bootstrap ourselves from sudo
499         print << ".";
500 *** Trying to re-execute the autoinstall process with 'sudo'...
501 .
502         my $missing = join(',', @Missing);
503         my $config  = join(',',
504             UNIVERSAL::isa($Config, 'HASH') ? %{$Config} : @{$Config}
505         ) if $Config;
506
507         return unless system('sudo', $^X, $0, "--config=$config", "--installdeps=$missing");
508
509         print << ".";
510 *** The 'sudo' command exited with error!  Resuming...
511 .
512     }
513
514     return _prompt(qq(
515 ==> Should we try to install the required module(s) anyway?), 'n'
516     ) =~ /^[Yy]/