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