[PAUSE] CPAN Upload: A/AN/ANDK/CPAN-1.83_64.tar.gz
[p5sagit/p5-mst-13.2.git] / lib / CPAN / HandleConfig.pm
1 package CPAN::HandleConfig;
2 use strict;
3 use vars qw(%can %keys $dot_cpan $VERSION);
4
5 $VERSION = sprintf "%.2f", substr(q$Rev: 488 $,4)/100;
6
7 %can = (
8   'commit' => "Commit changes to disk",
9   'defaults' => "Reload defaults from disk",
10   'init'   => "Interactive setting of all options",
11 );
12
13 %keys = map { $_ => undef } qw(
14     build_cache build_dir bzip2
15     cache_metadata commandnumber_in_prompt cpan_home curl
16     dontload_hash
17     ftp ftp_passive ftp_proxy
18     getcwd gpg gzip
19     histfile histsize http_proxy
20     inactivity_timeout index_expire inhibit_startup_message
21     keep_source_where
22     lynx
23     make make_arg make_install_arg make_install_make_command makepl_arg
24     mbuild_arg mbuild_install_arg mbuild_install_build_command mbuildpl_arg
25     ncftp ncftpget no_proxy pager
26     prefer_installer prerequisites_policy
27     scan_cache shell show_upload_date
28     tar term_is_latin
29     unzip urllist
30     wait_list wget
31 );
32 if ($^O eq "MSWin32") {
33     for my $k (qw(
34                   mbuild_install_build_command
35                   make_install_make_command
36                  )) {
37         delete $keys{$k};
38         if (exists $CPAN::Config->{$k}) {
39             $CPAN::Frontend->mywarn("deleting previously set config variable ".
40                                     "'$k' => '$CPAN::Config->{$k}'");
41             delete $CPAN::Config->{$k};
42         }
43     }
44 }
45
46 # returns true on successful action
47 sub edit {
48     my($self,@args) = @_;
49     return unless @args;
50     CPAN->debug("self[$self]args[".join(" | ",@args)."]");
51     my($o,$str,$func,$args,$key_exists);
52     $o = shift @args;
53     $DB::single = 1;
54     if($can{$o}) {
55         $self->$o(args => \@args);
56         return 1;
57     } else {
58         CPAN->debug("o[$o]") if $CPAN::DEBUG;
59         unless (exists $keys{$o}) {
60             $CPAN::Frontend->mywarn("Warning: unknown configuration variable '$o'\n");
61         }
62         if ($o =~ /list$/) {
63             $func = shift @args;
64             $func ||= "";
65             CPAN->debug("func[$func]") if $CPAN::DEBUG;
66             my $changed;
67             # Let's avoid eval, it's easier to comprehend without.
68             if ($func eq "push") {
69                 push @{$CPAN::Config->{$o}}, @args;
70                 $changed = 1;
71             } elsif ($func eq "pop") {
72                 pop @{$CPAN::Config->{$o}};
73                 $changed = 1;
74             } elsif ($func eq "shift") {
75                 shift @{$CPAN::Config->{$o}};
76                 $changed = 1;
77             } elsif ($func eq "unshift") {
78                 unshift @{$CPAN::Config->{$o}}, @args;
79                 $changed = 1;
80             } elsif ($func eq "splice") {
81                 splice @{$CPAN::Config->{$o}}, @args;
82                 $changed = 1;
83             } elsif (@args) {
84                 $CPAN::Config->{$o} = [@args];
85                 $changed = 1;
86             } else {
87                 $self->prettyprint($o);
88             }
89             if ($o eq "urllist" && $changed) {
90                 # reset the cached values
91                 undef $CPAN::FTP::Thesite;
92                 undef $CPAN::FTP::Themethod;
93             }
94             return $changed;
95         } elsif ($o =~ /_hash$/) {
96             @args = () if @args==1 && $args[0] eq "";
97             push @args, "" if @args % 2;
98             $CPAN::Config->{$o} = { @args };
99         } else {
100             $CPAN::Config->{$o} = $args[0] if defined $args[0];
101             $self->prettyprint($o);
102         }
103     }
104 }
105
106 sub prettyprint {
107   my($self,$k) = @_;
108   my $v = $CPAN::Config->{$k};
109   if (ref $v) {
110     my(@report);
111     if (ref $v eq "ARRAY") {
112       @report = map {"\t[$_]\n"} @$v;
113     } else {
114       @report = map { sprintf("\t%-18s => %s\n",
115                               map { "[$_]" } $_,
116                               defined $v->{$_} ? $v->{$_} : "UNDEFINED"
117                              )} keys %$v;
118     }
119     $CPAN::Frontend->myprint(
120                              join(
121                                   "",
122                                   sprintf(
123                                           "    %-18s\n",
124                                           $k
125                                          ),
126                                   @report
127                                  )
128                             );
129   } elsif (defined $v) {
130     $CPAN::Frontend->myprint(sprintf "    %-18s [%s]\n", $k, $v);
131   } else {
132     $CPAN::Frontend->myprint(sprintf "    %-18s [%s]\n", $k, "UNDEFINED");
133   }
134 }
135
136 sub commit {
137     my($self,@args) = @_;
138     my $configpm;
139     if (@args) {
140       if ($args[0] eq "args") {
141         # we have not signed that contract
142       } else {
143         $configpm = $args[0];
144       }
145     }
146     unless (defined $configpm){
147         $configpm ||= $INC{"CPAN/MyConfig.pm"};
148         $configpm ||= $INC{"CPAN/Config.pm"};
149         $configpm || Carp::confess(q{
150 CPAN::Config::commit called without an argument.
151 Please specify a filename where to save the configuration or try
152 "o conf init" to have an interactive course through configing.
153 });
154     }
155     my($mode);
156     if (-f $configpm) {
157         $mode = (stat $configpm)[2];
158         if ($mode && ! -w _) {
159             Carp::confess("$configpm is not writable");
160         }
161     }
162
163     my $msg;
164     $msg = <<EOF unless $configpm =~ /MyConfig/;
165
166 # This is CPAN.pm's systemwide configuration file. This file provides
167 # defaults for users, and the values can be changed in a per-user
168 # configuration file. The user-config file is being looked for as
169 # ~/.cpan/CPAN/MyConfig.pm.
170
171 EOF
172     $msg ||= "\n";
173     my($fh) = FileHandle->new;
174     rename $configpm, "$configpm~" if -f $configpm;
175     open $fh, ">$configpm" or
176         $CPAN::Frontend->mydie("Couldn't open >$configpm: $!");
177     $fh->print(qq[$msg\$CPAN::Config = \{\n]);
178     foreach (sort keys %$CPAN::Config) {
179         unless (exists $keys{$_}) {
180             $CPAN::Frontend->mywarn("Dropping unknown config variable '$_'\n");
181             delete $CPAN::Config->{$_};
182             next;
183         }
184         $fh->print(
185                    "  '$_' => ",
186                    $self->neatvalue($CPAN::Config->{$_}),
187                    ",\n"
188                   );
189     }
190
191     $fh->print("};\n1;\n__END__\n");
192     close $fh;
193
194     #$mode = 0444 | ( $mode & 0111 ? 0111 : 0 );
195     #chmod $mode, $configpm;
196 ###why was that so?    $self->defaults;
197     $CPAN::Frontend->myprint("commit: wrote '$configpm'\n");
198     1;
199 }
200
201 # stolen from MakeMaker; not taking the original because it is buggy;
202 # bugreport will have to say: keys of hashes remain unquoted and can
203 # produce syntax errors
204 sub neatvalue {
205     my($self, $v) = @_;
206     return "undef" unless defined $v;
207     my($t) = ref $v;
208     return "q[$v]" unless $t;
209     if ($t eq 'ARRAY') {
210         my(@m, @neat);
211         push @m, "[";
212         foreach my $elem (@$v) {
213             push @neat, "q[$elem]";
214         }
215         push @m, join ", ", @neat;
216         push @m, "]";
217         return join "", @m;
218     }
219     return "$v" unless $t eq 'HASH';
220     my(@m, $key, $val);
221     while (($key,$val) = each %$v){
222         last unless defined $key; # cautious programming in case (undef,undef) is true
223         push(@m,"q[$key]=>".$self->neatvalue($val)) ;
224     }
225     return "{ ".join(', ',@m)." }";
226 }
227
228 sub defaults {
229     my($self) = @_;
230     my $done;
231     for my $config (qw(CPAN/MyConfig.pm CPAN/Config.pm)) {
232       CPAN::Shell->reload_this($config) and $done++;
233       last if $done;
234     }
235     1;
236 }
237
238 sub init {
239     my($self,@args) = @_;
240     undef $CPAN::Config->{'inhibit_startup_message'}; # lazy trick to
241                                                       # have the least
242                                                       # important
243                                                       # variable
244                                                       # undefined
245     $self->load(@args);
246     1;
247 }
248
249 # This is a piece of repeated code that is abstracted here for
250 # maintainability.  RMB
251 #
252 sub _configpmtest {
253     my($configpmdir, $configpmtest) = @_; 
254     if (-w $configpmtest) {
255         return $configpmtest;
256     } elsif (-w $configpmdir) {
257         #_#_# following code dumped core on me with 5.003_11, a.k.
258         my $configpm_bak = "$configpmtest.bak";
259         unlink $configpm_bak if -f $configpm_bak;
260         if( -f $configpmtest ) {
261             if( rename $configpmtest, $configpm_bak ) {
262                                 $CPAN::Frontend->mywarn(<<END);
263 Old configuration file $configpmtest
264     moved to $configpm_bak
265 END
266             }
267         }
268         my $fh = FileHandle->new;
269         if ($fh->open(">$configpmtest")) {
270             $fh->print("1;\n");
271             return $configpmtest;
272         } else {
273             # Should never happen
274             Carp::confess("Cannot open >$configpmtest");
275         }
276     } else { return }
277 }
278
279 sub load {
280     my($self, %args) = @_;
281         $CPAN::Be_Silent++ if $args{be_silent};
282
283     my(@miss);
284     use Carp;
285     unless ($INC{"CPAN/MyConfig.pm"}) { # this guy has settled his needs already
286       eval {require CPAN::Config;}; # not everybody has one
287     }
288     unless ($dot_cpan++){
289       unshift @INC, File::Spec->catdir($ENV{HOME},".cpan");
290       eval {require CPAN::MyConfig;}; # override system wide settings
291       shift @INC;
292     }
293     return unless @miss = $self->missing_config_data;
294
295     require CPAN::FirstTime;
296     my($configpm,$fh,$redo,$theycalled);
297     $redo ||= "";
298     $theycalled++ if @miss==1 && $miss[0] eq 'inhibit_startup_message';
299     if (defined $INC{"CPAN/Config.pm"} && -w $INC{"CPAN/Config.pm"}) {
300         $configpm = $INC{"CPAN/Config.pm"};
301         $redo++;
302     } elsif (defined $INC{"CPAN/MyConfig.pm"} && -w $INC{"CPAN/MyConfig.pm"}) {
303         $configpm = $INC{"CPAN/MyConfig.pm"};
304         $redo++;
305     } else {
306         my($path_to_cpan) = File::Basename::dirname($INC{"CPAN.pm"});
307         my($configpmdir) = File::Spec->catdir($path_to_cpan,"CPAN");
308         my($configpmtest) = File::Spec->catfile($configpmdir,"Config.pm");
309         my $inc_key;
310         if (-d $configpmdir or File::Path::mkpath($configpmdir)) {
311             $configpm = _configpmtest($configpmdir,$configpmtest);
312             $inc_key = "CPAN/Config.pm";
313         }
314         unless ($configpm) {
315             $configpmdir = File::Spec->catdir($ENV{HOME},".cpan","CPAN");
316             File::Path::mkpath($configpmdir);
317             $configpmtest = File::Spec->catfile($configpmdir,"MyConfig.pm");
318             $configpm = _configpmtest($configpmdir,$configpmtest);
319             $inc_key = "CPAN/MyConfig.pm";
320         }
321         if ($configpm) {
322           $INC{$inc_key} = $configpm;
323         } else {
324           my $text = qq{WARNING: CPAN.pm is unable to } .
325               qq{create a configuration file.};
326           output($text, 'confess');
327         }
328
329     }
330     local($") = ", ";
331     $CPAN::Frontend->myprint(<<END) if $redo && ! $theycalled;
332 Sorry, we have to rerun the configuration dialog for CPAN.pm due to
333 the following indispensable but missing parameters:
334
335 @miss
336 END
337     $CPAN::Frontend->myprint(qq{
338 $configpm initialized.
339 });
340
341     sleep 2;
342     CPAN::FirstTime::init($configpm, %args);
343 }
344
345 sub missing_config_data {
346     my(@miss);
347     for (
348          "build_cache",
349          "build_dir",
350          "cache_metadata",
351          "cpan_home",
352          "ftp_proxy",
353          "gzip",
354          "http_proxy",
355          "index_expire",
356          "inhibit_startup_message",
357          "keep_source_where",
358          "make",
359          "make_arg",
360          "make_install_arg",
361          "makepl_arg",
362          "mbuild_arg",
363          "mbuild_install_arg",
364          "mbuild_install_build_command",
365          "mbuildpl_arg",
366          "no_proxy",
367          "pager",
368          "prerequisites_policy",
369          "scan_cache",
370          "tar",
371          "unzip",
372          "urllist",
373         ) {
374         next unless exists $keys{$_};
375         push @miss, $_ unless defined $CPAN::Config->{$_};
376     }
377     return @miss;
378 }
379
380 sub help {
381     $CPAN::Frontend->myprint(q[
382 Known options:
383   defaults  reload default config values from disk
384   commit    commit session changes to disk
385   init      go through a dialog to set all parameters
386
387 You may edit key values in the follow fashion (the "o" is a literal
388 letter o):
389
390   o conf build_cache 15
391
392   o conf build_dir "/foo/bar"
393
394   o conf urllist shift
395
396   o conf urllist unshift ftp://ftp.foo.bar/
397
398 ]);
399     undef; #don't reprint CPAN::Config
400 }
401
402 sub cpl {
403     my($word,$line,$pos) = @_;
404     $word ||= "";
405     CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG;
406     my(@words) = split " ", substr($line,0,$pos+1);
407     if (
408         defined($words[2])
409         and
410         (
411          $words[2] =~ /list$/ && @words == 3
412          ||
413          $words[2] =~ /list$/ && @words == 4 && length($word)
414         )
415        ) {
416         return grep /^\Q$word\E/, qw(splice shift unshift pop push);
417     } elsif (@words >= 4) {
418         return ();
419     }
420     my %seen;
421     my(@o_conf) =  sort grep { !$seen{$_}++ }
422         keys %can,
423             keys %$CPAN::Config,
424                 keys %keys;
425     return grep /^\Q$word\E/, @o_conf;
426 }
427
428
429 package ####::###### #hide from indexer
430     CPAN::Config;
431 # note: J. Nick Koston wrote me that they are using
432 # CPAN::Config->commit although undocumented. I suggested
433 # CPAN::Shell->o("conf","commit") even when ugly it is at least
434 # documented
435
436 # that's why I added the CPAN::Config class with autoload and
437 # deprecated warning
438
439 use strict;
440 use vars qw($AUTOLOAD $VERSION);
441 $VERSION = sprintf "%.2f", substr(q$Rev: 488 $,4)/100;
442
443 # formerly CPAN::HandleConfig was known as CPAN::Config
444 sub AUTOLOAD {
445   my($l) = $AUTOLOAD;
446   $CPAN::Frontend->mywarn("Dispatching deprecated method '$l' to CPAN::HandleConfig");
447   $l =~ s/.*:://;
448   CPAN::HandleConfig->$l(@_);
449 }
450
451 1;
452
453 __END__
454 # Local Variables:
455 # mode: cperl
456 # cperl-indent-level: 4
457 # End: