local version number bumps for CPAN.pm hotfixes
[p5sagit/p5-mst-13.2.git] / cpan / CPAN / lib / CPAN / FirstTime.pm
1 # -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
2 package CPAN::FirstTime;
3 use strict;
4
5 use ExtUtils::MakeMaker ();
6 use FileHandle ();
7 use File::Basename ();
8 use File::Path ();
9 use File::Spec ();
10 use CPAN::Mirrors ();
11 use vars qw($VERSION $silent);
12 $VERSION = "5.530001"; # 5.53 + local patches for bleadperl
13
14 =head1 NAME
15
16 CPAN::FirstTime - Utility for CPAN::Config file Initialization
17
18 =head1 SYNOPSIS
19
20 CPAN::FirstTime::init()
21
22 =head1 DESCRIPTION
23
24 The init routine asks a few questions and writes a CPAN/Config.pm or
25 CPAN/MyConfig.pm file (depending on what it is currently using).
26
27 In the following all questions and explanations regarding config
28 variables are collected.
29
30 =cut
31
32 # down until the next =back the manpage must be parsed by the program
33 # because the text is used in the init dialogues.
34
35 my @podpara = split /\n\n/, <<'=back';
36
37 =over 2
38
39 =item auto_commit
40
41 Normally CPAN.pm keeps config variables in memory and changes need to
42 be saved in a separate 'o conf commit' command to make them permanent
43 between sessions. If you set the 'auto_commit' option to true, changes
44 to a config variable are always automatically committed to disk.
45
46 Always commit changes to config variables to disk?
47
48 =item build_cache
49
50 CPAN.pm can limit the size of the disk area for keeping the build
51 directories with all the intermediate files.
52
53 Cache size for build directory (in MB)?
54
55 =item build_dir
56
57 Directory where the build process takes place?
58
59 =item build_dir_reuse
60
61 Until version 1.88 CPAN.pm never trusted the contents of the build_dir
62 directory between sessions. Since 1.88_58 CPAN.pm has a YAML-based
63 mechanism that makes it possible to share the contents of the
64 build_dir/ directory between different sessions with the same version
65 of perl. People who prefer to test things several days before
66 installing will like this feature because it safes a lot of time.
67
68 If you say yes to the following question, CPAN will try to store
69 enough information about the build process so that it can pick up in
70 future sessions at the same state of affairs as it left a previous
71 session.
72
73 Store and re-use state information about distributions between
74 CPAN.pm sessions?
75
76 =item build_requires_install_policy
77
78 When a module declares another one as a 'build_requires' prerequisite
79 this means that the other module is only needed for building or
80 testing the module but need not be installed permanently. In this case
81 you may wish to install that other module nonetheless or just keep it
82 in the 'build_dir' directory to have it available only temporarily.
83 Installing saves time on future installations but makes the perl
84 installation bigger.
85
86 You can choose if you want to always install (yes), never install (no)
87 or be always asked. In the latter case you can set the default answer
88 for the question to yes (ask/yes) or no (ask/no).
89
90 Policy on installing 'build_requires' modules (yes, no, ask/yes,
91 ask/no)?
92
93 =item cache_metadata
94
95 To considerably speed up the initial CPAN shell startup, it is
96 possible to use Storable to create a cache of metadata. If Storable is
97 not available, the normal index mechanism will be used.
98
99 Note: this mechanism is not used when use_sqlite is on and SQLLite is
100 running.
101
102 Cache metadata (yes/no)?
103
104 =item check_sigs
105
106 CPAN packages can be digitally signed by authors and thus verified
107 with the security provided by strong cryptography. The exact mechanism
108 is defined in the Module::Signature module. While this is generally
109 considered a good thing, it is not always convenient to the end user
110 to install modules that are signed incorrectly or where the key of the
111 author is not available or where some prerequisite for
112 Module::Signature has a bug and so on.
113
114 With the check_sigs parameter you can turn signature checking on and
115 off. The default is off for now because the whole tool chain for the
116 functionality is not yet considered mature by some. The author of
117 CPAN.pm would recommend setting it to true most of the time and
118 turning it off only if it turns out to be annoying.
119
120 Note that if you do not have Module::Signature installed, no signature
121 checks will be performed at all.
122
123 Always try to check and verify signatures if a SIGNATURE file is in
124 the package and Module::Signature is installed (yes/no)?
125
126 =item colorize_output
127
128 When you have Term::ANSIColor installed, you can turn on colorized
129 output to have some visual differences between normal CPAN.pm output,
130 warnings, debugging output, and the output of the modules being
131 installed. Set your favorite colors after some experimenting with the
132 Term::ANSIColor module.
133
134 Do you want to turn on colored output?
135
136 =item colorize_print
137
138 Color for normal output?
139
140 =item colorize_warn
141
142 Color for warnings?
143
144 =item colorize_debug
145
146 Color for debugging messages?
147
148 =item commandnumber_in_prompt
149
150 The prompt of the cpan shell can contain the current command number
151 for easier tracking of the session or be a plain string.
152
153 Do you want the command number in the prompt (yes/no)?
154
155 =item connect_to_internet_ok
156
157 If you have never defined your own C<urllist> in your configuration
158 then C<CPAN.pm> will be hesitant to use the built in default sites for
159 downloading. It will ask you once per session if a connection to the
160 internet is OK and only if you say yes, it will try to connect. But to
161 avoid this question, you can choose your favorite download sites once
162 and get away with it. Or, if you have no favorite download sites
163 answer yes to the following question.
164
165 If no urllist has been chosen yet, would you prefer CPAN.pm to connect
166 to the built-in default sites without asking? (yes/no)?
167
168 =item ftp_passive
169
170 Shall we always set the FTP_PASSIVE environment variable when dealing
171 with ftp download (yes/no)?
172
173 =item ftpstats_period
174
175 Statistics about downloads are truncated by size and period
176 simultaneously.
177
178 How many days shall we keep statistics about downloads?
179
180 =item ftpstats_size
181
182 Statistics about downloads are truncated by size and period
183 simultaneously.
184
185 How many items shall we keep in the statistics about downloads?
186
187 =item getcwd
188
189 CPAN.pm changes the current working directory often and needs to
190 determine its own current working directory. Per default it uses
191 Cwd::cwd but if this doesn't work on your system for some reason,
192 alternatives can be configured according to the following table:
193
194     cwd         Cwd::cwd
195     getcwd      Cwd::getcwd
196     fastcwd     Cwd::fastcwd
197     backtickcwd external command cwd
198
199 Preferred method for determining the current working directory?
200
201 =item halt_on_failure
202
203 Normaly, CPAN.pm continues processing the full list of targets and
204 dependencies, even if one of them fails.  However, you can specify 
205 that CPAN should halt after the first failure. 
206
207 Do you want to halt on failure (yes/no)?
208
209 =item histfile
210
211 If you have one of the readline packages (Term::ReadLine::Perl,
212 Term::ReadLine::Gnu, possibly others) installed, the interactive CPAN
213 shell will have history support. The next two questions deal with the
214 filename of the history file and with its size. If you do not want to
215 set this variable, please hit SPACE RETURN to the following question.
216
217 File to save your history?
218
219 =item histsize
220
221 Number of lines to save?
222
223 =item inactivity_timeout
224
225 Sometimes you may wish to leave the processes run by CPAN alone
226 without caring about them. Because the Makefile.PL or the Build.PL
227 sometimes contains question you're expected to answer, you can set a
228 timer that will kill a 'perl Makefile.PL' process after the specified
229 time in seconds.
230
231 If you set this value to 0, these processes will wait forever. This is
232 the default and recommended setting.
233
234 Timeout for inactivity during {Makefile,Build}.PL?
235
236 =item index_expire
237
238 The CPAN indexes are usually rebuilt once or twice per hour, but the
239 typical CPAN mirror mirrors only once or twice per day. Depending on
240 the quality of your mirror and your desire to be on the bleeding edge,
241 you may want to set the following value to more or less than one day
242 (which is the default). It determines after how many days CPAN.pm
243 downloads new indexes.
244
245 Let the index expire after how many days?
246
247 =item inhibit_startup_message
248
249 When the CPAN shell is started it normally displays a greeting message
250 that contains the running version and the status of readline support.
251
252 Do you want to turn this message off?
253
254 =item keep_source_where
255
256 Unless you are accessing the CPAN on your filesystem via a file: URL,
257 CPAN.pm needs to keep the source files it downloads somewhere. Please
258 supply a directory where the downloaded files are to be kept.
259
260 Download target directory?
261
262 =item load_module_verbosity
263
264 When CPAN.pm loads a module it needs for some optional feature, it
265 usually reports about module name and version. Choose 'v' to get this
266 message, 'none' to suppress it.
267
268 Verbosity level for loading modules (none or v)?
269
270 =item makepl_arg
271
272 Every Makefile.PL is run by perl in a separate process. Likewise we
273 run 'make' and 'make install' in separate processes. If you have
274 any parameters (e.g. PREFIX, UNINST or the like) you want to
275 pass to the calls, please specify them here.
276
277 If you don't understand this question, just press ENTER.
278
279 Typical frequently used settings:
280
281     PREFIX=~/perl    # non-root users (please see manual for more hints)
282
283 Parameters for the 'perl Makefile.PL' command?
284
285 =item make_arg
286
287 Parameters for the 'make' command? Typical frequently used setting:
288
289     -j3              # dual processor system (on GNU make)
290
291 Your choice:
292
293 =item make_install_arg
294
295 Parameters for the 'make install' command?
296 Typical frequently used setting:
297
298     UNINST=1         # to always uninstall potentially conflicting files
299
300 Your choice:
301
302 =item make_install_make_command
303
304 Do you want to use a different make command for 'make install'?
305 Cautious people will probably prefer:
306
307     su root -c make
308  or
309     sudo make
310  or
311     /path1/to/sudo -u admin_account /path2/to/make
312
313 or some such. Your choice:
314
315 =item mbuildpl_arg
316
317 A Build.PL is run by perl in a separate process. Likewise we run
318 './Build' and './Build install' in separate processes. If you have any
319 parameters you want to pass to the calls, please specify them here.
320
321 Typical frequently used settings:
322
323     --install_base /home/xxx             # different installation directory
324
325 Parameters for the 'perl Build.PL' command?
326
327 =item mbuild_arg
328
329 Parameters for the './Build' command? Setting might be:
330
331     --extra_linker_flags -L/usr/foo/lib  # non-standard library location
332
333 Your choice:
334
335 =item mbuild_install_arg
336
337 Parameters for the './Build install' command? Typical frequently used
338 setting:
339
340     --uninst 1                           # uninstall conflicting files
341
342 Your choice:
343
344 =item mbuild_install_build_command
345
346 Do you want to use a different command for './Build install'? Sudo
347 users will probably prefer:
348
349     su root -c ./Build
350  or
351     sudo ./Build
352  or
353     /path1/to/sudo -u admin_account ./Build
354
355 or some such. Your choice:
356
357 =item pager
358
359 What is your favorite pager program?
360
361 =item prefer_installer
362
363 When you have Module::Build installed and a module comes with both a
364 Makefile.PL and a Build.PL, which shall have precedence?
365
366 The main two standard installer modules are the old and well
367 established ExtUtils::MakeMaker (for short: EUMM) which uses the
368 Makefile.PL. And the next generation installer Module::Build (MB)
369 which works with the Build.PL (and often comes with a Makefile.PL
370 too). If a module comes only with one of the two we will use that one
371 but if both are supplied then a decision must be made between EUMM and
372 MB. See also http://rt.cpan.org/Ticket/Display.html?id=29235 for a
373 discussion about the right default.
374
375 Or, as a third option you can choose RAND which will make a random
376 decision (something regular CPAN testers will enjoy).
377
378 In case you can choose between running a Makefile.PL or a Build.PL,
379 which installer would you prefer (EUMM or MB or RAND)?
380
381 =item prefs_dir
382
383 CPAN.pm can store customized build environments based on regular
384 expressions for distribution names. These are YAML files where the
385 default options for CPAN.pm and the environment can be overridden and
386 dialog sequences can be stored that can later be executed by an
387 Expect.pm object. The CPAN.pm distribution comes with some prefab YAML
388 files that cover sample distributions that can be used as blueprints
389 to store one own prefs. Please check out the distroprefs/ directory of
390 the CPAN.pm distribution to get a quick start into the prefs system.
391
392 Directory where to store default options/environment/dialogs for
393 building modules that need some customization?
394
395 =item prerequisites_policy
396
397 The CPAN module can detect when a module which you are trying to build
398 depends on prerequisites. If this happens, it can build the
399 prerequisites for you automatically ('follow'), ask you for
400 confirmation ('ask'), or just ignore them ('ignore'). Please set your
401 policy to one of the three values.
402
403 Policy on building prerequisites (follow, ask or ignore)?
404
405 =item randomize_urllist
406
407 CPAN.pm can introduce some randomness when using hosts for download
408 that are configured in the urllist parameter. Enter a numeric value
409 between 0 and 1 to indicate how often you want to let CPAN.pm try a
410 random host from the urllist. A value of one specifies to always use a
411 random host as the first try. A value of zero means no randomness at
412 all. Anything in between specifies how often, on average, a random
413 host should be tried first.
414
415 Randomize parameter
416
417 =item scan_cache
418
419 By default, each time the CPAN module is started, cache scanning is
420 performed to keep the cache size in sync. To prevent this, answer
421 'never'.
422
423 Perform cache scanning (atstart or never)?
424
425 =item shell
426
427 What is your favorite shell?
428
429 =item show_unparsable_versions
430
431 During the 'r' command CPAN.pm finds modules without version number.
432 When the command finishes, it prints a report about this. If you
433 want this report to be very verbose, say yes to the following
434 variable.
435
436 Show all individual modules that have no $VERSION?
437
438 =item show_upload_date
439
440 The 'd' and the 'm' command normally only show you information they
441 have in their in-memory database and thus will never connect to the
442 internet. If you set the 'show_upload_date' variable to true, 'm' and
443 'd' will additionally show you the upload date of the module or
444 distribution. Per default this feature is off because it may require a
445 net connection to get at the upload date.
446
447 Always try to show upload date with 'd' and 'm' command (yes/no)?
448
449 =item show_zero_versions
450
451 During the 'r' command CPAN.pm finds modules with a version number of
452 zero. When the command finishes, it prints a report about this. If you
453 want this report to be very verbose, say yes to the following
454 variable.
455
456 Show all individual modules that have a $VERSION of zero?
457
458 =item tar_verbosity
459
460 When CPAN.pm uses the tar command, which switch for the verbosity
461 shall be used? Choose 'none' for quiet operation, 'v' for file
462 name listing, 'vv' for full listing.
463
464 Tar command verbosity level (none or v or vv)?
465
466 =item term_is_latin
467
468 The next option deals with the charset (aka character set) your
469 terminal supports. In general, CPAN is English speaking territory, so
470 the charset does not matter much but some CPAN have names that are
471 outside the ASCII range. If your terminal supports UTF-8, you should
472 say no to the next question. If it expects ISO-8859-1 (also known as
473 LATIN1) then you should say yes. If it supports neither, your answer
474 does not matter because you will not be able to read the names of some
475 authors anyway. If you answer no, names will be output in UTF-8.
476
477 Your terminal expects ISO-8859-1 (yes/no)?
478
479 =item term_ornaments
480
481 When using Term::ReadLine, you can turn ornaments on so that your
482 input stands out against the output from CPAN.pm.
483
484 Do you want to turn ornaments on?
485
486 =item test_report
487
488 The goal of the CPAN Testers project (http://testers.cpan.org/) is to
489 test as many CPAN packages as possible on as many platforms as
490 possible.  This provides valuable feedback to module authors and
491 potential users to identify bugs or platform compatibility issues and
492 improves the overall quality and value of CPAN.
493
494 One way you can contribute is to send test results for each module
495 that you install.  If you install the CPAN::Reporter module, you have
496 the option to automatically generate and email test reports to CPAN
497 Testers whenever you run tests on a CPAN package.
498
499 See the CPAN::Reporter documentation for additional details and
500 configuration settings.  If your firewall blocks outgoing email,
501 you will need to configure CPAN::Reporter before sending reports.
502
503 Email test reports if CPAN::Reporter is installed (yes/no)?
504
505 =item perl5lib_verbosity
506
507 When CPAN.pm extends @INC via PERL5LIB, it prints a list of
508 directories added (or a summary of how many directories are
509 added).  Choose 'v' to get this message, 'none' to suppress it.
510
511 Verbosity level for PERL5LIB changes (none or v)?
512
513 =item trust_test_report_history
514
515 When a distribution has already been tested by CPAN::Reporter on
516 this machine, CPAN can skip the test phase and just rely on the
517 test report history instead.
518
519 Note that this will not apply to distributions that failed tests
520 because of missing dependencies.  Also, tests can be run
521 regardless of the history using "force".
522
523 Do you want to rely on the test report history (yes/no)?
524
525 =item use_sqlite
526
527 CPAN::SQLite is a layer between the index files that are downloaded
528 from the CPAN and CPAN.pm that speeds up metadata queries and reduces
529 memory consumption of CPAN.pm considerably.
530
531 Use CPAN::SQLite if available? (yes/no)?
532
533 =item version_timeout
534
535 This timeout prevents CPAN from hanging when trying to parse a
536 pathologically coded $VERSION from a module.
537
538 The default is 15 seconds.  If you set this value to 0, no timeout
539 will occur, but this is not recommended.
540
541 Timeout for parsing module versions?
542
543 =item yaml_load_code
544
545 Both YAML.pm and YAML::Syck are capable of deserialising code. As this
546 requires a string eval, which might be a security risk, you can use
547 this option to enable or disable the deserialisation of code via
548 CPAN::DeferredCode. (Note: This does not work under perl 5.6)
549
550 Do you want to enable code deserialisation (yes/no)?
551
552 =item yaml_module
553
554 At the time of this writing (2009-03) there are three YAML
555 implementations working: YAML, YAML::Syck, and YAML::XS. The latter
556 two are faster but need a C compiler installed on your system. There
557 may be more alternative YAML conforming modules. When I tried two
558 other players, YAML::Tiny and YAML::Perl, they seemed not powerful
559 enough to work with CPAN.pm. This may have changed in the meantime.
560
561 Which YAML implementation would you prefer?
562
563 =back
564
565 =head1 LICENSE
566
567 This program is free software; you can redistribute it and/or
568 modify it under the same terms as Perl itself.
569
570 =cut
571
572 use vars qw( %prompts );
573
574 {
575
576     my @prompts = (
577
578 manual_config => qq[
579 CPAN is the world-wide archive of perl resources. It consists of about
580 300 sites that all replicate the same contents around the globe. Many
581 countries have at least one CPAN site already. The resources found on
582 CPAN are easily accessible with the CPAN.pm module. If you want to use
583 CPAN.pm, lots of things have to be configured. Fortunately, most of
584 them can be determined automatically. If you prefer the automatic
585 configuration, answer 'yes' below.
586
587 If you prefer to enter a dialog instead, you can answer 'no' to this
588 question and I'll let you configure in small steps one thing after the
589 other. (Note: you can revisit this dialog anytime later by typing 'o
590 conf init' at the cpan prompt.)
591
592 ],
593
594 auto_pick => qq{
595 Would you like me to automatically choose the best CPAN mirror
596 sites for you? (This means connecting to the Internet and could
597 take a couple minutes)},
598
599 config_intro => qq{
600
601 The following questions are intended to help you with the
602 configuration. The CPAN module needs a directory of its own to cache
603 important index files and maybe keep a temporary mirror of CPAN files.
604 This may be a site-wide or a personal directory.
605
606 },
607
608 # cpan_home => qq{ },
609
610 cpan_home_where => qq{
611
612 First of all, I'd like to create this directory. Where?
613
614 },
615
616 external_progs => qq{
617
618 The CPAN module will need a few external programs to work properly.
619 Please correct me, if I guess the wrong path for a program. Don't
620 panic if you do not have some of them, just press ENTER for those. To
621 disable the use of a program, you can type a space followed by ENTER.
622
623 },
624
625 proxy_intro => qq{
626
627 If you're accessing the net via proxies, you can specify them in the
628 CPAN configuration or via environment variables. The variable in
629 the \$CPAN::Config takes precedence.
630
631 },
632
633 proxy_user => qq{
634
635 If your proxy is an authenticating proxy, you can store your username
636 permanently. If you do not want that, just press RETURN. You will then
637 be asked for your username in every future session.
638
639 },
640
641 proxy_pass => qq{
642
643 Your password for the authenticating proxy can also be stored
644 permanently on disk. If this violates your security policy, just press
645 RETURN. You will then be asked for the password in every future
646 session.
647
648 },
649
650 urls_intro => qq{
651 Now you need to choose your CPAN mirror sites.  You can let me
652 pick mirrors for you, you can select them from a list or you
653 can enter them by hand.
654 },
655
656 urls_picker_intro => qq{First, pick a nearby continent and country by typing in the number(s)
657 in front of the item(s) you want to select. You can pick several of
658 each, separated by spaces. Then, you will be presented with a list of
659 URLs of CPAN mirrors in the countries you selected, along with
660 previously selected URLs. Select some of those URLs, or just keep the
661 old list. Finally, you will be prompted for any extra URLs -- file:,
662 ftp:, or http: -- that host a CPAN mirror.
663
664 You should select more than one (just in case the first isn't available).
665
666 },
667
668 password_warn => qq{
669
670 Warning: Term::ReadKey seems not to be available, your password will
671 be echoed to the terminal!
672
673 },
674
675               );
676
677     die "Coding error in \@prompts declaration.  Odd number of elements, above"
678         if (@prompts % 2);
679
680     %prompts = @prompts;
681
682     if (scalar(keys %prompts) != scalar(@prompts)/2) {
683         my %already;
684         for my $item (0..$#prompts) {
685             next if $item % 2;
686             die "$prompts[$item] is duplicated\n" if $already{$prompts[$item]}++;
687         }
688     }
689
690     shift @podpara;
691     while (@podpara) {
692         warn "Alert: cannot parse my own manpage for init dialog" unless $podpara[0] =~ s/^=item\s+//;
693         my $name = shift @podpara;
694         my @para;
695         while (@podpara && $podpara[0] !~ /^=item/) {
696             push @para, shift @podpara;
697         }
698         $prompts{$name} = pop @para;
699         if (@para) {
700             $prompts{$name . "_intro"} = join "", map { "$_\n\n" } @para;
701         }
702     }
703
704 }
705
706 sub init {
707     my($configpm, %args) = @_;
708     use Config;
709     # extra args after 'o conf init'
710     my $matcher = $args{args} && @{$args{args}} ? $args{args}[0] : '';
711     if ($matcher =~ /^\/(.*)\/$/) {
712         # case /regex/ => take the first, ignore the rest
713         $matcher = $1;
714         shift @{$args{args}};
715         if (@{$args{args}}) {
716             local $" = " ";
717             $CPAN::Frontend->mywarn("Ignoring excessive arguments '@{$args{args}}'");
718             $CPAN::Frontend->mysleep(2);
719         }
720     } elsif (0 == length $matcher) {
721     } elsif (0 && $matcher eq "~") { # extremely buggy, but a nice idea
722         my @unconfigured = grep { not exists $CPAN::Config->{$_}
723                                       or not defined $CPAN::Config->{$_}
724                                           or not length $CPAN::Config->{$_}
725                                   } keys %$CPAN::Config;
726         $matcher = "\\b(".join("|", @unconfigured).")\\b";
727         $CPAN::Frontend->mywarn("matcher[$matcher]");
728     } else {
729         # case WORD... => all arguments must be valid
730         for my $arg (@{$args{args}}) {
731             unless (exists $CPAN::HandleConfig::keys{$arg}) {
732                 $CPAN::Frontend->mywarn("'$arg' is not a valid configuration variable\n");
733                 return;
734             }
735         }
736         $matcher = "\\b(".join("|",@{$args{args}}).")\\b";
737     }
738     CPAN->debug("matcher[$matcher]") if $CPAN::DEBUG;
739
740     unless ($CPAN::VERSION) {
741         require CPAN::Nox;
742     }
743     require CPAN::HandleConfig;
744     CPAN::HandleConfig::require_myconfig_or_config();
745     $CPAN::Config ||= {};
746     local($/) = "\n";
747     local($\) = "";
748     local($|) = 1;
749
750     my($ans,$default); # why so half global?
751
752     #
753     #= Files, directories
754     #
755
756     unless ($matcher) {
757         $CPAN::Frontend->myprint($prompts{manual_config});
758     }
759
760     my $manual_conf;
761
762     local *_real_prompt;
763     if ( $args{autoconfig} ) {
764         $manual_conf = "no";
765     } elsif ($matcher) {
766         $manual_conf = "yes";
767     } else {
768         my $_conf = prompt("Would you like me to configure as much as possible ".
769                            "automatically?", "yes");
770         $manual_conf = ($_conf and $_conf =~ /^y/i) ? "no" : "yes";
771     }
772     CPAN->debug("manual_conf[$manual_conf]") if $CPAN::DEBUG;
773     my $fastread;
774     {
775         if ($manual_conf =~ /^y/i) {
776             $fastread = 0;
777         } else {
778             $fastread = 1;
779             $silent = 1;
780             $CPAN::Config->{urllist} ||= [];
781             $CPAN::Config->{connect_to_internet_ok} ||= 1;
782
783             local $^W = 0;
784             # prototype should match that of &MakeMaker::prompt
785             my $current_second = time;
786             my $current_second_count = 0;
787             my $i_am_mad = 0;
788             # silent prompting -- just quietly use default
789             *_real_prompt = sub { return $_[1] };
790         }
791     }
792
793     if (!$matcher or q{
794                        build_dir
795                        build_dir_reuse
796                        cpan_home
797                        keep_source_where
798                        prefs_dir
799                       } =~ /$matcher/) {
800         $CPAN::Frontend->myprint($prompts{config_intro}) unless $silent;
801
802         init_cpan_home($matcher);
803
804         my_dflt_prompt("keep_source_where",
805                        File::Spec->catdir($CPAN::Config->{cpan_home},"sources"),
806                        $matcher,
807                       );
808         my_dflt_prompt("build_dir",
809                        File::Spec->catdir($CPAN::Config->{cpan_home},"build"),
810                        $matcher
811                       );
812         my_yn_prompt(build_dir_reuse => 0, $matcher);
813         my_dflt_prompt("prefs_dir",
814                        File::Spec->catdir($CPAN::Config->{cpan_home},"prefs"),
815                        $matcher
816                       );
817     }
818
819     #
820     #= Config: auto_commit
821     #
822
823     my_yn_prompt(auto_commit => 0, $matcher);
824
825     #
826     #= Cache size, Index expire
827     #
828     my_dflt_prompt(build_cache => 100, $matcher);
829
830     my_dflt_prompt(index_expire => 1, $matcher);
831     my_prompt_loop(scan_cache => 'atstart', $matcher, 'atstart|never');
832
833     #
834     #= cache_metadata
835     #
836
837     my_yn_prompt(cache_metadata => 1, $matcher);
838     my_yn_prompt(use_sqlite => 0, $matcher);
839
840     #
841     #= Do we follow PREREQ_PM?
842     #
843
844     my_prompt_loop(prerequisites_policy => 'ask', $matcher,
845                    'follow|ask|ignore');
846     my_prompt_loop(build_requires_install_policy => 'ask/yes', $matcher,
847                    'yes|no|ask/yes|ask/no');
848
849     #
850     #= Module::Signature
851     #
852     my_yn_prompt(check_sigs => 0, $matcher);
853
854     #
855     #= CPAN::Reporter
856     #
857     if (!$matcher or 'test_report' =~ /$matcher/) {
858         my_yn_prompt(test_report => 0, $matcher);
859         if (
860             $CPAN::Config->{test_report} &&
861             $CPAN::META->has_inst("CPAN::Reporter") &&
862             CPAN::Reporter->can('configure')
863            ) {
864             local *_real_prompt;
865             *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt;
866             my $_conf = prompt("Would you like me configure CPAN::Reporter now?", $silent ? "no" : "yes");
867             if ($_conf =~ /^y/i) {
868               $CPAN::Frontend->myprint("\nProceeding to configure CPAN::Reporter.\n");
869               CPAN::Reporter::configure();
870               $CPAN::Frontend->myprint("\nReturning to CPAN configuration.\n");
871             }
872         }
873     }
874
875     my_yn_prompt(trust_test_report_history => 0, $matcher);
876
877     #
878     #= YAML vs. YAML::Syck
879     #
880     if (!$matcher or "yaml_module" =~ /$matcher/) {
881         my_dflt_prompt(yaml_module => "YAML", $matcher);
882         my $old_v = $CPAN::Config->{load_module_verbosity};
883         $CPAN::Config->{load_module_verbosity} = q[none];
884         unless ($CPAN::META->has_inst($CPAN::Config->{yaml_module})) {
885             $CPAN::Frontend->mywarn
886                 ("Warning (maybe harmless): '$CPAN::Config->{yaml_module}' not installed.\n");
887             $CPAN::Frontend->mysleep(3);
888         }
889         $CPAN::Config->{load_module_verbosity} = $old_v;
890     }
891
892     #
893     #= YAML code deserialisation
894     #
895     my_yn_prompt(yaml_load_code => 0, $matcher);
896
897     #
898     #= External programs
899     #
900     my(@path) = split /$Config{'path_sep'}/, $ENV{'PATH'};
901     _init_external_progs($matcher,\@path);
902
903     {
904         my $path = $CPAN::Config->{'pager'} ||
905             $ENV{PAGER} || find_exe("less",\@path) ||
906                 find_exe("more",\@path) || ($^O eq 'MacOS' ? $ENV{EDITOR} : 0 )
907                     || "more";
908         my_dflt_prompt(pager => $path, $matcher);
909     }
910
911     {
912         my $path = $CPAN::Config->{'shell'};
913         if ($path && File::Spec->file_name_is_absolute($path)) {
914             $CPAN::Frontend->mywarn("Warning: configured $path does not exist\n")
915                 unless -e $path;
916             $path = "";
917         }
918         $path ||= $ENV{SHELL};
919         $path ||= $ENV{COMSPEC} if $^O eq "MSWin32";
920         if ($^O eq 'MacOS') {
921             $CPAN::Config->{'shell'} = 'not_here';
922         } else {
923             $path ||= 'sh', $path =~ s,\\,/,g if $^O eq 'os2'; # Cosmetic only
924             my_dflt_prompt(shell => $path, $matcher);
925         }
926     }
927
928     #
929     # verbosity
930     #
931
932     my_prompt_loop(tar_verbosity => 'v', $matcher,
933                    'none|v|vv');
934     my_prompt_loop(load_module_verbosity => 'none', $matcher,
935                    'none|v');
936     my_prompt_loop(perl5lib_verbosity => 'v', $matcher,
937                    'none|v');
938     my_yn_prompt(inhibit_startup_message => 0, $matcher);
939
940     #
941     #= Installer, arguments to make etc.
942     #
943
944     my_prompt_loop(prefer_installer => 'MB', $matcher, 'MB|EUMM|RAND');
945
946     if (!$matcher or 'makepl_arg make_arg' =~ /$matcher/) {
947         my_dflt_prompt(makepl_arg => "", $matcher);
948         my_dflt_prompt(make_arg => "", $matcher);
949         if ( $CPAN::Config->{makepl_arg} =~ /LIBS=|INC=/ ) {
950             $CPAN::Frontend->mywarn( 
951                 "Warning: Using LIBS or INC in makepl_arg will likely break distributions\n" . 
952                 "that specify their own LIBS or INC options in Makefile.PL.\n"
953             );
954         }
955
956     }
957
958     require CPAN::HandleConfig;
959     if (exists $CPAN::HandleConfig::keys{make_install_make_command}) {
960         # as long as Windows needs $self->_build_command, we cannot
961         # support sudo on windows :-)
962         my_dflt_prompt(make_install_make_command => $CPAN::Config->{make} || "",
963                        $matcher);
964     }
965
966     my_dflt_prompt(make_install_arg => $CPAN::Config->{make_arg} || "",
967                    $matcher);
968
969     my_dflt_prompt(mbuildpl_arg => "", $matcher);
970     my_dflt_prompt(mbuild_arg => "", $matcher);
971
972     if (exists $CPAN::HandleConfig::keys{mbuild_install_build_command}
973         and $^O ne "MSWin32") {
974         # as long as Windows needs $self->_build_command, we cannot
975         # support sudo on windows :-)
976         my_dflt_prompt(mbuild_install_build_command => "./Build", $matcher);
977     }
978
979     my_dflt_prompt(mbuild_install_arg => "", $matcher);
980
981     #
982     #= Alarm period
983     #
984
985     my_dflt_prompt(inactivity_timeout => 0, $matcher);
986     my_dflt_prompt(version_timeout => 15, $matcher);
987
988     #
989     #== halt_on_failure
990     #
991     my_yn_prompt(halt_on_failure => 0, $matcher);
992
993     #
994     #= Proxies
995     #
996
997     my @proxy_vars = qw/ftp_proxy http_proxy no_proxy/;
998     my @proxy_user_vars = qw/proxy_user proxy_pass/;
999     if (!$matcher or "@proxy_vars @proxy_user_vars" =~ /$matcher/) {
1000         $CPAN::Frontend->myprint($prompts{proxy_intro}) unless $silent;
1001
1002         for (@proxy_vars) {
1003             $prompts{$_} = "Your $_?";
1004             my_dflt_prompt($_ => $ENV{$_}||"", $matcher);
1005         }
1006
1007         if ($CPAN::Config->{ftp_proxy} ||
1008             $CPAN::Config->{http_proxy}) {
1009
1010             $default = $CPAN::Config->{proxy_user} || $CPAN::LWP::UserAgent::USER || "";
1011
1012             $CPAN::Frontend->myprint($prompts{proxy_user}) unless $silent;
1013
1014             if ($CPAN::Config->{proxy_user} = prompt("Your proxy user id?",$default)) {
1015                 $CPAN::Frontend->myprint($prompts{proxy_pass}) unless $silent;
1016
1017                 if ($CPAN::META->has_inst("Term::ReadKey")) {
1018                     Term::ReadKey::ReadMode("noecho");
1019                 } else {
1020                     $CPAN::Frontend->myprint($prompts{password_warn}) unless $silent;
1021                 }
1022                 $CPAN::Config->{proxy_pass} = prompt_no_strip("Your proxy password?");
1023                 if ($CPAN::META->has_inst("Term::ReadKey")) {
1024                     Term::ReadKey::ReadMode("restore");
1025                 }
1026                 $CPAN::Frontend->myprint("\n\n") unless $silent;
1027             }
1028         }
1029     }
1030
1031     #
1032     #= how FTP works
1033     #
1034
1035     my_yn_prompt(ftp_passive => 1, $matcher);
1036
1037     #
1038     #= how cwd works
1039     #
1040
1041     my_prompt_loop(getcwd => 'cwd', $matcher,
1042                    'cwd|getcwd|fastcwd|backtickcwd');
1043
1044     #
1045     #= the CPAN shell itself (prompt, color)
1046     #
1047
1048     my_yn_prompt(commandnumber_in_prompt => 1, $matcher);
1049     my_yn_prompt(term_ornaments => 1, $matcher);
1050     if ("colorize_output colorize_print colorize_warn colorize_debug" =~ $matcher) {
1051         my_yn_prompt(colorize_output => 0, $matcher);
1052         if ($CPAN::Config->{colorize_output}) {
1053             if ($CPAN::META->has_inst("Term::ANSIColor")) {
1054                 my $T="gYw";
1055                 $CPAN::Frontend->myprint( "                                      on_  on_y ".
1056                     "        on_ma           on_\n") unless $silent;
1057                 $CPAN::Frontend->myprint( "                   on_black on_red  green ellow ".
1058                     "on_blue genta on_cyan white\n") unless $silent;
1059
1060                 for my $FG ("", "bold",
1061                             map {$_,"bold $_"} "black","red","green",
1062                             "yellow","blue",
1063                             "magenta",
1064                             "cyan","white") {
1065                     $CPAN::Frontend->myprint(sprintf( "%12s ", $FG)) unless $silent;
1066                     for my $BG ("",map {"on_$_"} qw(black red green yellow
1067                                                     blue magenta cyan white)) {
1068                             $CPAN::Frontend->myprint( $FG||$BG ?
1069                             Term::ANSIColor::colored("  $T  ","$FG $BG") : "  $T  ") unless $silent;
1070                     }
1071                     $CPAN::Frontend->myprint( "\n" ) unless $silent;
1072                 }
1073                 $CPAN::Frontend->myprint( "\n" ) unless $silent;
1074             }
1075             for my $tuple (
1076                            ["colorize_print", "bold blue on_white"],
1077                            ["colorize_warn", "bold red on_white"],
1078                            ["colorize_debug", "black on_cyan"],
1079                           ) {
1080                 my_dflt_prompt($tuple->[0] => $tuple->[1], $matcher);
1081                 if ($CPAN::META->has_inst("Term::ANSIColor")) {
1082                     eval { Term::ANSIColor::color($CPAN::Config->{$tuple->[0]})};
1083                     if ($@) {
1084                         $CPAN::Config->{$tuple->[0]} = $tuple->[1];
1085                         $CPAN::Frontend->mywarn($@."setting to default '$tuple->[1]'\n");
1086                     }
1087                 }
1088             }
1089         }
1090     }
1091
1092     #
1093     #== term_is_latin
1094     #
1095
1096     my_yn_prompt(term_is_latin => 1, $matcher);
1097
1098     #
1099     #== save history in file 'histfile'
1100     #
1101
1102     if (!$matcher or 'histfile histsize' =~ /$matcher/) {
1103         $CPAN::Frontend->myprint($prompts{histfile_intro}) unless $silent;
1104         defined($default = $CPAN::Config->{histfile}) or
1105             $default = File::Spec->catfile($CPAN::Config->{cpan_home},"histfile");
1106         my_dflt_prompt(histfile => $default, $matcher);
1107
1108         if ($CPAN::Config->{histfile}) {
1109             defined($default = $CPAN::Config->{histsize}) or $default = 100;
1110             my_dflt_prompt(histsize => $default, $matcher);
1111         }
1112     }
1113
1114     #
1115     #== do an ls on the m or the d command
1116     #
1117     my_yn_prompt(show_upload_date => 0, $matcher);
1118
1119     #
1120     #== verbosity at the end of the r command
1121     #
1122     if (!$matcher
1123         or 'show_unparsable_versions' =~ /$matcher/
1124         or 'show_zero_versions' =~ /$matcher/
1125        ) {
1126         $CPAN::Frontend->myprint($prompts{show_unparsable_or_zero_versions_intro});
1127         my_yn_prompt(show_unparsable_versions => 0, $matcher);
1128         my_yn_prompt(show_zero_versions => 0, $matcher);
1129     }
1130
1131     #
1132     #= MIRRORED.BY and conf_sites()
1133     #
1134
1135     # remember, this is only triggered if no urllist is given, so 0 is
1136     # fair and protects the default site from being overloaded and
1137     # gives the user more chances to select his own urllist.
1138     my_yn_prompt("connect_to_internet_ok" => $fastread ? 1 : 0, $matcher);
1139     $CPAN::Config->{urllist} ||= [];
1140     if ($matcher) {
1141         if ("urllist" =~ $matcher) {
1142             $CPAN::Frontend->myprint($prompts{urls_intro});
1143
1144             # conf_sites would go into endless loop with the smash prompt
1145             local *_real_prompt;
1146             *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt;
1147             my $_conf = prompt($prompts{auto_pick}, "yes");
1148
1149             if ( $_conf =~ /^y/i ) {
1150               conf_sites( auto_pick => 1 ) or bring_your_own();
1151             }
1152             else {
1153               my $_conf = prompt(
1154                 "Would you like to pick from the CPAN mirror list?", "yes"
1155               );
1156
1157               if ( $_conf =~ /^y/i ) {
1158                 conf_sites();
1159               }
1160               bring_your_own();
1161             }
1162             _print_urllist();
1163         }
1164         if ("randomize_urllist" =~ $matcher) {
1165             my_dflt_prompt(randomize_urllist => 0, $matcher);
1166         }
1167         if ("ftpstats_size" =~ $matcher) {
1168             my_dflt_prompt(ftpstats_size => 99, $matcher);
1169         }
1170         if ("ftpstats_period" =~ $matcher) {
1171             my_dflt_prompt(ftpstats_period => 14, $matcher);
1172         }
1173     } elsif ($fastread) {
1174         $silent = 0;
1175         local *_real_prompt;
1176         *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt;
1177         if ( @{ $CPAN::Config->{urllist} } ) {
1178             $CPAN::Frontend->myprint(
1179               "\nYour 'urllist' is already configured. Type 'o conf init urllist' to change it.\n"
1180             );
1181         }
1182         else {
1183           $CPAN::Frontend->myprint(
1184             "Autoconfigured everything but 'urllist'.\n"
1185           );
1186
1187           $CPAN::Frontend->myprint($prompts{urls_intro});
1188
1189           my $_conf = prompt($prompts{auto_pick}, "yes");
1190
1191           if ( $_conf =~ /^y/i ) {
1192             conf_sites( auto_pick => 1 ) or bring_your_own();
1193           }
1194           else {
1195             my $_conf = prompt(
1196               "Would you like to pick from the CPAN mirror list?", "yes"
1197             );
1198
1199             if ( $_conf =~ /^y/i ) {
1200               conf_sites();
1201             }
1202             bring_your_own();
1203           }
1204           _print_urllist();
1205         }
1206         $CPAN::Frontend->myprint(
1207             "\nAutoconfiguration complete.\n"
1208         );
1209     }
1210
1211     $silent = 0; # reset
1212
1213     $CPAN::Frontend->myprint("\n");
1214     if ($matcher && !$CPAN::Config->{auto_commit}) {
1215         $CPAN::Frontend->myprint("Please remember to call 'o conf commit' to ".
1216                                  "make the config permanent!\n");
1217     } else {
1218         CPAN::HandleConfig->commit($configpm);
1219     }
1220 }
1221
1222 sub _init_external_progs {
1223     my($matcher,$PATH) = @_;
1224     my @external_progs = qw/bzip2 gzip tar unzip
1225
1226                             make
1227
1228                             curl lynx wget ncftpget ncftp ftp
1229
1230                             gpg
1231
1232                             patch applypatch
1233                             /;
1234     if (!$matcher or "@external_progs" =~ /$matcher/) {
1235         $CPAN::Frontend->myprint($prompts{external_progs}) unless $silent;
1236
1237         my $old_warn = $^W;
1238         local $^W if $^O eq 'MacOS';
1239         local $^W = $old_warn;
1240         my $progname;
1241         for $progname (@external_progs) {
1242             next if $matcher && $progname !~ /$matcher/;
1243             if ($^O eq 'MacOS') {
1244                 $CPAN::Config->{$progname} = 'not_here';
1245                 next;
1246             }
1247
1248             my $progcall = $progname;
1249             unless ($matcher) {
1250                 # we really don't need ncftp if we have ncftpget, but
1251                 # if they chose this dialog via matcher, they shall have it
1252                 next if $progname eq "ncftp" && $CPAN::Config->{ncftpget} gt " ";
1253             }
1254             my $path = $CPAN::Config->{$progname}
1255                 || $Config::Config{$progname}
1256                     || "";
1257             if (File::Spec->file_name_is_absolute($path)) {
1258                 # testing existence is not good enough, some have these exe
1259                 # extensions
1260
1261                 # warn "Warning: configured $path does not exist\n" unless -e $path;
1262                 # $path = "";
1263             } elsif ($path =~ /^\s+$/) {
1264                 # preserve disabled programs
1265             } else {
1266                 $path = '';
1267             }
1268             unless ($path) {
1269                 # e.g. make -> nmake
1270                 $progcall = $Config::Config{$progname} if $Config::Config{$progname};
1271             }
1272
1273             $path ||= find_exe($progcall,$PATH);
1274             unless ($path) { # not -e $path, because find_exe already checked that
1275                 local $"=";";
1276                 $CPAN::Frontend->mywarn("Warning: $progcall not found in PATH[@$PATH]\n") unless $silent;
1277                 if ($progname eq "make") {
1278                     $CPAN::Frontend->mywarn("ALERT: 'make' is an essential tool for ".
1279                                             "building perl Modules. Please make sure you ".
1280                                             "have 'make' (or some equivalent) ".
1281                                             "working.\n"
1282                                            );
1283                     if ($^O eq "MSWin32") {
1284                         $CPAN::Frontend->mywarn("
1285 Windows users may want to follow this procedure when back in the CPAN shell:
1286
1287     look YVES/scripts/alien_nmake.pl
1288     perl alien_nmake.pl
1289
1290 This will install nmake on your system which can be used as a 'make'
1291 substitute. You can then revisit this dialog with
1292
1293     o conf init make
1294
1295 ");
1296                     }
1297                 }
1298             }
1299             $prompts{$progname} = "Where is your $progname program?";
1300             my_dflt_prompt($progname,$path,$matcher);
1301         }
1302     }
1303 }
1304
1305 sub init_cpan_home {
1306     my($matcher) = @_;
1307     if (!$matcher or 'cpan_home' =~ /$matcher/) {
1308         my $cpan_home = $CPAN::Config->{cpan_home}
1309             || File::Spec->catdir(CPAN::HandleConfig::home(), ".cpan");
1310
1311         if (-d $cpan_home) {
1312             $CPAN::Frontend->myprint(qq{
1313
1314 I see you already have a  directory
1315     $cpan_home
1316 Shall we use it as the general CPAN build and cache directory?
1317
1318 }) unless $silent;
1319         } else {
1320             # no cpan-home, must prompt and get one
1321             $CPAN::Frontend->myprint($prompts{cpan_home_where}) unless $silent;
1322         }
1323
1324         my $default = $cpan_home;
1325         my $loop = 0;
1326         my($last_ans,$ans);
1327         $CPAN::Frontend->myprint(" <cpan_home>\n") unless $silent;
1328     PROMPT: while ($ans = prompt("CPAN build and cache directory?",$default)) {
1329             if (File::Spec->file_name_is_absolute($ans)) {
1330                 my @cpan_home = split /[\/\\]/, $ans;
1331             DIR: for my $dir (@cpan_home) {
1332                     if ($dir =~ /^~/ and (!$last_ans or $ans ne $last_ans)) {
1333                         $CPAN::Frontend
1334                             ->mywarn("Warning: a tilde in the path will be ".
1335                                      "taken as a literal tilde. Please ".
1336                                      "confirm again if you want to keep it\n");
1337                         $last_ans = $default = $ans;
1338                         next PROMPT;
1339                     }
1340                 }
1341             } else {
1342                 require Cwd;
1343                 my $cwd = Cwd::cwd();
1344                 my $absans = File::Spec->catdir($cwd,$ans);
1345                 $CPAN::Frontend->mywarn("The path '$ans' is not an ".
1346                                         "absolute path. Please specify ".
1347                                         "an absolute path\n");
1348                 $default = $absans;
1349                 next PROMPT;
1350             }
1351             eval { File::Path::mkpath($ans); }; # dies if it can't
1352             if ($@) {
1353                 $CPAN::Frontend->mywarn("Couldn't create directory $ans.\n".
1354                                         "Please retry.\n");
1355                 next PROMPT;
1356             }
1357             if (-d $ans && -w _) {
1358                 last PROMPT;
1359             } else {
1360                 $CPAN::Frontend->mywarn("Couldn't find directory $ans\n".
1361                                         "or directory is not writable. Please retry.\n");
1362                 if (++$loop > 5) {
1363                     $CPAN::Frontend->mydie("Giving up");
1364                 }
1365             }
1366         }
1367         $CPAN::Config->{cpan_home} = $ans;
1368     }
1369 }
1370
1371 sub my_dflt_prompt {
1372     my ($item, $dflt, $m) = @_;
1373     my $default = $CPAN::Config->{$item} || $dflt;
1374
1375     if (!$silent && (!$m || $item =~ /$m/)) {
1376         if (my $intro = $prompts{$item . "_intro"}) {
1377             $CPAN::Frontend->myprint($intro);
1378         }
1379         $CPAN::Frontend->myprint(" <$item>\n");
1380         $CPAN::Config->{$item} = prompt($prompts{$item}, $default);
1381     } else {
1382         $CPAN::Config->{$item} = $default;
1383     }
1384 }
1385
1386 sub my_yn_prompt {
1387     my ($item, $dflt, $m) = @_;
1388     my $default;
1389     defined($default = $CPAN::Config->{$item}) or $default = $dflt;
1390
1391     # $DB::single = 1;
1392     if (!$silent && (!$m || $item =~ /$m/)) {
1393         if (my $intro = $prompts{$item . "_intro"}) {
1394             $CPAN::Frontend->myprint($intro);
1395         }
1396         $CPAN::Frontend->myprint(" <$item>\n");
1397         my $ans = prompt($prompts{$item}, $default ? 'yes' : 'no');
1398         $CPAN::Config->{$item} = ($ans =~ /^[y1]/i ? 1 : 0);
1399     } else {
1400         $CPAN::Config->{$item} = $default;
1401     }
1402 }
1403
1404 sub my_prompt_loop {
1405     my ($item, $dflt, $m, $ok) = @_;
1406     my $default = $CPAN::Config->{$item} || $dflt;
1407     my $ans;
1408
1409     if (!$silent && (!$m || $item =~ /$m/)) {
1410         $CPAN::Frontend->myprint($prompts{$item . "_intro"});
1411         $CPAN::Frontend->myprint(" <$item>\n");
1412         do { $ans = prompt($prompts{$item}, $default);
1413         } until $ans =~ /$ok/;
1414         $CPAN::Config->{$item} = $ans;
1415     } else {
1416         $CPAN::Config->{$item} = $default;
1417     }
1418 }
1419
1420
1421 # Here's the logic about the MIRRORED.BY file.  There are a number of scenarios:
1422 # (1) We have a cached MIRRORED.BY file
1423 #   (1a) We're auto-picking
1424 #       - Refresh it automatically if it's old
1425 #   (1b) Otherwise, ask if using cached is ok.  If old, default to no.
1426 #       - If cached is not ok, get it from the Internet. If it succeeds we use
1427 #         the new file.  Otherwise, we use the old file.
1428 # (2) We don't have a copy at all
1429 #   (2a) If we are allowed to connect, we try to get a new copy.  If it succeeds,
1430 #        we use it, otherwise, we warn about failure
1431 #   (2b) If we aren't allowed to connect, 
1432
1433 sub conf_sites {
1434     my %args = @_;
1435     # auto pick implies using the internet
1436     $CPAN::Config->{connect_to_internet_ok} = 1 if $args{auto_pick};
1437
1438     my $m = 'MIRRORED.BY';
1439     my $mby = File::Spec->catfile($CPAN::Config->{keep_source_where},$m);
1440     File::Path::mkpath(File::Basename::dirname($mby));
1441     # Why are we using MIRRORED.BY from the current directory?
1442     # Is this for testing? -- dagolden, 2009-11-05
1443     if (-f $mby && -f $m && -M $m < -M $mby) {
1444         require File::Copy;
1445         File::Copy::copy($m,$mby) or die "Could not update $mby: $!";
1446     }
1447     local $^T = time;
1448     # if we have a cached copy is not older than 60 days, we either
1449     # use it or refresh it or fall back to it if the refresh failed.
1450     if ($mby && -f $mby && -s _ > 0 ) {
1451       my $very_old = (-M $mby > 60);
1452       my $mtime = localtime((stat _)[9]);
1453       # if auto_pick, refresh anything old automatically
1454       if ( $args{auto_pick} ) {
1455         if ( $very_old ) {
1456           $CPAN::Frontend->myprint(qq{Trying to refresh your mirror list\n});
1457           eval { CPAN::FTP->localize($m,$mby,3,1) }
1458             or $CPAN::Frontend->myprint(qq{Refresh failed.  Using the old cached copy instead.\n});
1459           $CPAN::Frontend->myprint("\n");
1460         }
1461       }
1462       else {
1463         my $prompt = qq{Found a cached mirror list as of $mtime
1464
1465 If you'd like to just use the cached copy, answer 'yes', below.
1466 If you'd like an updated copy of the mirror list, answer 'no' and
1467 I'll get a fresh one from the Internet.
1468
1469 Shall I use the cached mirror list?};
1470         my $ans = prompt($prompt, $very_old ? "no" : "yes");
1471         if ($ans =~ /^n/i) {
1472           $CPAN::Frontend->myprint(qq{Trying to refresh your mirror list\n});
1473           # you asked for it from the Internet
1474           $CPAN::Config->{connect_to_internet_ok} = 1;
1475           eval { CPAN::FTP->localize($m,$mby,3,1) }
1476             or $CPAN::Frontend->myprint(qq{Refresh failed.  Using the old cached copy instead.\n});
1477           $CPAN::Frontend->myprint("\n");
1478         }
1479       }
1480     }
1481     # else there is no cached copy and we must fetch or fail
1482     else {
1483       # If they haven't agree to connect to the internet, ask again
1484       if ( ! $CPAN::Config->{connect_to_internet_ok} ) {
1485         my $prompt = q{You are missing a copy of the CPAN mirror list.
1486
1487 May I connect to the Internet to get it?};
1488         my $ans = prompt($prompt, "yes");
1489         if ($ans =~ /^y/i) {
1490           $CPAN::Config->{connect_to_internet_ok} = 1;
1491         }
1492       }
1493
1494       # Now get it from the Internet or complain
1495       if ( $CPAN::Config->{connect_to_internet_ok} ) {
1496         $CPAN::Frontend->myprint(qq{Trying to fetch a mirror list from the Internet\n});
1497         eval { CPAN::FTP->localize($m,$mby,3,1) }
1498           or $CPAN::Frontend->mywarn(<<'HERE');
1499 We failed to get a copy of the mirror list from the Internet.
1500 You will need to provide CPAN mirror URLs yourself.
1501 HERE
1502         $CPAN::Frontend->myprint("\n");
1503       }
1504       else {
1505         $CPAN::Frontend->mywarn(<<'HERE');
1506 You will need to provide CPAN mirror URLs yourself or set 
1507 'o conf connect_to_internet_ok 1' and try again.
1508 HERE
1509       }
1510     }
1511
1512     # if we finally have a good local MIRRORED.BY, get on with picking
1513     if (-f $mby && -s _ > 0){
1514         $CPAN::Config->{urllist} =
1515           $args{auto_pick} ? auto_mirrored_by($mby) : choose_mirrored_by($mby);
1516         return 1;
1517     }
1518
1519     return;
1520 }
1521
1522 sub find_exe {
1523     my($exe,$path) = @_;
1524     my($dir);
1525     #warn "in find_exe exe[$exe] path[@$path]";
1526     for $dir (@$path) {
1527         my $abs = File::Spec->catfile($dir,$exe);
1528         if (($abs = MM->maybe_command($abs))) {
1529             return $abs;
1530         }
1531     }
1532 }
1533
1534 sub picklist {
1535     my($items,$prompt,$default,$require_nonempty,$empty_warning)=@_;
1536     CPAN->debug("picklist('$items','$prompt','$default','$require_nonempty',".
1537                 "'$empty_warning')") if $CPAN::DEBUG;
1538     $default ||= '';
1539
1540     my $pos = 0;
1541
1542     my @nums;
1543   SELECTION: while (1) {
1544
1545         # display, at most, 15 items at a time
1546         my $limit = $#{ $items } - $pos;
1547         $limit = 15 if $limit > 15;
1548
1549         # show the next $limit items, get the new position
1550         $pos = display_some($items, $limit, $pos, $default);
1551         $pos = 0 if $pos >= @$items;
1552
1553         my $num = prompt($prompt,$default);
1554
1555         @nums = split (' ', $num);
1556         {
1557             my %seen;
1558             @nums = grep { !$seen{$_}++ } @nums;
1559         }
1560         my $i = scalar @$items;
1561         unrangify(\@nums);
1562         if (0 == @nums) {
1563             # cannot allow nothing because nothing means paging!
1564             # return;
1565         } elsif (grep (/\D/ || $_ < 1 || $_ > $i, @nums)) {
1566             $CPAN::Frontend->mywarn("invalid items entered, try again\n");
1567             if ("@nums" =~ /\D/) {
1568                 $CPAN::Frontend->mywarn("(we are expecting only numbers between 1 and $i)\n");
1569             }
1570             next SELECTION;
1571         }
1572         if ($require_nonempty && !@nums) {
1573             $CPAN::Frontend->mywarn("$empty_warning\n");
1574         }
1575
1576         # a blank line continues...
1577         unless (@nums){
1578             $CPAN::Frontend->mysleep(0.1); # prevent hot spinning process on the next bug
1579             next SELECTION;
1580         }
1581         last;
1582     }
1583     for (@nums) { $_-- }
1584     @{$items}[@nums];
1585 }
1586
1587 sub unrangify ($) {
1588     my($nums) = $_[0];
1589     my @nums2 = ();
1590     while (@{$nums||[]}) {
1591         my $n = shift @$nums;
1592         if ($n =~ /^(\d+)-(\d+)$/) {
1593             my @range = $1 .. $2;
1594             # warn "range[@range]";
1595             push @nums2, @range;
1596         } else {
1597             push @nums2, $n;
1598         }
1599     }
1600     push @$nums, @nums2;
1601 }
1602
1603 sub display_some {
1604     my ($items, $limit, $pos, $default) = @_;
1605     $pos ||= 0;
1606
1607     my @displayable = @$items[$pos .. ($pos + $limit)];
1608     for my $item (@displayable) {
1609         $CPAN::Frontend->myprint(sprintf "(%d) %s\n", ++$pos, $item);
1610     }
1611     my $hit_what = $default ? "SPACE RETURN" : "RETURN";
1612     $CPAN::Frontend->myprint(sprintf("%d more items, hit %s to show them\n",
1613                                      (@$items - $pos),
1614                                      $hit_what,
1615                                     ))
1616         if $pos < @$items;
1617     return $pos;
1618 }
1619
1620 sub auto_mirrored_by {
1621     my $local = shift or return;
1622     local $|=1;
1623     $CPAN::Frontend->myprint("Searching for the best CPAN mirrors (please be patient) ...");
1624     my $mirrors = CPAN::Mirrors->new($local);
1625     my $cnt = 0;
1626     my @best = $mirrors->best_mirrors(
1627       how_many => 5,
1628       callback => sub { $CPAN::Frontend->myprint(".") },
1629     );
1630     my $urllist = [ map { $_->ftp } @best ];
1631     push @$urllist, grep { /^file:/ } @{$CPAN::Config->{urllist}};
1632     $CPAN::Frontend->myprint(" done!\n\n");
1633     return $urllist;
1634 }
1635
1636 sub choose_mirrored_by {
1637     my $local = shift or return;
1638     my ($default);
1639     my $mirrors = CPAN::Mirrors->new($local);
1640     my @previous_urls = @{$CPAN::Config->{urllist}};
1641
1642     $CPAN::Frontend->myprint($prompts{urls_picker_intro});
1643
1644     my (@cont, $cont, %cont, @countries, @urls, %seen);
1645     my $no_previous_warn =
1646         "Sorry! since you don't have any existing picks, you must make a\n" .
1647             "geographic selection.";
1648     my $offer_cont = [sort $mirrors->continents];
1649     if (@previous_urls) {
1650         push @$offer_cont, "(edit previous picks)";
1651         $default = @$offer_cont;
1652     } else {
1653         # cannot allow nothing because nothing means paging!
1654         # push @$offer_cont, "(none of the above)";
1655     }
1656     @cont = picklist($offer_cont,
1657                      "Select your continent (or several nearby continents)",
1658                      $default,
1659                      ! @previous_urls,
1660                      $no_previous_warn);
1661     # cannot allow nothing because nothing means paging!
1662     # return unless @cont;
1663
1664     foreach $cont (@cont) {
1665         my @c = sort $mirrors->countries($cont);
1666         @cont{@c} = map ($cont, 0..$#c);
1667         @c = map ("$_ ($cont)", @c) if @cont > 1;
1668         push (@countries, @c);
1669     }
1670     if (@previous_urls && @countries) {
1671         push @countries, "(edit previous picks)";
1672         $default = @countries;
1673     }
1674
1675     if (@countries) {
1676         @countries = picklist (\@countries,
1677                                "Select your country (or several nearby countries)",
1678                                $default,
1679                                ! @previous_urls,
1680                                $no_previous_warn);
1681         %seen = map (($_ => 1), @previous_urls);
1682         # hmmm, should take list of defaults from CPAN::Config->{'urllist'}...
1683         foreach my $country (@countries) {
1684             next if $country =~ /edit previous picks/;
1685             (my $bare_country = $country) =~ s/ \(.*\)//;
1686             my @u;
1687             for my $m ( $mirrors->mirrors($bare_country) ) {
1688               push @u, $m->ftp if $m->ftp;
1689               push @u, $m->http if $m->http;
1690             }
1691             @u = grep (! $seen{$_}, @u);
1692             @u = map ("$_ ($bare_country)", @u)
1693                 if @countries > 1;
1694             push (@urls, sort @u);
1695         }
1696     }
1697     push (@urls, map ("$_ (previous pick)", @previous_urls));
1698     my $prompt = "Select as many URLs as you like (by number),
1699 put them on one line, separated by blanks, hyphenated ranges allowed
1700  e.g. '1 4 5' or '7 1-4 8'";
1701     if (@previous_urls) {
1702         $default = join (' ', ((scalar @urls) - (scalar @previous_urls) + 1) ..
1703                          (scalar @urls));
1704         $prompt .= "\n(or just hit RETURN to keep your previous picks)";
1705     }
1706
1707     @urls = picklist (\@urls, $prompt, $default);
1708     foreach (@urls) { s/ \(.*\)//; }
1709     return [ @urls ];
1710 }
1711
1712 sub bring_your_own {
1713     my $urllist = [ @{$CPAN::Config->{urllist}} ];
1714     my %seen = map (($_ => 1), @$urllist);
1715     my($ans,@urls);
1716     my $eacnt = 0; # empty answers
1717     $CPAN::Frontend->myprint(<<'HERE');
1718
1719 Now you can enter your own CPAN URLs by hand. A local CPAN mirror can be
1720 listed using a 'file:' URL like 'file:///path/to/cpan/'
1721
1722 HERE
1723     do {
1724         my $prompt = "Enter another URL or RETURN to quit:";
1725         unless (%seen) {
1726             $prompt = qq{CPAN.pm needs at least one URL where it can fetch CPAN files from.
1727
1728 Please enter your CPAN site:};
1729         }
1730         $ans = prompt ($prompt, "");
1731
1732         if ($ans) {
1733             $ans =~ s|/?\z|/|; # has to end with one slash
1734             # XXX This manipulation is odd.  Shouldn't we check that $ans is
1735             # a directory before converting to file:///?  And we need /// below,
1736             # too, don't we?  -- dagolden, 2009-11-05
1737             $ans = "file:$ans" unless $ans =~ /:/; # without a scheme is a file:
1738             if ($ans =~ /^\w+:\/./) {
1739                 push @urls, $ans unless $seen{$ans}++;
1740             } else {
1741                 $CPAN::Frontend->
1742                     myprint(sprintf(qq{"%s" doesn\'t look like an URL at first sight.
1743 I\'ll ignore it for now.
1744 You can add it to your %s
1745 later if you\'re sure it\'s right.\n},
1746                                    $ans,
1747                                    $INC{'CPAN/MyConfig.pm'}
1748                                    || $INC{'CPAN/Config.pm'}
1749                                    || "configuration file",
1750                                   ));
1751             }
1752         } else {
1753             if (++$eacnt >= 5) {
1754                 $CPAN::Frontend->
1755                     mywarn("Giving up.\n");
1756                 $CPAN::Frontend->mysleep(5);
1757                 return;
1758             }
1759         }
1760     } while $ans || !%seen;
1761
1762     @$urllist = CPAN::_uniq(@$urllist, @urls);
1763     $CPAN::Config->{urllist} = $urllist;
1764 }
1765
1766 sub _print_urllist {
1767     $CPAN::Frontend->myprint("New urllist\n");
1768     for ( @{$CPAN::Config->{urllist} || []} ) { 
1769       $CPAN::Frontend->myprint("  $_\n") 
1770     };
1771 }
1772
1773 sub _strip_spaces {
1774     $_[0] =~ s/^\s+//;  # no leading spaces
1775     $_[0] =~ s/\s+\z//; # no trailing spaces
1776 }
1777
1778 sub prompt ($;$) {
1779     unless (defined &_real_prompt) {
1780         *_real_prompt = \&CPAN::Shell::colorable_makemaker_prompt;
1781     }
1782     my $ans = _real_prompt(@_);
1783
1784     _strip_spaces($ans);
1785     $CPAN::Frontend->myprint("\n");
1786
1787     return $ans;
1788 }
1789
1790
1791 sub prompt_no_strip ($;$) {
1792     return _real_prompt(@_);
1793 }
1794
1795
1796
1797 1;