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