Storable support, v-version fixes.
[p5sagit/p5-mst-13.2.git] / lib / CPAN / FirstTime.pm
1 package CPAN::Mirrored::By;
2
3 sub new { 
4     my($self,@arg) = @_;
5     bless [@arg], $self;
6 }
7 sub continent { shift->[0] }
8 sub country { shift->[1] }
9 sub url { shift->[2] }
10
11 package CPAN::FirstTime;
12
13 use strict;
14 use ExtUtils::MakeMaker qw(prompt);
15 use FileHandle ();
16 use File::Basename ();
17 use File::Path ();
18 use vars qw($VERSION);
19 $VERSION = substr q$Revision: 1.41 $, 10;
20
21 =head1 NAME
22
23 CPAN::FirstTime - Utility for CPAN::Config file Initialization
24
25 =head1 SYNOPSIS
26
27 CPAN::FirstTime::init()
28
29 =head1 DESCRIPTION
30
31 The init routine asks a few questions and writes a CPAN::Config
32 file. Nothing special.
33
34 =cut
35
36
37 sub init {
38     my($configpm) = @_;
39     use Config;
40     unless ($CPAN::VERSION) {
41         require CPAN::Nox;
42     }
43     eval {require CPAN::Config;};
44     $CPAN::Config ||= {};
45     local($/) = "\n";
46     local($\) = "";
47     local($|) = 1;
48
49     my($ans,$default,$local,$cont,$url,$expected_size);
50
51     #
52     # Files, directories
53     #
54
55     print qq[
56
57 CPAN is the world-wide archive of perl resources. It consists of about
58 100 sites that all replicate the same contents all around the globe.
59 Many countries have at least one CPAN site already. The resources
60 found on CPAN are easily accessible with the CPAN.pm module. If you
61 want to use CPAN.pm, you have to configure it properly.
62
63 If you do not want to enter a dialog now, you can answer 'no' to this
64 question and I\'ll try to autoconfigure. (Note: you can revisit this
65 dialog anytime later by typing 'o conf init' at the cpan prompt.)
66
67 ];
68
69     my $manual_conf =
70         ExtUtils::MakeMaker::prompt("Are you ready for manual configuration?",
71                                     "yes");
72     my $fastread;
73     {
74       local $^W;
75       if ($manual_conf =~ /^\s*y/i) {
76         $fastread = 0;
77         *prompt = \&ExtUtils::MakeMaker::prompt;
78       } else {
79         $fastread = 1;
80         $CPAN::Config->{urllist} ||= [];
81         # prototype should match that of &MakeMaker::prompt
82         *prompt = sub ($;$) {
83           my($q,$a) = @_;
84           my($ret) = defined $a ? $a : "";
85           printf qq{%s [%s]\n\n}, $q, $ret;
86           $ret;
87         };
88       }
89     }
90     print qq{
91
92 The following questions are intended to help you with the
93 configuration. The CPAN module needs a directory of its own to cache
94 important index files and maybe keep a temporary mirror of CPAN files.
95 This may be a site-wide directory or a personal directory.
96
97 };
98
99     my $cpan_home = $CPAN::Config->{cpan_home} || MM->catdir($ENV{HOME}, ".cpan");
100     if (-d $cpan_home) {
101         print qq{
102
103 I see you already have a  directory
104     $cpan_home
105 Shall we use it as the general CPAN build and cache directory?
106
107 };
108     } else {
109         print qq{
110
111 First of all, I\'d like to create this directory. Where?
112
113 };
114     }
115
116     $default = $cpan_home;
117     while ($ans = prompt("CPAN build and cache directory?",$default)) {
118       eval { File::Path::mkpath($ans); }; # dies if it can't
119       if ($@) {
120         warn "Couldn't create directory $ans.
121 Please retry.\n";
122         next;
123       }
124       if (-d $ans && -w _) {
125         last;
126       } else {
127         warn "Couldn't find directory $ans
128   or directory is not writable. Please retry.\n";
129       }
130     }
131     $CPAN::Config->{cpan_home} = $ans;
132
133     print qq{
134
135 If you want, I can keep the source files after a build in the cpan
136 home directory. If you choose so then future builds will take the
137 files from there. If you don\'t want to keep them, answer 0 to the
138 next question.
139
140 };
141
142     $CPAN::Config->{keep_source_where} = MM->catdir($CPAN::Config->{cpan_home},"sources");
143     $CPAN::Config->{build_dir} = MM->catdir($CPAN::Config->{cpan_home},"build");
144
145     #
146     # Cache size, Index expire
147     #
148
149     print qq{
150
151 How big should the disk cache be for keeping the build directories
152 with all the intermediate files\?
153
154 };
155
156     $default = $CPAN::Config->{build_cache} || 10;
157     $ans = prompt("Cache size for build directory (in MB)?", $default);
158     $CPAN::Config->{build_cache} = $ans;
159
160     # XXX This the time when we refetch the index files (in days)
161     $CPAN::Config->{'index_expire'} = 1;
162
163     print qq{
164
165 By default, each time the CPAN module is started, cache scanning
166 is performed to keep the cache size in sync. To prevent from this,
167 disable the cache scanning with 'never'.
168
169 };
170
171     $default = $CPAN::Config->{scan_cache} || 'atstart';
172     do {
173         $ans = prompt("Perform cache scanning (atstart or never)?", $default);
174     } while ($ans ne 'atstart' && $ans ne 'never');
175     $CPAN::Config->{scan_cache} = $ans;
176
177     print qq{
178
179 To speed up the initial CPAN shell startup, it is possible to use
180 Storable or FreezeThaw to create an cache of metadata. If no
181 serializer is avaiable, the normal index mechanism will be used.
182
183 };
184
185     defined($default = $CPAN::Config->{cache_metadata}) or $default = 1;
186     do {
187         $ans = prompt("Cache metadata (yes/no)?", ($default ? 'yes' : 'no'));
188     } while ($ans !~ /^\s*[yn]/i);
189     $CPAN::Config->{cache_metadata} = ($ans =~ /^\s*y/i ? 1 : 0);
190
191     #
192     # prerequisites_policy
193     # Do we follow PREREQ_PM?
194     #
195     print qq{
196
197 The CPAN module can detect when a module that which you are trying to
198 build depends on prerequisites. If this happens, it can build the
199 prerequisites for you automatically ('follow'), ask you for
200 confirmation ('ask'), or just ignore them ('ignore'). Please set your
201 policy to one of the three values.
202
203 };
204
205     $default = $CPAN::Config->{prerequisites_policy} || 'ask';
206     do {
207       $ans =
208           prompt("Policy on building prerequisites (follow, ask or ignore)?",
209                  $default);
210     } while ($ans ne 'follow' && $ans ne 'ask' && $ans ne 'ignore');
211     $CPAN::Config->{prerequisites_policy} = $ans;
212
213     #
214     # External programs
215     #
216
217     print qq{
218
219 The CPAN module will need a few external programs to work
220 properly. Please correct me, if I guess the wrong path for a program.
221 Don\'t panic if you do not have some of them, just press ENTER for
222 those.
223
224 };
225
226     my $old_warn = $^W;
227     local $^W if $^O eq 'MacOS';
228     my(@path) = split /$Config{'path_sep'}/, $ENV{'PATH'};
229     local $^W = $old_warn;
230     my $progname;
231     for $progname (qw/gzip tar unzip make lynx ncftpget ncftp ftp/){
232       if ($^O eq 'MacOS') {
233           $CPAN::Config->{$progname} = 'not_here';
234           next;
235       }
236       my $progcall = $progname;
237       # we don't need ncftp if we have ncftpget
238       next if $progname eq "ncftp" && $CPAN::Config->{ncftpget} gt " ";
239       my $path = $CPAN::Config->{$progname} 
240           || $Config::Config{$progname}
241               || "";
242       if (MM->file_name_is_absolute($path)) {
243         # testing existence is not good enough, some have these exe
244         # extensions
245
246         # warn "Warning: configured $path does not exist\n" unless -e $path;
247         # $path = "";
248       } else {
249         $path = '';
250       }
251       unless ($path) {
252         # e.g. make -> nmake
253         $progcall = $Config::Config{$progname} if $Config::Config{$progname};
254       }
255
256       $path ||= find_exe($progcall,[@path]);
257       warn "Warning: $progcall not found in PATH\n" unless
258           $path; # not -e $path, because find_exe already checked that
259       $ans = prompt("Where is your $progname program?",$path) || $path;
260       $CPAN::Config->{$progname} = $ans;
261     }
262     my $path = $CPAN::Config->{'pager'} || 
263         $ENV{PAGER} || find_exe("less",[@path]) || 
264             find_exe("more",[@path]) || ($^O eq 'MacOS' ? $ENV{EDITOR} : 0 )
265             || "more";
266     $ans = prompt("What is your favorite pager program?",$path);
267     $CPAN::Config->{'pager'} = $ans;
268     $path = $CPAN::Config->{'shell'};
269     if (MM->file_name_is_absolute($path)) {
270         warn "Warning: configured $path does not exist\n" unless -e $path;
271         $path = "";
272     }
273     $path ||= $ENV{SHELL};
274     if ($^O eq 'MacOS') {
275         $CPAN::Config->{'shell'} = 'not_here';
276     } else {
277         $path =~ s,\\,/,g if $^O eq 'os2';      # Cosmetic only
278         $ans = prompt("What is your favorite shell?",$path);
279         $CPAN::Config->{'shell'} = $ans;
280     }
281
282     #
283     # Arguments to make etc.
284     #
285
286     print qq{
287
288 Every Makefile.PL is run by perl in a separate process. Likewise we
289 run \'make\' and \'make install\' in processes. If you have any parameters
290 \(e.g. PREFIX, INSTALLPRIVLIB, UNINST or the like\) you want to pass to
291 the calls, please specify them here.
292
293 If you don\'t understand this question, just press ENTER.
294
295 };
296
297     $default = $CPAN::Config->{makepl_arg} || "";
298     $CPAN::Config->{makepl_arg} =
299         prompt("Parameters for the 'perl Makefile.PL' command?",$default);
300     $default = $CPAN::Config->{make_arg} || "";
301     $CPAN::Config->{make_arg} = prompt("Parameters for the 'make' command?",$default);
302
303     $default = $CPAN::Config->{make_install_arg} || $CPAN::Config->{make_arg} || "";
304     $CPAN::Config->{make_install_arg} =
305         prompt("Parameters for the 'make install' command?",$default);
306
307     #
308     # Alarm period
309     #
310
311     print qq{
312
313 Sometimes you may wish to leave the processes run by CPAN alone
314 without caring about them. As sometimes the Makefile.PL contains
315 question you\'re expected to answer, you can set a timer that will
316 kill a 'perl Makefile.PL' process after the specified time in seconds.
317
318 If you set this value to 0, these processes will wait forever. This is
319 the default and recommended setting.
320
321 };
322
323     $default = $CPAN::Config->{inactivity_timeout} || 0;
324     $CPAN::Config->{inactivity_timeout} =
325         prompt("Timeout for inactivity during Makefile.PL?",$default);
326
327     # Proxies
328
329     print qq{
330
331 If you\'re accessing the net via proxies, you can specify them in the
332 CPAN configuration or via environment variables. The variable in
333 the \$CPAN::Config takes precedence.
334
335 };
336
337     for (qw/ftp_proxy http_proxy no_proxy/) {
338         $default = $CPAN::Config->{$_} || $ENV{$_};
339         $CPAN::Config->{$_} = prompt("Your $_?",$default);
340     }
341
342     #
343     # MIRRORED.BY
344     #
345
346     conf_sites() unless $fastread;
347
348     unless (@{$CPAN::Config->{'wait_list'}||[]}) {
349         print qq{
350
351 WAIT support is available as a Plugin. You need the CPAN::WAIT module
352 to actually use it.  But we need to know your favorite WAIT server. If
353 you don\'t know a WAIT server near you, just press ENTER.
354
355 };
356         $default = "wait://ls6.informatik.uni-dortmund.de:1404";
357         $ans = prompt("Your favorite WAIT server?\n  ",$default);
358         push @{$CPAN::Config->{'wait_list'}}, $ans;
359     }
360
361     # We don't ask that now, it will be noticed in time, won't it?
362     $CPAN::Config->{'inhibit_startup_message'} = 0;
363     $CPAN::Config->{'getcwd'} = 'cwd';
364
365     print "\n\n";
366     CPAN::Config->commit($configpm);
367 }
368
369 sub conf_sites {
370   my $m = 'MIRRORED.BY';
371   my $mby = MM->catfile($CPAN::Config->{keep_source_where},$m);
372   File::Path::mkpath(File::Basename::dirname($mby));
373   if (-f $mby && -f $m && -M $m < -M $mby) {
374     require File::Copy;
375     File::Copy::copy($m,$mby) or die "Could not update $mby: $!";
376   }
377   my $loopcount = 0;
378   local $^T = time;
379   while ($mby) {
380     if ( ! -f $mby ){
381       print qq{You have no $mby
382   I\'m trying to fetch one
383 };
384       $mby = CPAN::FTP->localize($m,$mby,3);
385     } elsif (-M $mby > 60 && $loopcount == 0) {
386       print qq{Your $mby is older than 60 days,
387   I\'m trying to fetch one
388 };
389       $mby = CPAN::FTP->localize($m,$mby,3);
390       $loopcount++;
391     } elsif (-s $mby == 0) {
392       print qq{You have an empty $mby,
393   I\'m trying to fetch one
394 };
395       $mby = CPAN::FTP->localize($m,$mby,3);
396     } else {
397       last;
398     }
399   }
400   read_mirrored_by($mby);
401   bring_your_own();
402 }
403
404 sub find_exe {
405     my($exe,$path) = @_;
406     my($dir);
407     #warn "in find_exe exe[$exe] path[@$path]";
408     for $dir (@$path) {
409         my $abs = MM->catfile($dir,$exe);
410         if (($abs = MM->maybe_command($abs))) {
411             return $abs;
412         }
413     }
414 }
415
416 sub picklist {
417     my($items,$prompt,$default,$require_nonempty,$empty_warning)=@_;
418     $default ||= '';
419
420     my ($item, $i);
421     for $item (@$items) {
422         printf "(%d) %s\n", ++$i, $item;
423     }
424
425     my @nums;
426     while (1) {
427         my $num = prompt($prompt,$default);
428         @nums = split (' ', $num);
429         (warn "invalid items entered, try again\n"), next
430             if grep (/\D/ || $_ < 1 || $_ > $i, @nums);
431         if ($require_nonempty) {
432             (warn "$empty_warning\n"), next
433                 unless @nums;
434         }
435         last;
436     }
437     print "\n";
438     for (@nums) { $_-- }
439     @{$items}[@nums];
440 }
441
442 sub read_mirrored_by {
443     my $local = shift or return;
444     my(%all,$url,$expected_size,$default,$ans,$host,$dst,$country,$continent,@location);
445     my $fh = FileHandle->new;
446     $fh->open($local) or die "Couldn't open $local: $!";
447     local $/ = "\012";
448     while (<$fh>) {
449         ($host) = /^([\w\.\-]+)/ unless defined $host;
450         next unless defined $host;
451         next unless /\s+dst_(dst|location)/;
452         /location\s+=\s+\"([^\"]+)/ and @location = (split /\s*,\s*/, $1) and
453             ($continent, $country) = @location[-1,-2];
454         $continent =~ s/\s\(.*//;
455         $continent =~ s/\W+$//; # if Jarkko doesn't know latitude/longitude
456         /dst_dst\s+=\s+\"([^\"]+)/  and $dst = $1;
457         next unless $host && $dst && $continent && $country;
458         $all{$continent}{$country}{$dst} = CPAN::Mirrored::By->new($continent,$country,$dst);
459         undef $host;
460         $dst=$continent=$country="";
461     }
462     $fh->close;
463     $CPAN::Config->{urllist} ||= [];
464     my(@previous_urls);
465     if (@previous_urls = @{$CPAN::Config->{urllist}}) {
466         $CPAN::Config->{urllist} = [];
467     }
468
469     print qq{
470
471 Now we need to know where your favorite CPAN sites are located. Push
472 a few sites onto the array (just in case the first on the array won\'t
473 work). If you are mirroring CPAN to your local workstation, specify a
474 file: URL.
475
476 First, pick a nearby continent and country (you can pick several of
477 each, separated by spaces, or none if you just want to keep your
478 existing selections). Then, you will be presented with a list of URLs
479 of CPAN mirrors in the countries you selected, along with previously
480 selected URLs. Select some of those URLs, or just keep the old list.
481 Finally, you will be prompted for any extra URLs -- file:, ftp:, or
482 http: -- that host a CPAN mirror.
483
484 };
485
486     my (@cont, $cont, %cont, @countries, @urls, %seen);
487     my $no_previous_warn = 
488        "Sorry! since you don't have any existing picks, you must make a\n" .
489        "geographic selection.";
490     @cont = picklist([sort keys %all],
491                      "Select your continent (or several nearby continents)",
492                      '',
493                      ! @previous_urls,
494                      $no_previous_warn);
495
496
497     foreach $cont (@cont) {
498         my @c = sort keys %{$all{$cont}};
499         @cont{@c} = map ($cont, 0..$#c);
500         @c = map ("$_ ($cont)", @c) if @cont > 1;
501         push (@countries, @c);
502     }
503
504     if (@countries) {
505         @countries = picklist (\@countries,
506                                "Select your country (or several nearby countries)",
507                                '',
508                                ! @previous_urls,
509                                $no_previous_warn);
510         %seen = map (($_ => 1), @previous_urls);
511         # hmmm, should take list of defaults from CPAN::Config->{'urllist'}...
512         foreach $country (@countries) {
513             (my $bare_country = $country) =~ s/ \(.*\)//;
514             my @u = sort keys %{$all{$cont{$bare_country}}{$bare_country}};
515             @u = grep (! $seen{$_}, @u);
516             @u = map ("$_ ($bare_country)", @u)
517                if @countries > 1;
518             push (@urls, @u);
519         }
520     }
521     push (@urls, map ("$_ (previous pick)", @previous_urls));
522     my $prompt = "Select as many URLs as you like";
523     if (@previous_urls) {
524        $default = join (' ', ((scalar @urls) - (scalar @previous_urls) + 1) ..
525                              (scalar @urls));
526        $prompt .= "\n(or just hit RETURN to keep your previous picks)";
527     }
528
529     @urls = picklist (\@urls, $prompt, $default);
530     foreach (@urls) { s/ \(.*\)//; }
531     push @{$CPAN::Config->{urllist}}, @urls;
532 }
533
534 sub bring_your_own {
535     my %seen = map (($_ => 1), @{$CPAN::Config->{urllist}});
536     my($ans,@urls);
537     do {
538         my $prompt = "Enter another URL or RETURN to quit:";
539         unless (%seen) {
540             $prompt = qq{CPAN.pm needs at least one URL where it can fetch CPAN files from.
541
542 Please enter your CPAN site:};
543         }
544         $ans = prompt ($prompt, "");
545
546         if ($ans) {
547             $ans =~ s|/?\z|/|; # has to end with one slash
548             $ans = "file:$ans" unless $ans =~ /:/; # without a scheme is a file:
549             if ($ans =~ /^\w+:\/./) {
550                push @urls, $ans unless $seen{$ans}++;
551             } else {
552                 print qq{"$ans" doesn\'t look like an URL at first sight.
553 I\'ll ignore it for now.  You can add it to $INC{'CPAN/MyConfig.pm'}
554 later if you\'re sure it\'s right.\n};
555             }
556         }
557     } while $ans || !%seen;
558
559     push @{$CPAN::Config->{urllist}}, @urls;
560     # xxx delete or comment these out when you're happy that it works
561     print "New set of picks:\n";
562     map { print "  $_\n" } @{$CPAN::Config->{urllist}};
563 }
564
565 1;