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