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