1 package CPAN::HandleConfig;
3 use vars qw(%can %keys $loading $VERSION);
11 CPAN::HandleConfig - internal configuration handling for CPAN.pm
15 $VERSION = "5.5005"; # see also CPAN::Config::VERSION at end of file
18 commit => "Commit changes to disk",
19 defaults => "Reload defaults from disk",
20 help => "Short help about 'o conf' usage",
21 init => "Interactive setting of all options",
24 # Q: where is the "How do I add a new config option" HOWTO?
25 # A1: svn diff -r 757:758 # where dagolden added test_report [git e997b71de88f1019a1472fc13cb97b1b7f96610f]
26 # A2: svn diff -r 985:986 # where andk added yaml_module [git 312b6d9b12b1bdec0b6e282d853482145475021f]
27 # A3: 1. add new config option to %keys below
28 # 2. add a Pod description in CPAN::FirstTime; it should include a
29 # prompt line; see others for examples
30 # 3. add a "matcher" section in CPAN::FirstTime::init that includes
31 # a prompt function; see others for examples
32 # 4. add config option to documentation section in CPAN.pm
34 %keys = map { $_ => undef }
41 "build_requires_install_policy",
49 "commandnumber_in_prompt",
51 "connect_to_internet_ok",
54 "dontload_hash", # deprecated after 1.83_68 (rev. 581)
70 "inhibit_startup_message",
72 "load_module_verbosity",
77 "make_install_make_command",
81 "mbuild_install_build_command",
92 "prefer_external_tar",
95 "prerequisites_policy",
102 "show_unparsable_versions",
104 "show_zero_versions",
111 "trust_test_report_history",
114 "use_prompt_default",
124 my %prefssupport = map { $_ => 1 }
126 "build_requires_install_policy",
129 "make_install_make_command",
134 # returns true on successful action
136 my($self,@args) = @_;
138 CPAN->debug("self[$self]args[".join(" | ",@args)."]");
139 my($o,$str,$func,$args,$key_exists);
142 my $success = $self->$o(args => \@args); # o conf init => sub init => sub load
144 die "Panic: could not configure CPAN.pm for args [@args]. Giving up.";
147 CPAN->debug("o[$o]") if $CPAN::DEBUG;
148 unless (exists $keys{$o}) {
149 $CPAN::Frontend->mywarn("Warning: unknown configuration variable '$o'\n");
154 # one day I used randomize_urllist for a boolean, so we must
155 # list them explicitly --ak
157 } elsif ($o =~ /^(wait_list|urllist|dontload_list|plugin_list)$/) {
165 CPAN->debug("func[$func]args[@args]") if $CPAN::DEBUG;
166 # Let's avoid eval, it's easier to comprehend without.
167 if ($func eq "push") {
168 push @{$CPAN::Config->{$o}}, @args;
170 } elsif ($func eq "pop") {
171 pop @{$CPAN::Config->{$o}};
173 } elsif ($func eq "shift") {
174 shift @{$CPAN::Config->{$o}};
176 } elsif ($func eq "unshift") {
177 unshift @{$CPAN::Config->{$o}}, @args;
179 } elsif ($func eq "splice") {
180 my $offset = shift @args || 0;
181 my $length = shift @args || 0;
182 splice @{$CPAN::Config->{$o}}, $offset, $length, @args; # may warn
185 $CPAN::Config->{$o} = [$func, @args];
188 $self->prettyprint($o);
191 if ($o eq "urllist") {
192 # reset the cached values
193 undef $CPAN::FTP::Thesite;
194 undef $CPAN::FTP::Themethod;
195 $CPAN::Index::LAST_TIME = 0;
196 } elsif ($o eq "dontload_list") {
197 # empty it, it will be built up again
198 $CPAN::META->{dontload_hash} = {};
201 } elsif ($o =~ /_hash$/) {
207 if (@args==1 && $args[0] eq "") {
209 } elsif (@args % 2) {
212 $CPAN::Config->{$o} = { @args };
220 if (defined $args[0]) {
221 $CPAN::CONFIG_DIRTY = 1;
222 $CPAN::Config->{$o} = $args[0];
225 $self->prettyprint($o)
226 if exists $keys{$o} or defined $CPAN::Config->{$o};
229 if ($CPAN::Config->{auto_commit}) {
232 $CPAN::CONFIG_DIRTY = 1;
233 $CPAN::Frontend->myprint("Please use 'o conf commit' to ".
234 "make the config permanent!\n\n");
242 my $v = $CPAN::Config->{$k};
245 if (ref $v eq "ARRAY") {
246 @report = map {"\t$_ \[$v->[$_]]\n"} 0..$#$v;
250 sprintf "\t%-18s => %s\n",
252 defined $v->{$_} ? "[$v->{$_}]" : "undef"
255 $CPAN::Frontend->myprint(
265 } elsif (defined $v) {
266 $CPAN::Frontend->myprint(sprintf " %-18s [%s]\n", $k, $v);
268 $CPAN::Frontend->myprint(sprintf " %-18s undef\n", $k);
272 # generally, this should be called without arguments so that the currently
273 # loaded config file is where changes are committed.
275 my($self,@args) = @_;
276 CPAN->debug("args[@args]") if $CPAN::DEBUG;
277 if ($CPAN::RUN_DEGRADED) {
278 $CPAN::Frontend->mydie(
279 "'o conf commit' disabled in ".
280 "degraded mode. Maybe try\n".
281 " !undef \$CPAN::RUN_DEGRADED\n"
284 my ($configpm, $must_reload);
286 # XXX does anything do this? can it be simplified? -- dagolden, 2011-01-19
288 if ($args[0] eq "args") {
289 # we have not signed that contract
291 $configpm = $args[0];
295 # use provided name or the current config or create a new MyConfig
296 $configpm ||= require_myconfig_or_config() || make_new_config();
298 # commit to MyConfig if we can't write to Config
299 if ( ! -w $configpm && $configpm =~ m{CPAN/Config\.pm} ) {
300 my $myconfig = _new_config_name();
301 $CPAN::Frontend->mywarn(
302 "Your $configpm file\n".
303 "is not writable. I will attempt to write your configuration to\n" .
304 "$myconfig instead.\n\n"
306 $configpm = make_new_config();
307 $must_reload++; # so it gets loaded as $INC{'CPAN/MyConfig.pm'}
310 # XXX why not just "-w $configpm"? -- dagolden, 2011-01-19
313 $mode = (stat $configpm)[2];
314 if ($mode && ! -w _) {
315 _die_cant_write_config($configpm);
319 $self->_write_config_file($configpm);
320 require_myconfig_or_config() if $must_reload;
322 #$mode = 0444 | ( $mode & 0111 ? 0111 : 0 );
323 #chmod $mode, $configpm;
324 ###why was that so? $self->defaults;
325 $CPAN::Frontend->myprint("commit: wrote '$configpm'\n");
326 $CPAN::CONFIG_DIRTY = 0;
330 sub _write_config_file {
331 my ($self, $configpm) = @_;
333 $msg = <<EOF if $configpm =~ m{CPAN/Config\.pm};
335 # This is CPAN.pm's systemwide configuration file. This file provides
336 # defaults for users, and the values can be changed in a per-user
337 # configuration file.
341 my($fh) = FileHandle->new;
342 rename $configpm, "$configpm~" if -f $configpm;
343 open $fh, ">$configpm" or
344 $CPAN::Frontend->mydie("Couldn't open >$configpm: $!");
345 $fh->print(qq[$msg\$CPAN::Config = \{\n]);
346 foreach (sort keys %$CPAN::Config) {
347 unless (exists $keys{$_}) {
348 # do not drop them: forward compatibility!
349 $CPAN::Frontend->mywarn("Unknown config variable '$_'\n");
354 $self->neatvalue($CPAN::Config->{$_}),
358 $fh->print("};\n1;\n__END__\n");
365 # stolen from MakeMaker; not taking the original because it is buggy;
366 # bugreport will have to say: keys of hashes remain unquoted and can
367 # produce syntax errors
370 return "undef" unless defined $v;
379 foreach my $elem (@$v) {
380 push @neat, "q[$elem]";
382 push @m, join ", ", @neat;
386 return "$v" unless $t eq 'HASH';
388 while (($key,$val) = each %$v) {
389 last unless defined $key; # cautious programming in case (undef,undef) is true
390 push(@m,"q[$key]=>".$self->neatvalue($val)) ;
392 return "{ ".join(', ',@m)." }";
397 if ($CPAN::RUN_DEGRADED) {
398 $CPAN::Frontend->mydie(
399 "'o conf defaults' disabled in ".
400 "degraded mode. Maybe try\n".
401 " !undef \$CPAN::RUN_DEGRADED\n"
405 for my $config (qw(CPAN/MyConfig.pm CPAN/Config.pm)) {
407 CPAN->debug("INC{'$config'}[$INC{$config}]") if $CPAN::DEBUG;
408 CPAN::Shell->_reload_this($config,{reloforce => 1});
409 $CPAN::Frontend->myprint("'$INC{$config}' reread\n");
413 $CPAN::CONFIG_DIRTY = 0;
417 =head2 C<< CLASS->safe_quote ITEM >>
419 Quotes an item to become safe against spaces
420 in shell interpolation. An item is enclosed
423 - the item contains spaces in the middle
424 - the item does not start with a quote
426 This happens to avoid shell interpolation
427 problems when whitespace is present in
430 This method uses C<commands_quote> to determine
431 the correct quote. If C<commands_quote> is
432 a space, no quoting will take place.
435 if it starts and ends with the same quote character: leave it as it is
437 if it contains no whitespace: leave it as it is
439 if it contains whitespace, then
441 if it contains quotes: better leave it as it is
443 else: quote it with the correct quote type for the box we're on
448 # Instead of patching the guess, set commands_quote
450 my ($quotes,$use_quote)
457 my ($self, $command) = @_;
458 # Set up quote/default quote
459 my $quote = $CPAN::Config->{commands_quote} || $quotes;
462 and defined($command )
464 and $command !~ /[$quote]/) {
465 return qq<$use_quote$command$use_quote>
472 my($self,@args) = @_;
473 CPAN->debug("self[$self]args[".join(",",@args)."]");
474 $self->load(do_init => 1, @args);
478 # Loads CPAN::MyConfig or fall-back to CPAN::Config. Will not reload a file
479 # if already loaded. Returns the path to the file %INC or else the empty string
481 # Note -- if CPAN::Config were loaded and CPAN::MyConfig subsequently
482 # created, calling this again will leave *both* in %INC
484 sub require_myconfig_or_config () {
485 if ( $INC{"CPAN/MyConfig.pm"} || _try_loading("CPAN::MyConfig", cpan_home())) {
486 return $INC{"CPAN/MyConfig.pm"};
488 elsif ( $INC{"CPAN/Config.pm"} || _try_loading("CPAN::Config") ) {
489 return $INC{"CPAN/Config.pm"};
496 # Load a module, but ignore "can't locate..." errors
497 # Optionally take a list of directories to add to @INC for the load
499 my ($module, @dirs) = @_;
500 (my $file = $module) =~ s{::}{/}g;
504 for my $dir ( @dirs ) {
505 if ( -f File::Spec->catfile($dir, $file) ) {
511 eval { require $file };
512 my $err_myconfig = $@;
513 if ($err_myconfig and $err_myconfig !~ m#locate \Q$file\E#) {
514 die "Error while requiring ${module}:\n$err_myconfig";
519 # prioritized list of possible places for finding "CPAN/MyConfig.pm"
520 sub cpan_home_dir_candidates {
522 my $old_v = $CPAN::Config->{load_module_verbosity};
523 $CPAN::Config->{load_module_verbosity} = q[none];
524 if ($CPAN::META->has_usable('File::HomeDir')) {
525 if ($^O ne 'darwin') {
526 push @dirs, File::HomeDir->my_data;
527 # my_data is ~/Library/Application Support on darwin,
528 # which causes issues in the toolchain.
530 push @dirs, File::HomeDir->my_home;
532 # Windows might not have HOME, so check it first
533 push @dirs, $ENV{HOME} if $ENV{HOME};
534 # Windows might have these instead
535 push( @dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
536 if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};
537 push @dirs, $ENV{USERPROFILE} if $ENV{USERPROFILE};
539 $CPAN::Config->{load_module_verbosity} = $old_v;
540 my $dotcpan = $^O eq 'VMS' ? '_cpan' : '.cpan';
541 @dirs = map { File::Spec->catdir($_, $dotcpan) } grep { defined } @dirs;
542 return wantarray ? @dirs : $dirs[0];
546 my($self, %args) = @_;
547 $CPAN::Be_Silent+=0; # protect against 'used only once'
548 $CPAN::Be_Silent++ if $args{be_silent}; # do not use; planned to be removed in 2011
549 my $do_init = delete $args{do_init} || 0;
550 my $make_myconfig = delete $args{make_myconfig};
551 $loading = 0 unless defined $loading;
553 my $configpm = require_myconfig_or_config;
554 my @miss = $self->missing_config_data;
555 CPAN->debug("do_init[$do_init]loading[$loading]miss[@miss]") if $CPAN::DEBUG;
556 return unless $do_init || @miss;
558 # I'm not how we'd ever wind up in a recursive loop, but I'm leaving
559 # this here for safety's sake -- dagolden, 2011-01-19
561 local $loading = ($loading||0) + 1;
563 # Warn if we have a config file, but things were found missing
564 if ($configpm && @miss && !$do_init) {
565 if ($make_myconfig || ( ! -w $configpm && $configpm =~ m{CPAN/Config\.pm})) {
566 $configpm = make_new_config();
567 $CPAN::Frontend->myprint(<<END);
568 The system CPAN configuration file has provided some default values,
569 but you need to complete the configuration dialog for CPAN.pm.
570 Configuration will be written to
575 $CPAN::Frontend->myprint(<<END);
576 Sorry, we have to rerun the configuration dialog for CPAN.pm due to
577 some missing parameters. Configuration will be written to
584 require CPAN::FirstTime;
585 return CPAN::FirstTime::init($configpm || make_new_config(), %args);
588 # Creates a new, empty config file at the preferred location
589 # Any existing will be renamed with a ".bak" suffix if possible
590 # If the file cannot be created, an exception is thrown
591 sub make_new_config {
592 my $configpm = _new_config_name();
593 my $configpmdir = File::Basename::dirname( $configpm );
594 File::Path::mkpath($configpmdir) unless -d $configpmdir;
596 if ( -w $configpmdir ) {
597 #_#_# following code dumped core on me with 5.003_11, a.k.
599 my $configpm_bak = "$configpm.bak";
600 unlink $configpm_bak if -f $configpm_bak;
601 if( rename $configpm, $configpm_bak ) {
602 $CPAN::Frontend->mywarn(<<END);
603 Old configuration file $configpm
604 moved to $configpm_bak
608 my $fh = FileHandle->new;
609 if ($fh->open(">$configpm")) {
614 _die_cant_write_config($configpm);
617 sub _die_cant_write_config {
619 $CPAN::Frontend->mydie(<<"END");
620 WARNING: CPAN.pm is unable to write a configuration file. You
621 must be able to create and write to '$configpm'.
623 Aborting configuration.
628 # From candidate directories, we would like (in descending preference order):
629 # * the one that contains a MyConfig file
630 # * one that exists (even without MyConfig)
631 # * the first one on the list
633 my @dirs = cpan_home_dir_candidates();
635 return $d if -f "$d/CPAN/MyConfig.pm";
643 sub _new_config_name {
644 return File::Spec->catfile(cpan_home(), 'CPAN', 'MyConfig.pm');
647 # returns mandatory but missing entries in the Config
648 sub missing_config_data {
660 #"inhibit_startup_message",
667 "mbuild_install_arg",
668 ($^O eq "MSWin32" ? "" : "mbuild_install_build_command"),
672 "prerequisites_policy",
678 next unless exists $keys{$_};
679 push @miss, $_ unless defined $CPAN::Config->{$_};
685 $CPAN::Frontend->myprint(q[
687 commit commit session changes to disk
688 defaults reload default config values from disk
690 init enter a dialog to set all or a set of parameters
692 Edit key values as in the following (the "o" is a literal letter o):
693 o conf build_cache 15
694 o conf build_dir "/foo/bar"
696 o conf urllist unshift ftp://ftp.foo.bar/
697 o conf inhibit_startup_message 1
700 1; #don't reprint CPAN::Config
704 my($word,$line,$pos) = @_;
706 CPAN->debug("word[$word] line[$line] pos[$pos]") if $CPAN::DEBUG;
707 my(@words) = split " ", substr($line,0,$pos+1);
716 @words == 4 && length($word)
719 return grep /^\Q$word\E/, qw(splice shift unshift pop push);
720 } elsif (defined($words[2])
727 @words >= 4 && length($word)
729 return sort grep /^\Q$word\E/, keys %keys;
730 } elsif (@words >= 4) {
734 my(@o_conf) = sort grep { !$seen{$_}++ }
738 return grep /^\Q$word\E/, @o_conf;
742 my($self,$distro,$what) = @_;
744 if ($prefssupport{$what}) {
745 return $CPAN::Config->{$what} unless
748 and $distro->prefs->{cpanconfig}
749 and defined $distro->prefs->{cpanconfig}{$what};
750 return $distro->prefs->{cpanconfig}{$what};
752 $CPAN::Frontend->mywarn("Warning: $what not yet officially ".
753 "supported for distroprefs, doing a normal lookup");
754 return $CPAN::Config->{$what};
761 CPAN::Config; ####::###### #hide from indexer
762 # note: J. Nick Koston wrote me that they are using
763 # CPAN::Config->commit although undocumented. I suggested
764 # CPAN::Shell->o("conf","commit") even when ugly it is at least
767 # that's why I added the CPAN::Config class with autoload and
771 use vars qw($AUTOLOAD $VERSION);
774 # formerly CPAN::HandleConfig was known as CPAN::Config
775 sub AUTOLOAD { ## no critic
776 my $class = shift; # e.g. in dh-make-perl: CPAN::Config
778 $CPAN::Frontend->mywarn("Dispatching deprecated method '$l' to CPAN::HandleConfig\n");
780 CPAN::HandleConfig->$l(@_);
790 This program is free software; you can redistribute it and/or
791 modify it under the same terms as Perl itself.
797 # cperl-indent-level: 4
799 # vim: ts=4 sts=4 sw=4: