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