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