CLI/Compat.pm untested

filter: Statementstmt 0.0% 0 / 1675 Branchbran 0.0% 0 / 692 Conditioncond 0.0% 0 / 435 MC/DCmcdc 0.0% 0 / 258 Subroutinesub 0.0% 0 / 193 Podpod 0.0% 0 / 134 totaltotal 0.0% 0 / 3387 CC 346 SCAR 53.2
CC
346
Cov
0%
build_stuff
1640.0
init_tools
812.0
install_module
272.0
CRAP 203.9
1 package Menlo::CLI::Compat;
2 use strict;
3 use Config;
4 use Cwd ();
5 use Menlo;
6 use Menlo::Dependency;
7 use Menlo::Util qw(WIN32);
8 use File::Basename ();
9 use File::Find ();
10 use File::Path ();
11 use File::Spec ();
12 use File::Copy ();
13 use File::Temp ();
14 use File::Which qw(which);
15 use Getopt::Long ();
16 use Symbol ();
17 use version ();
18  
19 use constant BAD_TAR => ($^O eq 'solaris' || $^O eq 'hpux');
20 use constant CAN_SYMLINK => eval { symlink("", ""); 1 };
21  
22 our $VERSION = '1.9022';
23  
24 if ($INC{"App/FatPacker/Trace.pm"}) {
25 require version::vpp;
26 }
27  
28 sub qs($) {
29 Menlo::Util::shell_quote($_[0]);
30 }
31  
32 sub determine_home {
33 my $class = shift;
34  
35 my $homedir = $ENV{HOME}
36 || eval { require File::HomeDir; File::HomeDir->my_home }
37 || join('', @ENV{qw(HOMEDRIVE HOMEPATH)}); # Win32
38  
39 if (WIN32) {
40 require Win32; # no fatpack
41 $homedir = Win32::GetShortPathName($homedir);
42 }
43  
44 return "$homedir/.cpanm";
45 }
46  
47 sub new {
48 my $class = shift;
49  
50 my $self = bless {
51 name => "Menlo",
52 home => $class->determine_home,
53 cmd => 'install',
54 seen => {},
55 notest => undef,
56 test_only => undef,
57 installdeps => undef,
58 force => undef,
59 sudo => undef,
60 make => undef,
61 verbose => undef,
62 quiet => undef,
63 interactive => undef,
64 log => undef,
65 mirrors => [],
66 mirror_only => undef,
67 mirror_index => undef,
68 cpanmetadb => "http://cpanmetadb.plackperl.org/v1.0/",
69 perl => $^X,
70 argv => [],
71 local_lib => undef,
72 self_contained => undef,
73 exclude_vendor => undef,
74 prompt_timeout => 0,
75 prompt => undef,
76 configure_timeout => 60,
77 build_timeout => 3600,
78 test_timeout => 1800,
79 try_lwp => 1,
80 try_wget => 1,
81 try_curl => 1,
82 uninstall_shadows => ($] < 5.012),
83 skip_installed => 1,
84 skip_satisfied => 0,
85 static_install => 1,
86 auto_cleanup => 7, # days
87 pod2man => 1,
88 installed_dists => 0,
89 install_types => ['requires'],
90 with_develop => 0,
91 with_configure => 0,
92 showdeps => 0,
93 scandeps => 0,
94 scandeps_tree => [],
95 format => 'tree',
96 save_dists => undef,
97 skip_configure => 0,
98 verify => 0,
99 report_perl_version => !$class->maybe_ci,
100 build_args => {},
101 features => {},
102 pure_perl => 0,
103 cpanfile_path => 'cpanfile',
104 @_,
105 }, $class;
106  
107 $self;
108 }
109  
110 sub env {
111 my($self, $key) = @_;
112 $ENV{"PERL_CPANM_" . $key};
113 }
114  
115 sub maybe_ci {
116 my $class = shift;
117 grep $ENV{$_}, qw( TRAVIS CI AUTOMATED_TESTING AUTHOR_TESTING );
118 }
119  
120 sub install_type_handlers {
121 my $self = shift;
122  
123 my @handlers;
124 for my $type (qw( recommends suggests )) {
125 push @handlers, "with-$type" => sub {
126 my %uniq;
127 $self->{install_types} = [ grep !$uniq{$_}++, @{$self->{install_types}}, $type ];
128 };
129 push @handlers, "without-$type" => sub {
130 $self->{install_types} = [ grep $_ ne $type, @{$self->{install_types}} ];
131 };
132 }
133  
134 @handlers;
135 }
136  
137 sub build_args_handlers {
138 my $self = shift;
139  
140 my @handlers;
141 for my $phase (qw( configure build test install )) {
142 push @handlers, "$phase-args=s" => \($self->{build_args}{$phase});
143 }
144  
145 @handlers;
146 }
147  
148 sub parse_options {
149 my $self = shift;
150  
151 local @ARGV = @{$self->{argv}};
152 push @ARGV, grep length, split /\s+/, $self->env('OPT');
153 push @ARGV, @_;
154  
155 Getopt::Long::Configure("bundling");
156 Getopt::Long::GetOptions(
157 'f|force' => sub { $self->{skip_installed} = 0; $self->{force} = 1 },
158 'n|notest!' => \$self->{notest},
159 'test-only' => sub { $self->{notest} = 0; $self->{skip_installed} = 0; $self->{test_only} = 1 },
160 'S|sudo!' => \$self->{sudo},
161 'v|verbose' => \$self->{verbose},
162 'verify!' => \$self->{verify},
163 'q|quiet!' => \$self->{quiet},
164 'h|help' => sub { $self->{action} = 'show_help' },
165 'V|version' => sub { $self->{action} = 'show_version' },
166 'perl=s' => sub {
167 $self->diag("--perl is deprecated since it's known to be fragile in figuring out dependencies. Run `$_[1] -S cpanm` instead.\n", 1);
168 $self->{perl} = $_[1];
169 },
170 'l|local-lib=s' => sub { $self->{local_lib} = $self->maybe_abs($_[1]) },
171 'L|local-lib-contained=s' => sub {
172 $self->{local_lib} = $self->maybe_abs($_[1]);
173 $self->{self_contained} = 1;
174 $self->{pod2man} = undef;
175 },
176 'self-contained!' => \$self->{self_contained},
177 'exclude-vendor!' => \$self->{exclude_vendor},
178 'mirror=s@' => $self->{mirrors},
179 'mirror-only!' => \$self->{mirror_only},
180 'mirror-index=s' => sub { $self->{mirror_index} = $self->maybe_abs($_[1]) },
181 'M|from=s' => sub {
182 $self->{mirrors} = [$_[1]];
183 $self->{mirror_only} = 1;
184 },
185 'cpanmetadb=s' => \$self->{cpanmetadb},
186 'cascade-search!' => \$self->{cascade_search},
187 'prompt!' => \$self->{prompt},
188 'installdeps' => \$self->{installdeps},
189 'skip-installed!' => \$self->{skip_installed},
190 'skip-satisfied!' => \$self->{skip_satisfied},
191 'reinstall' => sub { $self->{skip_installed} = 0 },
192 'interactive!' => \$self->{interactive},
193 'i|install' => sub { $self->{cmd} = 'install' },
194 'info' => sub { $self->{cmd} = 'info' },
195 'look' => sub { $self->{cmd} = 'look'; $self->{skip_installed} = 0 },
196 'U|uninstall' => sub { $self->{cmd} = 'uninstall' },
197 'self-upgrade' => sub { $self->{action} = 'self_upgrade' },
198 'uninst-shadows!' => \$self->{uninstall_shadows},
199 'lwp!' => \$self->{try_lwp},
200 'wget!' => \$self->{try_wget},
201 'curl!' => \$self->{try_curl},
202 'auto-cleanup=s' => \$self->{auto_cleanup},
203 'man-pages!' => \$self->{pod2man},
204 'scandeps' => \$self->{scandeps},
205 'showdeps' => sub { $self->{showdeps} = 1; $self->{skip_installed} = 0 },
206 'format=s' => \$self->{format},
207 'save-dists=s' => sub {
208 $self->{save_dists} = $self->maybe_abs($_[1]);
209 },
210 'skip-configure!' => \$self->{skip_configure},
211 'static-install!' => \$self->{static_install},
212 'dev!' => \$self->{dev_release},
213 'metacpan!' => \$self->{metacpan},
214 'report-perl-version!' => \$self->{report_perl_version},
215 'configure-timeout=i' => \$self->{configure_timeout},
216 'build-timeout=i' => \$self->{build_timeout},
217 'test-timeout=i' => \$self->{test_timeout},
218 'with-develop' => \$self->{with_develop},
219 'without-develop' => sub { $self->{with_develop} = 0 },
220 'with-configure' => \$self->{with_configure},
221 'without-configure' => sub { $self->{with_configure} = 0 },
222 'with-feature=s' => sub { $self->{features}{$_[1]} = 1 },
223 'without-feature=s' => sub { $self->{features}{$_[1]} = 0 },
224 'with-all-features' => sub { $self->{features}{__all} = 1 },
225 'pp|pureperl!' => \$self->{pure_perl},
226 "cpanfile=s" => \$self->{cpanfile_path},
227 $self->install_type_handlers,
228 $self->build_args_handlers,
229 );
230  
231 if (!@ARGV && $0 ne '-' && !-t STDIN){ # e.g. # cpanm < author/requires.cpanm
232 push @ARGV, $self->load_argv_from_fh(\*STDIN);
233 $self->{load_from_stdin} = 1;
234 }
235  
236 $self->{argv} = \@ARGV;
237 }
238  
239 sub check_upgrade {
240 my $self = shift;
241 my $install_base = $ENV{PERL_LOCAL_LIB_ROOT} ? $self->local_lib_target($ENV{PERL_LOCAL_LIB_ROOT}) : $Config{installsitebin};
242 if ($0 eq '-') {
243 # run from curl, that's fine
244 return;
245 } elsif ($0 !~ /^$install_base/) {
246 if ($0 =~ m!perlbrew/bin!) {
247 die <<DIE;
248 It appears your cpanm executable was installed via `perlbrew install-cpanm`.
249 cpanm --self-upgrade won't upgrade the version of cpanm you're running.
250  
251 Run the following command to get it upgraded.
252  
253 perlbrew install-cpanm
254  
255 DIE
256 } else {
257 die <<DIE;
258 You are running cpanm from the path where your current perl won't install executables to.
259 Because of that, cpanm --self-upgrade won't upgrade the version of cpanm you're running.
260  
261 cpanm path : $0
262 Install path : $Config{installsitebin}
263  
264 It means you either installed cpanm globally with system perl, or use distro packages such
265 as rpm or apt-get, and you have to use them again to upgrade cpanm.
266 DIE
267 }
268 }
269 }
270  
271 sub check_libs {
272 my $self = shift;
273 return if $self->{_checked}++;
274 $self->bootstrap_local_lib;
275 }
276  
277 sub setup_verify {
278 my $self = shift;
279  
280 my $has_modules = eval { require Module::Signature; require Digest::SHA; 1 };
281 $self->{cpansign} = which('cpansign');
282  
283 unless ($has_modules && $self->{cpansign}) {
284 warn "WARNING: Module::Signature and Digest::SHA is required for distribution verifications.\n";
285 $self->{verify} = 0;
286 }
287 }
288  
289 sub parse_module_args {
290 my($self, $module) = @_;
291  
292 # Plack@1.2 -> Plack~"==1.2"
293 # BUT don't expand @ in git URLs
294 $module =~ s/^([A-Za-z0-9_:]+)@([v\d\._]+)$/$1~== $2/;
295  
296 # Plack~1.20, DBI~"> 1.0, <= 2.0"
297 if ($module =~ /\~[v\d\._,\!<>= ]+$/) {
298 return split '~', $module, 2;
299 } else {
300 return $module, undef;
301 }
302 }
303  
304 sub run {
305 my $self = shift;
306  
307 my $code;
308 eval {
309 $code = ($self->_doit == 0);
310 }; if (my $e = $@) {
311 warn $e;
312 $code = 1;
313 }
314  
315 $self->{status} = $code;
316 }
317  
318 sub status {
319 $_[0]->{status};
320 }
321  
322 sub _doit {
323 my $self = shift;
324  
325 $self->setup_home;
326 $self->init_tools;
327 $self->setup_verify if $self->{verify};
328  
329 if (my $action = $self->{action}) {
330 $self->$action() and return 1;
331 }
332  
333 return $self->show_help(1)
334 unless @{$self->{argv}} or $self->{load_from_stdin};
335  
336 $self->configure_mirrors;
337  
338 my $cwd = Cwd::cwd;
339  
340 my @fail;
341 for my $module (@{$self->{argv}}) {
342 if ($module =~ s/\.pm$//i) {
343 my ($volume, $dirs, $file) = File::Spec->splitpath($module);
344 $module = join '::', grep { $_ } File::Spec->splitdir($dirs), $file;
345 }
346 ($module, my $version) = $self->parse_module_args($module);
347  
348 $self->chdir($cwd);
349 if ($self->{cmd} eq 'uninstall') {
350 $self->uninstall_module($module)
351 or push @fail, $module;
352 } else {
353 $self->install_module($module, 0, $version)
354 or push @fail, $module;
355 }
356 }
357  
358 if ($self->{base} && $self->{auto_cleanup}) {
359 $self->cleanup_workdirs;
360 }
361  
362 if ($self->{installed_dists}) {
363 my $dists = $self->{installed_dists} > 1 ? "distributions" : "distribution";
364 $self->diag("$self->{installed_dists} $dists installed\n", 1);
365 }
366  
367 if ($self->{scandeps}) {
368 $self->dump_scandeps();
369 }
370 # Workaround for older File::Temp's
371 # where creating a tempdir with an implicit $PWD
372 # causes tempdir non-cleanup if $PWD changes
373 # as paths are stored internally without being resolved
374 # absolutely.
375 # https://rt.cpan.org/Public/Bug/Display.html?id=44924
376 $self->chdir($cwd);
377  
378 return !@fail;
379 }
380  
381 sub setup_home {
382 my $self = shift;
383  
384 $self->{home} = $self->env('HOME') if $self->env('HOME');
385  
386 unless (_writable($self->{home})) {
387 die "Can't write to cpanm home '$self->{home}': You should fix it with chown/chmod first.\n";
388 }
389  
390 $self->{base} = "$self->{home}/work/" . time . ".$$";
391 File::Path::mkpath([ $self->{base} ], 0, 0777);
392  
393 # native path because we use shell redirect
394 $self->{log} = File::Spec->catfile($self->{base}, "build.log");
395 my $final_log = "$self->{home}/build.log";
396  
397 { open my $out, ">$self->{log}" or die "$self->{log}: $!" }
398  
399 if (CAN_SYMLINK) {
400 my $build_link = "$self->{home}/latest-build";
401 unlink $build_link;
402 symlink $self->{base}, $build_link;
403  
404 unlink $final_log;
405 symlink $self->{log}, $final_log;
406 } else {
407 my $log = $self->{log}; my $home = $self->{home};
408 $self->{at_exit} = sub {
409 my $self = shift;
410 my $temp_log = "$home/build.log." . time . ".$$";
411 File::Copy::copy($log, $temp_log)
412 && unlink($final_log);
413 rename($temp_log, $final_log);
414 }
415 }
416  
417 $self->chat("cpanm ($self->{name}) $Menlo::VERSION on perl $] built for $Config{archname}\n" .
418 "Work directory is $self->{base}\n");
419 }
420  
421 sub search_mirror_index_local {
422 my ($self, $local, $module, $version) = @_;
423 require CPAN::Common::Index::LocalPackage;
424 my $index = CPAN::Common::Index::LocalPackage->new({ source => $local });
425 $self->search_common($index, { package => $module }, $version);
426 }
427  
428 sub search_mirror_index {
429 my ($self, $mirror, $module, $version) = @_;
430 require Menlo::Index::Mirror;
431 my $index = Menlo::Index::Mirror->new({
432 mirror => $mirror,
433 cache => $self->source_for($mirror),
434 fetcher => sub { $self->mirror(@_) },
435 });
436 $self->search_common($index, { package => $module }, $version);
437 }
438  
439 sub search_common {
440 my($self, $index, $search_args, $want_version) = @_;
441  
442 $index->refresh_index;
443  
444 my $found = $index->search_packages($search_args);
445 $found = $self->cpan_module_common($found) if $found;
446  
447 return $found unless $self->{cascade_search};
448  
449 if ($found) {
450 if ($self->satisfy_version($found->{module}, $found->{module_version}, $want_version)) {
451 return $found;
452 } else {
453 $self->chat("Found $found->{module} $found->{module_version} which doesn't satisfy $want_version.\n");
454 }
455 }
456
457 return;
458 }
459  
460 sub with_version_range {
461 my($self, $version) = @_;
462 defined($version) && $version =~ /(?:<|!=|==)/;
463 }
464  
465 sub search_metacpan {
466 my($self, $module, $version, $dev_release) = @_;
467  
468 require Menlo::Index::MetaCPAN;
469 $self->chat("Searching $module ($version) on metacpan ...\n");
470  
471 my $index = Menlo::Index::MetaCPAN->new({ include_dev => $self->{dev_release} });
472 my $pkg = $self->search_common($index, { package => $module, version_range => $version }, $version);
473 return $pkg if $pkg;
474  
475 $self->diag_fail("Finding $module ($version) on metacpan failed.");
476 return;
477 }
478  
479 sub search_database {
480 my($self, $module, $version) = @_;
481  
482 my $found;
483  
484 if ($self->{dev_release} or $self->{metacpan}) {
485 $found = $self->search_metacpan($module, $version, $self->{dev_release}) and return $found;
486 $found = $self->search_cpanmetadb($module, $version, $self->{dev_release}) and return $found;
487 } else {
488 $found = $self->search_cpanmetadb($module, $version) and return $found;
489 $found = $self->search_metacpan($module, $version) and return $found;
490 }
491 }
492  
493 sub search_cpanmetadb {
494 my($self, $module, $version, $dev_release) = @_;
495  
496 require Menlo::Index::MetaDB;
497 $self->chat("Searching $module ($version) on cpanmetadb ...\n");
498  
499 my $args = { package => $module };
500 if ($self->with_version_range($version)) {
501 $args->{version_range} = $version;
502 }
503  
504 my $index = Menlo::Index::MetaDB->new({ uri => $self->{cpanmetadb} });
505 my $pkg = $self->search_common($index, $args, $version);
506 return $pkg if $pkg;
507  
508 $self->diag_fail("Finding $module on cpanmetadb failed.");
509 return;
510 }
511  
512 sub search_module {
513 my($self, $module, $version) = @_;
514  
515 if ($self->{mirror_index}) {
516 $self->mask_output( chat => "Searching $module on mirror index $self->{mirror_index} ...\n" );
517 my $pkg = $self->search_mirror_index_local($self->{mirror_index}, $module, $version);
518 return $pkg if $pkg;
519  
520 unless ($self->{cascade_search}) {
521 $self->mask_output( diag_fail => "Finding $module ($version) on mirror index $self->{mirror_index} failed." );
522 return;
523 }
524 }
525  
526 unless ($self->{mirror_only}) {
527 my $found = $self->search_database($module, $version);
528 return $found if $found;
529 }
530  
531 MIRROR: for my $mirror (@{ $self->{mirrors} }) {
532 $self->mask_output( chat => "Searching $module on mirror $mirror ...\n" );
533  
534 my $pkg = $self->search_mirror_index($mirror, $module, $version);
535 return $pkg if $pkg;
536  
537 $self->mask_output( diag_fail => "Finding $module ($version) on mirror $mirror failed." );
538 }
539  
540 return;
541 }
542  
543 sub source_for {
544 my($self, $mirror) = @_;
545 $mirror =~ s/[^\w\.\-]+/%/g;
546  
547 my $dir = "$self->{home}/sources/$mirror";
548 File::Path::mkpath([ $dir ], 0, 0777);
549  
550 return $dir;
551 }
552  
553 sub load_argv_from_fh {
554 my($self, $fh) = @_;
555  
556 my @argv;
557 while(defined(my $line = <$fh>)){
558 chomp $line;
559 $line =~ s/#.+$//; # comment
560 $line =~ s/^\s+//; # trim spaces
561 $line =~ s/\s+$//; # trim spaces
562  
563 push @argv, split ' ', $line if $line;
564 }
565 return @argv;
566 }
567  
568 sub show_version {
569 my $self = shift;
570  
571 print "cpanm ($self->{name}) version $VERSION ($0)\n";
572 print "perl version $] ($^X)\n\n";
573  
574 print " \%Config:\n";
575 for my $key (qw( archname installsitelib installsitebin installman1dir installman3dir
576 sitearchexp sitelibexp vendorarch vendorlibexp archlibexp privlibexp )) {
577 print " $key=$Config{$key}\n" if $Config{$key};
578 }
579  
580 print " \%ENV:\n";
581 for my $key (grep /^PERL/, sort keys %ENV) {
582 print " $key=$ENV{$key}\n";
583 }
584  
585 print " \@INC:\n";
586 for my $inc (@INC) {
587 print " $inc\n" unless ref($inc) eq 'CODE';
588 }
589  
590 return 1;
591 }
592  
593 sub show_help {
594 my $self = shift;
595  
596 if ($_[0]) {
597 print <<USAGE;
598 Usage: cpanm [options] Module [...]
599  
600 Try `cpanm --help` or `man cpanm` for more options.
601 USAGE
602 return;
603 }
604  
605 print <<HELP;
606 Usage: cpanm [options] Module [...]
607  
608 Options:
609 -v,--verbose Turns on chatty output
610 -q,--quiet Turns off the most output
611 --interactive Turns on interactive configure (required for Task:: modules)
612 -f,--force force install
613 -n,--notest Do not run unit tests
614 --test-only Run tests only, do not install
615 -S,--sudo sudo to run install commands
616 --installdeps Only install dependencies
617 --showdeps Only display direct dependencies
618 --reinstall Reinstall the distribution even if you already have the latest version installed
619 --mirror Specify the base URL for the mirror (e.g. http://cpan.cpantesters.org/)
620 --mirror-only Use the mirror's index file instead of the CPAN Meta DB
621 -M,--from Use only this mirror base URL and its index file
622 --prompt Prompt when configure/build/test fails
623 -l,--local-lib Specify the install base to install modules
624 -L,--local-lib-contained Specify the install base to install all non-core modules
625 --self-contained Install all non-core modules, even if they're already installed.
626 --auto-cleanup Number of days that cpanm's work directories expire in. Defaults to 7
627  
628 Commands:
629 --self-upgrade upgrades itself
630 --info Displays distribution info on CPAN
631 --look Opens the distribution with your SHELL
632 -U,--uninstall Uninstalls the modules (EXPERIMENTAL)
633 -V,--version Displays software version
634  
635 Examples:
636  
637 cpanm Test::More # install Test::More
638 cpanm MIYAGAWA/Plack-0.99_05.tar.gz # full distribution path
639 cpanm http://example.org/LDS/CGI.pm-3.20.tar.gz # install from URL
640 cpanm ~/dists/MyCompany-Enterprise-1.00.tar.gz # install from a local file
641 cpanm --interactive Task::Kensho # Configure interactively
642 cpanm . # install from local directory
643 cpanm --installdeps . # install all the deps for the current directory
644 cpanm -L extlib Plack # install Plack and all non-core deps into extlib
645 cpanm --mirror http://cpan.cpantesters.org/ DBI # use the fast-syncing mirror
646 cpanm -M https://cpan.metacpan.org App::perlbrew # use only this secure mirror and its index
647  
648 You can also specify the default options in PERL_CPANM_OPT environment variable in the shell rc:
649  
650 export PERL_CPANM_OPT="--prompt --reinstall -l ~/perl --mirror http://cpan.cpantesters.org"
651  
652 Type `man cpanm` or `perldoc cpanm` for the more detailed explanation of the options.
653  
654 HELP
655  
656 return 1;
657 }
658  
659 sub _writable {
660 my $dir = shift;
661 my @dir = File::Spec->splitdir($dir);
662 while (@dir) {
663 $dir = File::Spec->catdir(@dir);
664 if (-e $dir) {
665 return -w _;
666 }
667 pop @dir;
668 }
669  
670 return;
671 }
672  
673 sub maybe_abs {
674 my($self, $lib) = @_;
675 if ($lib eq '_' or $lib =~ /^~/ or File::Spec->file_name_is_absolute($lib)) {
676 return $lib;
677 } else {
678 return File::Spec->canonpath(File::Spec->catdir(Cwd::cwd(), $lib));
679 }
680 }
681  
682 sub local_lib_target {
683 my($self, $root) = @_;
684 # local::lib 1.008025 changed the order of PERL_LOCAL_LIB_ROOT
685 (grep { $_ ne '' } split /\Q$Config{path_sep}/, $root)[0];
686 }
687  
688 sub bootstrap_local_lib {
689 my $self = shift;
690  
691 # If -l is specified, use that.
692 if ($self->{local_lib}) {
693 return $self->setup_local_lib($self->{local_lib});
694 }
695  
696 # PERL_LOCAL_LIB_ROOT is defined. Run as local::lib mode without overwriting ENV
697 if ($ENV{PERL_LOCAL_LIB_ROOT} && $ENV{PERL_MM_OPT}) {
698 return $self->setup_local_lib($self->local_lib_target($ENV{PERL_LOCAL_LIB_ROOT}), 1);
699 }
700  
701 # root, locally-installed perl or --sudo: don't care about install_base
702 return if $self->{sudo} or (_writable($Config{installsitelib}) and _writable($Config{installsitebin}));
703  
704 # local::lib is configured in the shell -- yay
705 if ($ENV{PERL_MM_OPT} and ($ENV{MODULEBUILDRC} or $ENV{PERL_MB_OPT})) {
706 return;
707 }
708  
709 $self->setup_local_lib;
710  
711 $self->diag(<<DIAG, 1);
712 !
713 ! Can't write to $Config{installsitelib} and $Config{installsitebin}: Installing modules to $ENV{HOME}/perl5
714 ! To turn off this warning, you have to do one of the following:
715 ! - run me as a root or with --sudo option (to install to $Config{installsitelib} and $Config{installsitebin})
716 ! - Configure local::lib in your existing shell to set PERL_MM_OPT etc.
717 ! - Install local::lib by running the following commands
718 !
719 ! cpanm --local-lib=~/perl5 local::lib && eval \$(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
720 !
721 DIAG
722 sleep 2;
723 }
724  
725 sub upgrade_toolchain {
726 my($self, $config_deps) = @_;
727  
728 my %deps = map { $_->module => $_ } @$config_deps;
729  
730 # M::B 0.38 and EUMM 6.58 for MYMETA
731 # EU::Install 1.46 for local::lib
732 my $reqs = CPAN::Meta::Requirements->from_string_hash({
733 'Module::Build' => '0.38',
734 'ExtUtils::MakeMaker' => '6.58',
735 'ExtUtils::Install' => '1.46',
736 });
737  
738 if ($deps{"ExtUtils::MakeMaker"}) {
739 $deps{"ExtUtils::MakeMaker"}->merge_with($reqs);
740 } elsif ($deps{"Module::Build"}) {
741 $deps{"Module::Build"}->merge_with($reqs);
742 $deps{"ExtUtils::Install"} ||= Menlo::Dependency->new("ExtUtils::Install", 0, 'configure');
743 $deps{"ExtUtils::Install"}->merge_with($reqs);
744 }
745  
746 @$config_deps = values %deps;
747 }
748  
749 sub _core_only_inc {
750 my($self, $base) = @_;
751 require local::lib;
752 (
753 local::lib->resolve_path(local::lib->install_base_arch_path($base)),
754 local::lib->resolve_path(local::lib->install_base_perl_path($base)),
755 (!$self->{exclude_vendor} ? grep {$_} @Config{qw(vendorarch vendorlibexp)} : ()),
756 @Config{qw(archlibexp privlibexp)},
757 );
758 }
759  
760 sub _setup_local_lib_env {
761 my($self, $base) = @_;
762  
763 $self->diag(<<WARN, 1) if $base =~ /\s/;
764 WARNING: Your lib directory name ($base) contains a space in it. It's known to cause issues with perl builder tools such as local::lib and MakeMaker. You're recommended to rename your directory.
765 WARN
766  
767 local $SIG{__WARN__} = sub { }; # catch 'Attempting to write ...'
768 local::lib->setup_env_hash_for($base, 0);
769 }
770  
771 sub setup_local_lib {
772 my($self, $base, $no_env) = @_;
773 $base = undef if $base eq '_';
774  
775 require local::lib;
776 {
777 local $0 = 'cpanm'; # so curl/wget | perl works
778 $base ||= "~/perl5";
779 $base = local::lib->resolve_path($base);
780 if ($self->{self_contained}) {
781 my @inc = $self->_core_only_inc($base);
782 $self->{search_inc} = [ @inc ];
783 } else {
784 $self->{search_inc} = [
785 local::lib->install_base_arch_path($base),
786 local::lib->install_base_perl_path($base),
787 @INC,
788 ];
789 }
790 $self->_setup_local_lib_env($base) unless $no_env;
791 $self->{local_lib} = $base;
792 }
793 }
794  
795 sub prompt_bool {
796 my($self, $mess, $def) = @_;
797  
798 my $val = $self->prompt($mess, $def);
799 return lc $val eq 'y';
800 }
801  
802 sub prompt {
803 my($self, $mess, $def) = @_;
804  
805 my $isa_tty = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ;
806 my $dispdef = defined $def ? "[$def] " : " ";
807 $def = defined $def ? $def : "";
808  
809 if (!$self->{prompt} || (!$isa_tty && eof STDIN)) {
810 return $def;
811 }
812  
813 local $|=1;
814 local $\;
815 my $ans;
816 eval {
817 local $SIG{ALRM} = sub { undef $ans; die "alarm\n" };
818 print STDOUT "$mess $dispdef";
819 alarm $self->{prompt_timeout} if $self->{prompt_timeout};
820 $ans = <STDIN>;
821 alarm 0;
822 };
823 if ( defined $ans ) {
824 chomp $ans;
825 } else { # user hit ctrl-D or alarm timeout
826 print STDOUT "\n";
827 }
828  
829 return (!defined $ans || $ans eq '') ? $def : $ans;
830 }
831  
832 sub diag_ok {
833 my($self, $msg) = @_;
834 chomp $msg;
835 $msg ||= "OK";
836 if ($self->{in_progress}) {
837 $self->_diag("$msg\n");
838 $self->{in_progress} = 0;
839 }
840 $self->log("-> $msg\n");
841 }
842  
843 sub diag_fail {
844 my($self, $msg, $always) = @_;
845 chomp $msg;
846 if ($self->{in_progress}) {
847 $self->_diag("FAIL\n");
848 $self->{in_progress} = 0;
849 }
850  
851 if ($msg) {
852 $self->_diag("! $msg\n", $always, 1);
853 $self->log("-> FAIL $msg\n");
854 }
855 }
856  
857 sub diag_progress {
858 my($self, $msg) = @_;
859 chomp $msg;
860 $self->{in_progress} = 1;
861 $self->_diag("$msg ... ");
862 $self->log("$msg\n");
863 }
864  
865 sub _diag {
866 my($self, $msg, $always, $error) = @_;
867 my $fh = $error ? *STDERR : *STDOUT;
868 print {$fh} $msg if $always or $self->{verbose} or !$self->{quiet};
869 }
870  
871 sub diag {
872 my($self, $msg, $always) = @_;
873 $self->_diag($msg, $always);
874 $self->log($msg);
875 }
876  
877 sub chat {
878 my $self = shift;
879 print STDERR @_ if $self->{verbose};
880 $self->log(@_);
881 }
882  
883 sub mask_output {
884 my $self = shift;
885 my $method = shift;
886 $self->$method( $self->mask_uri_passwords(@_) );
887 }
888  
889 sub log {
890 my $self = shift;
891 open my $out, ">>$self->{log}";
892 print $out @_;
893 }
894  
895 sub run_command {
896 my($self, $cmd) = @_;
897  
898 # TODO move to a more appropriate runner method
899 if (ref $cmd eq 'CODE') {
900 if ($self->{verbose}) {
901 return $cmd->();
902 } else {
903 require Capture::Tiny;
904 open my $logfh, ">>", $self->{log};
905 my $ret;
906 Capture::Tiny::capture(sub { $ret = $cmd->() }, stdout => $logfh, stderr => $logfh);
907 return $ret;
908 }
909 }
910  
911 if (WIN32) {
912 $cmd = Menlo::Util::shell_quote(@$cmd) if ref $cmd eq 'ARRAY';
913 unless ($self->{verbose}) {
914 $cmd .= " >> " . Menlo::Util::shell_quote($self->{log}) . " 2>&1";
915 }
916 !system $cmd;
917 } else {
918 my $pid = fork;
919 if ($pid) {
920 waitpid $pid, 0;
921 return !$?;
922 } else {
923 $self->run_exec($cmd);
924 }
925 }
926 }
927  
928 sub run_exec {
929 my($self, $cmd) = @_;
930  
931 if (ref $cmd eq 'ARRAY') {
932 unless ($self->{verbose}) {
933 open my $logfh, ">>", $self->{log};
934 open STDERR, '>&', $logfh;
935 open STDOUT, '>&', $logfh;
936 close $logfh;
937 }
938 exec @$cmd;
939 } else {
940 unless ($self->{verbose}) {
941 $cmd .= " >> " . Menlo::Util::shell_quote($self->{log}) . " 2>&1";
942 }
943 exec $cmd;
944 }
945 }
946  
947 sub run_timeout {
948 my($self, $cmd, $timeout) = @_;
949  
950 return $self->run_command($cmd) if ref($cmd) eq 'CODE' || WIN32 || $self->{verbose} || !$timeout;
951  
952 my $pid = fork;
953 if ($pid) {
954 eval {
955 local $SIG{ALRM} = sub { die "alarm\n" };
956 alarm $timeout;
957 waitpid $pid, 0;
958 alarm 0;
959 };
960 if ($@ && $@ eq "alarm\n") {
961 $self->diag_fail("Timed out (> ${timeout}s). Use --verbose to retry.");
962 local $SIG{TERM} = 'IGNORE';
963 kill TERM => 0;
964 waitpid $pid, 0;
965 return;
966 }
967 return !$?;
968 } elsif ($pid == 0) {
969 $self->run_exec($cmd);
970 } else {
971 $self->chat("! fork failed: falling back to system()\n");
972 $self->run_command($cmd);
973 }
974 }
975  
976 sub append_args {
977 my($self, $cmd, $phase) = @_;
978  
979 return $cmd if ref $cmd ne 'ARRAY';
980
981 if (my $args = $self->{build_args}{$phase}) {
982 $cmd = join ' ', Menlo::Util::shell_quote(@$cmd), $args;
983 }
984  
985 $cmd;
986 }
987  
988 sub _use_unsafe_inc {
989 my($self, $dist) = @_;
990  
991 # if it's set in the env (i.e. user's shell), just use that
992 if (exists $ENV{PERL_USE_UNSAFE_INC}) {
993 return $ENV{PERL_USE_UNSAFE_INC};
994 }
995  
996 # it's set in CPAN Meta, prefer what the author says
997 if (exists $dist->{meta}{x_use_unsafe_inc}) {
998 $self->chat("Distribution opts in x_use_unsafe_inc: $dist->{meta}{x_use_unsafe_inc}\n");
999 return $dist->{meta}{x_use_unsafe_inc};
1000 }
1001  
1002 # otherwise set to 1 as a default to allow for old modules
1003 return 1;
1004 }
1005  
1006 sub configure {
1007 my($self, $cmd, $dist, $depth) = @_;
1008  
1009 # trick AutoInstall
1010 local $ENV{PERL5_CPAN_IS_RUNNING} = local $ENV{PERL5_CPANPLUS_IS_RUNNING} = $$;
1011  
1012 # e.g. skip CPAN configuration on local::lib
1013 local $ENV{PERL5_CPANM_IS_RUNNING} = $$;
1014  
1015 my $use_default = !$self->{interactive};
1016 local $ENV{PERL_MM_USE_DEFAULT} = $use_default;
1017  
1018 local $ENV{PERL_MM_OPT} = $ENV{PERL_MM_OPT};
1019 local $ENV{PERL_MB_OPT} = $ENV{PERL_MB_OPT};
1020  
1021 # skip man page generation
1022 unless ($self->{pod2man}) {
1023 $ENV{PERL_MM_OPT} .= " INSTALLMAN1DIR=none INSTALLMAN3DIR=none";
1024 $ENV{PERL_MB_OPT} .= " --config installman1dir= --config installsiteman1dir= --config installman3dir= --config installsiteman3dir=";
1025 }
1026  
1027 # Lancaster Consensus
1028 if ($self->{pure_perl}) {
1029 $ENV{PERL_MM_OPT} .= " PUREPERL_ONLY=1";
1030 $ENV{PERL_MB_OPT} .= " --pureperl-only";
1031 }
1032  
1033 local $ENV{PERL_USE_UNSAFE_INC} = $self->_use_unsafe_inc($dist);
1034  
1035 $cmd = $self->append_args($cmd, 'configure') if $depth == 0;
1036  
1037 local $self->{verbose} = $self->{verbose} || $self->{interactive};
1038 $self->run_timeout($cmd, $self->{configure_timeout});
1039 }
1040  
1041 sub build {
1042 my($self, $cmd, $distname, $dist, $depth) = @_;
1043  
1044 local $ENV{PERL_MM_USE_DEFAULT} = !$self->{interactive};
1045  
1046 local $ENV{PERL_USE_UNSAFE_INC} = $self->_use_unsafe_inc($dist);
1047  
1048 $cmd = $self->append_args($cmd, 'build') if $depth == 0;
1049  
1050 return 1 if $self->run_timeout($cmd, $self->{build_timeout});
1051 while (1) {
1052 my $ans = lc $self->prompt("Building $distname failed.\nYou can s)kip, r)etry, e)xamine build log, or l)ook ?", "s");
1053 return if $ans eq 's';
1054 return $self->build($cmd, $distname, $dist, $depth) if $ans eq 'r';
1055 $self->show_build_log if $ans eq 'e';
1056 $self->look if $ans eq 'l';
1057 }
1058 }
1059  
1060 sub test {
1061 my($self, $cmd, $distname, $dist, $depth) = @_;
1062 return 1 if $self->{notest};
1063  
1064 # https://rt.cpan.org/Ticket/Display.html?id=48965#txn-1013385
1065 local $ENV{PERL_MM_USE_DEFAULT} = !$self->{interactive};
1066  
1067 # https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md
1068 local $ENV{NONINTERACTIVE_TESTING} = !$self->{interactive};
1069  
1070 local $ENV{PERL_USE_UNSAFE_INC} = $self->_use_unsafe_inc($dist);
1071  
1072 $cmd = $self->append_args($cmd, 'test') if $depth == 0;
1073  
1074 return 1 if $self->run_timeout($cmd, $self->{test_timeout});
1075 if ($self->{force}) {
1076 $self->diag_fail("Testing $distname failed but installing it anyway.");
1077 return 1;
1078 } else {
1079 $self->diag_fail;
1080 while (1) {
1081 my $ans = lc $self->prompt("Testing $distname failed.\nYou can s)kip, r)etry, f)orce install, e)xamine build log, or l)ook ?", "s");
1082 return if $ans eq 's';
1083 return $self->test($cmd, $distname, $dist, $depth) if $ans eq 'r';
1084 return 1 if $ans eq 'f';
1085 $self->show_build_log if $ans eq 'e';
1086 $self->look if $ans eq 'l';
1087 }
1088 }
1089 }
1090  
1091 sub install {
1092 my($self, $cmd, $uninst_opts, $dist, $depth) = @_;
1093  
1094 if ($depth == 0 && $self->{test_only}) {
1095 return 1;
1096 }
1097  
1098 return $self->run_command($cmd) if ref $cmd eq 'CODE';
1099  
1100 local $ENV{PERL_USE_UNSAFE_INC} = $self->_use_unsafe_inc($dist);
1101  
1102 if ($self->{sudo}) {
1103 unshift @$cmd, "sudo";
1104 }
1105  
1106 if ($self->{uninstall_shadows} && !$ENV{PERL_MM_OPT}) {
1107 push @$cmd, @$uninst_opts;
1108 }
1109  
1110 $cmd = $self->append_args($cmd, 'install') if $depth == 0;
1111  
1112 $self->run_command($cmd);
1113 }
1114  
1115 sub look {
1116 my $self = shift;
1117  
1118 my $shell = $ENV{SHELL};
1119 $shell ||= $ENV{COMSPEC} if WIN32;
1120 if ($shell) {
1121 my $cwd = Cwd::cwd;
1122 $self->diag("Entering $cwd with $shell\n");
1123 system $shell;
1124 } else {
1125 $self->diag_fail("You don't seem to have a SHELL :/");
1126 }
1127 }
1128  
1129 sub show_build_log {
1130 my $self = shift;
1131  
1132 my @pagers = (
1133 $ENV{PAGER},
1134 (WIN32 ? () : ('less')),
1135 'more'
1136 );
1137 my $pager;
1138 while (@pagers) {
1139 $pager = shift @pagers;
1140 next unless $pager;
1141 $pager = which($pager);
1142 next unless $pager;
1143 last;
1144 }
1145  
1146 if ($pager) {
1147 if (WIN32) {
1148 system "@{[ qs $pager ]} < @{[ qs $self->{log}]}";
1149 } else {
1150 system $pager, $self->{log};
1151 }
1152 }
1153 else {
1154 $self->diag_fail("You don't seem to have a PAGER :/");
1155 }
1156 }
1157  
1158 sub chdir {
1159 my $self = shift;
1160 Cwd::chdir(File::Spec->canonpath($_[0])) or die "$_[0]: $!";
1161 }
1162  
1163 sub configure_mirrors {
1164 my $self = shift;
1165 unless (@{$self->{mirrors}}) {
1166 $self->{mirrors} = [ 'http://www.cpan.org' ];
1167 }
1168 for (@{$self->{mirrors}}) {
1169 s!^/!file:///!;
1170 s!/$!!;
1171 }
1172 }
1173  
1174 sub self_upgrade {
1175 my $self = shift;
1176 $self->check_upgrade;
1177 $self->{argv} = [ 'Menlo' ];
1178 return; # continue
1179 }
1180  
1181 sub install_module {
1182 my($self, $module, $depth, $version, $dep) = @_;
1183  
1184 $self->check_libs;
1185  
1186 if ($self->{seen}{$module}++) {
1187 # TODO: circular dependencies
1188 $self->chat("Already tried $module. Skipping.\n");
1189 return 1;
1190 }
1191  
1192 if ($self->{skip_satisfied}) {
1193 my($ok, $local) = $self->check_module($module, $version || 0);
1194 if ($ok) {
1195 $self->diag("You have $module ($local)\n", 1);
1196 return 1;
1197 }
1198 }
1199  
1200 my $dist = $self->resolve_name($module, $version, $dep);
1201 unless ($dist) {
1202 my $what = $module . ($version ? " ($version)" : "");
1203 $self->diag_fail("Couldn't find module or a distribution $what", 1);
1204 return;
1205 }
1206  
1207 if ($dist->{distvname} && $self->{seen}{$dist->{distvname}}++) {
1208 $self->chat("Already tried $dist->{distvname}. Skipping.\n");
1209 return 1;
1210 }
1211  
1212 if ($self->{cmd} eq 'info') {
1213 print $self->format_dist($dist), "\n";
1214 return 1;
1215 }
1216  
1217 $dist->{depth} = $depth; # ugly hack
1218  
1219 if ($dist->{module}) {
1220 unless ($self->satisfy_version($dist->{module}, $dist->{module_version}, $version)) {
1221 $self->diag("Found $dist->{module} $dist->{module_version} which doesn't satisfy $version.\n", 1);
1222 return;
1223 }
1224  
1225 # If a version is requested, it has to be the exact same version, otherwise, check as if
1226 # it is the minimum version you need.
1227 my $cmp = $version ? "==" : "";
1228 my $requirement = $dist->{module_version} ? "$cmp$dist->{module_version}" : 0;
1229 my($ok, $local) = $self->check_module($dist->{module}, $requirement);
1230 if ($self->{skip_installed} && $ok) {
1231 $self->diag("$dist->{module} is up to date. ($local)\n", 1);
1232 return 1;
1233 }
1234 }
1235  
1236 if ($dist->{dist} eq 'perl'){
1237 $self->diag("skipping $dist->{pathname}\n");
1238 return 1;
1239 }
1240  
1241 $self->diag("--> Working on $module\n");
1242  
1243 $dist->{dir} ||= $self->fetch_module($dist);
1244  
1245 unless ($dist->{dir}) {
1246 $self->diag_fail("Failed to fetch distribution $dist->{distvname}", 1);
1247 return;
1248 }
1249  
1250 $self->chat("Entering $dist->{dir}\n");
1251 $self->chdir($self->{base});
1252 $self->chdir($dist->{dir});
1253  
1254 if ($self->{cmd} eq 'look') {
1255 $self->look;
1256 return 1;
1257 }
1258  
1259 return $self->build_stuff($module, $dist, $depth);
1260 }
1261  
1262 sub uninstall_search_path {
1263 my $self = shift;
1264  
1265 $self->{local_lib}
1266 ? (local::lib->install_base_arch_path($self->{local_lib}),
1267 local::lib->install_base_perl_path($self->{local_lib}))
1268 : @Config{qw(installsitearch installsitelib)};
1269 }
1270  
1271 sub uninstall_module {
1272 my ($self, $module) = @_;
1273  
1274 $self->check_libs;
1275  
1276 my @inc = $self->uninstall_search_path;
1277  
1278 my($metadata, $packlist) = $self->packlists_containing($module, \@inc);
1279 unless ($packlist) {
1280 $self->diag_fail(<<DIAG, 1);
1281 $module is not found in the following directories and can't be uninstalled.
1282  
1283 @{[ join(" \n", map " $_", @inc) ]}
1284  
1285 DIAG
1286 return;
1287 }
1288  
1289 my @uninst_files = $self->uninstall_target($metadata, $packlist);
1290  
1291 $self->ask_permission($module, \@uninst_files) or return;
1292 $self->uninstall_files(@uninst_files, $packlist);
1293  
1294 $self->diag("Successfully uninstalled $module\n", 1);
1295  
1296 return 1;
1297 }
1298  
1299 sub packlists_containing {
1300 my($self, $module, $inc) = @_;
1301  
1302 require Module::Metadata;
1303 my $metadata = Module::Metadata->new_from_module($module, inc => $inc)
1304 or return;
1305  
1306 my $packlist;
1307 my $wanted = sub {
1308 return unless $_ eq '.packlist' && -f $_;
1309 for my $file ($self->unpack_packlist($File::Find::name)) {
1310 $packlist ||= $File::Find::name if $file eq $metadata->filename;
1311 }
1312 };
1313  
1314 {
1315 require File::pushd;
1316 my $pushd = File::pushd::pushd();
1317 my @search = grep -d $_, map File::Spec->catdir($_, 'auto'), @$inc;
1318 File::Find::find($wanted, @search);
1319 }
1320  
1321 return $metadata, $packlist;
1322 }
1323  
1324 sub uninstall_target {
1325 my($self, $metadata, $packlist) = @_;
1326  
1327 # If the module has a shadow install, or uses local::lib, then you can't just remove
1328 # all files in .packlist since it might have shadows in there
1329 if ($self->has_shadow_install($metadata) or $self->{local_lib}) {
1330 grep $self->should_unlink($_), $self->unpack_packlist($packlist);
1331 } else {
1332 $self->unpack_packlist($packlist);
1333 }
1334 }
1335  
1336 sub has_shadow_install {
1337 my($self, $metadata) = @_;
1338  
1339 # check if you have the module in site_perl *and* perl
1340 my @shadow = grep defined, map Module::Metadata->new_from_module($metadata->name, inc => [$_]), @INC;
1341 @shadow >= 2;
1342 }
1343  
1344 sub should_unlink {
1345 my($self, $file) = @_;
1346  
1347 # If local::lib is used, everything under the directory can be safely removed
1348 # Otherwise, bin and man files might be shared with the shadows i.e. site_perl vs perl
1349 # This is not 100% safe to keep the script there hoping to work with older version of .pm
1350 # files in the shadow, but there's nothing you can do about it.
1351 if ($self->{local_lib}) {
1352 $file =~ /^\Q$self->{local_lib}\E/;
1353 } else {
1354 !(grep $file =~ /^\Q$_\E/, @Config{qw(installbin installscript installman1dir installman3dir)});
1355 }
1356 }
1357  
1358 sub ask_permission {
1359 my ($self, $module, $files) = @_;
1360  
1361 $self->diag("$module contains the following files:\n\n");
1362 for my $file (@$files) {
1363 $self->diag(" $file\n");
1364 }
1365 $self->diag("\n");
1366  
1367 return 'force uninstall' if $self->{force};
1368 local $self->{prompt} = 1;
1369 return $self->prompt_bool("Are you sure you want to uninstall $module?", 'y');
1370 }
1371  
1372 sub unpack_packlist {
1373 my ($self, $packlist) = @_;
1374 open my $fh, '<', $packlist or die "$packlist: $!";
1375 map { chomp; $_ } <$fh>;
1376 }
1377  
1378 sub uninstall_files {
1379 my ($self, @files) = @_;
1380  
1381 $self->diag("\n");
1382  
1383 for my $file (@files) {
1384 $self->diag("Unlink: $file\n");
1385 unlink $file or $self->diag_fail("$!: $file");
1386 }
1387  
1388 $self->diag("\n");
1389  
1390 return 1;
1391 }
1392  
1393 sub format_dist {
1394 my($self, $dist) = @_;
1395  
1396 # TODO support --dist-format?
1397 return "$dist->{cpanid}/$dist->{filename}";
1398 }
1399  
1400 sub trim {
1401 local $_ = shift;
1402 tr/\n/ /d;
1403 s/^\s*|\s*$//g;
1404 $_;
1405 }
1406  
1407 sub fetch_module {
1408 my($self, $dist) = @_;
1409  
1410 $self->chdir($self->{base});
1411  
1412 for my $uri (@{$dist->{uris}}) {
1413 $self->mask_output( diag_progress => "Fetching $uri" );
1414  
1415 # Ugh, $dist->{filename} can contain sub directory
1416 my $filename = $dist->{filename} || $uri;
1417 my $name = File::Basename::basename($filename);
1418  
1419 my $cancelled;
1420 my $fetch = sub {
1421 my $file;
1422 eval {
1423 local $SIG{INT} = sub { $cancelled = 1; die "SIGINT\n" };
1424 $self->mirror($uri, $name);
1425 $file = $name if -e $name;
1426 };
1427 $self->diag("ERROR: " . trim("$@") . "\n", 1) if $@ && $@ ne "SIGINT\n";
1428 return $file;
1429 };
1430  
1431 my($try, $file);
1432 while ($try++ < 3) {
1433 $file = $fetch->();
1434 last if $cancelled or $file;
1435 $self->mask_output( diag_fail => "Download $uri failed. Retrying ... ");
1436 }
1437  
1438 if ($cancelled) {
1439 $self->diag_fail("Download cancelled.");
1440 return;
1441 }
1442  
1443 unless ($file) {
1444 $self->mask_output( diag_fail => "Failed to download $uri");
1445 next;
1446 }
1447  
1448 $self->diag_ok;
1449 $dist->{local_path} = File::Spec->rel2abs($name);
1450  
1451 my $dir = $self->unpack($file, $uri, $dist);
1452 next unless $dir; # unpack failed
1453  
1454 if (my $save = $self->{save_dists}) {
1455 # Only distros retrieved from CPAN have a pathname set
1456 my $path = $dist->{pathname} ? "$save/authors/id/$dist->{pathname}"
1457 : "$save/vendor/$file";
1458 $self->chat("Copying $name to $path\n");
1459 File::Path::mkpath([ File::Basename::dirname($path) ], 0, 0777);
1460 File::Copy::copy($file, $path) or warn $!;
1461 }
1462  
1463 return $dist, $dir;
1464 }
1465 }
1466  
1467 sub unpack {
1468 my($self, $file, $uri, $dist) = @_;
1469  
1470 if ($self->{verify}) {
1471 $self->verify_archive($file, $uri, $dist) or return;
1472 }
1473  
1474 $self->chat("Unpacking $file\n");
1475 my $dir = $file =~ /\.zip/i ? $self->unzip($file) : $self->untar($file);
1476 unless ($dir) {
1477 $self->diag_fail("Failed to unpack $file: no directory");
1478 }
1479 return $dir;
1480 }
1481  
1482 sub verify_checksums_signature {
1483 my($self, $chk_file) = @_;
1484  
1485 require Module::Signature; # no fatpack
1486  
1487 $self->chat("Verifying the signature of CHECKSUMS\n");
1488  
1489 my $rv = eval {
1490 local $SIG{__WARN__} = sub {}; # suppress warnings
1491 my $v = Module::Signature::_verify($chk_file);
1492 $v == Module::Signature::SIGNATURE_OK();
1493 };
1494 if ($rv) {
1495 $self->chat("Verified OK!\n");
1496 } else {
1497 $self->diag_fail("Verifying CHECKSUMS signature failed: $rv\n");
1498 return;
1499 }
1500  
1501 return 1;
1502 }
1503  
1504 sub verify_archive {
1505 my($self, $file, $uri, $dist) = @_;
1506  
1507 unless ($dist->{cpanid}) {
1508 $self->chat("Archive '$file' does not seem to be from PAUSE. Skip verification.\n");
1509 return 1;
1510 }
1511  
1512 (my $mirror = $uri) =~ s!/authors/id.*$!!;
1513  
1514 (my $chksum_uri = $uri) =~ s!/[^/]*$!/CHECKSUMS!;
1515 my $chk_file = $self->source_for($mirror) . "/$dist->{cpanid}.CHECKSUMS";
1516 $self->mask_output( diag_progress => "Fetching $chksum_uri" );
1517 $self->mirror($chksum_uri, $chk_file);
1518  
1519 unless (-e $chk_file) {
1520 $self->diag_fail("Fetching $chksum_uri failed.\n");
1521 return;
1522 }
1523  
1524 $self->diag_ok;
1525 $self->verify_checksums_signature($chk_file) or return;
1526 $self->verify_checksum($file, $chk_file);
1527 }
1528  
1529 sub verify_checksum {
1530 my($self, $file, $chk_file) = @_;
1531  
1532 $self->chat("Verifying the SHA1 for $file\n");
1533  
1534 open my $fh, "<$chk_file" or die "$chk_file: $!";
1535 my $data = join '', <$fh>;
1536 $data =~ s/\015?\012/\n/g;
1537  
1538 require Safe; # no fatpack
1539 my $chksum = Safe->new->reval($data);
1540  
1541 if (!ref $chksum or ref $chksum ne 'HASH') {
1542 $self->diag_fail("! Checksum file downloaded from $chk_file is broken.\n");
1543 return;
1544 }
1545  
1546 if (my $sha = $chksum->{$file}{sha256}) {
1547 my $hex = $self->sha_for(256, $file);
1548 if ($hex eq $sha) {
1549 $self->chat("Checksum for $file: Verified!\n");
1550 } else {
1551 $self->diag_fail("Checksum mismatch for $file\n");
1552 return;
1553 }
1554 } else {
1555 $self->chat("Checksum for $file not found in CHECKSUMS.\n");
1556 return;
1557 }
1558 }
1559  
1560 sub sha_for {
1561 my($self, $alg, $file) = @_;
1562  
1563 require Digest::SHA; # no fatpack
1564  
1565 open my $fh, "<", $file or die "$file: $!";
1566 my $dg = Digest::SHA->new($alg);
1567 my($data);
1568 while (read($fh, $data, 4096)) {
1569 $dg->add($data);
1570 }
1571  
1572 return $dg->hexdigest;
1573 }
1574  
1575 sub verify_signature {
1576 my($self, $dist) = @_;
1577  
1578 $self->diag_progress("Verifying the SIGNATURE file");
1579 my $out = `@{[ qs $self->{cpansign} ]} -v --skip 2>&1`;
1580 $self->log($out);
1581  
1582 if ($out =~ /Signature verified OK/) {
1583 $self->diag_ok("Verified OK");
1584 return 1;
1585 } else {
1586 $self->diag_fail("SIGNATURE verification for $dist->{filename} failed\n");
1587 return;
1588 }
1589 }
1590  
1591 sub resolve_name {
1592 my($self, $module, $version, $dep) = @_;
1593  
1594 if ($dep && $dep->url) {
1595 if ($dep->url =~ m!authors/id/(.*)!) {
1596 return $self->cpan_dist($1, $dep->url);
1597 } else {
1598 return { uris => [ $dep->url ] };
1599 }
1600 }
1601  
1602 if ($dep && $dep->dist) {
1603 return $self->cpan_dist($dep->dist, undef, $dep->mirror);
1604 }
1605  
1606 # Git
1607 if ($module =~ /(?:^git:|\.git(?:@.+)?$)/) {
1608 return $self->git_uri($module);
1609 }
1610  
1611 # URL
1612 if ($module =~ /^(ftp|https?|file):/) {
1613 if ($module =~ m!authors/id/(.*)!) {
1614 return $self->cpan_dist($1, $module);
1615 } else {
1616 return { uris => [ $module ] };
1617 }
1618 }
1619  
1620 # Directory
1621 if ($module =~ m!^[\./]! && -d $module) {
1622 return {
1623 source => 'local',
1624 dir => Cwd::abs_path($module),
1625 };
1626 }
1627  
1628 # File
1629 if (-f $module) {
1630 return {
1631 source => 'local',
1632 uris => [ "file://" . Cwd::abs_path($module) ],
1633 };
1634 }
1635  
1636 # cpan URI
1637 if ($module =~ s!^cpan:///distfile/!!) {
1638 return $self->cpan_dist($module);
1639 }
1640  
1641 # PAUSEID/foo
1642 # P/PA/PAUSEID/foo
1643 if ($module =~ m!^(?:[A-Z]/[A-Z]{2}/)?([A-Z]{2}[\-A-Z0-9]*/.*)$!) {
1644 return $self->cpan_dist($1);
1645 }
1646  
1647 # Module name
1648 return $self->search_module($module, $version);
1649 }
1650  
1651 sub cpan_module_common {
1652 my($self, $match) = @_;
1653  
1654 (my $distfile = $match->{uri}) =~ s!^cpan:///distfile/!!;
1655  
1656 my $mirrors = $self->{mirrors};
1657 if ($match->{download_uri}) {
1658 (my $mirror = $match->{download_uri}) =~ s!/authors/id/.*$!!;
1659 $mirrors = [$mirror];
1660 }
1661  
1662 local $self->{mirrors} = $mirrors;
1663 return $self->cpan_module($match->{package}, $distfile, $match->{version});
1664 }
1665  
1666 sub cpan_module {
1667 my($self, $module, $dist_file, $version) = @_;
1668  
1669 my $dist = $self->cpan_dist($dist_file);
1670 $dist->{module} = $module;
1671 $dist->{module_version} = $version if $version && $version ne 'undef';
1672  
1673 return $dist;
1674 }
1675  
1676 sub cpan_dist {
1677 my($self, $dist, $url, $mirror) = @_;
1678  
1679 # strip trailing slash
1680 $mirror =~ s!/$!! if $mirror;
1681  
1682 $dist =~ s!^([A-Z]{2})!substr($1,0,1)."/".substr($1,0,2)."/".$1!e;
1683  
1684 require CPAN::DistnameInfo;
1685 my $d = CPAN::DistnameInfo->new($dist);
1686  
1687 if ($url) {
1688 $url = [ $url ] unless ref $url eq 'ARRAY';
1689 } else {
1690 my $id = $d->cpanid;
1691 my $fn = substr($id, 0, 1) . "/" . substr($id, 0, 2) . "/" . $id . "/" . $d->filename;
1692  
1693 my @mirrors = $mirror ? ($mirror) : @{$self->{mirrors}};
1694 my @urls = map "$_/authors/id/$fn", @mirrors;
1695  
1696 $url = \@urls,
1697 }
1698  
1699 return {
1700 $d->properties,
1701 source => 'cpan',
1702 uris => $url,
1703 };
1704 }
1705  
1706 sub git_uri {
1707 my ($self, $uri) = @_;
1708  
1709 # similar to http://www.pip-installer.org/en/latest/logic.html#vcs-support
1710 # git URL has to end with .git when you need to use pin @ commit/tag/branch
1711  
1712 ($uri, my $commitish) = split /(?<=\.git)@/i, $uri, 2;
1713  
1714 my $dir = File::Temp::tempdir(CLEANUP => 1);
1715  
1716 $self->mask_output( diag_progress => "Cloning $uri" );
1717 $self->run_command([ 'git', 'clone', $uri, $dir ]);
1718  
1719 unless (-e "$dir/.git") {
1720 $self->diag_fail("Failed cloning git repository $uri", 1);
1721 return;
1722 }
1723  
1724 if ($commitish) {
1725 require File::pushd;
1726 my $dir = File::pushd::pushd($dir);
1727  
1728 unless ($self->run_command([ 'git', 'checkout', $commitish ])) {
1729 $self->diag_fail("Failed to checkout '$commitish' in git repository $uri\n");
1730 return;
1731 }
1732 }
1733  
1734 $self->diag_ok;
1735  
1736 return {
1737 source => 'local',
1738 dir => $dir,
1739 };
1740 }
1741  
1742 sub core_version_for {
1743 my($self, $module) = @_;
1744  
1745 require Module::CoreList; # no fatpack
1746 unless (exists $Module::CoreList::version{$]+0}) {
1747 die sprintf("Module::CoreList %s (loaded from %s) doesn't seem to have entries for perl $]. " .
1748 "You're strongly recommended to upgrade Module::CoreList from CPAN.\n",
1749 $Module::CoreList::VERSION, $INC{"Module/CoreList.pm"});
1750 }
1751  
1752 unless (exists $Module::CoreList::version{$]+0}{$module}) {
1753 return -1;
1754 }
1755  
1756 return $Module::CoreList::version{$]+0}{$module};
1757 }
1758  
1759 sub search_inc {
1760 my $self = shift;
1761 $self->{search_inc} ||= do {
1762 # strip lib/ and fatlib/ from search path when booted from dev
1763 if (defined $::Bin) {
1764 [grep !/^\Q$::Bin\E\/..\/(?:fat)?lib$/, @INC]
1765 } else {
1766 [@INC]
1767 }
1768 };
1769 }
1770  
1771 sub check_module {
1772 my($self, $mod, $want_ver) = @_;
1773  
1774 require Module::Metadata;
1775 my $meta = Module::Metadata->new_from_module($mod, inc => $self->search_inc)
1776 or return 0, undef;
1777  
1778 my $version = $meta->version;
1779  
1780 # When -L is in use, the version loaded from 'perl' library path
1781 # might be newer than (or actually wasn't core at) the version
1782 # that is shipped with the current perl
1783 if ($self->{self_contained} && $self->loaded_from_perl_lib($meta)) {
1784 $version = $self->core_version_for($mod);
1785 return 0, undef if $version && $version == -1;
1786 }
1787  
1788 $self->{local_versions}{$mod} = $version;
1789  
1790 if ($self->is_deprecated($meta)){
1791 return 0, $version;
1792 } elsif ($self->satisfy_version($mod, $version, $want_ver)) {
1793 return 1, ($version || 'undef');
1794 } else {
1795 return 0, $version;
1796 }
1797 }
1798  
1799 sub satisfy_version {
1800 my($self, $mod, $version, $want_ver) = @_;
1801  
1802 $want_ver = '0' unless defined($want_ver) && length($want_ver);
1803  
1804 require CPAN::Meta::Requirements;
1805 my $requirements = CPAN::Meta::Requirements->new;
1806 $requirements->add_string_requirement($mod, $want_ver);
1807 $requirements->accepts_module($mod, $version);
1808 }
1809  
1810 sub unsatisfy_how {
1811 my($self, $ver, $want_ver) = @_;
1812  
1813 if ($want_ver =~ /^[v0-9\.\_]+$/) {
1814 return "$ver < $want_ver";
1815 } else {
1816 return "$ver doesn't satisfy $want_ver";
1817 }
1818 }
1819  
1820 sub is_deprecated {
1821 my($self, $meta) = @_;
1822  
1823 my $deprecated = eval {
1824 require Module::CoreList; # no fatpack
1825 Module::CoreList::is_deprecated($meta->{module});
1826 };
1827  
1828 return $deprecated && $self->loaded_from_perl_lib($meta);
1829 }
1830  
1831 sub loaded_from_perl_lib {
1832 my($self, $meta) = @_;
1833  
1834 require Config;
1835 my @dirs = qw(archlibexp privlibexp);
1836 if ($self->{self_contained} && ! $self->{exclude_vendor} && $Config{vendorarch}) {
1837 unshift @dirs, qw(vendorarch vendorlibexp);
1838 }
1839 for my $dir (@dirs) {
1840 my $confdir = $Config{$dir};
1841 if ($confdir eq substr($meta->filename, 0, length($confdir))) {
1842 return 1;
1843 }
1844 }
1845  
1846 return;
1847 }
1848  
1849 sub should_install {
1850 my($self, $mod, $ver) = @_;
1851  
1852 $self->chat("Checking if you have $mod $ver ... ");
1853 my($ok, $local) = $self->check_module($mod, $ver);
1854  
1855 if ($ok) { $self->chat("Yes ($local)\n") }
1856 elsif ($local) { $self->chat("No (" . $self->unsatisfy_how($local, $ver) . ")\n") }
1857 else { $self->chat("No\n") }
1858  
1859 return $mod unless $ok;
1860 return;
1861 }
1862  
1863 sub check_perl_version {
1864 my($self, $version) = @_;
1865 require CPAN::Meta::Requirements;
1866 my $req = CPAN::Meta::Requirements->from_string_hash({ perl => $version });
1867 $req->accepts_module(perl => $]);
1868 }
1869  
1870 sub install_deps {
1871 my($self, $dir, $depth, @deps) = @_;
1872  
1873 my(@install, %seen, @fail);
1874 for my $dep (@deps) {
1875 next if $seen{$dep->module};
1876 if ($dep->module eq 'perl') {
1877 if ($dep->is_requirement && !$self->check_perl_version($dep->version)) {
1878 $self->diag("Needs perl @{[$dep->version]}, you have $]\n");
1879 push @fail, 'perl';
1880 }
1881 } elsif ($self->should_install($dep->module, $dep->version)) {
1882 push @install, $dep;
1883 $seen{$dep->module} = 1;
1884 }
1885 }
1886  
1887 if (@install) {
1888 $self->diag("==> Found dependencies: " . join(", ", map $_->module, @install) . "\n");
1889 }
1890  
1891 for my $dep (@install) {
1892 $self->install_module($dep->module, $depth + 1, $dep->version, $dep);
1893 }
1894  
1895 $self->chdir($self->{base});
1896 $self->chdir($dir) if $dir;
1897  
1898 if ($self->{scandeps}) {
1899 return 1; # Don't check if dependencies are installed, since with --scandeps they aren't
1900 }
1901 my @not_ok = $self->unsatisfied_deps(@deps);
1902 if (@not_ok) {
1903 return 0, \@not_ok;
1904 } else {
1905 return 1;
1906 }
1907 }
1908  
1909 sub unsatisfied_deps {
1910 my($self, @deps) = @_;
1911  
1912 require CPAN::Meta::Check;
1913 require CPAN::Meta::Requirements;
1914  
1915 my $reqs = CPAN::Meta::Requirements->new;
1916 for my $dep (grep $_->is_requirement, @deps) {
1917 $reqs->add_string_requirement($dep->module => $dep->requires_version || '0');
1918 }
1919  
1920 my $ret = CPAN::Meta::Check::check_requirements($reqs, 'requires', $self->{search_inc});
1921 grep defined, values %$ret;
1922 }
1923  
1924 sub install_deps_bailout {
1925 my($self, $target, $dir, $depth, @deps) = @_;
1926  
1927 my($ok, $fail) = $self->install_deps($dir, $depth, @deps);
1928 if (!$ok) {
1929 $self->diag_fail("Installing the dependencies failed: " . join(", ", @$fail), 1);
1930 unless ($self->prompt_bool("Do you want to continue building $target anyway?", "n")) {
1931 $self->diag_fail("Bailing out the installation for $target.", 1);
1932 return;
1933 }
1934 }
1935  
1936 return 1;
1937 }
1938  
1939 sub build_stuff {
1940 my($self, $stuff, $dist, $depth) = @_;
1941  
1942 if ($self->{verify} && -e 'SIGNATURE') {
1943 $self->verify_signature($dist) or return;
1944 }
1945  
1946 require CPAN::Meta;
1947  
1948 my($meta_file) = grep -f, qw(META.json META.yml);
1949 if ($meta_file) {
1950 $self->chat("Checking configure dependencies from $meta_file\n");
1951 $dist->{cpanmeta} = eval { CPAN::Meta->load_file($meta_file) };
1952 } elsif ($dist->{dist} && $dist->{version}) {
1953 $self->chat("META.yml/json not found. Creating skeleton for it.\n");
1954 $dist->{cpanmeta} = CPAN::Meta->new({ name => $dist->{dist}, version => $dist->{version} });
1955 }
1956  
1957 $dist->{meta} = $dist->{cpanmeta} ? $dist->{cpanmeta}->as_struct : {};
1958  
1959 if ($self->opts_in_static_install($dist->{cpanmeta})) {
1960 $dist->{static_install} = 1;
1961 }
1962  
1963 my @config_deps;
1964  
1965 if ($dist->{cpanmeta}) {
1966 push @config_deps, Menlo::Dependency->from_prereqs(
1967 $dist->{cpanmeta}->effective_prereqs, ['configure'], $self->{install_types},
1968 );
1969 }
1970  
1971 if (-e 'Build.PL' && !@config_deps) {
1972 push @config_deps, Menlo::Dependency->from_versions(
1973 { 'Module::Build' => '0.38' }, 'configure',
1974 );
1975 }
1976  
1977 $self->merge_with_cpanfile($dist, \@config_deps);
1978  
1979 $self->upgrade_toolchain(\@config_deps);
1980  
1981 my $target = $dist->{meta}{name} ? "$dist->{meta}{name}-$dist->{meta}{version}" : $dist->{dir};
1982  
1983 unless ($self->skip_configure($dist, $depth)) {
1984 $self->install_deps_bailout($target, $dist->{dir}, $depth, @config_deps)
1985 or return;
1986 }
1987  
1988 $self->diag_progress("Configuring $target");
1989  
1990 my $configure_state = $self->configure_this($dist, $depth);
1991 $self->diag_ok($configure_state->{configured_ok} ? "OK" : "N/A");
1992  
1993 if ($dist->{cpanmeta} && $dist->{source} eq 'cpan') {
1994 $dist->{provides} = $dist->{cpanmeta}{provides} || $self->extract_packages($dist->{cpanmeta}, ".");
1995 }
1996  
1997 # install direct 'test' dependencies for --installdeps, even with --notest
1998 # TODO: remove build dependencies for static install
1999 my $deps_only = $self->deps_only($depth);
2000 $dist->{want_phases} = $self->{notest} && !$self->deps_only($depth)
2001 ? [qw( build runtime )] : [qw( build test runtime )];
2002  
2003 push @{$dist->{want_phases}}, 'develop' if $self->{with_develop} && $depth == 0;
2004 push @{$dist->{want_phases}}, 'configure' if $self->{with_configure} && $depth == 0;
2005  
2006 my @deps = $self->find_prereqs($dist);
2007 my $module_name = $self->find_module_name($configure_state) || $dist->{meta}{name};
2008 $module_name =~ s/-/::/g;
2009  
2010 if ($self->{showdeps}) {
2011 for my $dep (@config_deps, @deps) {
2012 print $dep->module, ($dep->version ? ("~".$dep->version) : ""), "\n";
2013 }
2014 return 1;
2015 }
2016  
2017 my $distname = $dist->{meta}{name} ? "$dist->{meta}{name}-$dist->{meta}{version}" : $stuff;
2018  
2019 my $walkup;
2020 if ($self->{scandeps}) {
2021 $walkup = $self->scandeps_append_child($dist);
2022 }
2023  
2024 $self->install_deps_bailout($distname, $dist->{dir}, $depth, @deps)
2025 or return;
2026  
2027 if ($self->{scandeps}) {
2028 unless ($configure_state->{configured_ok}) {
2029 my $diag = <<DIAG;
2030 ! Configuring $distname failed. See $self->{log} for details.
2031 ! You might have to install the following modules first to get --scandeps working correctly.
2032 DIAG
2033 if (@config_deps) {
2034 my @tree = @{$self->{scandeps_tree}};
2035 $diag .= "!\n" . join("", map "! * $_->[0]{module}\n", @tree[0..$#tree-1]) if @tree;
2036 }
2037 $self->diag("!\n$diag!\n", 1);
2038 }
2039 $walkup->();
2040 return 1;
2041 }
2042  
2043 if ($self->{installdeps} && $depth == 0) {
2044 if ($configure_state->{configured_ok}) {
2045 $self->diag("<== Installed dependencies for $stuff. Finishing.\n");
2046 return 1;
2047 } else {
2048 $self->diag("! Configuring $distname failed. See $self->{log} for details.\n", 1);
2049 return;
2050 }
2051 }
2052  
2053 my $installed;
2054 if ($configure_state->{static_install}) {
2055 $self->diag_progress("Building " . ($self->{notest} ? "" : "and testing ") . $distname);
2056 $self->build(sub { $configure_state->{static_install}->build }, $distname, $dist, $depth) &&
2057 $self->test(sub { $configure_state->{static_install}->build("test") }, $distname, $dist, $depth) &&
2058 $self->install(sub { $configure_state->{static_install}->build("install") }, [], $dist, $depth) &&
2059 $installed++;
2060 } elsif ($configure_state->{use_module_build} && -e 'Build' && -f _) {
2061 $self->diag_progress("Building " . ($self->{notest} ? "" : "and testing ") . $distname);
2062 $self->build([ $self->{perl}, "./Build" ], $distname, $dist, $depth) &&
2063 $self->test([ $self->{perl}, "./Build", "test" ], $distname, $dist, $depth) &&
2064 $self->install([ $self->{perl}, "./Build", "install" ], [ "--uninst", 1 ], $dist, $depth) &&
2065 $installed++;
2066 } elsif ($self->{make} && -e 'Makefile') {
2067 $self->diag_progress("Building " . ($self->{notest} ? "" : "and testing ") . $distname);
2068 $self->build([ $self->{make} ], $distname, $dist, $depth) &&
2069 $self->test([ $self->{make}, "test" ], $distname, $dist, $depth) &&
2070 $self->install([ $self->{make}, "install" ], [ "UNINST=1" ], $dist, $depth) &&
2071 $installed++;
2072 } else {
2073 my $why;
2074 my $configure_failed = $configure_state->{configured} && !$configure_state->{configured_ok};
2075 if ($configure_failed) { $why = "Configure failed for $distname." }
2076 elsif ($self->{make}) { $why = "The distribution doesn't have a proper Makefile.PL/Build.PL" }
2077 else { $why = "Can't configure the distribution. You probably need to have 'make'." }
2078  
2079 $self->diag_fail("$why See $self->{log} for details.", 1);
2080 return;
2081 }
2082  
2083 if ($installed && $self->{test_only}) {
2084 $self->diag_ok;
2085 $self->diag("Successfully tested $distname\n", 1);
2086 } elsif ($installed) {
2087 my $local = $self->{local_versions}{$dist->{module} || ''};
2088 my $version = $dist->{module_version} || $dist->{meta}{version} || $dist->{version};
2089 my $reinstall = $local && ($local eq $version);
2090 my $action = $local && !$reinstall
2091 ? $self->is_downgrade($version, $local)
2092 ? "downgraded"
2093 : "upgraded"
2094 : undef;
2095  
2096 my $how = $reinstall ? "reinstalled $distname"
2097 : $local ? "installed $distname ($action from $local)"
2098 : "installed $distname" ;
2099 my $msg = "Successfully $how";
2100 $self->diag_ok;
2101 $self->diag("$msg\n", 1);
2102 $self->{installed_dists}++;
2103 $self->save_meta($stuff, $dist, $module_name, \@config_deps, \@deps);
2104 return 1;
2105 } else {
2106 my $what = $self->{test_only} ? "Testing" : "Installing";
2107 $self->diag_fail("$what $stuff failed. See $self->{log} for details. Retry with --force to force install it.", 1);
2108 return;
2109 }
2110 }
2111  
2112 sub is_downgrade {
2113 my($self, $va, $vb) = @_;
2114 eval { version::->new($va) < $vb };
2115 }
2116  
2117 sub opts_in_static_install {
2118 my($self, $meta) = @_;
2119  
2120 return if !$self->{static_install};
2121  
2122 # --sudo requires running a separate shell to prevent persistent configuration
2123 # uninstall-shadows (default on < 5.12) is not supported in BuildPL spec, yet.
2124 return if $self->{sudo} or $self->{uninstall_shadows};
2125  
2126 return $meta->{x_static_install} && $meta->{x_static_install} == 1;
2127 }
2128  
2129 sub skip_configure {
2130 my($self, $dist, $depth) = @_;
2131  
2132 return 1 if $self->{skip_configure};
2133 return 1 if $dist->{static_install};
2134 return 1 if $self->no_dynamic_config($dist->{meta}) && $self->deps_only($depth);
2135  
2136 return;
2137 }
2138  
2139 sub no_dynamic_config {
2140 my($self, $meta) = @_;
2141 exists $meta->{dynamic_config} && $meta->{dynamic_config} == 0;
2142 }
2143  
2144 sub deps_only {
2145 my($self, $depth) = @_;
2146 ($self->{installdeps} && $depth == 0)
2147 or $self->{showdeps}
2148 or $self->{scandeps};
2149 }
2150  
2151 sub perl_requirements {
2152 my($self, @requires) = @_;
2153  
2154 my @perl;
2155 for my $requires (grep defined, @requires) {
2156 if (exists $requires->{perl}) {
2157 push @perl, Menlo::Dependency->new(perl => $requires->{perl});
2158 }
2159 }
2160  
2161 return @perl;
2162 }
2163  
2164 sub configure_this {
2165 my($self, $dist, $depth) = @_;
2166  
2167 my $deps_only = $self->deps_only($depth);
2168 if (-e $self->{cpanfile_path} && $deps_only) {
2169 require Module::CPANfile;
2170 $dist->{cpanfile} = eval { Module::CPANfile->load($self->{cpanfile_path}) };
2171 $self->diag_fail($@, 1) if $@;
2172  
2173 $self->{cpanfile_global} ||= $dist->{cpanfile};
2174  
2175 return {
2176 configured => 1,
2177 configured_ok => !!$dist->{cpanfile},
2178 use_module_build => 0,
2179 };
2180 }
2181  
2182 if ($self->{skip_configure}) {
2183 my $eumm = -e 'Makefile';
2184 my $mb = -e 'Build' && -f _;
2185 return {
2186 configured => 1,
2187 configured_ok => $eumm || $mb,
2188 use_module_build => $mb,
2189 };
2190 }
2191  
2192 if ($deps_only && $self->no_dynamic_config($dist->{meta})) {
2193 return {
2194 configured => 1,
2195 configured_ok => exists $dist->{meta}{prereqs},
2196 use_module_build => 0,
2197 };
2198 }
2199  
2200 my $state = {};
2201  
2202 my $try_static = sub {
2203 if ($dist->{static_install}) {
2204 $self->chat("Distribution opts in x_static_install: $dist->{meta}{x_static_install}\n");
2205 $self->static_install_configure($state, $dist, $depth);
2206 }
2207 };
2208  
2209 my $try_eumm = sub {
2210 if (-e 'Makefile.PL') {
2211 $self->chat("Running Makefile.PL\n");
2212  
2213 # NOTE: according to Devel::CheckLib, most XS modules exit
2214 # with 0 even if header files are missing, to avoid receiving
2215 # tons of FAIL reports in such cases. So exit code can't be
2216 # trusted if it went well.
2217 if ($self->configure([ $self->{perl}, "Makefile.PL" ], $dist, $depth)) {
2218 $state->{configured_ok} = -e 'Makefile';
2219 }
2220 $state->{configured}++;
2221 }
2222 };
2223  
2224 my $try_mb = sub {
2225 if (-e 'Build.PL') {
2226 $self->chat("Running Build.PL\n");
2227 if ($self->configure([ $self->{perl}, "Build.PL" ], $dist, $depth)) {
2228 $state->{configured_ok} = -e 'Build' && -f _;
2229 }
2230 $state->{use_module_build}++;
2231 $state->{configured}++;
2232 }
2233 };
2234  
2235 for my $try ($try_static, $try_mb, $try_eumm) {
2236 $try->();
2237 last if $state->{configured_ok};
2238 }
2239  
2240 unless ($state->{configured_ok}) {
2241 while (1) {
2242 my $ans = lc $self->prompt("Configuring $dist->{dist} failed.\nYou can s)kip, r)etry, e)xamine build log, or l)ook ?", "s");
2243 last if $ans eq 's';
2244 return $self->configure_this($dist, $depth) if $ans eq 'r';
2245 $self->show_build_log if $ans eq 'e';
2246 $self->look if $ans eq 'l';
2247 }
2248 }
2249  
2250 return $state;
2251 }
2252  
2253 sub static_install_configure {
2254 my($self, $state, $dist, $depth) = @_;
2255  
2256 my $args = $depth == 0 ? $self->{build_args}{configure} : [];
2257  
2258 require Menlo::Builder::Static;
2259 my $builder = Menlo::Builder::Static->new(meta => $dist->{cpanmeta});
2260 $self->configure(sub { $builder->configure($args || []) }, $dist, $depth);
2261  
2262 $state->{configured_ok} = 1;
2263 $state->{static_install} = $builder;
2264 $state->{configured}++;
2265 }
2266  
2267 sub find_module_name {
2268 my($self, $state) = @_;
2269  
2270 return unless $state->{configured_ok};
2271  
2272 if ($state->{use_module_build} &&
2273 -e "_build/build_params") {
2274 my $params = do { open my $in, "_build/build_params"; eval(join "", <$in>) };
2275 return eval { $params->[2]{module_name} } || undef;
2276 } elsif (-e "Makefile") {
2277 open my $mf, "Makefile";
2278 while (<$mf>) {
2279 if (/^\#\s+NAME\s+=>\s+(.*)/) {
2280 return eval($1);
2281 }
2282 }
2283 }
2284  
2285 return;
2286 }
2287  
2288 sub list_files {
2289 my $self = shift;
2290  
2291 if (-e 'MANIFEST') {
2292 require ExtUtils::Manifest;
2293 my $manifest = eval { ExtUtils::Manifest::manifind() } || {};
2294 return sort { lc $a cmp lc $b } keys %$manifest;
2295 } else {
2296 require File::Find;
2297 my @files;
2298 my $finder = sub {
2299 my $name = $File::Find::name;
2300 $name =~ s!\.[/\\]!!;
2301 push @files, $name;
2302 };
2303 File::Find::find($finder, ".");
2304 return sort { lc $a cmp lc $b } @files;
2305 }
2306 }
2307  
2308 sub extract_packages {
2309 my($self, $meta, $dir) = @_;
2310  
2311 my $try = sub {
2312 my $file = shift;
2313 return 0 if $file =~ m!^(?:x?t|inc|local|perl5|fatlib|_build)/!;
2314 return 1 unless $meta->{no_index};
2315 return 0 if grep { $file =~ m!^$_/! } @{$meta->{no_index}{directory} || []};
2316 return 0 if grep { $file eq $_ } @{$meta->{no_index}{file} || []};
2317 return 1;
2318 };
2319  
2320 require Parse::PMFile;
2321  
2322 my @files = grep { /\.pm(?:\.PL)?$/ && $try->($_) } $self->list_files;
2323  
2324 my $provides = { };
2325  
2326 for my $file (@files) {
2327 my $parser = Parse::PMFile->new($meta, { UNSAFE => 1, ALLOW_DEV_VERSION => 1 });
2328 my $packages = $parser->parse($file);
2329  
2330 while (my($package, $meta) = each %$packages) {
2331 $provides->{$package} ||= {
2332 file => $meta->{infile},
2333 ($meta->{version} eq 'undef') ? () : (version => $meta->{version}),
2334 };
2335 }
2336 }
2337  
2338 return $provides;
2339 }
2340  
2341 sub save_meta {
2342 my($self, $module, $dist, $module_name, $config_deps, $build_deps) = @_;
2343  
2344 return unless $dist->{distvname} && $dist->{source} eq 'cpan';
2345  
2346 my $base = ($ENV{PERL_MM_OPT} || '') =~ /INSTALL_BASE=/
2347 ? ($self->install_base($ENV{PERL_MM_OPT}) . "/lib/perl5") : $Config{sitelibexp};
2348  
2349 my $provides = $dist->{provides};
2350  
2351 File::Path::mkpath("blib/meta", 0, 0777);
2352  
2353 my $local = {
2354 name => $module_name,
2355 target => $module,
2356 version => exists $provides->{$module_name}
2357 ? ($provides->{$module_name}{version} || $dist->{version}) : $dist->{version},
2358 dist => $dist->{distvname},
2359 pathname => $dist->{pathname},
2360 provides => $provides,
2361 };
2362  
2363 require JSON::PP;
2364 open my $fh, ">", "blib/meta/install.json" or die $!;
2365 print $fh JSON::PP::encode_json($local);
2366  
2367 File::Copy::copy("MYMETA.json", "blib/meta/MYMETA.json");
2368  
2369 my @cmd = (
2370 ($self->{sudo} ? 'sudo' : ()),
2371 $^X,
2372 '-MExtUtils::Install=install',
2373 '-e',
2374 qq[install({ 'blib/meta' => '$base/$Config{archname}/.meta/$dist->{distvname}' })],
2375 );
2376 $self->run_command(\@cmd);
2377 }
2378  
2379 sub install_base {
2380 my($self, $mm_opt) = @_;
2381 $mm_opt =~ /INSTALL_BASE=(\S+)/ and return $1;
2382 die "Your PERL_MM_OPT doesn't contain INSTALL_BASE";
2383 }
2384  
2385 sub configure_features {
2386 my($self, $dist, @features) = @_;
2387 map $_->identifier, grep { $self->effective_feature($dist, $_) } @features;
2388 }
2389  
2390 sub effective_feature {
2391 my($self, $dist, $feature) = @_;
2392  
2393 if ($dist->{depth} == 0) {
2394 my $value = $self->{features}{$feature->identifier};
2395 return $value if defined $value;
2396 return 1 if $self->{features}{__all};
2397 }
2398  
2399 if ($self->{interactive}) {
2400 require CPAN::Meta::Requirements;
2401  
2402 $self->diag("[@{[ $feature->description ]}]\n", 1);
2403  
2404 my $req = CPAN::Meta::Requirements->new;
2405 for my $phase (@{$dist->{want_phases}}) {
2406 for my $type (@{$self->{install_types}}) {
2407 $req->add_requirements($feature->prereqs->requirements_for($phase, $type));
2408 }
2409 }
2410  
2411 my $reqs = $req->as_string_hash;
2412 my @missing;
2413 for my $module (keys %$reqs) {
2414 if ($self->should_install($module, $req->{$module})) {
2415 push @missing, $module;
2416 }
2417 }
2418  
2419 if (@missing) {
2420 my $howmany = @missing;
2421 $self->diag("==> Found missing dependencies: " . join(", ", @missing) . "\n", 1);
2422 local $self->{prompt} = 1;
2423 return $self->prompt_bool("Install the $howmany optional module(s)?", "y");
2424 }
2425 }
2426  
2427 return;
2428 }
2429  
2430 sub find_prereqs {
2431 my($self, $dist) = @_;
2432  
2433 my @deps = $self->extract_meta_prereqs($dist);
2434  
2435 if ($dist->{module} =~ /^Bundle::/i) {
2436 push @deps, $self->bundle_deps($dist);
2437 }
2438  
2439 $self->merge_with_cpanfile($dist, \@deps);
2440  
2441 return @deps;
2442 }
2443  
2444 sub merge_with_cpanfile {
2445 my($self, $dist, $deps) = @_;
2446  
2447 if ($self->{cpanfile_requirements} && !$dist->{cpanfile}) {
2448 for my $dep (@$deps) {
2449 $dep->merge_with($self->{cpanfile_requirements});
2450 }
2451 }
2452  
2453 if ($self->{cpanfile_global}) {
2454 for my $dep (@$deps) {
2455 my $opts = $self->{cpanfile_global}->options_for_module($dep->module)
2456 or next;
2457  
2458 $dep->dist($opts->{dist}) if $opts->{dist};
2459 $dep->mirror($opts->{mirror}) if $opts->{mirror};
2460 $dep->url($opts->{url}) if $opts->{url};
2461 }
2462 }
2463 }
2464  
2465 sub extract_meta_prereqs {
2466 my($self, $dist) = @_;
2467  
2468 if ($dist->{cpanfile}) {
2469 my @features = $self->configure_features($dist, $dist->{cpanfile}->features);
2470 my $prereqs = $dist->{cpanfile}->prereqs_with(@features);
2471 # TODO: creating requirements is useful even without cpanfile to detect conflicting prereqs
2472 $self->{cpanfile_requirements} = $prereqs->merged_requirements($dist->{want_phases}, ['requires']);
2473 return Menlo::Dependency->from_prereqs($prereqs, $dist->{want_phases}, $self->{install_types});
2474 }
2475  
2476 require CPAN::Meta;
2477  
2478 my @meta = qw(MYMETA.json MYMETA.yml);
2479 if ($self->no_dynamic_config($dist->{meta})) {
2480 push @meta, qw(META.json META.yml);
2481 }
2482  
2483 my @deps;
2484 my($meta_file) = grep -f, @meta;
2485 if ($meta_file) {
2486 $self->chat("Checking dependencies from $meta_file ...\n");
2487 my $mymeta = eval { CPAN::Meta->load_file($meta_file, { lazy_validation => 1 }) };
2488 if ($mymeta) {
2489 $dist->{meta}{name} = $mymeta->name;
2490 $dist->{meta}{version} = $mymeta->version;
2491 return $self->extract_prereqs($mymeta, $dist);
2492 }
2493 }
2494  
2495 $self->diag_fail("No MYMETA file is found after configure. Your toolchain is too old?");
2496 return;
2497 }
2498  
2499 sub bundle_deps {
2500 my($self, $dist) = @_;
2501  
2502 my $match;
2503 if ($dist->{module}) {
2504 $match = sub {
2505 my $meta = Module::Metadata->new_from_file($_[0]);
2506 $meta && ($meta->name eq $dist->{module});
2507 };
2508 } else {
2509 $match = sub { 1 };
2510 }
2511  
2512 my @files;
2513 File::Find::find({
2514 wanted => sub {
2515 push @files, File::Spec->rel2abs($_) if /\.pm$/i && $match->($_);
2516 },
2517 no_chdir => 1,
2518 }, '.');
2519  
2520 my @deps;
2521  
2522 for my $file (@files) {
2523 open my $pod, "<", $file or next;
2524 my $in_contents;
2525 while (<$pod>) {
2526 if (/^=head\d\s+CONTENTS/) {
2527 $in_contents = 1;
2528 } elsif (/^=/) {
2529 $in_contents = 0;
2530 } elsif ($in_contents) {
2531 /^(\S+)\s*(\S+)?/
2532 and push @deps, Menlo::Dependency->new($1, $self->maybe_version($2));
2533 }
2534 }
2535 }
2536  
2537 return @deps;
2538 }
2539  
2540 sub maybe_version {
2541 my($self, $string) = @_;
2542 return $string && $string =~ /^\.?\d/ ? $string : undef;
2543 }
2544  
2545 sub extract_prereqs {
2546 my($self, $meta, $dist) = @_;
2547  
2548 my @features = $self->configure_features($dist, $meta->features);
2549  
2550 my $prereqs = $meta->effective_prereqs(\@features)->clone;
2551 $self->adjust_prereqs($dist, $prereqs);
2552  
2553 return Menlo::Dependency->from_prereqs($prereqs, $dist->{want_phases}, $self->{install_types});
2554 }
2555  
2556 sub adjust_prereqs {
2557 my($self, $dist, $prereqs) = @_;
2558  
2559 # Workaround for Module::Install 1.04 creating a bogus (higher) MakeMaker requirement that it needs in build_requires
2560 # Assuming MakeMaker requirement is already satisfied in configure_requires, there's no need to have higher version of
2561 # MakeMaker in build/test anyway. https://github.com/miyagawa/cpanminus/issues/463
2562 if (-e "inc/Module/Install.pm") {
2563 for my $phase (qw( build test runtime )) {
2564 my $reqs = $prereqs->requirements_for($phase, 'requires');
2565 if ($reqs->requirements_for_module('ExtUtils::MakeMaker')) {
2566 $reqs->clear_requirement('ExtUtils::MakeMaker');
2567 $reqs->add_minimum('ExtUtils::MakeMaker' => 0);
2568 }
2569 }
2570 }
2571  
2572 # Static installation is optional and we're adding runtime dependencies
2573 if ($dist->{static_install}) {
2574 my $reqs = $prereqs->requirements_for('test' => 'requires');
2575 $reqs->add_minimum('TAP::Harness::Env' => 0);
2576 }
2577 }
2578  
2579 sub cleanup_workdirs {
2580 my $self = shift;
2581  
2582 my $expire = time - 24 * 60 * 60 * $self->{auto_cleanup};
2583 my @targets;
2584  
2585 opendir my $dh, "$self->{home}/work";
2586 while (my $e = readdir $dh) {
2587 next if $e !~ /^(\d+)\.\d+$/; # {UNIX time}.{PID}
2588 my $time = $1;
2589 if ($time < $expire) {
2590 push @targets, "$self->{home}/work/$e";
2591 }
2592 }
2593  
2594 if (@targets) {
2595 if (@targets >= 64) {
2596 $self->diag("Expiring " . scalar(@targets) . " work directories. This might take a while...\n");
2597 } else {
2598 $self->chat("Expiring " . scalar(@targets) . " work directories.\n");
2599 }
2600 File::Path::rmtree(\@targets, 0, 0); # safe = 0, since blib usually doesn't have write bits
2601 }
2602 }
2603  
2604 sub scandeps_append_child {
2605 my($self, $dist) = @_;
2606  
2607 my $new_node = [ $dist, [] ];
2608  
2609 my $curr_node = $self->{scandeps_current} || [ undef, $self->{scandeps_tree} ];
2610 push @{$curr_node->[1]}, $new_node;
2611  
2612 $self->{scandeps_current} = $new_node;
2613  
2614 return sub { $self->{scandeps_current} = $curr_node };
2615 }
2616  
2617 sub dump_scandeps {
2618 my $self = shift;
2619  
2620 if ($self->{format} eq 'tree') {
2621 $self->walk_down(sub {
2622 my($dist, $depth) = @_;
2623 if ($depth == 0) {
2624 print "$dist->{distvname}\n";
2625 } else {
2626 print " " x ($depth - 1);
2627 print "\\_ $dist->{distvname}\n";
2628 }
2629 }, 1);
2630 } elsif ($self->{format} =~ /^dists?$/) {
2631 $self->walk_down(sub {
2632 my($dist, $depth) = @_;
2633 print $self->format_dist($dist), "\n";
2634 }, 0);
2635 } elsif ($self->{format} eq 'json') {
2636 require JSON::PP;
2637 print JSON::PP::encode_json($self->{scandeps_tree});
2638 } elsif ($self->{format} eq 'yaml') {
2639 require CPAN::Meta::YAML;
2640 print CPAN::Meta::YAML::Dump($self->{scandeps_tree});
2641 } else {
2642 $self->diag("Unknown format: $self->{format}\n");
2643 }
2644 }
2645  
2646 sub walk_down {
2647 my($self, $cb, $pre) = @_;
2648 $self->_do_walk_down($self->{scandeps_tree}, $cb, 0, $pre);
2649 }
2650  
2651 sub _do_walk_down {
2652 my($self, $children, $cb, $depth, $pre) = @_;
2653  
2654 # DFS - $pre determines when we call the callback
2655 for my $node (@$children) {
2656 $cb->($node->[0], $depth) if $pre;
2657 $self->_do_walk_down($node->[1], $cb, $depth + 1, $pre);
2658 $cb->($node->[0], $depth) unless $pre;
2659 }
2660 }
2661  
2662 sub DESTROY {
2663 my $self = shift;
2664 $self->{at_exit}->($self) if $self->{at_exit};
2665 }
2666  
2667 # Utils
2668  
2669 sub mirror {
2670 my($self, $uri, $local) = @_;
2671 if ($uri =~ /^file:/) {
2672 $self->file_mirror($uri, $local);
2673 } else {
2674 $self->{http}->mirror($uri, $local);
2675 }
2676 }
2677  
2678 sub untar { $_[0]->{_backends}{untar}->(@_) };
2679 sub unzip { $_[0]->{_backends}{unzip}->(@_) };
2680  
2681 sub uri_to_file {
2682 my($self, $uri) = @_;
2683  
2684 # file:///path/to/file -> /path/to/file
2685 # file://C:/path -> C:/path
2686 if ($uri =~ s!file:/+!!) {
2687 $uri = "/$uri" unless $uri =~ m![a-zA-Z]:!;
2688 }
2689  
2690 return $uri;
2691 }
2692  
2693 sub file_get {
2694 my($self, $uri) = @_;
2695 my $file = $self->uri_to_file($uri);
2696 open my $fh, "<$file" or return;
2697 join '', <$fh>;
2698 }
2699  
2700 sub file_mirror {
2701 my($self, $uri, $path) = @_;
2702 my $file = $self->uri_to_file($uri);
2703  
2704 my $source_mtime = (stat $file)[9];
2705  
2706 # Don't mirror a file that's already there (like the index)
2707 return 1 if -e $path && (stat $path)[9] >= $source_mtime;
2708  
2709 File::Copy::copy($file, $path);
2710  
2711 utime $source_mtime, $source_mtime, $path;
2712 }
2713  
2714 sub configure_http {
2715 my $self = shift;
2716  
2717 require HTTP::Tinyish;
2718  
2719 my @try = qw(HTTPTiny);
2720 unshift @try, 'Wget' if $self->{try_wget};
2721 unshift @try, 'Curl' if $self->{try_curl};
2722 unshift @try, 'LWP' if $self->{try_lwp};
2723  
2724 my @protocol = ('http');
2725 push @protocol, 'https'
2726 if grep /^https:/, @{$self->{mirrors}};
2727  
2728 my $backend;
2729 for my $try (map "HTTP::Tinyish::$_", @try) {
2730 if (my $meta = HTTP::Tinyish->configure_backend($try)) {
2731 if ((grep $try->supports($_), @protocol) == @protocol) {
2732 for my $tool (sort keys %$meta){
2733 (my $desc = $meta->{$tool}) =~ s/^(.*?)\n.*/$1/s;
2734 $self->chat("You have $tool: $desc\n");
2735 }
2736 $backend = $try;
2737 last;
2738 }
2739 }
2740 }
2741  
2742 $backend->new(agent => "Menlo/$Menlo::VERSION", verify_SSL => 1);
2743 }
2744  
2745 sub init_tools {
2746 my $self = shift;
2747  
2748 return if $self->{initialized}++;
2749  
2750 if ($self->{make} = which($Config{make})) {
2751 $self->chat("You have make $self->{make}\n");
2752 }
2753  
2754 $self->{http} = $self->configure_http;
2755  
2756 my $tar = which('tar');
2757 my $tar_ver;
2758 my $maybe_bad_tar = sub { WIN32 || BAD_TAR || (($tar_ver = `@{[ qs $tar ]} --version 2>/dev/null`) =~ /GNU.*1\.13/i) };
2759  
2760 if ($tar && !$maybe_bad_tar->()) {
2761 chomp $tar_ver;
2762 $self->chat("You have $tar: $tar_ver\n");
2763 $self->{_backends}{untar} = sub {
2764 my($self, $tarfile) = @_;
2765  
2766 my $xf = ($self->{verbose} ? 'v' : '')."xf";
2767 my $ar = $tarfile =~ /bz2$/ ? 'j' : 'z';
2768  
2769 my($root, @others) = `@{[ qs $tar ]} ${ar}tf @{[ qs $tarfile ]}`
2770 or return undef;
2771  
2772 FILE: {
2773 chomp $root;
2774 $root =~ s!^\./!!;
2775 $root =~ s{^(.+?)/.*$}{$1};
2776  
2777 if (!length($root)) {
2778 # archive had ./ as the first entry, so try again
2779 $root = shift(@others);
2780 redo FILE if $root;
2781 }
2782 }
2783  
2784 $self->run_command([ $tar, $ar.$xf, $tarfile ]);
2785 return $root if -d $root;
2786  
2787 $self->diag_fail("Bad archive: $tarfile");
2788 return undef;
2789 }
2790 } elsif ( $tar
2791 and my $gzip = which('gzip')
2792 and my $bzip2 = which('bzip2')) {
2793 $self->chat("You have $tar, $gzip and $bzip2\n");
2794 $self->{_backends}{untar} = sub {
2795 my($self, $tarfile) = @_;
2796  
2797 my $x = "x" . ($self->{verbose} ? 'v' : '') . "f -";
2798 my $ar = $tarfile =~ /bz2$/ ? $bzip2 : $gzip;
2799  
2800 my($root, @others) = `@{[ qs $ar ]} -dc @{[ qs $tarfile ]} | @{[ qs $tar ]} tf -`
2801 or return undef;
2802  
2803 FILE: {
2804 chomp $root;
2805 $root =~ s!^\./!!;
2806 $root =~ s{^(.+?)/.*$}{$1};
2807  
2808 if (!length($root)) {
2809 # archive had ./ as the first entry, so try again
2810 $root = shift(@others);
2811 redo FILE if $root;
2812 }
2813 }
2814  
2815 system "@{[ qs $ar ]} -dc @{[ qs $tarfile ]} | @{[ qs $tar ]} $x";
2816 return $root if -d $root;
2817  
2818 $self->diag_fail("Bad archive: $tarfile");
2819 return undef;
2820 }
2821 } elsif (eval { require Archive::Tar }) { # uses too much memory!
2822 $self->chat("Falling back to Archive::Tar $Archive::Tar::VERSION\n");
2823 $self->{_backends}{untar} = sub {
2824 my $self = shift;
2825 my $t = Archive::Tar->new($_[0]);
2826 my($root, @others) = $t->list_files;
2827 FILE: {
2828 $root =~ s!^\./!!;
2829 $root =~ s{^(.+?)/.*$}{$1};
2830  
2831 if (!length($root)) {
2832 # archive had ./ as the first entry, so try again
2833 $root = shift(@others);
2834 redo FILE if $root;
2835 }
2836 }
2837 $t->extract;
2838 return -d $root ? $root : undef;
2839 };
2840 } else {
2841 $self->{_backends}{untar} = sub {
2842 die "Failed to extract $_[1] - You need to have tar or Archive::Tar installed.\n";
2843 };
2844 }
2845  
2846 if (my $unzip = which('unzip')) {
2847 $self->chat("You have $unzip\n");
2848 $self->{_backends}{unzip} = sub {
2849 my($self, $zipfile) = @_;
2850  
2851 my @opt = $self->{verbose} ? () : ('-q');
2852 my(undef, $root, @others) = `@{[ qs $unzip ]} -t @{[ qs $zipfile ]}`
2853 or return undef;
2854 FILE: {
2855 chomp $root;
2856 if ($root !~ s{^\s+testing:\s+([^/]+)/.*?\s+OK$}{$1}) {
2857 $root = shift(@others);
2858 redo FILE if $root;
2859 }
2860 }
2861  
2862 $self->run_command([ $unzip, @opt, $zipfile ]);
2863 return $root if -d $root;
2864  
2865 $self->diag_fail("Bad archive: '$root' $zipfile");
2866 return undef;
2867 }
2868 } else {
2869 $self->{_backends}{unzip} = sub {
2870 eval { require Archive::Zip }
2871 or die "Failed to extract $_[1] - You need to have unzip or Archive::Zip installed.\n";
2872 my($self, $file) = @_;
2873 my $zip = Archive::Zip->new();
2874 my $status;
2875 $status = $zip->read($file);
2876 $self->diag_fail("Read of file '$file' failed")
2877 if $status != Archive::Zip::AZ_OK();
2878 my @members = $zip->members();
2879 for my $member ( @members ) {
2880 my $af = $member->fileName();
2881 next if ($af =~ m!^(/|\.\./)!);
2882 $status = $member->extractToFileNamed( $af );
2883 $self->diag_fail("Extracting of file 'af' from zipfile '$file' failed")
2884 if $status != Archive::Zip::AZ_OK();
2885 }
2886  
2887 my ($root) = $zip->membersMatching( qr<^[^/]+/$> );
2888 $root &&= $root->fileName;
2889 return -d $root ? $root : undef;
2890 };
2891 }
2892 }
2893  
2894 sub mask_uri_passwords {
2895 my($self, @strings) = @_;
2896 s{ (https?://) ([^:/]+) : [^@/]+ @ }{$1$2:********@}gx for @strings;
2897 return @strings;
2898 }
2899  
2900 1;
2901  
2902 __END__