Update CPAN.pm to 1.93_03
[p5sagit/p5-mst-13.2.git] / lib / CPAN / HandleConfig.pm
1 package CPAN::HandleConfig;
2 use strict;
3 use vars qw(%can %keys $loading $VERSION);
4
5 $VERSION = "5.5";
6
7 %can = (
8         commit   => "Commit changes to disk",
9         defaults => "Reload defaults from disk",
10         help     => "Short help about 'o conf' usage",
11         init     => "Interactive setting of all options",
12 );
13
14 # Q: where is the "How do I add a new config option" HOWTO?
15 # A1: svn diff -r 757:758 # where dagolden added test_report
16 # A2: svn diff -r 985:986 # where andk added yaml_module
17 # A3: 1. add new config option to %keys below
18 #     2. add a Pod description in CPAN::FirstTime; it should include a
19 #        prompt line; see others for examples
20 #     3. add a "matcher" section in CPAN::FirstTime::init that includes
21 #        a prompt function; see others for examples
22 #     4. add config option to documentation section in CPAN.pm
23
24 %keys = map { $_ => undef }
25     (
26      "applypatch",
27      "auto_commit",
28      "build_cache",
29      "build_dir",
30      "build_dir_reuse",
31      "build_requires_install_policy",
32      "bzip2",
33      "cache_metadata",
34      "check_sigs",
35      "colorize_debug",
36      "colorize_output",
37      "colorize_print",
38      "colorize_warn",
39      "commandnumber_in_prompt",
40      "commands_quote",
41      "connect_to_internet_ok",
42      "cpan_home",
43      "curl",
44      "dontload_hash", # deprecated after 1.83_68 (rev. 581)
45      "dontload_list",
46      "ftp",
47      "ftp_passive",
48      "ftp_proxy",
49      "ftpstats_size",
50      "ftpstats_period",
51      "getcwd",
52      "gpg",
53      "gzip",
54      "halt_on_failure",
55      "histfile",
56      "histsize",
57      "http_proxy",
58      "inactivity_timeout",
59      "index_expire",
60      "inhibit_startup_message",
61      "keep_source_where",
62      "load_module_verbosity",
63      "lynx",
64      "make",
65      "make_arg",
66      "make_install_arg",
67      "make_install_make_command",
68      "makepl_arg",
69      "mbuild_arg",
70      "mbuild_install_arg",
71      "mbuild_install_build_command",
72      "mbuildpl_arg",
73      "ncftp",
74      "ncftpget",
75      "no_proxy",
76      "pager",
77      "password",
78      "patch",
79      "perl5lib_verbosity",
80      "prefer_installer",
81      "prefs_dir",
82      "prerequisites_policy",
83      "proxy_pass",
84      "proxy_user",
85      "randomize_urllist",
86      "scan_cache",
87      "shell",
88      "show_unparsable_versions",
89      "show_upload_date",
90      "show_zero_versions",
91      "tar",
92      "tar_verbosity",
93      "term_is_latin",
94      "term_ornaments",
95      "test_report",
96      "trust_test_report_history",
97      "unzip",
98      "urllist",
99      "use_sqlite",
100      "username",
101      "wait_list",
102      "wget",
103      "yaml_load_code",
104      "yaml_module",
105     );
106
107 my %prefssupport = map { $_ => 1 }
108     (
109      "build_requires_install_policy",
110      "check_sigs",
111      "make",
112      "make_install_make_command",
113      "prefer_installer",
114      "test_report",
115     );
116
117 # returns true on successful action
118 sub edit {
119     my($self,@args) = @_;
120     return unless @args;
121     CPAN->debug("self[$self]args[".join(" | ",@args)."]");
122     my($o,$str,$func,$args,$key_exists);
123     $o = shift @args;
124     if($can{$o}) {
125         $self->$o(args => \@args); # o conf init => sub init => sub load
126         return 1;
127     } else {
128         CPAN->debug("o[$o]") if $CPAN::DEBUG;
129         unless (exists $keys{$o}) {
130             $CPAN::Frontend->mywarn("Warning: unknown configuration variable '$o'\n");
131         }
132         my $changed;
133
134
135         # one day I used randomize_urllist for a boolean, so we must
136         # list them explicitly --ak
137         if (0) {
138         } elsif ($o =~ /^(wait_list|urllist|dontload_list)$/) {
139
140             #
141             # ARRAYS
142             #
143
144             $func = shift @args;
145             $func ||= "";
146             CPAN->debug("func[$func]args[@args]") if $CPAN::DEBUG;
147             # Let's avoid eval, it's easier to comprehend without.
148             if ($func eq "push") {
149                 push @{$CPAN::Config->{$o}}, @args;
150                 $changed = 1;
151             } elsif ($func eq "pop") {
152                 pop @{$CPAN::Config->{$o}};
153                 $changed = 1;
154             } elsif ($func eq "shift") {
155                 shift @{$CPAN::Config->{$o}};
156                 $changed = 1;
157             } elsif ($func eq "unshift") {
158                 unshift @{$CPAN::Config->{$o}}, @args;
159                 $changed = 1;
160             } elsif ($func eq "splice") {
161                 my $offset = shift @args || 0;
162                 my $length = shift @args || 0;
163                 splice @{$CPAN::Config->{$o}}, $offset, $length, @args; # may warn
164                 $changed = 1;
165             } elsif ($func) {
166                 $CPAN::Config->{$o} = [$func, @args];
167                 $changed = 1;
168             } else {
169                 $self->prettyprint($o);
170             }
171             if ($changed) {
172                 if ($o eq "urllist") {
173                     # reset the cached values
174                     undef $CPAN::FTP::Thesite;
175                     undef $CPAN::FTP::Themethod;
176                     $CPAN::Index::LAST_TIME = 0;
177                 } elsif ($o eq "dontload_list") {
178                     # empty it, it will be built up again
179                     $CPAN::META->{dontload_hash} = {};
180                 }
181             }
182         } elsif ($o =~ /_hash$/) {
183
184             #
185             # HASHES
186             #
187
188             if (@args==1 && $args[0] eq "") {
189                 @args = ();
190             } elsif (@args % 2) {
191                 push @args, "";
192             }
193             $CPAN::Config->{$o} = { @args };
194             $changed = 1;
195         } else {
196
197             #
198             # SCALARS
199             #
200
201             if (defined $args[0]) {
202                 $CPAN::CONFIG_DIRTY = 1;
203                 $CPAN::Config->{$o} = $args[0];
204                 $changed = 1;
205             }
206             $self->prettyprint($o)
207                 if exists $keys{$o} or defined $CPAN::Config->{$o};
208         }
209         if ($changed) {
210             if ($CPAN::Config->{auto_commit}) {
211                 $self->commit;
212             } else {
213                 $CPAN::CONFIG_DIRTY = 1;
214                 $CPAN::Frontend->myprint("Please use 'o conf commit' to ".
215                                          "make the config permanent!\n\n");
216             }
217         }
218     }
219 }
220
221 sub prettyprint {
222     my($self,$k) = @_;
223     my $v = $CPAN::Config->{$k};
224     if (ref $v) {
225         my(@report);
226         if (ref $v eq "ARRAY") {
227             @report = map {"\t$_ \[$v->[$_]]\n"} 0..$#$v;
228         } else {
229             @report = map
230                 {
231                     sprintf "\t%-18s => %s\n",
232                                "[$_]",
233                                         defined $v->{$_} ? "[$v->{$_}]" : "undef"
234                 } keys %$v;
235         }
236         $CPAN::Frontend->myprint(
237                                  join(
238                                       "",
239                                       sprintf(
240                                               "    %-18s\n",
241                                               $k
242                                              ),
243                                       @report
244                                      )
245                                 );
246     } elsif (defined $v) {
247         $CPAN::Frontend->myprint(sprintf "    %-18s [%s]\n", $k, $v);
248     } else {
249         $CPAN::Frontend->myprint(sprintf "    %-18s undef\n", $k);
250     }
251 }
252
253 sub commit {
254     my($self,@args) = @_;
255     CPAN->debug("args[@args]") if $CPAN::DEBUG;
256     if ($CPAN::RUN_DEGRADED) {
257                              $CPAN::Frontend->mydie(
258                                                     "'o conf commit' disabled in ".
259                                                     "degraded mode. Maybe try\n".
260                                                     " !undef \$CPAN::RUN_DEGRADED\n"
261                                                    );
262     }
263     my $configpm;
264     if (@args) {
265       if ($args[0] eq "args") {
266         # we have not signed that contract
267       } else {
268         $configpm = $args[0];
269       }
270     }
271     unless (defined $configpm) {
272         $configpm ||= $INC{"CPAN/MyConfig.pm"};
273         $configpm ||= $INC{"CPAN/Config.pm"};
274         $configpm || Carp::confess(q{
275 CPAN::Config::commit called without an argument.
276 Please specify a filename where to save the configuration or try
277 "o conf init" to have an interactive course through configing.
278 });
279     }
280     my($mode);
281     if (-f $configpm) {
282         $mode = (stat $configpm)[2];
283         if ($mode && ! -w _) {
284             Carp::confess("$configpm is not writable");
285         }
286     }
287
288     my $msg;
289     my $home = home();
290     $msg = <<EOF unless $configpm =~ /MyConfig/;
291
292 # This is CPAN.pm's systemwide configuration file. This file provides
293 # defaults for users, and the values can be changed in a per-user
294 # configuration file. The user-config file is being looked for as
295 # $home/.cpan/CPAN/MyConfig.pm.
296
297 EOF
298     $msg ||= "\n";
299     my($fh) = FileHandle->new;
300     rename $configpm, "$configpm~" if -f $configpm;
301     open $fh, ">$configpm" or
302         $CPAN::Frontend->mydie("Couldn't open >$configpm: $!");
303     $fh->print(qq[$msg\$CPAN::Config = \{\n]);
304     foreach (sort keys %$CPAN::Config) {
305         unless (exists $keys{$_}) {
306             # do not drop them: forward compatibility!
307             $CPAN::Frontend->mywarn("Unknown config variable '$_'\n");
308             next;
309         }
310         $fh->print(
311             "  '$_' => ",
312             $self->neatvalue($CPAN::Config->{$_}),
313             ",\n"
314         );
315     }
316
317     $fh->print("};\n1;\n__END__\n");
318     close $fh;
319
320     #$mode = 0444 | ( $mode & 0111 ? 0111 : 0 );
321     #chmod $mode, $configpm;
322 ###why was that so?    $self->defaults;
323     $CPAN::Frontend->myprint("commit: wrote '$configpm'\n");
324     $CPAN::CONFIG_DIRTY = 0;
325     1;
326 }
327
328 # stolen from MakeMaker; not taking the original because it is buggy;
329 # bugreport will have to say: keys of hashes remain unquoted and can
330 # produce syntax errors
331 sub neatvalue {
332     my($self, $v) = @_;
333     return "undef" unless defined $v;
334     my($t) = ref $v;
335     unless ($t) {
336         $v =~ s/\\/\\\\/g;
337         return "q[$v]";
338     }
339     if ($t eq 'ARRAY') {
340         my(@m, @neat);
341         push @m, "[";
342         foreach my $elem (@$v) {
343             push @neat, "q[$elem]";
344         }
345         push @m, join ", ", @neat;
346         push @m, "]";
347         return join "", @m;
348     }
349     return "$v" unless $t eq 'HASH';
350     my(@m, $key, $val);
351     while (($key,$val) = each %$v) {
352         last unless defined $key; # cautious programming in case (undef,undef) is true
353         push(@m,"q[$key]=>".$self->neatvalue($val)) ;
354     }
355     return "{ ".join(', ',@m)." }";
356 }
357
358 sub defaults {
359     my($self) = @_;
360     if ($CPAN::RUN_DEGRADED) {
361                              $CPAN::Frontend->mydie(
362                                                     "'o conf defaults' disabled in ".
363                                                     "degraded mode. Maybe try\n".
364                                                     " !undef \$CPAN::RUN_DEGRADED\n"
365                                                    );
366     }
367     my $done;
368     for my $config (qw(CPAN/MyConfig.pm CPAN/Config.pm)) {
369         if ($INC{$config}) {
370             CPAN->debug("INC{'$config'}[$INC{$config}]") if $CPAN::DEBUG;
371             CPAN::Shell->_reload_this($config,{reloforce => 1});
372             $CPAN::Frontend->myprint("'$INC{$config}' reread\n");
373             last;
374         }
375     }
376     $CPAN::CONFIG_DIRTY = 0;
377     1;
378 }
379
380 =head2 C<< CLASS->safe_quote ITEM >>
381
382 Quotes an item to become safe against spaces
383 in shell interpolation. An item is enclosed
384 in double quotes if:
385
386   - the item contains spaces in the middle
387   - the item does not start with a quote
388
389 This happens to avoid shell interpolation
390 problems when whitespace is present in
391 directory names.
392
393 This method uses C<commands_quote> to determine
394 the correct quote. If C<commands_quote> is
395 a space, no quoting will take place.
396
397
398 if it starts and ends with the same quote character: leave it as it is
399
400 if it contains no whitespace: leave it as it is
401
402 if it contains whitespace, then
403
404 if it contains quotes: better leave it as it is
405
406 else: quote it with the correct quote type for the box we're on
407
408 =cut
409
410 {
411     # Instead of patching the guess, set commands_quote
412     # to the right value
413     my ($quotes,$use_quote)
414         = $^O eq 'MSWin32'
415             ? ('"', '"')
416                 : (q{"'}, "'")
417                     ;
418
419     sub safe_quote {
420         my ($self, $command) = @_;
421         # Set up quote/default quote
422         my $quote = $CPAN::Config->{commands_quote} || $quotes;
423
424         if ($quote ne ' '
425             and defined($command )
426             and $command =~ /\s/
427             and $command !~ /[$quote]/) {
428             return qq<$use_quote$command$use_quote>
429         }
430         return $command;
431     }
432 }
433
434 sub init {
435     my($self,@args) = @_;
436     CPAN->debug("self[$self]args[".join(",",@args)."]");
437     $self->load(doit => 1, @args);
438     1;
439 }
440
441 # This is a piece of repeated code that is abstracted here for
442 # maintainability.  RMB
443 #
444 sub _configpmtest {
445     my($configpmdir, $configpmtest) = @_;
446     if (-w $configpmtest) {
447         return $configpmtest;
448     } elsif (-w $configpmdir) {
449         #_#_# following code dumped core on me with 5.003_11, a.k.
450         my $configpm_bak = "$configpmtest.bak";
451         unlink $configpm_bak if -f $configpm_bak;
452         if( -f $configpmtest ) {
453             if( rename $configpmtest, $configpm_bak ) {
454                 $CPAN::Frontend->mywarn(<<END);
455 Old configuration file $configpmtest
456     moved to $configpm_bak
457 END
458             }
459         }
460         my $fh = FileHandle->new;
461         if ($fh->open(">$configpmtest")) {
462             $fh->print("1;\n");
463             return $configpmtest;
464         } else {
465             # Should never happen
466             Carp::confess("Cannot open >$configpmtest");
467         }
468     } else { return }
469 }
470
471 sub require_myconfig_or_config () {
472     return if $INC{"CPAN/MyConfig.pm"};
473     local @INC = @INC;
474     my $home = home();
475     unshift @INC, File::Spec->catdir($home,'.cpan');
476     eval { require CPAN::MyConfig };
477     my $err_myconfig = $@;
478     if ($err_myconfig and $err_myconfig !~ m#locate CPAN/MyConfig\.pm#) {
479         die "Error while requiring CPAN::MyConfig:\n$err_myconfig";
480     }
481     unless ($INC{"CPAN/MyConfig.pm"}) { # this guy has settled his needs already
482       eval {require CPAN::Config;}; # not everybody has one
483       my $err_config = $@;
484       if ($err_config and $err_config !~ m#locate CPAN/Config\.pm#) {
485           die "Error while requiring CPAN::Config:\n$err_config";
486       }
487     }
488 }
489
490 sub home () {
491     my $home;
492     # Suppress load messages until we load the config and know whether
493     # load messages are desired.  Otherwise, it's unexpected and odd 
494     # why one load message pops up even when verbosity is turned off.
495     # This means File::HomeDir load messages are never seen, but I
496     # think that's probably OK -- DAGOLDEN
497     
498     # 5.6.2 seemed to segfault localizing a value in a hashref 
499     # so do it manually instead
500     my $old_v = $CPAN::Config->{load_module_verbosity};
501     $CPAN::Config->{load_module_verbosity} = q[none];
502     if ($CPAN::META->has_usable("File::HomeDir")) {
503         $home = File::HomeDir->can('my_dot_config')
504             ? File::HomeDir->my_dot_config
505                 : File::HomeDir->my_data;
506         unless (defined $home) {
507             $home = File::HomeDir->my_home
508         }
509     }
510     unless (defined $home) {
511         $home = $ENV{HOME};
512     }
513     $CPAN::Config->{load_module_verbosity} = $old_v;
514     $home;
515 }
516
517 sub load {
518     my($self, %args) = @_;
519     $CPAN::Be_Silent++ if $args{be_silent};
520     my $doit;
521     $doit = delete $args{doit};
522
523     use Carp;
524     require_myconfig_or_config;
525     my @miss = $self->missing_config_data;
526     return unless $doit || @miss;
527     return if $loading;
528     $loading++;
529
530     require CPAN::FirstTime;
531     my($configpm,$fh,$redo);
532     $redo ||= "";
533     if (defined $INC{"CPAN/Config.pm"} && -w $INC{"CPAN/Config.pm"}) {
534         $configpm = $INC{"CPAN/Config.pm"};
535         $redo++;
536     } elsif (defined $INC{"CPAN/MyConfig.pm"} && -w $INC{"CPAN/MyConfig.pm"}) {
537         $configpm = $INC{"CPAN/MyConfig.pm"};
538         $redo++;
539     } else {
540         my($path_to_cpan) = File::Basename::dirname($INC{"CPAN.pm"});
541         my($configpmdir) = File::Spec->catdir($path_to_cpan,"CPAN");
542         my($configpmtest) = File::Spec->catfile($configpmdir,"Config.pm");
543         my $inc_key;
544         if (-d $configpmdir or File::Path::mkpath($configpmdir)) {
545             $configpm = _configpmtest($configpmdir,$configpmtest);
546             $inc_key = "CPAN/Config.pm";
547         }
548         unless ($configpm) {
549             $configpmdir = File::Spec->catdir(home,".cpan","CPAN");
550             File::Path::mkpath($configpmdir);
551             $configpmtest = File::Spec->catfile($configpmdir,"MyConfig.pm");
552             $configpm = _configpmtest($configpmdir,$configpmtest);
553             $inc_key = "CPAN/MyConfig.pm";
554         }
555         if ($configpm) {
556           $INC{$inc_key} = $configpm;
557         } else {
558           my $text = qq{WARNING: CPAN.pm is unable to } .
559               qq{create a configuration file.};
560           output($text, 'confess');
561         }
562
563     }
564     local($") = ", ";
565     if ($redo && !$doit) {
566         $CPAN::Frontend->myprint(<<END);
567 Sorry, we have to rerun the configuration dialog for CPAN.pm due to
568 some missing parameters...
569
570 END
571         $args{args} = \@miss;
572     }
573     CPAN::FirstTime::init($configpm, %args);
574     $loading--;
575     return;
576 }
577
578
579 # returns mandatory but missing entries in the Config
580 sub missing_config_data {
581     my(@miss);
582     for (
583          "auto_commit",
584          "build_cache",
585          "build_dir",
586          "cache_metadata",
587          "cpan_home",
588          "ftp_proxy",
589          #"gzip",
590          "http_proxy",
591          "index_expire",
592          #"inhibit_startup_message",
593          "keep_source_where",
594          #"make",
595          "make_arg",
596          "make_install_arg",
597          "makepl_arg",
598          "mbuild_arg",
599          "mbuild_install_arg",
600          ($^O eq "MSWin32" ? "" : "mbuild_install_build_command"),
601          "mbuildpl_arg",
602          "no_proxy",
603          #"pager",
604          "prerequisites_policy",
605          "scan_cache",
606          #"tar",
607          #"unzip",
608          "urllist",
609         ) {
610         next unless exists $keys{$_};
611         push @miss, $_ unless defined $CPAN::Config->{$_};
612     }
613     return @miss;
614 }
615
616 sub help {
617     $CPAN::Frontend->myprint(q[
618 Known options:
619   commit    commit session changes to disk
620   defaults  reload default config values from disk
621   help      this help
622   init      enter a dialog to set all or a set of parameters
623
624 Edit key values as in the following (the "o" is a literal letter o):
625   o conf build_cache 15
626   o conf build_dir "/foo/bar"
627   o conf urllist shift
628   o conf urllist unshift ftp://ftp.foo.bar/
629   o conf inhibit_startup_message 1
630
631 ]);
632     undef; #don't reprint CPAN::Config
633 }
634
635 sub cpl {
636     my($word,$line,$pos) = @_;
637     $word ||= "";
638     CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG;
639     my(@words) = split " ", substr($line,0,$pos+1);
640     if (
641         defined($words[2])
642         and
643         $words[2] =~ /list$/
644         and
645         (
646         @words == 3
647         ||
648         @words == 4 && length($word)
649         )
650        ) {
651         return grep /^\Q$word\E/, qw(splice shift unshift pop push);
652     } elsif (defined($words[2])
653              and
654              $words[2] eq "init"
655              and
656             (
657              @words == 3
658              ||
659              @words >= 4 && length($word)
660             )) {
661         return sort grep /^\Q$word\E/, keys %keys;
662     } elsif (@words >= 4) {
663         return ();
664     }
665     my %seen;
666     my(@o_conf) =  sort grep { !$seen{$_}++ }
667         keys %can,
668             keys %$CPAN::Config,
669                 keys %keys;
670     return grep /^\Q$word\E/, @o_conf;
671 }
672
673 sub prefs_lookup {
674     my($self,$distro,$what) = @_;
675
676     if ($prefssupport{$what}) {
677         return $CPAN::Config->{$what} unless
678             $distro
679                 and $distro->prefs
680                     and $distro->prefs->{cpanconfig}
681                         and defined $distro->prefs->{cpanconfig}{$what};
682         return $distro->prefs->{cpanconfig}{$what};
683     } else {
684         $CPAN::Frontend->mywarn("Warning: $what not yet officially ".
685                                 "supported for distroprefs, doing a normal lookup");
686         return $CPAN::Config->{$what};
687     }
688 }
689
690
691 {
692     package
693         CPAN::Config; ####::###### #hide from indexer
694     # note: J. Nick Koston wrote me that they are using
695     # CPAN::Config->commit although undocumented. I suggested
696     # CPAN::Shell->o("conf","commit") even when ugly it is at least
697     # documented
698
699     # that's why I added the CPAN::Config class with autoload and
700     # deprecated warning
701
702     use strict;
703     use vars qw($AUTOLOAD $VERSION);
704     $VERSION = "5.5";
705
706     # formerly CPAN::HandleConfig was known as CPAN::Config
707     sub AUTOLOAD {
708         my $class = shift; # e.g. in dh-make-perl: CPAN::Config
709         my($l) = $AUTOLOAD;
710         $CPAN::Frontend->mywarn("Dispatching deprecated method '$l' to CPAN::HandleConfig\n");
711         $l =~ s/.*:://;
712         CPAN::HandleConfig->$l(@_);
713     }
714 }
715
716 1;
717
718 __END__
719
720 =head1 LICENSE
721
722 This program is free software; you can redistribute it and/or
723 modify it under the same terms as Perl itself.
724
725 =cut
726
727 # Local Variables:
728 # mode: cperl
729 # cperl-indent-level: 4
730 # End: