This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
9e7385e4035f301b0b45bc2403393b90826b25d0
[perl5.git] / cpan / CPAN / lib / CPAN.pm
1 # -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
2 # vim: ts=4 sts=4 sw=4:
3 use strict;
4 package CPAN;
5 $CPAN::VERSION = '1.94_63';
6 $CPAN::VERSION =~ s/_//;
7
8 # we need to run chdir all over and we would get at wrong libraries
9 # there
10 use File::Spec ();
11 BEGIN {
12     if (File::Spec->can("rel2abs")) {
13         for my $inc (@INC) {
14             $inc = File::Spec->rel2abs($inc) unless ref $inc;
15         }
16     }
17 }
18 use CPAN::Author;
19 use CPAN::HandleConfig;
20 use CPAN::Version;
21 use CPAN::Bundle;
22 use CPAN::CacheMgr;
23 use CPAN::Complete;
24 use CPAN::Debug;
25 use CPAN::Distribution;
26 use CPAN::Distrostatus;
27 use CPAN::FTP;
28 use CPAN::Index 1.93; # https://rt.cpan.org/Ticket/Display.html?id=43349
29 use CPAN::InfoObj;
30 use CPAN::Module;
31 use CPAN::Prompt;
32 use CPAN::URL;
33 use CPAN::Queue;
34 use CPAN::Tarzip;
35 use CPAN::DeferredCode;
36 use CPAN::Shell;
37 use CPAN::LWP::UserAgent;
38 use CPAN::Exception::RecursiveDependency;
39 use CPAN::Exception::yaml_not_installed;
40
41 use Carp ();
42 use Config ();
43 use Cwd qw(chdir);
44 use DirHandle ();
45 use Exporter ();
46 use ExtUtils::MakeMaker qw(prompt); # for some unknown reason,
47                                     # 5.005_04 does not work without
48                                     # this
49 use File::Basename ();
50 use File::Copy ();
51 use File::Find;
52 use File::Path ();
53 use FileHandle ();
54 use Fcntl qw(:flock);
55 use Safe ();
56 use Sys::Hostname qw(hostname);
57 use Text::ParseWords ();
58 use Text::Wrap ();
59
60 # protect against "called too early"
61 sub find_perl ();
62 sub anycwd ();
63 sub _uniq;
64
65 no lib ".";
66
67 require Mac::BuildTools if $^O eq 'MacOS';
68 if ($ENV{PERL5_CPAN_IS_RUNNING} && $$ != $ENV{PERL5_CPAN_IS_RUNNING}) {
69     $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION} ||= $ENV{PERL5_CPAN_IS_RUNNING};
70     my @rec = _uniq split(/,/, $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION}), $$;
71     $ENV{PERL5_CPAN_IS_RUNNING_IN_RECURSION} = join ",", @rec;
72     # warn "# Note: Recursive call of CPAN.pm detected\n";
73     my $w = sprintf "# Note: CPAN.pm is running in process %d now", pop @rec;
74     my %sleep = (
75                  5 => 30,
76                  6 => 60,
77                  7 => 120,
78                 );
79     my $sleep = @rec > 7 ? 300 : ($sleep{scalar @rec}||0);
80     my $verbose = @rec >= 4;
81     while (@rec) {
82         $w .= sprintf " which has been called by process %d", pop @rec;
83     }
84     if ($sleep) {
85         $w .= ".\n\n# Sleeping $sleep seconds to protect other processes\n";
86     }
87     if ($verbose) {
88         warn $w;
89     }
90     local $| = 1;
91     while ($sleep > 0) {
92         printf "\r#%5d", --$sleep;
93         sleep 1;
94     }
95     print "\n";
96 }
97 $ENV{PERL5_CPAN_IS_RUNNING}=$$;
98 $ENV{PERL5_CPANPLUS_IS_RUNNING}=$$; # https://rt.cpan.org/Ticket/Display.html?id=23735
99
100 END { $CPAN::End++; &cleanup; }
101
102 $CPAN::Signal ||= 0;
103 $CPAN::Frontend ||= "CPAN::Shell";
104 unless (@CPAN::Defaultsites) {
105     @CPAN::Defaultsites = map {
106         CPAN::URL->new(TEXT => $_, FROM => "DEF")
107     }
108         "http://www.perl.org/CPAN/",
109         "ftp://ftp.perl.org/pub/CPAN/";
110 }
111 # $CPAN::iCwd (i for initial)
112 $CPAN::iCwd ||= CPAN::anycwd();
113 $CPAN::Perl ||= CPAN::find_perl();
114 $CPAN::Defaultdocs ||= "http://search.cpan.org/perldoc?";
115 $CPAN::Defaultrecent ||= "http://search.cpan.org/uploads.rdf";
116 $CPAN::Defaultrecent ||= "http://cpan.uwinnipeg.ca/htdocs/cpan.xml";
117
118 # our globals are getting a mess
119 use vars qw(
120             $AUTOLOAD
121             $Be_Silent
122             $CONFIG_DIRTY
123             $Defaultdocs
124             $Echo_readline
125             $Frontend
126             $GOTOSHELL
127             $HAS_USABLE
128             $Have_warned
129             $MAX_RECURSION
130             $META
131             $RUN_DEGRADED
132             $Signal
133             $SQLite
134             $Suppress_readline
135             $VERSION
136             $autoload_recursion
137             $term
138             @Defaultsites
139             @EXPORT
140            );
141
142 $MAX_RECURSION = 32;
143
144 @CPAN::ISA = qw(CPAN::Debug Exporter);
145
146 # note that these functions live in CPAN::Shell and get executed via
147 # AUTOLOAD when called directly
148 @EXPORT = qw(
149              autobundle
150              bundle
151              clean
152              cvs_import
153              expand
154              force
155              fforce
156              get
157              install
158              install_tested
159              is_tested
160              make
161              mkmyconfig
162              notest
163              perldoc
164              readme
165              recent
166              recompile
167              report
168              shell
169              smoke
170              test
171              upgrade
172             );
173
174 sub soft_chdir_with_alternatives ($);
175
176 {
177     $autoload_recursion ||= 0;
178
179     #-> sub CPAN::AUTOLOAD ;
180     sub AUTOLOAD { ## no critic
181         $autoload_recursion++;
182         my($l) = $AUTOLOAD;
183         $l =~ s/.*:://;
184         if ($CPAN::Signal) {
185             warn "Refusing to autoload '$l' while signal pending";
186             $autoload_recursion--;
187             return;
188         }
189         if ($autoload_recursion > 1) {
190             my $fullcommand = join " ", map { "'$_'" } $l, @_;
191             warn "Refusing to autoload $fullcommand in recursion\n";
192             $autoload_recursion--;
193             return;
194         }
195         my(%export);
196         @export{@EXPORT} = '';
197         CPAN::HandleConfig->load unless $CPAN::Config_loaded++;
198         if (exists $export{$l}) {
199             CPAN::Shell->$l(@_);
200         } else {
201             die(qq{Unknown CPAN command "$AUTOLOAD". }.
202                 qq{Type ? for help.\n});
203         }
204         $autoload_recursion--;
205     }
206 }
207
208 {
209     my $x = *SAVEOUT; # avoid warning
210     open($x,">&STDOUT") or die "dup failed";
211     my $redir = 0;
212     sub _redirect(@) {
213         #die if $redir;
214         local $_;
215         push(@_,undef);
216         while(defined($_=shift)) {
217             if (s/^\s*>//){
218                 my ($m) = s/^>// ? ">" : "";
219                 s/\s+//;
220                 $_=shift unless length;
221                 die "no dest" unless defined;
222                 open(STDOUT,">$m$_") or die "open:$_:$!\n";
223                 $redir=1;
224             } elsif ( s/^\s*\|\s*// ) {
225                 my $pipe="| $_";
226                 while(defined($_[0])){
227                     $pipe .= ' ' . shift;
228                 }
229                 open(STDOUT,$pipe) or die "open:$pipe:$!\n";
230                 $redir=1;
231             } else {
232                 push(@_,$_);
233             }
234         }
235         return @_;
236     }
237     sub _unredirect {
238         return unless $redir;
239         $redir = 0;
240         ## redirect: unredirect and propagate errors.  explicit close to wait for pipe.
241         close(STDOUT);
242         open(STDOUT,">&SAVEOUT");
243         die "$@" if "$@";
244         ## redirect: done
245     }
246 }
247
248 sub _uniq {
249     my(@list) = @_;
250     my %seen;
251     return grep { !$seen{$_}++ } @list;
252 }
253
254 #-> sub CPAN::shell ;
255 sub shell {
256     my($self) = @_;
257     $Suppress_readline = ! -t STDIN unless defined $Suppress_readline;
258     CPAN::HandleConfig->load unless $CPAN::Config_loaded++;
259
260     my $oprompt = shift || CPAN::Prompt->new;
261     my $prompt = $oprompt;
262     my $commandline = shift || "";
263     $CPAN::CurrentCommandId ||= 1;
264
265     local($^W) = 1;
266     unless ($Suppress_readline) {
267         require Term::ReadLine;
268         if (! $term
269             or
270             $term->ReadLine eq "Term::ReadLine::Stub"
271            ) {
272             $term = Term::ReadLine->new('CPAN Monitor');
273         }
274         if ($term->ReadLine eq "Term::ReadLine::Gnu") {
275             my $attribs = $term->Attribs;
276             $attribs->{attempted_completion_function} = sub {
277                 &CPAN::Complete::gnu_cpl;
278             }
279         } else {
280             $readline::rl_completion_function =
281                 $readline::rl_completion_function = 'CPAN::Complete::cpl';
282         }
283         if (my $histfile = $CPAN::Config->{'histfile'}) {{
284             unless ($term->can("AddHistory")) {
285                 $CPAN::Frontend->mywarn("Terminal does not support AddHistory.\n");
286                 last;
287             }
288             $META->readhist($term,$histfile);
289         }}
290         for ($CPAN::Config->{term_ornaments}) { # alias
291             local $Term::ReadLine::termcap_nowarn = 1;
292             $term->ornaments($_) if defined;
293         }
294         # $term->OUT is autoflushed anyway
295         my $odef = select STDERR;
296         $| = 1;
297         select STDOUT;
298         $| = 1;
299         select $odef;
300     }
301
302     $META->checklock();
303     my @cwd = grep { defined $_ and length $_ }
304         CPAN::anycwd(),
305               File::Spec->can("tmpdir") ? File::Spec->tmpdir() : (),
306                     File::Spec->rootdir();
307     my $try_detect_readline;
308     $try_detect_readline = $term->ReadLine eq "Term::ReadLine::Stub" if $term;
309     unless ($CPAN::Config->{inhibit_startup_message}) {
310         my $rl_avail = $Suppress_readline ? "suppressed" :
311             ($term->ReadLine ne "Term::ReadLine::Stub") ? "enabled" :
312                 "available (maybe install Bundle::CPAN or Bundle::CPANxxl?)";
313         $CPAN::Frontend->myprint(
314                                  sprintf qq{
315 cpan shell -- CPAN exploration and modules installation (v%s)
316 Enter 'h' for help.
317
318 },
319                                  $CPAN::VERSION,
320                                  $rl_avail
321                                 )
322     }
323     my($continuation) = "";
324     my $last_term_ornaments;
325   SHELLCOMMAND: while () {
326         if ($Suppress_readline) {
327             if ($Echo_readline) {
328                 $|=1;
329             }
330             print $prompt;
331             last SHELLCOMMAND unless defined ($_ = <> );
332             if ($Echo_readline) {
333                 # backdoor: I could not find a way to record sessions
334                 print $_;
335             }
336             chomp;
337         } else {
338             last SHELLCOMMAND unless
339                 defined ($_ = $term->readline($prompt, $commandline));
340         }
341         $_ = "$continuation$_" if $continuation;
342         s/^\s+//;
343         next SHELLCOMMAND if /^$/;
344         s/^\s*\?\s*/help /;
345         if (/^(?:q(?:uit)?|bye|exit)\s*$/i) {
346             last SHELLCOMMAND;
347         } elsif (s/\\$//s) {
348             chomp;
349             $continuation = $_;
350             $prompt = "    > ";
351         } elsif (/^\!/) {
352             s/^\!//;
353             my($eval) = $_;
354             package
355                 CPAN::Eval; # hide from the indexer
356             use strict;
357             use vars qw($import_done);
358             CPAN->import(':DEFAULT') unless $import_done++;
359             CPAN->debug("eval[$eval]") if $CPAN::DEBUG;
360             eval($eval);
361             warn $@ if $@;
362             $continuation = "";
363             $prompt = $oprompt;
364         } elsif (/./) {
365             my(@line);
366             eval { @line = Text::ParseWords::shellwords($_) };
367             warn($@), next SHELLCOMMAND if $@;
368             warn("Text::Parsewords could not parse the line [$_]"),
369                 next SHELLCOMMAND unless @line;
370             $CPAN::META->debug("line[".join("|",@line)."]") if $CPAN::DEBUG;
371             my $command = shift @line;
372             eval {
373                 local (*STDOUT)=*STDOUT;
374                 @line = _redirect(@line);
375                 CPAN::Shell->$command(@line)
376               };
377             my $command_error = $@;
378             _unredirect;
379             my $reported_error;
380             if ($command_error) {
381                 my $err = $command_error;
382                 if (ref $err and $err->isa('CPAN::Exception::blocked_urllist')) {
383                     $CPAN::Frontend->mywarn("Client not fully configured, please proceed with configuring.$err");
384                     $reported_error = ref $err;
385                 } else {
386                     # I'd prefer never to arrive here and make all errors exception objects
387                     if ($err =~ /\S/) {
388                         require Carp;
389                         require Dumpvalue;
390                         my $dv = Dumpvalue->new(tick => '"');
391                         Carp::cluck(sprintf "Catching error: %s", $dv->stringify($err));
392                     }
393                 }
394             }
395             if ($command =~ /^(
396                              # classic commands
397                              make
398                              |test
399                              |install
400                              |clean
401
402                              # pragmas for classic commands
403                              |ff?orce
404                              |notest
405
406                              # compounds
407                              |report
408                              |smoke
409                              |upgrade
410                             )$/x) {
411                 # only commands that tell us something about failed distros
412                 # eval necessary for people without an urllist
413                 eval {CPAN::Shell->failed($CPAN::CurrentCommandId,1);};
414                 if (my $err = $@) {
415                     unless (ref $err and $reported_error eq ref $err) {
416                         die $@;
417                     }
418                 }
419             }
420             soft_chdir_with_alternatives(\@cwd);
421             $CPAN::Frontend->myprint("\n");
422             $continuation = "";
423             $CPAN::CurrentCommandId++;
424             $prompt = $oprompt;
425         }
426     } continue {
427         $commandline = ""; # I do want to be able to pass a default to
428                            # shell, but on the second command I see no
429                            # use in that
430         $Signal=0;
431         CPAN::Queue->nullify_queue;
432         if ($try_detect_readline) {
433             if ($CPAN::META->has_inst("Term::ReadLine::Gnu")
434                 ||
435                 $CPAN::META->has_inst("Term::ReadLine::Perl")
436             ) {
437                 delete $INC{"Term/ReadLine.pm"};
438                 my $redef = 0;
439                 local($SIG{__WARN__}) = CPAN::Shell::paintdots_onreload(\$redef);
440                 require Term::ReadLine;
441                 $CPAN::Frontend->myprint("\n$redef subroutines in ".
442                                          "Term::ReadLine redefined\n");
443                 $GOTOSHELL = 1;
444             }
445         }
446         if ($term and $term->can("ornaments")) {
447             for ($CPAN::Config->{term_ornaments}) { # alias
448                 if (defined $_) {
449                     if (not defined $last_term_ornaments
450                         or $_ != $last_term_ornaments
451                     ) {
452                         local $Term::ReadLine::termcap_nowarn = 1;
453                         $term->ornaments($_);
454                         $last_term_ornaments = $_;
455                     }
456                 } else {
457                     undef $last_term_ornaments;
458                 }
459             }
460         }
461         for my $class (qw(Module Distribution)) {
462             # again unsafe meta access?
463             for my $dm (keys %{$CPAN::META->{readwrite}{"CPAN::$class"}}) {
464                 next unless $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor};
465                 CPAN->debug("BUG: $class '$dm' was in command state, resetting");
466                 delete $CPAN::META->{readwrite}{"CPAN::$class"}{$dm}{incommandcolor};
467             }
468         }
469         if ($GOTOSHELL) {
470             $GOTOSHELL = 0; # not too often
471             $META->savehist if $CPAN::term && $CPAN::term->can("GetHistory");
472             @_ = ($oprompt,"");
473             goto &shell;
474         }
475     }
476     soft_chdir_with_alternatives(\@cwd);
477 }
478
479 #-> CPAN::soft_chdir_with_alternatives ;
480 sub soft_chdir_with_alternatives ($) {
481     my($cwd) = @_;
482     unless (@$cwd) {
483         my $root = File::Spec->rootdir();
484         $CPAN::Frontend->mywarn(qq{Warning: no good directory to chdir to!
485 Trying '$root' as temporary haven.
486 });
487         push @$cwd, $root;
488     }
489     while () {
490         if (chdir $cwd->[0]) {
491             return;
492         } else {
493             if (@$cwd>1) {
494                 $CPAN::Frontend->mywarn(qq{Could not chdir to "$cwd->[0]": $!
495 Trying to chdir to "$cwd->[1]" instead.
496 });
497                 shift @$cwd;
498             } else {
499                 $CPAN::Frontend->mydie(qq{Could not chdir to "$cwd->[0]": $!});
500             }
501         }
502     }
503 }
504
505 sub _flock {
506     my($fh,$mode) = @_;
507     if ( $Config::Config{d_flock} || $Config::Config{d_fcntl_can_lock} ) {
508         return flock $fh, $mode;
509     } elsif (!$Have_warned->{"d_flock"}++) {
510         $CPAN::Frontend->mywarn("Your OS does not seem to support locking; continuing and ignoring all locking issues\n");
511         $CPAN::Frontend->mysleep(5);
512         return 1;
513     } else {
514         return 1;
515     }
516 }
517
518 sub _use_file_homedir () {
519     my $use_file_homedir = $CPAN::Config->{use_file_homedir};
520     unless (defined $use_file_homedir) {
521         if ($^O =~ /^(MSWin32|darwin)$/) {
522             $use_file_homedir = 1;
523         } else {
524             $use_file_homedir = 0;
525         }
526     }
527     if ($use_file_homedir
528         and not $CPAN::META->has_usable("File::HomeDir")) {
529         my $v = $File::HomeDir::VERSION;
530         if (CPAN::Version->vgt($v,0)) {
531             $CPAN::Frontend->mydie("Version of File::HomeDir ($v) is insufficient. Please upgrade or try 'o conf init use_file_homedir'");
532         } else {
533             $CPAN::Frontend->mydie("File::HomeDir not installed. Please install it or try 'o conf init use_file_homedir'");
534         }
535     }
536     return $use_file_homedir;
537 }
538
539 sub _yaml_module () {
540     my $yaml_module = $CPAN::Config->{yaml_module} || "YAML";
541     if (
542         $yaml_module ne "YAML"
543         &&
544         !$CPAN::META->has_inst($yaml_module)
545        ) {
546         # $CPAN::Frontend->mywarn("'$yaml_module' not installed, falling back to 'YAML'\n");
547         $yaml_module = "YAML";
548     }
549     if ($yaml_module eq "YAML"
550         &&
551         $CPAN::META->has_inst($yaml_module)
552         &&
553         $YAML::VERSION < 0.60
554         &&
555         !$Have_warned->{"YAML"}++
556        ) {
557         $CPAN::Frontend->mywarn("Warning: YAML version '$YAML::VERSION' is too low, please upgrade!\n".
558                                 "I'll continue but problems are *very* likely to happen.\n"
559                                );
560         $CPAN::Frontend->mysleep(5);
561     }
562     return $yaml_module;
563 }
564
565 # CPAN::_yaml_loadfile
566 sub _yaml_loadfile {
567     my($self,$local_file) = @_;
568     return +[] unless -s $local_file;
569     my $yaml_module = _yaml_module;
570     if ($CPAN::META->has_inst($yaml_module)) {
571         # temporarly enable yaml code deserialisation
572         no strict 'refs';
573         # 5.6.2 could not do the local() with the reference
574         # so we do it manually instead
575         my $old_loadcode = ${"$yaml_module\::LoadCode"};
576         ${ "$yaml_module\::LoadCode" } = $CPAN::Config->{yaml_load_code} || 0;
577
578         my ($code, @yaml);
579         if ($code = UNIVERSAL::can($yaml_module, "LoadFile")) {
580             eval { @yaml = $code->($local_file); };
581             if ($@) {
582                 # this shall not be done by the frontend
583                 die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@);
584             }
585         } elsif ($code = UNIVERSAL::can($yaml_module, "Load")) {
586             local *FH;
587             open FH, $local_file or die "Could not open '$local_file': $!";
588             local $/;
589             my $ystream = <FH>;
590             eval { @yaml = $code->($ystream); };
591             if ($@) {
592                 # this shall not be done by the frontend
593                 die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"parse",$@);
594             }
595         }
596         ${"$yaml_module\::LoadCode"} = $old_loadcode;
597         return \@yaml;
598     } else {
599         # this shall not be done by the frontend
600         die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "parse");
601     }
602     return +[];
603 }
604
605 # CPAN::_yaml_dumpfile
606 sub _yaml_dumpfile {
607     my($self,$local_file,@what) = @_;
608     my $yaml_module = _yaml_module;
609     if ($CPAN::META->has_inst($yaml_module)) {
610         my $code;
611         if (UNIVERSAL::isa($local_file, "FileHandle")) {
612             $code = UNIVERSAL::can($yaml_module, "Dump");
613             eval { print $local_file $code->(@what) };
614         } elsif ($code = UNIVERSAL::can($yaml_module, "DumpFile")) {
615             eval { $code->($local_file,@what); };
616         } elsif ($code = UNIVERSAL::can($yaml_module, "Dump")) {
617             local *FH;
618             open FH, ">$local_file" or die "Could not open '$local_file': $!";
619             print FH $code->(@what);
620         }
621         if ($@) {
622             die CPAN::Exception::yaml_process_error->new($yaml_module,$local_file,"dump",$@);
623         }
624     } else {
625         if (UNIVERSAL::isa($local_file, "FileHandle")) {
626             # I think this case does not justify a warning at all
627         } else {
628             die CPAN::Exception::yaml_not_installed->new($yaml_module, $local_file, "dump");
629         }
630     }
631 }
632
633 sub _init_sqlite () {
634     unless ($CPAN::META->has_inst("CPAN::SQLite")) {
635         $CPAN::Frontend->mywarn(qq{CPAN::SQLite not installed, trying to work without\n})
636             unless $Have_warned->{"CPAN::SQLite"}++;
637         return;
638     }
639     require CPAN::SQLite::META; # not needed since CVS version of 2006-12-17
640     $CPAN::SQLite ||= CPAN::SQLite::META->new($CPAN::META);
641 }
642
643 {
644     my $negative_cache = {};
645     sub _sqlite_running {
646         if ($negative_cache->{time} && time < $negative_cache->{time} + 60) {
647             # need to cache the result, otherwise too slow
648             return $negative_cache->{fact};
649         } else {
650             $negative_cache = {}; # reset
651         }
652         my $ret = $CPAN::Config->{use_sqlite} && ($CPAN::SQLite || _init_sqlite());
653         return $ret if $ret; # fast anyway
654         $negative_cache->{time} = time;
655         return $negative_cache->{fact} = $ret;
656     }
657 }
658
659 $META ||= CPAN->new; # In case we re-eval ourselves we need the ||
660
661 # from here on only subs.
662 ################################################################################
663
664 sub _perl_fingerprint {
665     my($self,$other_fingerprint) = @_;
666     my $dll = eval {OS2::DLLname()};
667     my $mtime_dll = 0;
668     if (defined $dll) {
669         $mtime_dll = (-f $dll ? (stat(_))[9] : '-1');
670     }
671     my $mtime_perl = (-f CPAN::find_perl ? (stat(_))[9] : '-1');
672     my $this_fingerprint = {
673                             '$^X' => CPAN::find_perl,
674                             sitearchexp => $Config::Config{sitearchexp},
675                             'mtime_$^X' => $mtime_perl,
676                             'mtime_dll' => $mtime_dll,
677                            };
678     if ($other_fingerprint) {
679         if (exists $other_fingerprint->{'stat($^X)'}) { # repair fp from rev. 1.88_57
680             $other_fingerprint->{'mtime_$^X'} = $other_fingerprint->{'stat($^X)'}[9];
681         }
682         # mandatory keys since 1.88_57
683         for my $key (qw($^X sitearchexp mtime_dll mtime_$^X)) {
684             return unless $other_fingerprint->{$key} eq $this_fingerprint->{$key};
685         }
686         return 1;
687     } else {
688         return $this_fingerprint;
689     }
690 }
691
692 sub suggest_myconfig () {
693   SUGGEST_MYCONFIG: if(!$INC{'CPAN/MyConfig.pm'}) {
694         $CPAN::Frontend->myprint("You don't seem to have a user ".
695                                  "configuration (MyConfig.pm) yet.\n");
696         my $new = CPAN::Shell::colorable_makemaker_prompt("Do you want to create a ".
697                                               "user configuration now? (Y/n)",
698                                               "yes");
699         if($new =~ m{^y}i) {
700             CPAN::Shell->mkmyconfig();
701             return &checklock;
702         } else {
703             $CPAN::Frontend->mydie("OK, giving up.");
704         }
705     }
706 }
707
708 #-> sub CPAN::all_objects ;
709 sub all_objects {
710     my($mgr,$class) = @_;
711     CPAN::HandleConfig->load unless $CPAN::Config_loaded++;
712     CPAN->debug("mgr[$mgr] class[$class]") if $CPAN::DEBUG;
713     CPAN::Index->reload;
714     values %{ $META->{readwrite}{$class} }; # unsafe meta access, ok
715 }
716
717 # Called by shell, not in batch mode. In batch mode I see no risk in
718 # having many processes updating something as installations are
719 # continually checked at runtime. In shell mode I suspect it is
720 # unintentional to open more than one shell at a time
721
722 #-> sub CPAN::checklock ;
723 sub checklock {
724     my($self) = @_;
725     my $lockfile = File::Spec->catfile($CPAN::Config->{cpan_home},".lock");
726     if (-f $lockfile && -M _ > 0) {
727         my $fh = FileHandle->new($lockfile) or
728             $CPAN::Frontend->mydie("Could not open lockfile '$lockfile': $!");
729         my $otherpid  = <$fh>;
730         my $otherhost = <$fh>;
731         $fh->close;
732         if (defined $otherpid && $otherpid) {
733             chomp $otherpid;
734         }
735         if (defined $otherhost && $otherhost) {
736             chomp $otherhost;
737         }
738         my $thishost  = hostname();
739         if (defined $otherhost && defined $thishost &&
740             $otherhost ne '' && $thishost ne '' &&
741             $otherhost ne $thishost) {
742             $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Lockfile '$lockfile'\n".
743                                            "reports other host $otherhost and other ".
744                                            "process $otherpid.\n".
745                                            "Cannot proceed.\n"));
746         } elsif ($RUN_DEGRADED) {
747             $CPAN::Frontend->mywarn("Running in downgraded mode (experimental)\n");
748         } elsif (defined $otherpid && $otherpid) {
749             return if $$ == $otherpid; # should never happen
750             $CPAN::Frontend->mywarn(
751                                     qq{
752 There seems to be running another CPAN process (pid $otherpid).  Contacting...
753 });
754             if (kill 0, $otherpid or $!{EPERM}) {
755                 $CPAN::Frontend->mywarn(qq{Other job is running.\n});
756                 my($ans) =
757                     CPAN::Shell::colorable_makemaker_prompt
758                         (qq{Shall I try to run in downgraded }.
759                         qq{mode? (Y/n)},"y");
760                 if ($ans =~ /^y/i) {
761                     $CPAN::Frontend->mywarn("Running in downgraded mode (experimental).
762 Please report if something unexpected happens\n");
763                     $RUN_DEGRADED = 1;
764                     for ($CPAN::Config) {
765                         # XXX
766                         # $_->{build_dir_reuse} = 0; # 2006-11-17 akoenig Why was that?
767                         $_->{commandnumber_in_prompt} = 0; # visibility
768                         $_->{histfile}       = "";  # who should win otherwise?
769                         $_->{cache_metadata} = 0;   # better would be a lock?
770                         $_->{use_sqlite}     = 0;   # better would be a write lock!
771                         $_->{auto_commit}    = 0;   # we are violent, do not persist
772                         $_->{test_report}    = 0;   # Oliver Paukstadt had sent wrong reports in degraded mode
773                     }
774                 } else {
775                     $CPAN::Frontend->mydie("
776 You may want to kill the other job and delete the lockfile. On UNIX try:
777     kill $otherpid
778     rm $lockfile
779 ");
780                 }
781             } elsif (-w $lockfile) {
782                 my($ans) =
783                     CPAN::Shell::colorable_makemaker_prompt
784                         (qq{Other job not responding. Shall I overwrite }.
785                         qq{the lockfile '$lockfile'? (Y/n)},"y");
786             $CPAN::Frontend->myexit("Ok, bye\n")
787                 unless $ans =~ /^y/i;
788             } else {
789                 Carp::croak(
790                     qq{Lockfile '$lockfile' not writable by you. }.
791                     qq{Cannot proceed.\n}.
792                     qq{    On UNIX try:\n}.
793                     qq{    rm '$lockfile'\n}.
794                     qq{  and then rerun us.\n}
795                 );
796             }
797         } else {
798             $CPAN::Frontend->mydie(sprintf("CPAN.pm panic: Found invalid lockfile ".
799                                            "'$lockfile', please remove. Cannot proceed.\n"));
800         }
801     }
802     my $dotcpan = $CPAN::Config->{cpan_home};
803     eval { File::Path::mkpath($dotcpan);};
804     if ($@) {
805         # A special case at least for Jarkko.
806         my $firsterror = $@;
807         my $seconderror;
808         my $symlinkcpan;
809         if (-l $dotcpan) {
810             $symlinkcpan = readlink $dotcpan;
811             die "readlink $dotcpan failed: $!" unless defined $symlinkcpan;
812             eval { File::Path::mkpath($symlinkcpan); };
813             if ($@) {
814                 $seconderror = $@;
815             } else {
816                 $CPAN::Frontend->mywarn(qq{
817 Working directory $symlinkcpan created.
818 });
819             }
820         }
821         unless (-d $dotcpan) {
822             my $mess = qq{
823 Your configuration suggests "$dotcpan" as your
824 CPAN.pm working directory. I could not create this directory due
825 to this error: $firsterror\n};
826             $mess .= qq{
827 As "$dotcpan" is a symlink to "$symlinkcpan",
828 I tried to create that, but I failed with this error: $seconderror
829 } if $seconderror;
830             $mess .= qq{
831 Please make sure the directory exists and is writable.
832 };
833             $CPAN::Frontend->mywarn($mess);
834             return suggest_myconfig;
835         }
836     } # $@ after eval mkpath $dotcpan
837     if (0) { # to test what happens when a race condition occurs
838         for (reverse 1..10) {
839             print $_, "\n";
840             sleep 1;
841         }
842     }
843     # locking
844     if (!$RUN_DEGRADED && !$self->{LOCKFH}) {
845         my $fh;
846         unless ($fh = FileHandle->new("+>>$lockfile")) {
847             $CPAN::Frontend->mywarn(qq{
848
849 Your configuration suggests that CPAN.pm should use a working
850 directory of
851     $CPAN::Config->{cpan_home}
852 Unfortunately we could not create the lock file
853     $lockfile
854 due to '$!'.
855
856 Please make sure that the configuration variable
857     \$CPAN::Config->{cpan_home}
858 points to a directory where you can write a .lock file. You can set
859 this variable in either a CPAN/MyConfig.pm or a CPAN/Config.pm in your
860 \@INC path;
861 });
862             return suggest_myconfig;
863         }
864         my $sleep = 1;
865         while (!CPAN::_flock($fh, LOCK_EX|LOCK_NB)) {
866             if ($sleep>10) {
867                 $CPAN::Frontend->mydie("Giving up\n");
868             }
869             $CPAN::Frontend->mysleep($sleep++);
870             $CPAN::Frontend->mywarn("Could not lock lockfile with flock: $!; retrying\n");
871         }
872
873         seek $fh, 0, 0;
874         truncate $fh, 0;
875         $fh->autoflush(1);
876         $fh->print($$, "\n");
877         $fh->print(hostname(), "\n");
878         $self->{LOCK} = $lockfile;
879         $self->{LOCKFH} = $fh;
880     }
881     $SIG{TERM} = sub {
882         my $sig = shift;
883         &cleanup;
884         $CPAN::Frontend->mydie("Got SIG$sig, leaving");
885     };
886     $SIG{INT} = sub {
887       # no blocks!!!
888         my $sig = shift;
889         &cleanup if $Signal;
890         die "Got yet another signal" if $Signal > 1;
891         $CPAN::Frontend->mydie("Got another SIG$sig") if $Signal;
892         $CPAN::Frontend->mywarn("Caught SIG$sig, trying to continue\n");
893         $Signal++;
894     };
895
896 #       From: Larry Wall <larry@wall.org>
897 #       Subject: Re: deprecating SIGDIE
898 #       To: perl5-porters@perl.org
899 #       Date: Thu, 30 Sep 1999 14:58:40 -0700 (PDT)
900 #
901 #       The original intent of __DIE__ was only to allow you to substitute one
902 #       kind of death for another on an application-wide basis without respect
903 #       to whether you were in an eval or not.  As a global backstop, it should
904 #       not be used any more lightly (or any more heavily :-) than class
905 #       UNIVERSAL.  Any attempt to build a general exception model on it should
906 #       be politely squashed.  Any bug that causes every eval {} to have to be
907 #       modified should be not so politely squashed.
908 #
909 #       Those are my current opinions.  It is also my optinion that polite
910 #       arguments degenerate to personal arguments far too frequently, and that
911 #       when they do, it's because both people wanted it to, or at least didn't
912 #       sufficiently want it not to.
913 #
914 #       Larry
915
916     # global backstop to cleanup if we should really die
917     $SIG{__DIE__} = \&cleanup;
918     $self->debug("Signal handler set.") if $CPAN::DEBUG;
919 }
920
921 #-> sub CPAN::DESTROY ;
922 sub DESTROY {
923     &cleanup; # need an eval?
924 }
925
926 #-> sub CPAN::anycwd ;
927 sub anycwd () {
928     my $getcwd;
929     $getcwd = $CPAN::Config->{'getcwd'} || 'cwd';
930     CPAN->$getcwd();
931 }
932
933 #-> sub CPAN::cwd ;
934 sub cwd {Cwd::cwd();}
935
936 #-> sub CPAN::getcwd ;
937 sub getcwd {Cwd::getcwd();}
938
939 #-> sub CPAN::fastcwd ;
940 sub fastcwd {Cwd::fastcwd();}
941
942 #-> sub CPAN::backtickcwd ;
943 sub backtickcwd {my $cwd = `cwd`; chomp $cwd; $cwd}
944
945 # Adapted from Probe::Perl
946 #-> sub CPAN::_perl_is_same
947 sub _perl_is_same {
948   my ($perl) = @_;
949   return MM->maybe_command($perl)
950     && `$perl -MConfig=myconfig -e print -e myconfig` eq Config->myconfig;
951 }
952
953 # Adapted in part from Probe::Perl
954 #-> sub CPAN::find_perl ;
955 sub find_perl () {
956     if ( File::Spec->file_name_is_absolute($^X) ) {
957         return $^X;
958     }
959     else {
960         my $exe = $Config::Config{exe_ext};
961         my @candidates = (
962             File::Spec->catfile($CPAN::iCwd,$^X),
963             $Config::Config{'perlpath'},
964         );
965         for my $perl_name ($^X, 'perl', 'perl5', "perl$]") {
966             for my $path (File::Spec->path(), $Config::Config{'binexp'}) {
967                 if ( defined($path) && length $path && -d $path ) {
968                     my $perl = File::Spec->catfile($path,$perl_name);
969                     push @candidates, $perl;
970                     # try with extension if not provided already
971                     if ($^O eq 'VMS') {
972                         # VMS might have a file version at the end
973                         push @candidates, $perl . $exe
974                             unless $perl =~ m/$exe(;\d+)?$/i;
975                     } elsif (defined $exe && length $exe) {
976                         push @candidates, $perl . $exe
977                             unless $perl =~ m/$exe$/i;
978                     }
979                 }
980             }
981         }
982         for my $perl ( @candidates ) {
983             if (MM->maybe_command($perl) && _perl_is_same($perl)) {
984                 $^X = $perl;
985                 return $perl;
986             }
987         }
988     }
989     return $^X; # default fall back
990 }
991
992 #-> sub CPAN::exists ;
993 sub exists {
994     my($mgr,$class,$id) = @_;
995     CPAN::HandleConfig->load unless $CPAN::Config_loaded++;
996     CPAN::Index->reload;
997     ### Carp::croak "exists called without class argument" unless $class;
998     $id ||= "";
999     $id =~ s/:+/::/g if $class eq "CPAN::Module";
1000     my $exists;
1001     if (CPAN::_sqlite_running) {
1002         $exists = (exists $META->{readonly}{$class}{$id} or
1003                    $CPAN::SQLite->set($class, $id));
1004     } else {
1005         $exists =  exists $META->{readonly}{$class}{$id};
1006     }
1007     $exists ||= exists $META->{readwrite}{$class}{$id}; # unsafe meta access, ok
1008 }
1009
1010 #-> sub CPAN::delete ;
1011 sub delete {
1012   my($mgr,$class,$id) = @_;
1013   delete $META->{readonly}{$class}{$id}; # unsafe meta access, ok
1014   delete $META->{readwrite}{$class}{$id}; # unsafe meta access, ok
1015 }
1016
1017 #-> sub CPAN::has_usable
1018 # has_inst is sometimes too optimistic, we should replace it with this
1019 # has_usable whenever a case is given
1020 sub has_usable {
1021     my($self,$mod,$message) = @_;
1022     return 1 if $HAS_USABLE->{$mod};
1023     my $has_inst = $self->has_inst($mod,$message);
1024     return unless $has_inst;
1025     my $usable;
1026     $usable = {
1027
1028                #
1029                # these subroutines die if they believe the installed version is unusable;
1030                #
1031
1032                LWP => [ # we frequently had "Can't locate object
1033                         # method "new" via package "LWP::UserAgent" at
1034                         # (eval 69) line 2006
1035                        sub {require LWP},
1036                        sub {require LWP::UserAgent},
1037                        sub {require HTTP::Request},
1038                        sub {require URI::URL;
1039                             unless (CPAN::Version->vge(URI::URL::->VERSION,0.08)) {
1040                                 for ("Will not use URI::URL, need 0.08\n") {
1041                                     $CPAN::Frontend->mywarn($_);
1042                                     die $_;
1043                                 }
1044                             }
1045                        },
1046                       ],
1047                'Net::FTP' => [
1048                             sub {require Net::FTP},
1049                             sub {require Net::Config},
1050                            ],
1051                'HTTP::Tiny' => [
1052                             sub {
1053                                 require HTTP::Tiny;
1054                                 unless (CPAN::Version->vge(HTTP::Tiny->VERSION, 0.005)) {
1055                                     for ("Will not use HTTP::Tiny, need version 0.005\n") {
1056                                         $CPAN::Frontend->mywarn($_);
1057                                         die $_;
1058                                     }
1059                                 }
1060                             },
1061                            ],
1062                'File::HomeDir' => [
1063                                    sub {require File::HomeDir;
1064                                         unless (CPAN::Version->vge(File::HomeDir::->VERSION, 0.65)) {
1065                                             for ("Will not use File::HomeDir, need 0.65\n") {
1066                                                 $CPAN::Frontend->mywarn($_);
1067                                                 die $_;
1068                                             }
1069                                         }
1070                                     },
1071                                   ],
1072                'Archive::Tar' => [
1073                                   sub {require Archive::Tar;
1074                                        my $demand = "1.50";
1075                                        unless (CPAN::Version->vge(Archive::Tar::->VERSION, $demand)) {
1076                                             my $atv = Archive::Tar->VERSION;
1077                                             for ("You have Archive::Tar $atv, but $demand or later is recommended. Please upgrade.\n") {
1078                                                 $CPAN::Frontend->mywarn($_);
1079                                             # don't die, because we may need
1080                                             # Archive::Tar to upgrade
1081                                             }
1082                                             
1083                                        }
1084                                   },
1085                                  ],
1086                'File::Temp' => [
1087                                 # XXX we should probably delete from
1088                                 # %INC too so we can load after we
1089                                 # installed a new enough version --
1090                                 # I'm not sure.
1091                                 sub {require File::Temp;
1092                                      unless (CPAN::Version->vge(File::Temp::->VERSION,0.16)) {
1093                                          for ("Will not use File::Temp, need 0.16\n") {
1094                                                 $CPAN::Frontend->mywarn($_);
1095                                                 die $_;
1096                                          }
1097                                      }
1098                                 },
1099                                ]
1100               };
1101     if ($usable->{$mod}) {
1102         for my $c (0..$#{$usable->{$mod}}) {
1103             my $code = $usable->{$mod}[$c];
1104             my $ret = eval { &$code() };
1105             $ret = "" unless defined $ret;
1106             if ($@) {
1107                 # warn "DEBUG: c[$c]\$\@[$@]ret[$ret]";
1108                 return;
1109             }
1110         }
1111     }
1112     return $HAS_USABLE->{$mod} = 1;
1113 }
1114
1115 #-> sub CPAN::has_inst
1116 sub has_inst {
1117     my($self,$mod,$message) = @_;
1118     Carp::croak("CPAN->has_inst() called without an argument")
1119         unless defined $mod;
1120     my %dont = map { $_ => 1 } keys %{$CPAN::META->{dontload_hash}||{}},
1121         keys %{$CPAN::Config->{dontload_hash}||{}},
1122             @{$CPAN::Config->{dontload_list}||[]};
1123     if (defined $message && $message eq "no"  # afair only used by Nox
1124         ||
1125         $dont{$mod}
1126        ) {
1127       $CPAN::META->{dontload_hash}{$mod}||=1; # unsafe meta access, ok
1128       return 0;
1129     }
1130     my $file = $mod;
1131     my $obj;
1132     $file =~ s|::|/|g;
1133     $file .= ".pm";
1134     if ($INC{$file}) {
1135         # checking %INC is wrong, because $INC{LWP} may be true
1136         # although $INC{"URI/URL.pm"} may have failed. But as
1137         # I really want to say "bla loaded OK", I have to somehow
1138         # cache results.
1139         ### warn "$file in %INC"; #debug
1140         return 1;
1141     } elsif (eval { require $file }) {
1142         # eval is good: if we haven't yet read the database it's
1143         # perfect and if we have installed the module in the meantime,
1144         # it tries again. The second require is only a NOOP returning
1145         # 1 if we had success, otherwise it's retrying
1146
1147         my $mtime = (stat $INC{$file})[9];
1148         # privileged files loaded by has_inst; Note: we use $mtime
1149         # as a proxy for a checksum.
1150         $CPAN::Shell::reload->{$file} = $mtime;
1151         my $v = eval "\$$mod\::VERSION";
1152         $v = $v ? " (v$v)" : "";
1153         CPAN::Shell->optprint("load_module","CPAN: $mod loaded ok$v\n");
1154         if ($mod eq "CPAN::WAIT") {
1155             push @CPAN::Shell::ISA, 'CPAN::WAIT';
1156         }
1157         return 1;
1158     } elsif ($mod eq "Net::FTP") {
1159         $CPAN::Frontend->mywarn(qq{
1160   Please, install Net::FTP as soon as possible. CPAN.pm installs it for you
1161   if you just type
1162       install Bundle::libnet
1163
1164 }) unless $Have_warned->{"Net::FTP"}++;
1165         $CPAN::Frontend->mysleep(3);
1166     } elsif ($mod eq "Digest::SHA") {
1167         if ($Have_warned->{"Digest::SHA"}++) {
1168             $CPAN::Frontend->mywarn(qq{CPAN: checksum security checks disabled }.
1169                                      qq{because Digest::SHA not installed.\n});
1170         } else {
1171             $CPAN::Frontend->mywarn(qq{
1172   CPAN: checksum security checks disabled because Digest::SHA not installed.
1173   Please consider installing the Digest::SHA module.
1174
1175 });
1176             $CPAN::Frontend->mysleep(2);
1177         }
1178     } elsif ($mod eq "Module::Signature") {
1179         # NOT prefs_lookup, we are not a distro
1180         my $check_sigs = $CPAN::Config->{check_sigs};
1181         if (not $check_sigs) {
1182             # they do not want us:-(
1183         } elsif (not $Have_warned->{"Module::Signature"}++) {
1184             # No point in complaining unless the user can
1185             # reasonably install and use it.
1186             if (eval { require Crypt::OpenPGP; 1 } ||
1187                 (
1188                  defined $CPAN::Config->{'gpg'}
1189                  &&
1190                  $CPAN::Config->{'gpg'} =~ /\S/
1191                 )
1192                ) {
1193                 $CPAN::Frontend->mywarn(qq{
1194   CPAN: Module::Signature security checks disabled because Module::Signature
1195   not installed.  Please consider installing the Module::Signature module.
1196   You may also need to be able to connect over the Internet to the public
1197   keyservers like pool.sks-keyservers.net or pgp.mit.edu.
1198
1199 });
1200                 $CPAN::Frontend->mysleep(2);
1201             }
1202         }
1203     } else {
1204         delete $INC{$file}; # if it inc'd LWP but failed during, say, URI
1205     }
1206     return 0;
1207 }
1208
1209 #-> sub CPAN::instance ;
1210 sub instance {
1211     my($mgr,$class,$id) = @_;
1212     CPAN::Index->reload;
1213     $id ||= "";
1214     # unsafe meta access, ok?
1215     return $META->{readwrite}{$class}{$id} if exists $META->{readwrite}{$class}{$id};
1216     $META->{readwrite}{$class}{$id} ||= $class->new(ID => $id);
1217 }
1218
1219 #-> sub CPAN::new ;
1220 sub new {
1221     bless {}, shift;
1222 }
1223
1224 #-> sub CPAN::_exit_messages ;
1225 sub _exit_messages {
1226     my ($self) = @_;
1227     $self->{exit_messages} ||= [];
1228 }
1229
1230 #-> sub CPAN::cleanup ;
1231 sub cleanup {
1232   # warn "cleanup called with arg[@_] End[$CPAN::End] Signal[$Signal]";
1233   local $SIG{__DIE__} = '';
1234   my($message) = @_;
1235   my $i = 0;
1236   my $ineval = 0;
1237   my($subroutine);
1238   while ((undef,undef,undef,$subroutine) = caller(++$i)) {
1239       $ineval = 1, last if
1240         $subroutine eq '(eval)';
1241   }
1242   return if $ineval && !$CPAN::End;
1243   return unless defined $META->{LOCK};
1244   return unless -f $META->{LOCK};
1245   $META->savehist;
1246   $META->{cachemgr} ||= CPAN::CacheMgr->new('atexit');
1247   close $META->{LOCKFH};
1248   unlink $META->{LOCK};
1249   # require Carp;
1250   # Carp::cluck("DEBUGGING");
1251   if ( $CPAN::CONFIG_DIRTY ) {
1252       $CPAN::Frontend->mywarn("Warning: Configuration not saved.\n");
1253   }
1254   $CPAN::Frontend->myprint("Lockfile removed.\n");
1255   for my $msg ( @{ $META->_exit_messages } ) {
1256       $CPAN::Frontend->myprint($msg);
1257   }
1258 }
1259
1260 #-> sub CPAN::readhist
1261 sub readhist {
1262     my($self,$term,$histfile) = @_;
1263     my $histsize = $CPAN::Config->{'histsize'} || 100;
1264     $term->Attribs->{'MaxHistorySize'} = $histsize if (defined($term->Attribs->{'MaxHistorySize'}));
1265     my($fh) = FileHandle->new;
1266     open $fh, "<$histfile" or return;
1267     local $/ = "\n";
1268     while (<$fh>) {
1269         chomp;
1270         $term->AddHistory($_);
1271     }
1272     close $fh;
1273 }
1274
1275 #-> sub CPAN::savehist
1276 sub savehist {
1277     my($self) = @_;
1278     my($histfile,$histsize);
1279     unless ($histfile = $CPAN::Config->{'histfile'}) {
1280         $CPAN::Frontend->mywarn("No history written (no histfile specified).\n");
1281         return;
1282     }
1283     $histsize = $CPAN::Config->{'histsize'} || 100;
1284     if ($CPAN::term) {
1285         unless ($CPAN::term->can("GetHistory")) {
1286             $CPAN::Frontend->mywarn("Terminal does not support GetHistory.\n");
1287             return;
1288         }
1289     } else {
1290         return;
1291     }
1292     my @h = $CPAN::term->GetHistory;
1293     splice @h, 0, @h-$histsize if @h>$histsize;
1294     my($fh) = FileHandle->new;
1295     open $fh, ">$histfile" or $CPAN::Frontend->mydie("Couldn't open >$histfile: $!");
1296     local $\ = local $, = "\n";
1297     print $fh @h;
1298     close $fh;
1299 }
1300
1301 #-> sub CPAN::is_tested
1302 sub is_tested {
1303     my($self,$what,$when) = @_;
1304     unless ($what) {
1305         Carp::cluck("DEBUG: empty what");
1306         return;
1307     }
1308     $self->{is_tested}{$what} = $when;
1309 }
1310
1311 #-> sub CPAN::reset_tested
1312 # forget all distributions tested -- resets what gets included in PERL5LIB
1313 sub reset_tested {
1314     my ($self) = @_;
1315     $self->{is_tested} = {};
1316 }
1317
1318 #-> sub CPAN::is_installed
1319 # unsets the is_tested flag: as soon as the thing is installed, it is
1320 # not needed in set_perl5lib anymore
1321 sub is_installed {
1322     my($self,$what) = @_;
1323     delete $self->{is_tested}{$what};
1324 }
1325
1326 sub _list_sorted_descending_is_tested {
1327     my($self) = @_;
1328     sort
1329         { ($self->{is_tested}{$b}||0) <=> ($self->{is_tested}{$a}||0) }
1330             keys %{$self->{is_tested}}
1331 }
1332
1333 #-> sub CPAN::set_perl5lib
1334 # Notes on max environment variable length:
1335 #   - Win32 : XP or later, 8191; Win2000 or NT4, 2047
1336 {
1337 my $fh;
1338 sub set_perl5lib {
1339     my($self,$for) = @_;
1340     unless ($for) {
1341         (undef,undef,undef,$for) = caller(1);
1342         $for =~ s/.*://;
1343     }
1344     $self->{is_tested} ||= {};
1345     return unless %{$self->{is_tested}};
1346     my $env = $ENV{PERL5LIB};
1347     $env = $ENV{PERLLIB} unless defined $env;
1348     my @env;
1349     push @env, split /\Q$Config::Config{path_sep}\E/, $env if defined $env and length $env;
1350     #my @dirs = map {("$_/blib/arch", "$_/blib/lib")} keys %{$self->{is_tested}};
1351     #$CPAN::Frontend->myprint("Prepending @dirs to PERL5LIB.\n");
1352
1353     my @dirs = map {("$_/blib/arch", "$_/blib/lib")} $self->_list_sorted_descending_is_tested;
1354     return if !@dirs;
1355
1356     if (@dirs < 12) {
1357         $CPAN::Frontend->optprint('perl5lib', "Prepending @dirs to PERL5LIB for '$for'\n");
1358         $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env;
1359     } elsif (@dirs < 24 ) {
1360         my @d = map {my $cp = $_;
1361                      $cp =~ s/^\Q$CPAN::Config->{build_dir}\E/%BUILDDIR%/;
1362                      $cp
1363                  } @dirs;
1364         $CPAN::Frontend->optprint('perl5lib', "Prepending @d to PERL5LIB; ".
1365                                  "%BUILDDIR%=$CPAN::Config->{build_dir} ".
1366                                  "for '$for'\n"
1367                                 );
1368         $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env;
1369     } else {
1370         my $cnt = keys %{$self->{is_tested}};
1371         $CPAN::Frontend->optprint('perl5lib', "Prepending blib/arch and blib/lib of ".
1372                                  "$cnt build dirs to PERL5LIB; ".
1373                                  "for '$for'\n"
1374                                 );
1375         $ENV{PERL5LIB} = join $Config::Config{path_sep}, @dirs, @env;
1376     }
1377 }}
1378
1379
1380 1;
1381
1382
1383 __END__
1384
1385 =head1 NAME
1386
1387 CPAN - query, download and build perl modules from CPAN sites
1388
1389 =head1 SYNOPSIS
1390
1391 Interactive mode:
1392
1393   perl -MCPAN -e shell
1394
1395 --or--
1396
1397   cpan
1398
1399 Basic commands:
1400
1401   # Modules:
1402
1403   cpan> install Acme::Meta                       # in the shell
1404
1405   CPAN::Shell->install("Acme::Meta");            # in perl
1406
1407   # Distributions:
1408
1409   cpan> install NWCLARK/Acme-Meta-0.02.tar.gz    # in the shell
1410
1411   CPAN::Shell->
1412     install("NWCLARK/Acme-Meta-0.02.tar.gz");    # in perl
1413
1414   # module objects:
1415
1416   $mo = CPAN::Shell->expandany($mod);
1417   $mo = CPAN::Shell->expand("Module",$mod);      # same thing
1418
1419   # distribution objects:
1420
1421   $do = CPAN::Shell->expand("Module",$mod)->distribution;
1422   $do = CPAN::Shell->expandany($distro);         # same thing
1423   $do = CPAN::Shell->expand("Distribution",
1424                             $distro);            # same thing
1425
1426 =head1 DESCRIPTION
1427
1428 The CPAN module automates or at least simplifies the make and install
1429 of perl modules and extensions. It includes some primitive searching
1430 capabilities and knows how to use LWP, HTTP::Tiny, Net::FTP and certain
1431 external download clients to fetch distributions from the net.
1432
1433 These are fetched from one or more mirrored CPAN (Comprehensive
1434 Perl Archive Network) sites and unpacked in a dedicated directory.
1435
1436 The CPAN module also supports named and versioned
1437 I<bundles> of modules. Bundles simplify handling of sets of
1438 related modules. See Bundles below.
1439
1440 The package contains a session manager and a cache manager. The
1441 session manager keeps track of what has been fetched, built, and
1442 installed in the current session. The cache manager keeps track of the
1443 disk space occupied by the make processes and deletes excess space
1444 using a simple FIFO mechanism.
1445
1446 All methods provided are accessible in a programmer style and in an
1447 interactive shell style.
1448
1449 =head2 CPAN::shell([$prompt, $command]) Starting Interactive Mode
1450
1451 Enter interactive mode by running
1452
1453     perl -MCPAN -e shell
1454
1455 or
1456
1457     cpan
1458
1459 which puts you into a readline interface. If C<Term::ReadKey> and
1460 either of C<Term::ReadLine::Perl> or C<Term::ReadLine::Gnu> are installed,
1461 history and command completion are supported.
1462
1463 Once at the command line, type C<h> for one-page help
1464 screen; the rest should be self-explanatory.
1465
1466 The function call C<shell> takes two optional arguments: one the
1467 prompt, the second the default initial command line (the latter
1468 only works if a real ReadLine interface module is installed).
1469
1470 The most common uses of the interactive modes are
1471
1472 =over 2
1473
1474 =item Searching for authors, bundles, distribution files and modules
1475
1476 There are corresponding one-letter commands C<a>, C<b>, C<d>, and C<m>
1477 for each of the four categories and another, C<i> for any of the
1478 mentioned four. Each of the four entities is implemented as a class
1479 with slightly differing methods for displaying an object.
1480
1481 Arguments to these commands are either strings exactly matching
1482 the identification string of an object, or regular expressions 
1483 matched case-insensitively against various attributes of the
1484 objects. The parser only recognizes a regular expression when you
1485 enclose it with slashes.
1486
1487 The principle is that the number of objects found influences how an
1488 item is displayed. If the search finds one item, the result is
1489 displayed with the rather verbose method C<as_string>, but if 
1490 more than one is found, each object is displayed with the terse method
1491 C<as_glimpse>.
1492
1493 Examples:
1494
1495   cpan> m Acme::MetaSyntactic
1496   Module id = Acme::MetaSyntactic
1497       CPAN_USERID  BOOK (Philippe Bruhat (BooK) <[...]>)
1498       CPAN_VERSION 0.99
1499       CPAN_FILE    B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz
1500       UPLOAD_DATE  2006-11-06
1501       MANPAGE      Acme::MetaSyntactic - Themed metasyntactic variables names
1502       INST_FILE    /usr/local/lib/perl/5.10.0/Acme/MetaSyntactic.pm
1503       INST_VERSION 0.99
1504   cpan> a BOOK
1505   Author id = BOOK
1506       EMAIL        [...]
1507       FULLNAME     Philippe Bruhat (BooK)
1508   cpan> d BOOK/Acme-MetaSyntactic-0.99.tar.gz
1509   Distribution id = B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz
1510       CPAN_USERID  BOOK (Philippe Bruhat (BooK) <[...]>)
1511       CONTAINSMODS Acme::MetaSyntactic Acme::MetaSyntactic::Alias [...]
1512       UPLOAD_DATE  2006-11-06
1513   cpan> m /lorem/
1514   Module  = Acme::MetaSyntactic::loremipsum (BOOK/Acme-MetaSyntactic-0.99.tar.gz)
1515   Module    Text::Lorem            (ADEOLA/Text-Lorem-0.3.tar.gz)
1516   Module    Text::Lorem::More      (RKRIMEN/Text-Lorem-More-0.12.tar.gz)
1517   Module    Text::Lorem::More::Source (RKRIMEN/Text-Lorem-More-0.12.tar.gz)
1518   cpan> i /berlin/
1519   Distribution    BEATNIK/Filter-NumberLines-0.02.tar.gz
1520   Module  = DateTime::TimeZone::Europe::Berlin (DROLSKY/DateTime-TimeZone-0.7904.tar.gz)
1521   Module    Filter::NumberLines    (BEATNIK/Filter-NumberLines-0.02.tar.gz)
1522   Author          [...]
1523
1524 The examples illustrate several aspects: the first three queries
1525 target modules, authors, or distros directly and yield exactly one
1526 result. The last two use regular expressions and yield several
1527 results. The last one targets all of bundles, modules, authors, and
1528 distros simultaneously. When more than one result is available, they
1529 are printed in one-line format.
1530
1531 =item C<get>, C<make>, C<test>, C<install>, C<clean> modules or distributions
1532
1533 These commands take any number of arguments and investigate what is
1534 necessary to perform the action. Argument processing is as follows:
1535
1536   known module name in format Foo/Bar.pm   module
1537   other embedded slash                     distribution
1538     - with trailing slash dot              directory
1539   enclosing slashes                        regexp
1540   known module name in format Foo::Bar     module
1541
1542 If the argument is a distribution file name (recognized by embedded
1543 slashes), it is processed. If it is a module, CPAN determines the
1544 distribution file in which this module is included and processes that,
1545 following any dependencies named in the module's META.yml or
1546 Makefile.PL (this behavior is controlled by the configuration
1547 parameter C<prerequisites_policy>). If an argument is enclosed in
1548 slashes it is treated as a regular expression: it is expanded and if
1549 the result is a single object (distribution, bundle or module), this
1550 object is processed.
1551
1552 Example:
1553
1554     install Dummy::Perl                   # installs the module
1555     install AUXXX/Dummy-Perl-3.14.tar.gz  # installs that distribution
1556     install /Dummy-Perl-3.14/             # same if the regexp is unambiguous
1557
1558 C<get> downloads a distribution file and untars or unzips it, C<make>
1559 builds it, C<test> runs the test suite, and C<install> installs it.
1560
1561 Any C<make> or C<test> is run unconditionally. An
1562
1563   install <distribution_file>
1564
1565 is also run unconditionally. But for
1566
1567   install <module>
1568
1569 CPAN checks whether an install is needed and prints
1570 I<module up to date> if the distribution file containing
1571 the module doesn't need updating.
1572
1573 CPAN also keeps track of what it has done within the current session
1574 and doesn't try to build a package a second time regardless of whether it
1575 succeeded or not. It does not repeat a test run if the test
1576 has been run successfully before. Same for install runs.
1577
1578 The C<force> pragma may precede another command (currently: C<get>,
1579 C<make>, C<test>, or C<install>) to execute the command from scratch
1580 and attempt to continue past certain errors. See the section below on
1581 the C<force> and the C<fforce> pragma.
1582
1583 The C<notest> pragma skips the test part in the build
1584 process.
1585
1586 Example:
1587
1588     cpan> notest install Tk
1589
1590 A C<clean> command results in a
1591
1592   make clean
1593
1594 being executed within the distribution file's working directory.
1595
1596 =item C<readme>, C<perldoc>, C<look> module or distribution
1597
1598 C<readme> displays the README file of the associated distribution.
1599 C<Look> gets and untars (if not yet done) the distribution file,
1600 changes to the appropriate directory and opens a subshell process in
1601 that directory. C<perldoc> displays the module's pod documentation 
1602 in html or plain text format.
1603
1604 =item C<ls> author
1605
1606 =item C<ls> globbing_expression
1607
1608 The first form lists all distribution files in and below an author's
1609 CPAN directory as stored in the CHECKUMS files distributed on
1610 CPAN. The listing recurses into subdirectories.
1611
1612 The second form limits or expands the output with shell
1613 globbing as in the following examples:
1614
1615       ls JV/make*
1616       ls GSAR/*make*
1617       ls */*make*
1618
1619 The last example is very slow and outputs extra progress indicators
1620 that break the alignment of the result.
1621
1622 Note that globbing only lists directories explicitly asked for, for
1623 example FOO/* will not list FOO/bar/Acme-Sthg-n.nn.tar.gz. This may be
1624 regarded as a bug that may be changed in some future version.
1625
1626 =item C<failed>
1627
1628 The C<failed> command reports all distributions that failed on one of
1629 C<make>, C<test> or C<install> for some reason in the currently
1630 running shell session.
1631
1632 =item Persistence between sessions
1633
1634 If the C<YAML> or the C<YAML::Syck> module is installed a record of
1635 the internal state of all modules is written to disk after each step.
1636 The files contain a signature of the currently running perl version
1637 for later perusal.
1638
1639 If the configurations variable C<build_dir_reuse> is set to a true
1640 value, then CPAN.pm reads the collected YAML files. If the stored
1641 signature matches the currently running perl, the stored state is
1642 loaded into memory such that persistence between sessions
1643 is effectively established.
1644
1645 =item The C<force> and the C<fforce> pragma
1646
1647 To speed things up in complex installation scenarios, CPAN.pm keeps
1648 track of what it has already done and refuses to do some things a
1649 second time. A C<get>, a C<make>, and an C<install> are not repeated.
1650 A C<test> is repeated only if the previous test was unsuccessful. The
1651 diagnostic message when CPAN.pm refuses to do something a second time
1652 is one of I<Has already been >C<unwrapped|made|tested successfully> or
1653 something similar. Another situation where CPAN refuses to act is an
1654 C<install> if the corresponding C<test> was not successful.
1655
1656 In all these cases, the user can override this stubborn behaviour by
1657 prepending the command with the word force, for example:
1658
1659   cpan> force get Foo
1660   cpan> force make AUTHOR/Bar-3.14.tar.gz
1661   cpan> force test Baz
1662   cpan> force install Acme::Meta
1663
1664 Each I<forced> command is executed with the corresponding part of its
1665 memory erased.
1666
1667 The C<fforce> pragma is a variant that emulates a C<force get> which
1668 erases the entire memory followed by the action specified, effectively
1669 restarting the whole get/make/test/install procedure from scratch.
1670
1671 =item Lockfile
1672
1673 Interactive sessions maintain a lockfile, by default C<~/.cpan/.lock>.
1674 Batch jobs can run without a lockfile and not disturb each other.
1675
1676 The shell offers to run in I<downgraded mode> when another process is
1677 holding the lockfile. This is an experimental feature that is not yet
1678 tested very well. This second shell then does not write the history
1679 file, does not use the metadata file, and has a different prompt.
1680
1681 =item Signals
1682
1683 CPAN.pm installs signal handlers for SIGINT and SIGTERM. While you are
1684 in the cpan-shell, it is intended that you can press C<^C> anytime and
1685 return to the cpan-shell prompt. A SIGTERM will cause the cpan-shell
1686 to clean up and leave the shell loop. You can emulate the effect of a
1687 SIGTERM by sending two consecutive SIGINTs, which usually means by
1688 pressing C<^C> twice.
1689
1690 CPAN.pm ignores SIGPIPE. If the user sets C<inactivity_timeout>, a
1691 SIGALRM is used during the run of the C<perl Makefile.PL> or C<perl
1692 Build.PL> subprocess. A SIGALRM is also used during module version
1693 parsing, and is controlled by C<version_timeout>.
1694
1695 =back
1696
1697 =head2 CPAN::Shell
1698
1699 The commands available in the shell interface are methods in
1700 the package CPAN::Shell. If you enter the shell command, your
1701 input is split by the Text::ParseWords::shellwords() routine, which
1702 acts like most shells do. The first word is interpreted as the
1703 method to be invoked, and the rest of the words are treated as the method's arguments.
1704 Continuation lines are supported by ending a line with a
1705 literal backslash.
1706
1707 =head2 autobundle
1708
1709 C<autobundle> writes a bundle file into the
1710 C<$CPAN::Config-E<gt>{cpan_home}/Bundle> directory. The file contains
1711 a list of all modules that are both available from CPAN and currently
1712 installed within @INC. The name of the bundle file is based on the
1713 current date and a counter.
1714
1715 =head2 hosts
1716
1717 Note: this feature is still in alpha state and may change in future
1718 versions of CPAN.pm
1719
1720 This commands provides a statistical overview over recent download
1721 activities. The data for this is collected in the YAML file
1722 C<FTPstats.yml> in your C<cpan_home> directory. If no YAML module is
1723 configured or YAML not installed, no stats are provided.
1724
1725 =head2 mkmyconfig
1726
1727 mkmyconfig() writes your own CPAN::MyConfig file into your C<~/.cpan/>
1728 directory so that you can save your own preferences instead of the
1729 system-wide ones.
1730
1731 =head2 recent ***EXPERIMENTAL COMMAND***
1732
1733 The C<recent> command downloads a list of recent uploads to CPAN and
1734 displays them I<slowly>. While the command is running, a $SIG{INT} 
1735 exits the loop after displaying the current item.
1736
1737 B<Note>: This command requires XML::LibXML installed.
1738
1739 B<Note>: This whole command currently is just a hack and will
1740 probably change in future versions of CPAN.pm, but the general
1741 approach will likely remain.
1742
1743 B<Note>: See also L<smoke>
1744
1745 =head2 recompile
1746
1747 recompile() is a special command that takes no argument and
1748 runs the make/test/install cycle with brute force over all installed
1749 dynamically loadable extensions (aka XS modules) with 'force' in
1750 effect. The primary purpose of this command is to finish a network
1751 installation. Imagine you have a common source tree for two different
1752 architectures. You decide to do a completely independent fresh
1753 installation. You start on one architecture with the help of a Bundle
1754 file produced earlier. CPAN installs the whole Bundle for you, but
1755 when you try to repeat the job on the second architecture, CPAN
1756 responds with a C<"Foo up to date"> message for all modules. So you
1757 invoke CPAN's recompile on the second architecture and you're done.
1758
1759 Another popular use for C<recompile> is to act as a rescue in case your
1760 perl breaks binary compatibility. If one of the modules that CPAN uses
1761 is in turn depending on binary compatibility (so you cannot run CPAN
1762 commands), then you should try the CPAN::Nox module for recovery.
1763
1764 =head2 report Bundle|Distribution|Module
1765
1766 The C<report> command temporarily turns on the C<test_report> config
1767 variable, then runs the C<force test> command with the given
1768 arguments. The C<force> pragma reruns the tests and repeats
1769 every step that might have failed before.
1770
1771 =head2 smoke ***EXPERIMENTAL COMMAND***
1772
1773 B<*** WARNING: this command downloads and executes software from CPAN to
1774 your computer of completely unknown status. You should never do
1775 this with your normal account and better have a dedicated well
1776 separated and secured machine to do this. ***>
1777
1778 The C<smoke> command takes the list of recent uploads to CPAN as
1779 provided by the C<recent> command and tests them all. While the
1780 command is running $SIG{INT} is defined to mean that the current item
1781 shall be skipped.
1782
1783 B<Note>: This whole command currently is just a hack and will
1784 probably change in future versions of CPAN.pm, but the general
1785 approach will likely remain.
1786
1787 B<Note>: See also L<recent>
1788
1789 =head2 upgrade [Module|/Regex/]...
1790
1791 The C<upgrade> command first runs an C<r> command with the given
1792 arguments and then installs the newest versions of all modules that
1793 were listed by that.
1794
1795 =head2 The four C<CPAN::*> Classes: Author, Bundle, Module, Distribution
1796
1797 Although it may be considered internal, the class hierarchy does matter
1798 for both users and programmer. CPAN.pm deals with the four
1799 classes mentioned above, and those classes all share a set of methods. Classical
1800 single polymorphism is in effect. A metaclass object registers all
1801 objects of all kinds and indexes them with a string. The strings
1802 referencing objects have a separated namespace (well, not completely
1803 separated):
1804
1805          Namespace                         Class
1806
1807    words containing a "/" (slash)      Distribution
1808     words starting with Bundle::          Bundle
1809           everything else            Module or Author
1810
1811 Modules know their associated Distribution objects. They always refer
1812 to the most recent official release. Developers may mark their releases
1813 as unstable development versions (by inserting an underbar into the
1814 module version number which will also be reflected in the distribution
1815 name when you run 'make dist'), so the really hottest and newest
1816 distribution is not always the default.  If a module Foo circulates
1817 on CPAN in both version 1.23 and 1.23_90, CPAN.pm offers a convenient
1818 way to install version 1.23 by saying
1819
1820     install Foo
1821
1822 This would install the complete distribution file (say
1823 BAR/Foo-1.23.tar.gz) with all accompanying material. But if you would
1824 like to install version 1.23_90, you need to know where the
1825 distribution file resides on CPAN relative to the authors/id/
1826 directory. If the author is BAR, this might be BAR/Foo-1.23_90.tar.gz;
1827 so you would have to say
1828
1829     install BAR/Foo-1.23_90.tar.gz
1830
1831 The first example will be driven by an object of the class
1832 CPAN::Module, the second by an object of class CPAN::Distribution.
1833
1834 =head2 Integrating local directories
1835
1836 Note: this feature is still in alpha state and may change in future
1837 versions of CPAN.pm
1838
1839 Distribution objects are normally distributions from the CPAN, but
1840 there is a slightly degenerate case for Distribution objects, too, of
1841 projects held on the local disk. These distribution objects have the
1842 same name as the local directory and end with a dot. A dot by itself
1843 is also allowed for the current directory at the time CPAN.pm was
1844 used. All actions such as C<make>, C<test>, and C<install> are applied
1845 directly to that directory. This gives the command C<cpan .> an
1846 interesting touch: while the normal mantra of installing a CPAN module
1847 without CPAN.pm is one of
1848
1849     perl Makefile.PL                 perl Build.PL
1850            ( go and get prerequisites )
1851     make                             ./Build
1852     make test                        ./Build test
1853     make install                     ./Build install
1854
1855 the command C<cpan .> does all of this at once. It figures out which
1856 of the two mantras is appropriate, fetches and installs all
1857 prerequisites, takes care of them recursively, and finally finishes the
1858 installation of the module in the current directory, be it a CPAN
1859 module or not.
1860
1861 The typical usage case is for private modules or working copies of
1862 projects from remote repositories on the local disk.
1863
1864 =head2 Redirection
1865
1866 The usual shell redirection symbols C< | > and C<< > >> are recognized
1867 by the cpan shell B<only when surrounded by whitespace>. So piping to
1868 pager or redirecting output into a file works somewhat as in a normal
1869 shell, with the stipulation that you must type extra spaces.
1870
1871 =head1 CONFIGURATION
1872
1873 When the CPAN module is used for the first time, a configuration
1874 dialogue tries to determine a couple of site specific options. The
1875 result of the dialog is stored in a hash reference C< $CPAN::Config >
1876 in a file CPAN/Config.pm.
1877
1878 Default values defined in the CPAN/Config.pm file can be
1879 overridden in a user specific file: CPAN/MyConfig.pm. Such a file is
1880 best placed in C<$HOME/.cpan/CPAN/MyConfig.pm>, because C<$HOME/.cpan> is
1881 added to the search path of the CPAN module before the use() or
1882 require() statements. The mkmyconfig command writes this file for you.
1883
1884 The C<o conf> command has various bells and whistles:
1885
1886 =over
1887
1888 =item completion support
1889
1890 If you have a ReadLine module installed, you can hit TAB at any point
1891 of the commandline and C<o conf> will offer you completion for the
1892 built-in subcommands and/or config variable names.
1893
1894 =item displaying some help: o conf help
1895
1896 Displays a short help
1897
1898 =item displaying current values: o conf [KEY]
1899
1900 Displays the current value(s) for this config variable. Without KEY,
1901 displays all subcommands and config variables.
1902
1903 Example:
1904
1905   o conf shell
1906
1907 If KEY starts and ends with a slash, the string in between is
1908 treated as a regular expression and only keys matching this regex
1909 are displayed
1910
1911 Example:
1912
1913   o conf /color/
1914
1915 =item changing of scalar values: o conf KEY VALUE
1916
1917 Sets the config variable KEY to VALUE. The empty string can be
1918 specified as usual in shells, with C<''> or C<"">
1919
1920 Example:
1921
1922   o conf wget /usr/bin/wget
1923
1924 =item changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST
1925
1926 If a config variable name ends with C<list>, it is a list. C<o conf
1927 KEY shift> removes the first element of the list, C<o conf KEY pop>
1928 removes the last element of the list. C<o conf KEYS unshift LIST>
1929 prepends a list of values to the list, C<o conf KEYS push LIST>
1930 appends a list of valued to the list.
1931
1932 Likewise, C<o conf KEY splice LIST> passes the LIST to the corresponding
1933 splice command.
1934
1935 Finally, any other list of arguments is taken as a new list value for
1936 the KEY variable discarding the previous value.
1937
1938 Examples:
1939
1940   o conf urllist unshift http://cpan.dev.local/CPAN
1941   o conf urllist splice 3 1
1942   o conf urllist http://cpan1.local http://cpan2.local ftp://ftp.perl.org
1943
1944 =item reverting to saved: o conf defaults
1945
1946 Reverts all config variables to the state in the saved config file.
1947
1948 =item saving the config: o conf commit
1949
1950 Saves all config variables to the current config file (CPAN/Config.pm
1951 or CPAN/MyConfig.pm that was loaded at start).
1952
1953 =back
1954
1955 The configuration dialog can be started any time later again by
1956 issuing the command C< o conf init > in the CPAN shell. A subset of
1957 the configuration dialog can be run by issuing C<o conf init WORD>
1958 where WORD is any valid config variable or a regular expression.
1959
1960 =head2 Config Variables
1961
1962 The following keys in the hash reference $CPAN::Config are
1963 currently defined:
1964
1965   applypatch         path to external prg
1966   auto_commit        commit all changes to config variables to disk
1967   build_cache        size of cache for directories to build modules
1968   build_dir          locally accessible directory to build modules
1969   build_dir_reuse    boolean if distros in build_dir are persistent
1970   build_requires_install_policy
1971                      to install or not to install when a module is
1972                      only needed for building. yes|no|ask/yes|ask/no
1973   bzip2              path to external prg
1974   cache_metadata     use serializer to cache metadata
1975   check_sigs         if signatures should be verified
1976   colorize_debug     Term::ANSIColor attributes for debugging output
1977   colorize_output    boolean if Term::ANSIColor should colorize output
1978   colorize_print     Term::ANSIColor attributes for normal output
1979   colorize_warn      Term::ANSIColor attributes for warnings
1980   commandnumber_in_prompt
1981                      boolean if you want to see current command number
1982   commands_quote     preferred character to use for quoting external
1983                      commands when running them. Defaults to double
1984                      quote on Windows, single tick everywhere else;
1985                      can be set to space to disable quoting
1986   connect_to_internet_ok
1987                      whether to ask if opening a connection is ok before
1988                      urllist is specified
1989   cpan_home          local directory reserved for this package
1990   curl               path to external prg
1991   dontload_hash      DEPRECATED
1992   dontload_list      arrayref: modules in the list will not be
1993                      loaded by the CPAN::has_inst() routine
1994   ftp                path to external prg
1995   ftp_passive        if set, the envariable FTP_PASSIVE is set for downloads
1996   ftp_proxy          proxy host for ftp requests
1997   ftpstats_period    max number of days to keep download statistics
1998   ftpstats_size      max number of items to keep in the download statistics
1999   getcwd             see below
2000   gpg                path to external prg
2001   gzip               location of external program gzip
2002   halt_on_failure    stop processing after the first failure of queued
2003                      items or dependencies
2004   histfile           file to maintain history between sessions
2005   histsize           maximum number of lines to keep in histfile
2006   http_proxy         proxy host for http requests
2007   inactivity_timeout breaks interactive Makefile.PLs or Build.PLs
2008                      after this many seconds inactivity. Set to 0 to
2009                      disable timeouts.
2010   index_expire       refetch index files after this many days 
2011   inhibit_startup_message
2012                      if true, suppress the startup message
2013   keep_source_where  directory in which to keep the source (if we do)
2014   load_module_verbosity
2015                      report loading of optional modules used by CPAN.pm
2016   lynx               path to external prg
2017   make               location of external make program
2018   make_arg           arguments that should always be passed to 'make'
2019   make_install_make_command
2020                      the make command for running 'make install', for
2021                      example 'sudo make'
2022   make_install_arg   same as make_arg for 'make install'
2023   makepl_arg         arguments passed to 'perl Makefile.PL'
2024   mbuild_arg         arguments passed to './Build'
2025   mbuild_install_arg arguments passed to './Build install'
2026   mbuild_install_build_command
2027                      command to use instead of './Build' when we are
2028                      in the install stage, for example 'sudo ./Build'
2029   mbuildpl_arg       arguments passed to 'perl Build.PL'
2030   ncftp              path to external prg
2031   ncftpget           path to external prg
2032   no_proxy           don't proxy to these hosts/domains (comma separated list)
2033   pager              location of external program more (or any pager)
2034   password           your password if you CPAN server wants one
2035   patch              path to external prg
2036   patches_dir        local directory containing patch files
2037   perl5lib_verbosity verbosity level for PERL5LIB additions
2038   prefer_external_tar
2039                      per default all untar operations are done with
2040                      Archive::Tar; by setting this variable to true
2041                      the external tar command is used if available
2042   prefer_installer   legal values are MB and EUMM: if a module comes
2043                      with both a Makefile.PL and a Build.PL, use the
2044                      former (EUMM) or the latter (MB); if the module
2045                      comes with only one of the two, that one will be
2046                      used no matter the setting
2047   prerequisites_policy
2048                      what to do if you are missing module prerequisites
2049                      ('follow' automatically, 'ask' me, or 'ignore')
2050                      For 'follow', also sets PERL_AUTOINSTALL and
2051                      PERL_EXTUTILS_AUTOINSTALL for "--defaultdeps" if
2052                      not already set
2053   prefs_dir          local directory to store per-distro build options
2054   proxy_user         username for accessing an authenticating proxy
2055   proxy_pass         password for accessing an authenticating proxy
2056   randomize_urllist  add some randomness to the sequence of the urllist
2057   scan_cache         controls scanning of cache ('atstart', 'atexit' or 'never')
2058   shell              your favorite shell
2059   show_unparsable_versions
2060                      boolean if r command tells which modules are versionless
2061   show_upload_date   boolean if commands should try to determine upload date
2062   show_zero_versions boolean if r command tells for which modules $version==0
2063   tar                location of external program tar
2064   tar_verbosity      verbosity level for the tar command
2065   term_is_latin      deprecated: if true Unicode is translated to ISO-8859-1
2066                      (and nonsense for characters outside latin range)
2067   term_ornaments     boolean to turn ReadLine ornamenting on/off
2068   test_report        email test reports (if CPAN::Reporter is installed)
2069   trust_test_report_history
2070                      skip testing when previously tested ok (according to
2071                      CPAN::Reporter history)
2072   unzip              location of external program unzip
2073   urllist            arrayref to nearby CPAN sites (or equivalent locations)
2074   use_file_homedir   use File::HomeDir to determine home directory and storage
2075                      locations
2076   use_sqlite         use CPAN::SQLite for metadata storage (fast and lean)
2077   username           your username if you CPAN server wants one
2078   version_timeout    stops version parsing after this many seconds.
2079                      Default is 15 secs. Set to 0 to disable.
2080   wait_list          arrayref to a wait server to try (See CPAN::WAIT)
2081   wget               path to external prg
2082   yaml_load_code     enable YAML code deserialisation via CPAN::DeferredCode
2083   yaml_module        which module to use to read/write YAML files
2084
2085 You can set and query each of these options interactively in the cpan
2086 shell with the C<o conf> or the C<o conf init> command as specified below.
2087
2088 =over 2
2089
2090 =item C<o conf E<lt>scalar optionE<gt>>
2091
2092 prints the current value of the I<scalar option>
2093
2094 =item C<o conf E<lt>scalar optionE<gt> E<lt>valueE<gt>>
2095
2096 Sets the value of the I<scalar option> to I<value>
2097
2098 =item C<o conf E<lt>list optionE<gt>>
2099
2100 prints the current value of the I<list option> in MakeMaker's
2101 neatvalue format.
2102
2103 =item C<o conf E<lt>list optionE<gt> [shift|pop]>
2104
2105 shifts or pops the array in the I<list option> variable
2106
2107 =item C<o conf E<lt>list optionE<gt> [unshift|push|splice] E<lt>listE<gt>>
2108
2109 works like the corresponding perl commands.
2110
2111 =item interactive editing: o conf init [MATCH|LIST]
2112
2113 Runs an interactive configuration dialog for matching variables.
2114 Without argument runs the dialog over all supported config variables.
2115 To specify a MATCH the argument must be enclosed by slashes.
2116
2117 Examples:
2118
2119   o conf init ftp_passive ftp_proxy
2120   o conf init /color/
2121
2122 Note: this method of setting config variables often provides more
2123 explanation about the functioning of a variable than the manpage.
2124
2125 =back
2126
2127 =head2 CPAN::anycwd($path): Note on config variable getcwd
2128
2129 CPAN.pm changes the current working directory often and needs to
2130 determine its own current working directory. By default it uses
2131 Cwd::cwd, but if for some reason this doesn't work on your system,
2132 configure alternatives according to the following table:
2133
2134 =over 4
2135
2136 =item cwd
2137
2138 Calls Cwd::cwd
2139
2140 =item getcwd
2141
2142 Calls Cwd::getcwd
2143
2144 =item fastcwd
2145
2146 Calls Cwd::fastcwd
2147
2148 =item backtickcwd
2149
2150 Calls the external command cwd.
2151
2152 =back
2153
2154 =head2 Note on the format of the urllist parameter
2155
2156 urllist parameters are URLs according to RFC 1738. We do a little
2157 guessing if your URL is not compliant, but if you have problems with
2158 C<file> URLs, please try the correct format. Either:
2159
2160     file://localhost/whatever/ftp/pub/CPAN/
2161
2162 or
2163
2164     file:///home/ftp/pub/CPAN/
2165
2166 =head2 The urllist parameter has CD-ROM support
2167
2168 The C<urllist> parameter of the configuration table contains a list of
2169 URLs used for downloading. If the list contains any
2170 C<file> URLs, CPAN always tries there first. This
2171 feature is disabled for index files. So the recommendation for the
2172 owner of a CD-ROM with CPAN contents is: include your local, possibly
2173 outdated CD-ROM as a C<file> URL at the end of urllist, e.g.
2174
2175   o conf urllist push file://localhost/CDROM/CPAN
2176
2177 CPAN.pm will then fetch the index files from one of the CPAN sites
2178 that come at the beginning of urllist. It will later check for each
2179 module to see whether there is a local copy of the most recent version.
2180
2181 Another peculiarity of urllist is that the site that we could
2182 successfully fetch the last file from automatically gets a preference
2183 token and is tried as the first site for the next request. So if you
2184 add a new site at runtime it may happen that the previously preferred
2185 site will be tried another time. This means that if you want to disallow
2186 a site for the next transfer, it must be explicitly removed from
2187 urllist.
2188
2189 =head2 Maintaining the urllist parameter
2190
2191 If you have YAML.pm (or some other YAML module configured in
2192 C<yaml_module>) installed, CPAN.pm collects a few statistical data
2193 about recent downloads. You can view the statistics with the C<hosts>
2194 command or inspect them directly by looking into the C<FTPstats.yml>
2195 file in your C<cpan_home> directory.
2196
2197 To get some interesting statistics, it is recommended that
2198 C<randomize_urllist> be set; this introduces some amount of
2199 randomness into the URL selection.
2200
2201 =head2 The C<requires> and C<build_requires> dependency declarations
2202
2203 Since CPAN.pm version 1.88_51 modules declared as C<build_requires> by
2204 a distribution are treated differently depending on the config
2205 variable C<build_requires_install_policy>. By setting
2206 C<build_requires_install_policy> to C<no>, such a module is not 
2207 installed. It is only built and tested, and then kept in the list of
2208 tested but uninstalled modules. As such, it is available during the
2209 build of the dependent module by integrating the path to the
2210 C<blib/arch> and C<blib/lib> directories in the environment variable
2211 PERL5LIB. If C<build_requires_install_policy> is set ti C<yes>, then
2212 both modules declared as C<requires> and those declared as
2213 C<build_requires> are treated alike. By setting to C<ask/yes> or
2214 C<ask/no>, CPAN.pm asks the user and sets the default accordingly.
2215
2216 =head2 Configuration for individual distributions (I<Distroprefs>)
2217
2218 (B<Note:> This feature has been introduced in CPAN.pm 1.8854 and is
2219 still considered beta quality)
2220
2221 Distributions on CPAN usually behave according to what we call the
2222 CPAN mantra. Or since the advent of Module::Build we should talk about
2223 two mantras:
2224
2225     perl Makefile.PL     perl Build.PL
2226     make                 ./Build
2227     make test            ./Build test
2228     make install         ./Build install
2229
2230 But some modules cannot be built with this mantra. They try to get
2231 some extra data from the user via the environment, extra arguments, or
2232 interactively--thus disturbing the installation of large bundles like
2233 Phalanx100 or modules with many dependencies like Plagger.
2234
2235 The distroprefs system of C<CPAN.pm> addresses this problem by
2236 allowing the user to specify extra informations and recipes in YAML
2237 files to either
2238
2239 =over
2240
2241 =item
2242
2243 pass additional arguments to one of the four commands,
2244
2245 =item
2246
2247 set environment variables
2248
2249 =item
2250
2251 instantiate an Expect object that reads from the console, waits for
2252 some regular expressions and enters some answers
2253
2254 =item
2255
2256 temporarily override assorted C<CPAN.pm> configuration variables
2257
2258 =item
2259
2260 specify dependencies the original maintainer forgot 
2261
2262 =item
2263
2264 disable the installation of an object altogether
2265
2266 =back
2267
2268 See the YAML and Data::Dumper files that come with the C<CPAN.pm>
2269 distribution in the C<distroprefs/> directory for examples.
2270
2271 =head2 Filenames
2272
2273 The YAML files themselves must have the C<.yml> extension; all other
2274 files are ignored (for two exceptions see I<Fallback Data::Dumper and
2275 Storable> below). The containing directory can be specified in
2276 C<CPAN.pm> in the C<prefs_dir> config variable. Try C<o conf init
2277 prefs_dir> in the CPAN shell to set and activate the distroprefs
2278 system.
2279
2280 Every YAML file may contain arbitrary documents according to the YAML
2281 specification, and every document is treated as an entity that
2282 can specify the treatment of a single distribution.
2283
2284 Filenames can be picked arbitrarily; C<CPAN.pm> always reads
2285 all files (in alphabetical order) and takes the key C<match> (see
2286 below in I<Language Specs>) as a hashref containing match criteria
2287 that determine if the current distribution matches the YAML document
2288 or not.
2289
2290 =head2 Fallback Data::Dumper and Storable
2291
2292 If neither your configured C<yaml_module> nor YAML.pm is installed,
2293 CPAN.pm falls back to using Data::Dumper and Storable and looks for
2294 files with the extensions C<.dd> or C<.st> in the C<prefs_dir>
2295 directory. These files are expected to contain one or more hashrefs.
2296 For Data::Dumper generated files, this is expected to be done with by
2297 defining C<$VAR1>, C<$VAR2>, etc. The YAML shell would produce these
2298 with the command
2299
2300     ysh < somefile.yml > somefile.dd
2301
2302 For Storable files the rule is that they must be constructed such that
2303 C<Storable::retrieve(file)> returns an array reference and the array
2304 elements represent one distropref object each. The conversion from
2305 YAML would look like so:
2306
2307     perl -MYAML=LoadFile -MStorable=nstore -e '
2308         @y=LoadFile(shift);
2309         nstore(\@y, shift)' somefile.yml somefile.st
2310
2311 In bootstrapping situations it is usually sufficient to translate only
2312 a few YAML files to Data::Dumper for crucial modules like
2313 C<YAML::Syck>, C<YAML.pm> and C<Expect.pm>. If you prefer Storable
2314 over Data::Dumper, remember to pull out a Storable version that writes
2315 an older format than all the other Storable versions that will need to
2316 read them.
2317
2318 =head2 Blueprint
2319
2320 The following example contains all supported keywords and structures
2321 with the exception of C<eexpect> which can be used instead of
2322 C<expect>.
2323
2324   ---
2325   comment: "Demo"
2326   match:
2327     module: "Dancing::Queen"
2328     distribution: "^CHACHACHA/Dancing-"
2329     not_distribution: "\.zip$"
2330     perl: "/usr/local/cariba-perl/bin/perl"
2331     perlconfig:
2332       archname: "freebsd"
2333       not_cc: "gcc"
2334     env:
2335       DANCING_FLOOR: "Shubiduh"
2336   disabled: 1
2337   cpanconfig:
2338     make: gmake
2339   pl:
2340     args:
2341       - "--somearg=specialcase"
2342
2343     env: {}
2344
2345     expect:
2346       - "Which is your favorite fruit"
2347       - "apple\n"
2348
2349   make:
2350     args:
2351       - all
2352       - extra-all
2353
2354     env: {}
2355
2356     expect: []
2357
2358     commandline: "echo SKIPPING make"
2359
2360   test:
2361     args: []
2362
2363     env: {}
2364
2365     expect: []
2366
2367   install:
2368     args: []
2369
2370     env:
2371       WANT_TO_INSTALL: YES
2372
2373     expect:
2374       - "Do you really want to install"
2375       - "y\n"
2376
2377   patches:
2378     - "ABCDE/Fedcba-3.14-ABCDE-01.patch"
2379
2380   depends:
2381     configure_requires:
2382       LWP: 5.8
2383     build_requires:
2384       Test::Exception: 0.25
2385     requires:
2386       Spiffy: 0.30
2387
2388
2389 =head2 Language Specs
2390
2391 Every YAML document represents a single hash reference. The valid keys
2392 in this hash are as follows:
2393
2394 =over
2395
2396 =item comment [scalar]
2397
2398 A comment
2399
2400 =item cpanconfig [hash]
2401
2402 Temporarily override assorted C<CPAN.pm> configuration variables.
2403
2404 Supported are: C<build_requires_install_policy>, C<check_sigs>,
2405 C<make>, C<make_install_make_command>, C<prefer_installer>,
2406 C<test_report>. Please report as a bug when you need another one
2407 supported.
2408
2409 =item depends [hash] *** EXPERIMENTAL FEATURE ***
2410
2411 All three types, namely C<configure_requires>, C<build_requires>, and
2412 C<requires> are supported in the way specified in the META.yml
2413 specification. The current implementation I<merges> the specified
2414 dependencies with those declared by the package maintainer. In a
2415 future implementation this may be changed to override the original
2416 declaration.
2417
2418 =item disabled [boolean]
2419
2420 Specifies that this distribution shall not be processed at all.
2421
2422 =item features [array] *** EXPERIMENTAL FEATURE ***
2423
2424 Experimental implementation to deal with optional_features from
2425 META.yml. Still needs coordination with installer software and
2426 currently works only for META.yml declaring C<dynamic_config=0>. Use
2427 with caution.
2428
2429 =item goto [string]
2430
2431 The canonical name of a delegate distribution to install
2432 instead. Useful when a new version, although it tests OK itself,
2433 breaks something else or a developer release or a fork is already
2434 uploaded that is better than the last released version.
2435
2436 =item install [hash]
2437
2438 Processing instructions for the C<make install> or C<./Build install>
2439 phase of the CPAN mantra. See below under I<Processing Instructions>.
2440
2441 =item make [hash]
2442
2443 Processing instructions for the C<make> or C<./Build> phase of the
2444 CPAN mantra. See below under I<Processing Instructions>.
2445
2446 =item match [hash]
2447
2448 A hashref with one or more of the keys C<distribution>, C<modules>,
2449 C<perl>, C<perlconfig>, and C<env> that specify whether a document is
2450 targeted at a specific CPAN distribution or installation.
2451 Keys prefixed with C<not_> negates the corresponding match.
2452
2453 The corresponding values are interpreted as regular expressions. The
2454 C<distribution> related one will be matched against the canonical
2455 distribution name, e.g. "AUTHOR/Foo-Bar-3.14.tar.gz".
2456
2457 The C<module> related one will be matched against I<all> modules
2458 contained in the distribution until one module matches.
2459
2460 The C<perl> related one will be matched against C<$^X> (but with the
2461 absolute path).
2462
2463 The value associated with C<perlconfig> is itself a hashref that is
2464 matched against corresponding values in the C<%Config::Config> hash
2465 living in the C<Config.pm> module.
2466 Keys prefixed with C<not_> negates the corresponding match.
2467
2468 The value associated with C<env> is itself a hashref that is
2469 matched against corresponding values in the C<%ENV> hash.
2470 Keys prefixed with C<not_> negates the corresponding match.
2471
2472 If more than one restriction of C<module>, C<distribution>, etc. is
2473 specified, the results of the separately computed match values must
2474 all match. If so, the hashref represented by the
2475 YAML document is returned as the preference structure for the current
2476 distribution.
2477
2478 =item patches [array]
2479
2480 An array of patches on CPAN or on the local disk to be applied in
2481 order via an external patch program. If the value for the C<-p>
2482 parameter is C<0> or C<1> is determined by reading the patch
2483 beforehand. The path to each patch is either an absolute path on the
2484 local filesystem or relative to a patch directory specified in the
2485 C<patches_dir> configuration variable or in the format of a canonical
2486 distroname. For examples please consult the distroprefs/ directory in
2487 the CPAN.pm distribution (these examples are not installed by
2488 default).
2489
2490 Note: if the C<applypatch> program is installed and C<CPAN::Config>
2491 knows about it B<and> a patch is written by the C<makepatch> program,
2492 then C<CPAN.pm> lets C<applypatch> apply the patch. Both C<makepatch>
2493 and C<applypatch> are available from CPAN in the C<JV/makepatch-*>
2494 distribution.
2495
2496 =item pl [hash]
2497
2498 Processing instructions for the C<perl Makefile.PL> or C<perl
2499 Build.PL> phase of the CPAN mantra. See below under I<Processing
2500 Instructions>.
2501
2502 =item test [hash]
2503
2504 Processing instructions for the C<make test> or C<./Build test> phase
2505 of the CPAN mantra. See below under I<Processing Instructions>.
2506
2507 =back
2508
2509 =head2 Processing Instructions
2510
2511 =over
2512
2513 =item args [array]
2514
2515 Arguments to be added to the command line
2516
2517 =item commandline
2518
2519 A full commandline to run via C<system()>.
2520 During execution, the environment variable PERL is set
2521 to $^X (but with an absolute path). If C<commandline> is specified,
2522 C<args> is not used.
2523
2524 =item eexpect [hash]
2525
2526 Extended C<expect>. This is a hash reference with four allowed keys,
2527 C<mode>, C<timeout>, C<reuse>, and C<talk>.
2528
2529 You must install the C<Expect> module to use C<eexpect>. CPAN.pm
2530 does not install it for you.
2531
2532 C<mode> may have the values C<deterministic> for the case where all
2533 questions come in the order written down and C<anyorder> for the case
2534 where the questions may come in any order. The default mode is
2535 C<deterministic>.
2536
2537 C<timeout> denotes a timeout in seconds. Floating-point timeouts are
2538 OK. With C<mode=deterministic>, the timeout denotes the
2539 timeout per question; with C<mode=anyorder> it denotes the
2540 timeout per byte received from the stream or questions.
2541
2542 C<talk> is a reference to an array that contains alternating questions
2543 and answers. Questions are regular expressions and answers are literal
2544 strings. The Expect module watches the stream from the
2545 execution of the external program (C<perl Makefile.PL>, C<perl
2546 Build.PL>, C<make>, etc.).
2547
2548 For C<mode=deterministic>, the CPAN.pm injects the
2549 corresponding answer as soon as the stream matches the regular expression.
2550
2551 For C<mode=anyorder> CPAN.pm answers a question as soon
2552 as the timeout is reached for the next byte in the input stream. In
2553 this mode you can use the C<reuse> parameter to decide what will
2554 happen with a question-answer pair after it has been used. In the
2555 default case (reuse=0) it is removed from the array, avoiding being
2556 used again accidentally. If you want to answer the
2557 question C<Do you really want to do that> several times, then it must
2558 be included in the array at least as often as you want this answer to
2559 be given. Setting the parameter C<reuse> to 1 makes this repetition
2560 unnecessary.
2561
2562 =item env [hash]
2563
2564 Environment variables to be set during the command
2565
2566 =item expect [array]
2567
2568 You must install the C<Expect> module to use C<expect>. CPAN.pm
2569 does not install it for you.
2570
2571 C<< expect: <array> >> is a short notation for this C<eexpect>:
2572
2573         eexpect:
2574                 mode: deterministic
2575                 timeout: 15
2576                 talk: <array>
2577
2578 =back
2579
2580 =head2 Schema verification with C<Kwalify>
2581
2582 If you have the C<Kwalify> module installed (which is part of the
2583 Bundle::CPANxxl), then all your distroprefs files are checked for
2584 syntactic correctness.
2585
2586 =head2 Example Distroprefs Files
2587
2588 C<CPAN.pm> comes with a collection of example YAML files. Note that these
2589 are really just examples and should not be used without care because
2590 they cannot fit everybody's purpose. After all, the authors of the
2591 packages that ask questions had a need to ask, so you should watch
2592 their questions and adjust the examples to your environment and your
2593 needs. You have been warned:-)
2594
2595 =head1 PROGRAMMER'S INTERFACE
2596
2597 If you do not enter the shell, shell commands are 
2598 available both as methods (C<CPAN::Shell-E<gt>install(...)>) and as
2599 functions in the calling package (C<install(...)>).  Before calling low-level
2600 commands, it makes sense to initialize components of CPAN you need, e.g.:
2601
2602   CPAN::HandleConfig->load;
2603   CPAN::Shell::setup_output;
2604   CPAN::Index->reload;
2605
2606 High-level commands do such initializations automatically.
2607
2608 There's currently only one class that has a stable interface -
2609 CPAN::Shell. All commands that are available in the CPAN shell are
2610 methods of the class CPAN::Shell. Each of the commands that produce
2611 listings of modules (C<r>, C<autobundle>, C<u>) also return a list of
2612 the IDs of all modules within the list.
2613
2614 =over 2
2615
2616 =item expand($type,@things)
2617
2618 The IDs of all objects available within a program are strings that can
2619 be expanded to the corresponding real objects with the
2620 C<CPAN::Shell-E<gt>expand("Module",@things)> method. Expand returns a
2621 list of CPAN::Module objects according to the C<@things> arguments
2622 given. In scalar context, it returns only the first element of the
2623 list.
2624
2625 =item expandany(@things)
2626
2627 Like expand, but returns objects of the appropriate type, i.e.
2628 CPAN::Bundle objects for bundles, CPAN::Module objects for modules, and
2629 CPAN::Distribution objects for distributions. Note: it does not expand
2630 to CPAN::Author objects.
2631
2632 =item Programming Examples
2633
2634 This enables the programmer to do operations that combine
2635 functionalities that are available in the shell.
2636
2637     # install everything that is outdated on my disk:
2638     perl -MCPAN -e 'CPAN::Shell->install(CPAN::Shell->r)'
2639
2640     # install my favorite programs if necessary:
2641     for $mod (qw(Net::FTP Digest::SHA Data::Dumper)) {
2642         CPAN::Shell->install($mod);
2643     }
2644
2645     # list all modules on my disk that have no VERSION number
2646     for $mod (CPAN::Shell->expand("Module","/./")) {
2647         next unless $mod->inst_file;
2648         # MakeMaker convention for undefined $VERSION:
2649         next unless $mod->inst_version eq "undef";
2650         print "No VERSION in ", $mod->id, "\n";
2651     }
2652
2653     # find out which distribution on CPAN contains a module:
2654     print CPAN::Shell->expand("Module","Apache::Constants")->cpan_file
2655
2656 Or if you want to schedule a I<cron> job to watch CPAN, you could list
2657 all modules that need updating. First a quick and dirty way:
2658
2659     perl -e 'use CPAN; CPAN::Shell->r;'
2660
2661 If you don't want any output should all modules be
2662 up to date, parse the output of above command for the regular
2663 expression C</modules are up to date/> and decide to mail the output
2664 only if it doesn't match. 
2665
2666 If you prefer to do it more in a programmerish style in one single
2667 process, something like this may better suit you:
2668
2669   # list all modules on my disk that have newer versions on CPAN
2670   for $mod (CPAN::Shell->expand("Module","/./")) {
2671     next unless $mod->inst_file;
2672     next if $mod->uptodate;
2673     printf "Module %s is installed as %s, could be updated to %s from CPAN\n",
2674         $mod->id, $mod->inst_version, $mod->cpan_version;
2675   }
2676
2677 If that gives too much output every day, you may want to
2678 watch only for three modules. You can write
2679
2680   for $mod (CPAN::Shell->expand("Module","/Apache|LWP|CGI/")) {
2681
2682 as the first line instead. Or you can combine some of the above
2683 tricks:
2684
2685   # watch only for a new mod_perl module
2686   $mod = CPAN::Shell->expand("Module","mod_perl");
2687   exit if $mod->uptodate;
2688   # new mod_perl arrived, let me know all update recommendations
2689   CPAN::Shell->r;
2690
2691 =back
2692
2693 =head2 Methods in the other Classes
2694
2695 =over 4
2696
2697 =item CPAN::Author::as_glimpse()
2698
2699 Returns a one-line description of the author
2700
2701 =item CPAN::Author::as_string()
2702
2703 Returns a multi-line description of the author
2704
2705 =item CPAN::Author::email()
2706
2707 Returns the author's email address
2708
2709 =item CPAN::Author::fullname()
2710
2711 Returns the author's name
2712
2713 =item CPAN::Author::name()
2714
2715 An alias for fullname
2716
2717 =item CPAN::Bundle::as_glimpse()
2718
2719 Returns a one-line description of the bundle
2720
2721 =item CPAN::Bundle::as_string()
2722
2723 Returns a multi-line description of the bundle
2724
2725 =item CPAN::Bundle::clean()
2726
2727 Recursively runs the C<clean> method on all items contained in the bundle.
2728
2729 =item CPAN::Bundle::contains()
2730
2731 Returns a list of objects' IDs contained in a bundle. The associated
2732 objects may be bundles, modules or distributions.
2733
2734 =item CPAN::Bundle::force($method,@args)
2735
2736 Forces CPAN to perform a task that it normally would have refused to
2737 do. Force takes as arguments a method name to be called and any number
2738 of additional arguments that should be passed to the called method.
2739 The internals of the object get the needed changes so that CPAN.pm
2740 does not refuse to take the action. The C<force> is passed recursively
2741 to all contained objects. See also the section above on the C<force>
2742 and the C<fforce> pragma.
2743
2744 =item CPAN::Bundle::get()
2745
2746 Recursively runs the C<get> method on all items contained in the bundle
2747
2748 =item CPAN::Bundle::inst_file()
2749
2750 Returns the highest installed version of the bundle in either @INC or
2751 C<< $CPAN::Config->{cpan_home} >>. Note that this is different from
2752 CPAN::Module::inst_file.
2753
2754 =item CPAN::Bundle::inst_version()
2755
2756 Like CPAN::Bundle::inst_file, but returns the $VERSION
2757
2758 =item CPAN::Bundle::uptodate()
2759
2760 Returns 1 if the bundle itself and all its members are uptodate.
2761
2762 =item CPAN::Bundle::install()
2763
2764 Recursively runs the C<install> method on all items contained in the bundle
2765
2766 =item CPAN::Bundle::make()
2767
2768 Recursively runs the C<make> method on all items contained in the bundle
2769
2770 =item CPAN::Bundle::readme()
2771
2772 Recursively runs the C<readme> method on all items contained in the bundle
2773
2774 =item CPAN::Bundle::test()
2775
2776 Recursively runs the C<test> method on all items contained in the bundle
2777
2778 =item CPAN::Distribution::as_glimpse()
2779
2780 Returns a one-line description of the distribution
2781
2782 =item CPAN::Distribution::as_string()
2783
2784 Returns a multi-line description of the distribution
2785
2786 =item CPAN::Distribution::author
2787
2788 Returns the CPAN::Author object of the maintainer who uploaded this
2789 distribution
2790
2791 =item CPAN::Distribution::pretty_id()
2792
2793 Returns a string of the form "AUTHORID/TARBALL", where AUTHORID is the
2794 author's PAUSE ID and TARBALL is the distribution filename.
2795
2796 =item CPAN::Distribution::base_id()
2797
2798 Returns the distribution filename without any archive suffix.  E.g
2799 "Foo-Bar-0.01"
2800
2801 =item CPAN::Distribution::clean()
2802
2803 Changes to the directory where the distribution has been unpacked and
2804 runs C<make clean> there.
2805
2806 =item CPAN::Distribution::containsmods()
2807
2808 Returns a list of IDs of modules contained in a distribution file.
2809 Works only for distributions listed in the 02packages.details.txt.gz
2810 file. This typically means that just most recent version of a
2811 distribution is covered.
2812
2813 =item CPAN::Distribution::cvs_import()
2814
2815 Changes to the directory where the distribution has been unpacked and
2816 runs something like
2817
2818     cvs -d $cvs_root import -m $cvs_log $cvs_dir $userid v$version
2819
2820 there.
2821
2822 =item CPAN::Distribution::dir()
2823
2824 Returns the directory into which this distribution has been unpacked.
2825
2826 =item CPAN::Distribution::force($method,@args)
2827
2828 Forces CPAN to perform a task that it normally would have refused to
2829 do. Force takes as arguments a method name to be called and any number
2830 of additional arguments that should be passed to the called method.
2831 The internals of the object get the needed changes so that CPAN.pm
2832 does not refuse to take the action. See also the section above on the
2833 C<force> and the C<fforce> pragma.
2834
2835 =item CPAN::Distribution::get()
2836
2837 Downloads the distribution from CPAN and unpacks it. Does nothing if
2838 the distribution has already been downloaded and unpacked within the
2839 current session.
2840
2841 =item CPAN::Distribution::install()
2842
2843 Changes to the directory where the distribution has been unpacked and
2844 runs the external command C<make install> there. If C<make> has not
2845 yet been run, it will be run first. A C<make test> is issued in
2846 any case and if this fails, the install is cancelled. The
2847 cancellation can be avoided by letting C<force> run the C<install> for
2848 you.
2849
2850 This install method only has the power to install the distribution if
2851 there are no dependencies in the way. To install an object along with all 
2852 its dependencies, use CPAN::Shell->install.
2853
2854 Note that install() gives no meaningful return value. See uptodate().
2855
2856 =item CPAN::Distribution::install_tested()
2857
2858 Install all distributions that have tested sucessfully but
2859 not yet installed. See also C<is_tested>.
2860
2861 =item CPAN::Distribution::isa_perl()
2862
2863 Returns 1 if this distribution file seems to be a perl distribution.
2864 Normally this is derived from the file name only, but the index from
2865 CPAN can contain a hint to achieve a return value of true for other
2866 filenames too.
2867
2868 =item CPAN::Distribution::look()
2869
2870 Changes to the directory where the distribution has been unpacked and
2871 opens a subshell there. Exiting the subshell returns.
2872
2873 =item CPAN::Distribution::make()
2874
2875 First runs the C<get> method to make sure the distribution is
2876 downloaded and unpacked. Changes to the directory where the
2877 distribution has been unpacked and runs the external commands C<perl
2878 Makefile.PL> or C<perl Build.PL> and C<make> there.
2879
2880 =item CPAN::Distribution::perldoc()
2881
2882 Downloads the pod documentation of the file associated with a
2883 distribution (in HTML format) and runs it through the external
2884 command I<lynx> specified in C<< $CPAN::Config->{lynx} >>. If I<lynx>
2885 isn't available, it converts it to plain text with the external
2886 command I<html2text> and runs it through the pager specified
2887 in C<< $CPAN::Config->{pager} >>.
2888
2889 =item CPAN::Distribution::prefs()
2890
2891 Returns the hash reference from the first matching YAML file that the
2892 user has deposited in the C<prefs_dir/> directory. The first
2893 succeeding match wins. The files in the C<prefs_dir/> are processed
2894 alphabetically, and the canonical distroname (e.g.
2895 AUTHOR/Foo-Bar-3.14.tar.gz) is matched against the regular expressions
2896 stored in the $root->{match}{distribution} attribute value.
2897 Additionally all module names contained in a distribution are matched
2898 against the regular expressions in the $root->{match}{module} attribute
2899 value. The two match values are ANDed together. Each of the two
2900 attributes are optional.
2901
2902 =item CPAN::Distribution::prereq_pm()
2903
2904 Returns the hash reference that has been announced by a distribution
2905 as the C<requires> and C<build_requires> elements. These can be
2906 declared either by the C<META.yml> (if authoritative) or can be
2907 deposited after the run of C<Build.PL> in the file C<./_build/prereqs>
2908 or after the run of C<Makfile.PL> written as the C<PREREQ_PM> hash in
2909 a comment in the produced C<Makefile>. I<Note>: this method only works
2910 after an attempt has been made to C<make> the distribution. Returns
2911 undef otherwise.
2912
2913 =item CPAN::Distribution::readme()
2914
2915 Downloads the README file associated with a distribution and runs it
2916 through the pager specified in C<< $CPAN::Config->{pager} >>.
2917
2918 =item CPAN::Distribution::reports()
2919
2920 Downloads report data for this distribution from www.cpantesters.org
2921 and displays a subset of them.
2922
2923 =item CPAN::Distribution::read_yaml()
2924
2925 Returns the content of the META.yml of this distro as a hashref. Note:
2926 works only after an attempt has been made to C<make> the distribution.
2927 Returns undef otherwise. Also returns undef if the content of META.yml
2928 is not authoritative. (The rules about what exactly makes the content
2929 authoritative are still in flux.)
2930
2931 =item CPAN::Distribution::test()
2932
2933 Changes to the directory where the distribution has been unpacked and
2934 runs C<make test> there.
2935
2936 =item CPAN::Distribution::uptodate()
2937
2938 Returns 1 if all the modules contained in the distribution are
2939 uptodate. Relies on containsmods.
2940
2941 =item CPAN::Index::force_reload()
2942
2943 Forces a reload of all indices.
2944
2945 =item CPAN::Index::reload()
2946
2947 Reloads all indices if they have not been read for more than
2948 C<< $CPAN::Config->{index_expire} >> days.
2949
2950 =item CPAN::InfoObj::dump()
2951
2952 CPAN::Author, CPAN::Bundle, CPAN::Module, and CPAN::Distribution
2953 inherit this method. It prints the data structure associated with an
2954 object. Useful for debugging. Note: the data structure is considered
2955 internal and thus subject to change without notice.
2956
2957 =item CPAN::Module::as_glimpse()
2958
2959 Returns a one-line description of the module in four columns: The
2960 first column contains the word C<Module>, the second column consists
2961 of one character: an equals sign if this module is already installed
2962 and uptodate, a less-than sign if this module is installed but can be
2963 upgraded, and a space if the module is not installed. The third column
2964 is the name of the module and the fourth column gives maintainer or
2965 distribution information.
2966
2967 =item CPAN::Module::as_string()
2968
2969 Returns a multi-line description of the module
2970
2971 =item CPAN::Module::clean()
2972
2973 Runs a clean on the distribution associated with this module.
2974
2975 =item CPAN::Module::cpan_file()
2976
2977 Returns the filename on CPAN that is associated with the module.
2978
2979 =item CPAN::Module::cpan_version()
2980
2981 Returns the latest version of this module available on CPAN.
2982
2983 =item CPAN::Module::cvs_import()
2984
2985 Runs a cvs_import on the distribution associated with this module.
2986
2987 =item CPAN::Module::description()
2988
2989 Returns a 44 character description of this module. Only available for
2990 modules listed in The Module List (CPAN/modules/00modlist.long.html
2991 or 00modlist.long.txt.gz)
2992
2993 =item CPAN::Module::distribution()
2994
2995 Returns the CPAN::Distribution object that contains the current
2996 version of this module.
2997
2998 =item CPAN::Module::dslip_status()
2999
3000 Returns a hash reference. The keys of the hash are the letters C<D>,
3001 C<S>, C<L>, C<I>, and <P>, for development status, support level,
3002 language, interface and public licence respectively. The data for the
3003 DSLIP status are collected by pause.perl.org when authors register
3004 their namespaces. The values of the 5 hash elements are one-character
3005 words whose meaning is described in the table below. There are also 5
3006 hash elements C<DV>, C<SV>, C<LV>, C<IV>, and <PV> that carry a more
3007 verbose value of the 5 status variables.
3008
3009 Where the 'DSLIP' characters have the following meanings:
3010
3011   D - Development Stage  (Note: *NO IMPLIED TIMESCALES*):
3012     i   - Idea, listed to gain consensus or as a placeholder
3013     c   - under construction but pre-alpha (not yet released)
3014     a/b - Alpha/Beta testing
3015     R   - Released
3016     M   - Mature (no rigorous definition)
3017     S   - Standard, supplied with Perl 5
3018
3019   S - Support Level:
3020     m   - Mailing-list
3021     d   - Developer
3022     u   - Usenet newsgroup comp.lang.perl.modules
3023     n   - None known, try comp.lang.perl.modules
3024     a   - abandoned; volunteers welcome to take over maintainance
3025
3026   L - Language Used:
3027     p   - Perl-only, no compiler needed, should be platform independent
3028     c   - C and perl, a C compiler will be needed
3029     h   - Hybrid, written in perl with optional C code, no compiler needed
3030     +   - C++ and perl, a C++ compiler will be needed
3031     o   - perl and another language other than C or C++
3032
3033   I - Interface Style
3034     f   - plain Functions, no references used
3035     h   - hybrid, object and function interfaces available
3036     n   - no interface at all (huh?)
3037     r   - some use of unblessed References or ties
3038     O   - Object oriented using blessed references and/or inheritance
3039
3040   P - Public License
3041     p   - Standard-Perl: user may choose between GPL and Artistic
3042     g   - GPL: GNU General Public License
3043     l   - LGPL: "GNU Lesser General Public License" (previously known as
3044           "GNU Library General Public License")
3045     b   - BSD: The BSD License
3046     a   - Artistic license alone
3047     2   - Artistic license 2.0 or later
3048     o   - open source: appoved by www.opensource.org
3049     d   - allows distribution without restrictions
3050     r   - restricted distribtion
3051     n   - no license at all
3052
3053 =item CPAN::Module::force($method,@args)
3054
3055 Forces CPAN to perform a task it would normally refuse to
3056 do. Force takes as arguments a method name to be invoked and any number
3057 of additional arguments to pass that method.
3058 The internals of the object get the needed changes so that CPAN.pm
3059 does not refuse to take the action. See also the section above on the
3060 C<force> and the C<fforce> pragma.
3061
3062 =item CPAN::Module::get()
3063
3064 Runs a get on the distribution associated with this module.
3065
3066 =item CPAN::Module::inst_file()
3067
3068 Returns the filename of the module found in @INC. The first file found
3069 is reported, just as perl itself stops searching @INC once it finds a
3070 module.
3071
3072 =item CPAN::Module::available_file()
3073
3074 Returns the filename of the module found in PERL5LIB or @INC. The
3075 first file found is reported. The advantage of this method over
3076 C<inst_file> is that modules that have been tested but not yet
3077 installed are included because PERL5LIB keeps track of tested modules.
3078
3079 =item CPAN::Module::inst_version()
3080
3081 Returns the version number of the installed module in readable format.
3082
3083 =item CPAN::Module::available_version()
3084
3085 Returns the version number of the available module in readable format.
3086
3087 =item CPAN::Module::install()
3088
3089 Runs an C<install> on the distribution associated with this module.
3090
3091 =item CPAN::Module::look()
3092
3093 Changes to the directory where the distribution associated with this
3094 module has been unpacked and opens a subshell there. Exiting the
3095 subshell returns.
3096
3097 =item CPAN::Module::make()
3098
3099 Runs a C<make> on the distribution associated with this module.
3100
3101 =item CPAN::Module::manpage_headline()
3102
3103 If module is installed, peeks into the module's manpage, reads the
3104 headline, and returns it. Moreover, if the module has been downloaded
3105 within this session, does the equivalent on the downloaded module even
3106 if it hasn't been installed yet.
3107
3108 =item CPAN::Module::perldoc()
3109
3110 Runs a C<perldoc> on this module.
3111
3112 =item CPAN::Module::readme()
3113
3114 Runs a C<readme> on the distribution associated with this module.
3115
3116 =item CPAN::Module::reports()
3117
3118 Calls the reports() method on the associated distribution object.
3119
3120 =item CPAN::Module::test()
3121
3122 Runs a C<test> on the distribution associated with this module.
3123
3124 =item CPAN::Module::uptodate()
3125
3126 Returns 1 if the module is installed and up-to-date.
3127
3128 =item CPAN::Module::userid()
3129
3130 Returns the author's ID of the module.
3131
3132 =back
3133
3134 =head2 Cache Manager
3135
3136 Currently the cache manager only keeps track of the build directory
3137 ($CPAN::Config->{build_dir}). It is a simple FIFO mechanism that
3138 deletes complete directories below C<build_dir> as soon as the size of
3139 all directories there gets bigger than $CPAN::Config->{build_cache}
3140 (in MB). The contents of this cache may be used for later
3141 re-installations that you intend to do manually, but will never be
3142 trusted by CPAN itself. This is due to the fact that the user might
3143 use these directories for building modules on different architectures.
3144
3145 There is another directory ($CPAN::Config->{keep_source_where}) where
3146 the original distribution files are kept. This directory is not
3147 covered by the cache manager and must be controlled by the user. If
3148 you choose to have the same directory as build_dir and as
3149 keep_source_where directory, then your sources will be deleted with
3150 the same fifo mechanism.
3151
3152 =head2 Bundles
3153
3154 A bundle is just a perl module in the namespace Bundle:: that does not
3155 define any functions or methods. It usually only contains documentation.
3156
3157 It starts like a perl module with a package declaration and a $VERSION
3158 variable. After that the pod section looks like any other pod with the
3159 only difference being that I<one special pod section> exists starting with
3160 (verbatim):
3161
3162     =head1 CONTENTS
3163
3164 In this pod section each line obeys the format
3165
3166         Module_Name [Version_String] [- optional text]
3167
3168 The only required part is the first field, the name of a module
3169 (e.g. Foo::Bar, ie. I<not> the name of the distribution file). The rest
3170 of the line is optional. The comment part is delimited by a dash just
3171 as in the man page header.
3172
3173 The distribution of a bundle should follow the same convention as
3174 other distributions.
3175
3176 Bundles are treated specially in the CPAN package. If you say 'install
3177 Bundle::Tkkit' (assuming such a bundle exists), CPAN will install all
3178 the modules in the CONTENTS section of the pod. You can install your
3179 own Bundles locally by placing a conformant Bundle file somewhere into
3180 your @INC path. The autobundle() command which is available in the
3181 shell interface does that for you by including all currently installed
3182 modules in a snapshot bundle file.
3183
3184 =head1 PREREQUISITES
3185
3186 The CPAN program is trying to depend on as little as possible so the
3187 user can use it in hostile enviroment. It works better the more goodies
3188 the environment provides. For example if you try in the CPAN shell
3189
3190   install Bundle::CPAN
3191
3192 or
3193
3194   install Bundle::CPANxxl
3195
3196 you will find the shell more convenient than the bare shell before.
3197
3198 If you have a local mirror of CPAN and can access all files with
3199 "file:" URLs, then you only need a perl later than perl5.003 to run
3200 this module. Otherwise Net::FTP is strongly recommended. LWP may be
3201 required for non-UNIX systems, or if your nearest CPAN site is
3202 associated with a URL that is not C<ftp:>.
3203
3204 If you have neither Net::FTP nor LWP, there is a fallback mechanism
3205 implemented for an external ftp command or for an external lynx
3206 command.
3207
3208 =head1 UTILITIES
3209
3210 =head2 Finding packages and VERSION
3211
3212 This module presumes that all packages on CPAN
3213
3214 =over 2
3215
3216 =item *
3217
3218 declare their $VERSION variable in an easy to parse manner. This
3219 prerequisite can hardly be relaxed because it consumes far too much
3220 memory to load all packages into the running program just to determine
3221 the $VERSION variable. Currently all programs that are dealing with
3222 version use something like this
3223
3224     perl -MExtUtils::MakeMaker -le \
3225         'print MM->parse_version(shift)' filename
3226
3227 If you are author of a package and wonder if your $VERSION can be
3228 parsed, please try the above method.
3229
3230 =item *
3231
3232 come as compressed or gzipped tarfiles or as zip files and contain a
3233 C<Makefile.PL> or C<Build.PL> (well, we try to handle a bit more, but
3234 with little enthusiasm).
3235
3236 =back
3237
3238 =head2 Debugging
3239
3240 Debugging this module is more than a bit complex due to interference from
3241 the software producing the indices on CPAN, the mirroring process on CPAN,
3242 packaging, configuration, synchronicity, and even (gasp!) due to bugs
3243 within the CPAN.pm module itself.
3244
3245 For debugging the code of CPAN.pm itself in interactive mode, some 
3246 debugging aid can be turned on for most packages within
3247 CPAN.pm with one of
3248
3249 =over 2
3250
3251 =item o debug package...
3252
3253 sets debug mode for packages.
3254
3255 =item o debug -package...
3256
3257 unsets debug mode for packages.
3258
3259 =item o debug all
3260
3261 turns debugging on for all packages.
3262
3263 =item o debug number
3264
3265 =back
3266
3267 which sets the debugging packages directly. Note that C<o debug 0>
3268 turns debugging off.
3269
3270 What seems a successful strategy is the combination of C<reload
3271 cpan> and the debugging switches. Add a new debug statement while
3272 running in the shell and then issue a C<reload cpan> and see the new
3273 debugging messages immediately without losing the current context.
3274
3275 C<o debug> without an argument lists the valid package names and the
3276 current set of packages in debugging mode. C<o debug> has built-in
3277 completion support.
3278
3279 For debugging of CPAN data there is the C<dump> command which takes
3280 the same arguments as make/test/install and outputs each object's
3281 Data::Dumper dump. If an argument looks like a perl variable and
3282 contains one of C<$>, C<@> or C<%>, it is eval()ed and fed to
3283 Data::Dumper directly.
3284
3285 =head2 Floppy, Zip, Offline Mode
3286
3287 CPAN.pm works nicely without network access, too. If you maintain machines
3288 that are not networked at all, you should consider working with C<file:>
3289 URLs. You'll have to collect your modules somewhere first. So
3290 you might use CPAN.pm to put together all you need on a networked
3291 machine. Then copy the $CPAN::Config->{keep_source_where} (but not
3292 $CPAN::Config->{build_dir}) directory on a floppy. This floppy is kind
3293 of a personal CPAN. CPAN.pm on the non-networked machines works nicely
3294 with this floppy. See also below the paragraph about CD-ROM support.
3295
3296 =head2 Basic Utilities for Programmers
3297
3298 =over 2
3299
3300 =item has_inst($module)
3301
3302 Returns true if the module is installed. Used to load all modules into
3303 the running CPAN.pm that are considered optional. The config variable
3304 C<dontload_list> intercepts the C<has_inst()> call such
3305 that an optional module is not loaded despite being available. For
3306 example, the following command will prevent C<YAML.pm> from being
3307 loaded:
3308
3309     cpan> o conf dontload_list push YAML
3310
3311 See the source for details.
3312
3313 =item has_usable($module)
3314
3315 Returns true if the module is installed and in a usable state. Only
3316 useful for a handful of modules that are used internally. See the
3317 source for details.
3318
3319 =item instance($module)
3320
3321 The constructor for all the singletons used to represent modules,
3322 distributions, authors, and bundles. If the object already exists, this
3323 method returns the object; otherwise, it calls the constructor.
3324
3325 =back
3326
3327 =head1 SECURITY
3328
3329 There's no strong security layer in CPAN.pm. CPAN.pm helps you to
3330 install foreign, unmasked, unsigned code on your machine. We compare
3331 to a checksum that comes from the net just as the distribution file
3332 itself. But we try to make it easy to add security on demand:
3333
3334 =head2 Cryptographically signed modules
3335
3336 Since release 1.77, CPAN.pm has been able to verify cryptographically
3337 signed module distributions using Module::Signature.  The CPAN modules
3338 can be signed by their authors, thus giving more security.  The simple
3339 unsigned MD5 checksums that were used before by CPAN protect mainly
3340 against accidental file corruption.
3341
3342 You will need to have Module::Signature installed, which in turn
3343 requires that you have at least one of Crypt::OpenPGP module or the
3344 command-line F<gpg> tool installed.
3345
3346 You will also need to be able to connect over the Internet to the public
3347 keyservers, like pgp.mit.edu, and their port 11731 (the HKP protocol).
3348
3349 The configuration parameter check_sigs is there to turn signature
3350 checking on or off.
3351
3352 =head1 EXPORT
3353
3354 Most functions in package CPAN are exported by default. The reason
3355 for this is that the primary use is intended for the cpan shell or for
3356 one-liners.
3357
3358 =head1 ENVIRONMENT
3359
3360 When the CPAN shell enters a subshell via the look command, it sets
3361 the environment CPAN_SHELL_LEVEL to 1, or increments that variable if it is
3362 already set.
3363
3364 When CPAN runs, it sets the environment variable PERL5_CPAN_IS_RUNNING
3365 to the ID of the running process. It also sets
3366 PERL5_CPANPLUS_IS_RUNNING to prevent runaway processes which could
3367 happen with older versions of Module::Install.
3368
3369 When running C<perl Makefile.PL>, the environment variable
3370 C<PERL5_CPAN_IS_EXECUTING> is set to the full path of the
3371 C<Makefile.PL> that is being executed. This prevents runaway processes
3372 with newer versions of Module::Install.
3373
3374 When the config variable ftp_passive is set, all downloads will be run
3375 with the environment variable FTP_PASSIVE set to this value. This is
3376 in general a good idea as it influences both Net::FTP and LWP based
3377 connections. The same effect can be achieved by starting the cpan
3378 shell with this environment variable set. For Net::FTP alone, one can
3379 also always set passive mode by running libnetcfg.
3380
3381 =head1 POPULATE AN INSTALLATION WITH LOTS OF MODULES
3382
3383 Populating a freshly installed perl with one's favorite modules is pretty
3384 easy if you maintain a private bundle definition file. To get a useful
3385 blueprint of a bundle definition file, the command autobundle can be used
3386 on the CPAN shell command line. This command writes a bundle definition
3387 file for all modules installed for the current perl
3388 interpreter. It's recommended to run this command once only, and from then
3389 on maintain the file manually under a private name, say
3390 Bundle/my_bundle.pm. With a clever bundle file you can then simply say
3391
3392     cpan> install Bundle::my_bundle
3393
3394 then answer a few questions and go out for coffee (possibly
3395 even in a different city).
3396
3397 Maintaining a bundle definition file means keeping track of two
3398 things: dependencies and interactivity. CPAN.pm sometimes fails on
3399 calculating dependencies because not all modules define all MakeMaker
3400 attributes correctly, so a bundle definition file should specify
3401 prerequisites as early as possible. On the other hand, it's 
3402 annoying that so many distributions need some interactive configuring. So
3403 what you can try to accomplish in your private bundle file is to have the
3404 packages that need to be configured early in the file and the gentle
3405 ones later, so you can go out for cofeee after a few minutes and leave CPAN.pm
3406 to churn away untended.
3407
3408 =head1 WORKING WITH CPAN.pm BEHIND FIREWALLS
3409
3410 Thanks to Graham Barr for contributing the following paragraphs about
3411 the interaction between perl, and various firewall configurations. For
3412 further information on firewalls, it is recommended to consult the
3413 documentation that comes with the I<ncftp> program. If you are unable to
3414 go through the firewall with a simple Perl setup, it is likely
3415 that you can configure I<ncftp> so that it works through your firewall.
3416
3417 =head2 Three basic types of firewalls
3418
3419 Firewalls can be categorized into three basic types.
3420
3421 =over 4
3422
3423 =item http firewall
3424
3425 This is when the firewall machine runs a web server, and to access the
3426 outside world, you must do so via that web server. If you set environment
3427 variables like http_proxy or ftp_proxy to values beginning with http://,
3428 or in your web browser you've proxy information set, then you know
3429 you are running behind an http firewall.
3430
3431 To access servers outside these types of firewalls with perl (even for
3432 ftp), you need LWP or HTTP::Tiny.
3433
3434 =item ftp firewall
3435
3436 This where the firewall machine runs an ftp server. This kind of
3437 firewall will only let you access ftp servers outside the firewall.
3438 This is usually done by connecting to the firewall with ftp, then
3439 entering a username like "user@outside.host.com".
3440
3441 To access servers outside these type of firewalls with perl, you
3442 need Net::FTP.
3443
3444 =item One-way visibility
3445
3446 One-way visibility means these firewalls try to make themselves 
3447 invisible to users inside the firewall. An FTP data connection is
3448 normally created by sending your IP address to the remote server and then
3449 listening for the return connection. But the remote server will not be able to
3450 connect to you because of the firewall. For these types of firewall,
3451 FTP connections need to be done in a passive mode.
3452
3453 There are two that I can think off.
3454
3455 =over 4
3456
3457 =item SOCKS
3458
3459 If you are using a SOCKS firewall, you will need to compile perl and link
3460 it with the SOCKS library.  This is what is normally called a 'socksified'
3461 perl. With this executable you will be able to connect to servers outside
3462 the firewall as if it were not there.
3463
3464 =item IP Masquerade
3465
3466 This is when the firewall implemented in the kernel (via NAT, or networking
3467 address translation), it allows you to hide a complete network behind one
3468 IP address. With this firewall no special compiling is needed as you can
3469 access hosts directly.
3470
3471 For accessing ftp servers behind such firewalls you usually need to
3472 set the environment variable C<FTP_PASSIVE> or the config variable
3473 ftp_passive to a true value.
3474
3475 =back
3476
3477 =back
3478
3479 =head2 Configuring lynx or ncftp for going through a firewall
3480
3481 If you can go through your firewall with e.g. lynx, presumably with a
3482 command such as
3483
3484     /usr/local/bin/lynx -pscott:tiger
3485
3486 then you would configure CPAN.pm with the command
3487
3488     o conf lynx "/usr/local/bin/lynx -pscott:tiger"
3489
3490 That's all. Similarly for ncftp or ftp, you would configure something
3491 like
3492
3493     o conf ncftp "/usr/bin/ncftp -f /home/scott/ncftplogin.cfg"
3494
3495 Your mileage may vary...
3496
3497 =head1 FAQ
3498
3499 =over 4
3500
3501 =item 1)
3502
3503 I installed a new version of module X but CPAN keeps saying,
3504 I have the old version installed
3505
3506 Probably you B<do> have the old version installed. This can
3507 happen if a module installs itself into a different directory in the
3508 @INC path than it was previously installed. This is not really a
3509 CPAN.pm problem, you would have the same problem when installing the
3510 module manually. The easiest way to prevent this behaviour is to add
3511 the argument C<UNINST=1> to the C<make install> call, and that is why
3512 many people add this argument permanently by configuring
3513
3514   o conf make_install_arg UNINST=1
3515
3516 =item 2)
3517
3518 So why is UNINST=1 not the default?
3519
3520 Because there are people who have their precise expectations about who
3521 may install where in the @INC path and who uses which @INC array. In
3522 fine tuned environments C<UNINST=1> can cause damage.
3523
3524 =item 3)
3525
3526 I want to clean up my mess, and install a new perl along with
3527 all modules I have. How do I go about it?
3528
3529 Run the autobundle command for your old perl and optionally rename the
3530 resulting bundle file (e.g. Bundle/mybundle.pm), install the new perl
3531 with the Configure option prefix, e.g.
3532
3533     ./Configure -Dprefix=/usr/local/perl-5.6.78.9
3534
3535 Install the bundle file you produced in the first step with something like
3536
3537     cpan> install Bundle::mybundle
3538
3539 and you're done.
3540
3541 =item 4)
3542
3543 When I install bundles or multiple modules with one command
3544 there is too much output to keep track of.
3545
3546 You may want to configure something like
3547
3548   o conf make_arg "| tee -ai /root/.cpan/logs/make.out"
3549   o conf make_install_arg "| tee -ai /root/.cpan/logs/make_install.out"
3550
3551 so that STDOUT is captured in a file for later inspection.
3552
3553
3554 =item 5)
3555
3556 I am not root, how can I install a module in a personal directory?
3557
3558 First of all, you will want to use your own configuration, not the one
3559 that your root user installed. If you do not have permission to write
3560 in the cpan directory that root has configured, you will be asked if
3561 you want to create your own config. Answering "yes" will bring you into
3562 CPAN's configuration stage, using the system config for all defaults except
3563 things that have to do with CPAN's work directory, saving your choices to
3564 your MyConfig.pm file.
3565
3566 You can also manually initiate this process with the following command:
3567
3568     % perl -MCPAN -e 'mkmyconfig'
3569
3570 or by running
3571
3572     mkmyconfig
3573
3574 from the CPAN shell.
3575
3576 You will most probably also want to configure something like this:
3577
3578   o conf makepl_arg "LIB=~/myperl/lib \
3579                     INSTALLMAN1DIR=~/myperl/man/man1 \
3580                     INSTALLMAN3DIR=~/myperl/man/man3 \
3581                     INSTALLSCRIPT=~/myperl/bin \
3582                     INSTALLBIN=~/myperl/bin"
3583
3584 and then the equivalent command for Module::Build, which is
3585
3586   o conf mbuildpl_arg "--lib=~/myperl/lib \
3587                     --installman1dir=~/myperl/man/man1 \
3588                     --installman3dir=~/myperl/man/man3 \
3589                     --installscript=~/myperl/bin \
3590                     --installbin=~/myperl/bin"
3591
3592 You can make this setting permanent like all C<o conf> settings with
3593 C<o conf commit> or by setting C<auto_commit> beforehand.
3594
3595 You will have to add ~/myperl/man to the MANPATH environment variable
3596 and also tell your perl programs to look into ~/myperl/lib, e.g. by
3597 including
3598
3599   use lib "$ENV{HOME}/myperl/lib";
3600
3601 or setting the PERL5LIB environment variable.
3602
3603 While we're speaking about $ENV{HOME}, it might be worth mentioning,
3604 that for Windows and Darwin (and when use_file_homedir is turned on)
3605 we use the File::HomeDir module that provides an equivalent to the
3606 concept of the home directory on Unix.
3607
3608 Another thing you should bear in mind is that the UNINST parameter can
3609 be dangerous when you are installing into a private area because you
3610 might accidentally remove modules that other people depend on that are
3611 not using the private area.
3612
3613 =item 6)
3614
3615 How to get a package, unwrap it, and make a change before building it?
3616
3617 Have a look at the C<look> (!) command.
3618
3619 =item 7)
3620
3621 I installed a Bundle and had a couple of fails. When I
3622 retried, everything resolved nicely. Can this be fixed to work
3623 on first try?
3624
3625 The reason for this is that CPAN does not know the dependencies of all
3626 modules when it starts out. To decide about the additional items to
3627 install, it just uses data found in the META.yml file or the generated
3628 Makefile. An undetected missing piece breaks the process. But it may
3629 well be that your Bundle installs some prerequisite later than some
3630 depending item and thus your second try is able to resolve everything.
3631 Please note, CPAN.pm does not know the dependency tree in advance and
3632 cannot sort the queue of things to install in a topologically correct
3633 order. It resolves perfectly well B<if> all modules declare the
3634 prerequisites correctly with the PREREQ_PM attribute to MakeMaker or
3635 the C<requires> stanza of Module::Build. For bundles which fail and
3636 you need to install often, it is recommended to sort the Bundle
3637 definition file manually.
3638
3639 =item 8)
3640
3641 In our intranet, we have many modules for internal use. How
3642 can I integrate these modules with CPAN.pm but without uploading
3643 the modules to CPAN?
3644
3645 Have a look at the CPAN::Site module.
3646
3647 =item 9)
3648
3649 When I run CPAN's shell, I get an error message about things in my
3650 C</etc/inputrc> (or C<~/.inputrc>) file.
3651
3652 These are readline issues and can only be fixed by studying readline
3653 configuration on your architecture and adjusting the referenced file
3654 accordingly. Please make a backup of the C</etc/inputrc> or C<~/.inputrc>
3655 and edit them. Quite often harmless changes like uppercasing or
3656 lowercasing some arguments solves the problem.
3657
3658 =item 10)
3659
3660 Some authors have strange characters in their names.
3661
3662 Internally CPAN.pm uses the UTF-8 charset. If your terminal is
3663 expecting ISO-8859-1 charset, a converter can be activated by setting
3664 term_is_latin to a true value in your config file. One way of doing so
3665 would be
3666
3667     cpan> o conf term_is_latin 1
3668
3669 If other charset support is needed, please file a bugreport against
3670 CPAN.pm at rt.cpan.org and describe your needs. Maybe we can extend
3671 the support or maybe UTF-8 terminals become widely available.
3672
3673 Note: this config variable is deprecated and will be removed in a
3674 future version of CPAN.pm. It will be replaced with the conventions
3675 around the family of $LANG and $LC_* environment variables.
3676
3677 =item 11)
3678
3679 When an install fails for some reason and then I correct the error
3680 condition and retry, CPAN.pm refuses to install the module, saying
3681 C<Already tried without success>.
3682
3683 Use the force pragma like so
3684
3685   force install Foo::Bar
3686
3687 Or you can use
3688
3689   look Foo::Bar
3690
3691 and then C<make install> directly in the subshell.
3692
3693 =item 12)
3694
3695 How do I install a "DEVELOPER RELEASE" of a module?
3696
3697 By default, CPAN will install the latest non-developer release of a
3698 module. If you want to install a dev release, you have to specify the
3699 partial path starting with the author id to the tarball you wish to
3700 install, like so:
3701
3702     cpan> install KWILLIAMS/Module-Build-0.27_07.tar.gz
3703
3704 Note that you can use the C<ls> command to get this path listed.
3705
3706 =item 13)
3707
3708 How do I install a module and all its dependencies from the commandline,
3709 without being prompted for anything, despite my CPAN configuration
3710 (or lack thereof)?
3711
3712 CPAN uses ExtUtils::MakeMaker's prompt() function to ask its questions, so
3713 if you set the PERL_MM_USE_DEFAULT environment variable, you shouldn't be
3714 asked any questions at all (assuming the modules you are installing are
3715 nice about obeying that variable as well):
3716
3717     % PERL_MM_USE_DEFAULT=1 perl -MCPAN -e 'install My::Module'
3718
3719 =item 14)
3720
3721 How do I create a Module::Build based Build.PL derived from an
3722 ExtUtils::MakeMaker focused Makefile.PL?
3723
3724 http://search.cpan.org/dist/Module-Build-Convert/
3725
3726 =item 15)
3727
3728 I'm frequently irritated with the CPAN shell's inability to help me
3729 select a good mirror.
3730
3731 CPAN can now help you select a "good" mirror, based on which ones have the
3732 lowest 'ping' round-trip times.  From the shell, use the command 'o conf init
3733 urllist' and allow CPAN to automatically select mirrors for you.
3734
3735 Beyond that help, the urllist config parameter is yours. You can add and remove
3736 sites at will. You should find out which sites have the best uptodateness,
3737 bandwidth, reliability, etc. and are topologically close to you. Some people
3738 prefer fast downloads, others uptodateness, others reliability.  You decide
3739 which to try in which order.
3740
3741 Henk P. Penning maintains a site that collects data about CPAN sites:
3742
3743   http://www.cs.uu.nl/people/henkp/mirmon/cpan.html
3744
3745 Also, feel free to play with experimental features. Run
3746
3747   o conf init randomize_urllist ftpstats_period ftpstats_size
3748
3749 and choose your favorite parameters. After a few downloads running the
3750 C<hosts> command will probably assist you in choosing the best mirror
3751 sites.
3752
3753 =item 16)
3754
3755 Why do I get asked the same questions every time I start the shell?
3756
3757 You can make your configuration changes permanent by calling the
3758 command C<o conf commit>. Alternatively set the C<auto_commit>
3759 variable to true by running C<o conf init auto_commit> and answering
3760 the following question with yes.
3761
3762 =item 17)
3763
3764 Older versions of CPAN.pm had the original root directory of all
3765 tarballs in the build directory. Now there are always random
3766 characters appended to these directory names. Why was this done?
3767
3768 The random characters are provided by File::Temp and ensure that each
3769 module's individual build directory is unique. This makes running
3770 CPAN.pm in concurrent processes simultaneously safe.
3771
3772 =item 18)
3773
3774 Speaking of the build directory. Do I have to clean it up myself?
3775
3776 You have the choice to set the config variable C<scan_cache> to
3777 C<never>. Then you must clean it up yourself. The other possible
3778 value, C<atstart> only cleans up the build directory when you start
3779 the CPAN shell. If you never start up the CPAN shell, you probably
3780 also have to clean up the build directory yourself.
3781
3782 =back
3783
3784 =head1 COMPATIBILITY
3785
3786 =head2 OLD PERL VERSIONS
3787
3788 CPAN.pm is regularly tested to run under 5.004, 5.005, and assorted
3789 newer versions. It is getting more and more difficult to get the
3790 minimal prerequisites working on older perls. It is close to
3791 impossible to get the whole Bundle::CPAN working there. If you're in
3792 the position to have only these old versions, be advised that CPAN is
3793 designed to work fine without the Bundle::CPAN installed.
3794
3795 To get things going, note that GBARR/Scalar-List-Utils-1.18.tar.gz is
3796 compatible with ancient perls and that File::Temp is listed as a
3797 prerequisite but CPAN has reasonable workarounds if it is missing.
3798
3799 =head2 CPANPLUS
3800
3801 This module and its competitor, the CPANPLUS module, are both much
3802 cooler than the other. CPAN.pm is older. CPANPLUS was designed to be
3803 more modular, but it was never intended to be compatible with CPAN.pm.
3804
3805 =head2 CPANMINUS
3806
3807 In the year 2010 App::cpanminus was launched as a new approach to a
3808 cpan shell with a considerably smaller footprint. Very cool stuff.
3809
3810 =head1 SECURITY ADVICE
3811
3812 This software enables you to upgrade software on your computer and so
3813 is inherently dangerous because the newly installed software may
3814 contain bugs and may alter the way your computer works or even make it
3815 unusable. Please consider backing up your data before every upgrade.
3816
3817 =head1 BUGS
3818
3819 Please report bugs via L<http://rt.cpan.org/>
3820
3821 Before submitting a bug, please make sure that the traditional method
3822 of building a Perl module package from a shell by following the
3823 installation instructions of that package still works in your
3824 environment.
3825
3826 =head1 AUTHOR
3827
3828 Andreas Koenig C<< <andk@cpan.org> >>
3829
3830 =head1 LICENSE
3831
3832 This program is free software; you can redistribute it and/or
3833 modify it under the same terms as Perl itself.
3834
3835 See L<http://www.perl.com/perl/misc/Artistic.html>
3836
3837 =head1 TRANSLATIONS
3838
3839 Kawai,Takanori provides a Japanese translation of a very old version
3840 of this manpage at
3841 L<http://homepage3.nifty.com/hippo2000/perltips/CPAN.htm>
3842
3843 =head1 SEE ALSO
3844
3845 Many people enter the CPAN shell by running the L<cpan> utility
3846 program which is installed in the same directory as perl itself. So if
3847 you have this directory in your PATH variable (or some equivalent in
3848 your operating system) then typing C<cpan> in a console window will
3849 work for you as well. Above that the utility provides several
3850 commandline shortcuts.
3851
3852 =cut