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