Test for the qr// construct
[p5sagit/p5-mst-13.2.git] / lib / Module / Build / Base.pm
1 package Module::Build::Base;
2
3 use strict;
4 BEGIN { require 5.00503 }
5
6 use Carp;
7 use Config;
8 use File::Copy ();
9 use File::Find ();
10 use File::Path ();
11 use File::Basename ();
12 use File::Spec 0.82 ();
13 use File::Compare ();
14 use Data::Dumper ();
15 use IO::File ();
16 use Text::ParseWords ();
17
18 use Module::Build::ModuleInfo;
19 use Module::Build::Notes;
20 use Module::Build::Config;
21
22
23 #################### Constructors ###########################
24 sub new {
25   my $self = shift()->_construct(@_);
26
27   $self->{invoked_action} = $self->{action} ||= 'Build_PL';
28   $self->cull_args(@ARGV);
29   
30   die "Too early to specify a build action '$self->{action}'.  Do 'Build $self->{action}' instead.\n"
31     if $self->{action} && $self->{action} ne 'Build_PL';
32
33   $self->dist_name;
34   $self->dist_version;
35
36   $self->check_manifest;
37   $self->check_prereq;
38   $self->check_autofeatures;
39
40   $self->_set_install_paths;
41   $self->_find_nested_builds;
42
43   return $self;
44 }
45
46 sub resume {
47   my $package = shift;
48   my $self = $package->_construct(@_);
49   $self->read_config;
50
51   # If someone called Module::Build->current() or
52   # Module::Build->new_from_context() and the correct class to use is
53   # actually a *subclass* of Module::Build, we may need to load that
54   # subclass here and re-delegate the resume() method to it.
55   unless ( UNIVERSAL::isa($package, $self->build_class) ) {
56     my $build_class = $self->build_class;
57     my $config_dir = $self->config_dir || '_build';
58     my $build_lib = File::Spec->catdir( $config_dir, 'lib' );
59     unshift( @INC, $build_lib );
60     unless ( $build_class->can('new') ) {
61       eval "require $build_class; 1" or die "Failed to re-load '$build_class': $@";
62     }
63     return $build_class->resume(@_);
64   }
65
66   unless ($self->_perl_is_same($self->{properties}{perl})) {
67     my $perl = $self->find_perl_interpreter;
68     $self->log_warn(" * WARNING: Configuration was initially created with '$self->{properties}{perl}',\n".
69                     "   but we are now using '$perl'.\n");
70   }
71   
72   $self->cull_args(@ARGV);
73
74   unless ($self->allow_mb_mismatch) {
75     my $mb_version = $Module::Build::VERSION;
76     die(" * ERROR: Configuration was initially created with Module::Build version '$self->{properties}{mb_version}',\n".
77         "   but we are now using version '$mb_version'.  Please re-run the Build.PL or Makefile.PL script.\n")
78     if $mb_version ne $self->{properties}{mb_version};
79   }
80   
81   $self->{invoked_action} = $self->{action} ||= 'build';
82   
83   return $self;
84 }
85
86 sub new_from_context {
87   my ($package, %args) = @_;
88   
89   # XXX Read the META.yml and see whether we need to run the Build.PL?
90   
91   # Run the Build.PL.  We use do() rather than run_perl_script() so
92   # that it runs in this process rather than a subprocess, because we
93   # need to make sure that the environment is the same during Build.PL
94   # as it is during resume() (and thereafter).
95   {
96     local @ARGV = $package->unparse_args(\%args);
97     do 'Build.PL';
98     die $@ if $@;
99   }
100   return $package->resume;
101 }
102
103 sub current {
104   # hmm, wonder what the right thing to do here is
105   local @ARGV;
106   return shift()->resume;
107 }
108
109 sub _construct {
110   my ($package, %input) = @_;
111
112   my $args   = delete $input{args}   || {};
113   my $config = delete $input{config} || {};
114
115   my $self = bless {
116                     args => {%$args},
117                     config => Module::Build::Config->new(values => $config),
118                     properties => {
119                                    base_dir        => $package->cwd,
120                                    mb_version      => $Module::Build::VERSION,
121                                    %input,
122                                   },
123                     phash => {},
124                    }, $package;
125
126   $self->_set_defaults;
127   my ($p, $ph) = ($self->{properties}, $self->{phash});
128
129   foreach (qw(notes config_data features runtime_params cleanup auto_features)) {
130     my $file = File::Spec->catfile($self->config_dir, $_);
131     $ph->{$_} = Module::Build::Notes->new(file => $file);
132     $ph->{$_}->restore if -e $file;
133     if (exists $p->{$_}) {
134       my $vals = delete $p->{$_};
135       while (my ($k, $v) = each %$vals) {
136         $self->$_($k, $v);
137       }
138     }
139   }
140
141   # The following warning could be unnecessary if the user is running
142   # an embedded perl, but there aren't too many of those around, and
143   # embedded perls aren't usually used to install modules, and the
144   # installation process sometimes needs to run external scripts
145   # (e.g. to run tests).
146   $p->{perl} = $self->find_perl_interpreter
147     or $self->log_warn("Warning: Can't locate your perl binary");
148
149   my $blibdir = sub { File::Spec->catdir($p->{blib}, @_) };
150   $p->{bindoc_dirs} ||= [ $blibdir->("script") ];
151   $p->{libdoc_dirs} ||= [ $blibdir->("lib"), $blibdir->("arch") ];
152
153   $p->{dist_author} = [ $p->{dist_author} ] if defined $p->{dist_author} and not ref $p->{dist_author};
154
155   # Synonyms
156   $p->{requires} = delete $p->{prereq} if defined $p->{prereq};
157   $p->{script_files} = delete $p->{scripts} if defined $p->{scripts};
158
159   # Convert to arrays
160   for ('extra_compiler_flags', 'extra_linker_flags') {
161     $p->{$_} = [ $self->split_like_shell($p->{$_}) ] if exists $p->{$_};
162   }
163
164   $self->add_to_cleanup( @{delete $p->{add_to_cleanup}} )
165     if $p->{add_to_cleanup};
166
167   return $self;
168 }
169
170 ################## End constructors #########################
171
172 sub log_info { print @_ unless shift()->quiet }
173 sub log_verbose { shift()->log_info(@_) if $_[0]->verbose }
174 sub log_warn {
175   # Try to make our call stack invisible
176   shift;
177   if (@_ and $_[-1] !~ /\n$/) {
178     my (undef, $file, $line) = caller();
179     warn @_, " at $file line $line.\n";
180   } else {
181     warn @_;
182   }
183 }
184
185
186 sub _set_install_paths {
187   my $self = shift;
188   my $c = $self->{config};
189   my $p = $self->{properties};
190
191   my @libstyle = $c->get('installstyle') ?
192       File::Spec->splitdir($c->get('installstyle')) : qw(lib perl5);
193   my $arch     = $c->get('archname');
194   my $version  = $c->get('version');
195
196   my $bindoc  = $c->get('installman1dir') || undef;
197   my $libdoc  = $c->get('installman3dir') || undef;
198
199   my $binhtml = $c->get('installhtml1dir') || $c->get('installhtmldir') || undef;
200   my $libhtml = $c->get('installhtml3dir') || $c->get('installhtmldir') || undef;
201
202   $p->{install_sets} =
203     {
204      core   => {
205                 lib     => $c->get('installprivlib'),
206                 arch    => $c->get('installarchlib'),
207                 bin     => $c->get('installbin'),
208                 script  => $c->get('installscript'),
209                 bindoc  => $bindoc,
210                 libdoc  => $libdoc,
211                 binhtml => $binhtml,
212                 libhtml => $libhtml,
213                },
214      site   => {
215                 lib     => $c->get('installsitelib'),
216                 arch    => $c->get('installsitearch'),
217                 bin     => $c->get('installsitebin') || $c->get('installbin'),
218                 script  => $c->get('installsitescript') ||
219                            $c->get('installsitebin') || $c->get('installscript'),
220                 bindoc  => $c->get('installsiteman1dir') || $bindoc,
221                 libdoc  => $c->get('installsiteman3dir') || $libdoc,
222                 binhtml => $c->get('installsitehtml1dir') || $binhtml,
223                 libhtml => $c->get('installsitehtml3dir') || $libhtml,
224                },
225      vendor => {
226                 lib     => $c->get('installvendorlib'),
227                 arch    => $c->get('installvendorarch'),
228                 bin     => $c->get('installvendorbin') || $c->get('installbin'),
229                 script  => $c->get('installvendorscript') ||
230                            $c->get('installvendorbin') || $c->get('installscript'),
231                 bindoc  => $c->get('installvendorman1dir') || $bindoc,
232                 libdoc  => $c->get('installvendorman3dir') || $libdoc,
233                 binhtml => $c->get('installvendorhtml1dir') || $binhtml,
234                 libhtml => $c->get('installvendorhtml3dir') || $libhtml,
235                },
236     };
237
238   $p->{original_prefix} =
239     {
240      core   => $c->get('installprefixexp') || $c->get('installprefix') ||
241                $c->get('prefixexp')        || $c->get('prefix') || '',
242      site   => $c->get('siteprefixexp'),
243      vendor => $c->get('usevendorprefix') ? $c->get('vendorprefixexp') : '',
244     };
245   $p->{original_prefix}{site} ||= $p->{original_prefix}{core};
246
247   # Note: you might be tempted to use $Config{installstyle} here
248   # instead of hard-coding lib/perl5, but that's been considered and
249   # (at least for now) rejected.  `perldoc Config` has some wisdom
250   # about it.
251   $p->{install_base_relpaths} =
252     {
253      lib     => ['lib', 'perl5'],
254      arch    => ['lib', 'perl5', $arch],
255      bin     => ['bin'],
256      script  => ['bin'],
257      bindoc  => ['man', 'man1'],
258      libdoc  => ['man', 'man3'],
259      binhtml => ['html'],
260      libhtml => ['html'],
261     };
262
263   $p->{prefix_relpaths} =
264     {
265      core => {
266               lib        => [@libstyle],
267               arch       => [@libstyle, $version, $arch],
268               bin        => ['bin'],
269               script     => ['bin'],
270               bindoc     => ['man', 'man1'],
271               libdoc     => ['man', 'man3'],
272               binhtml    => ['html'],
273               libhtml    => ['html'],
274              },
275      vendor => {
276                 lib        => [@libstyle],
277                 arch       => [@libstyle, $version, $arch],
278                 bin        => ['bin'],
279                 script     => ['bin'],
280                 bindoc     => ['man', 'man1'],
281                 libdoc     => ['man', 'man3'],
282                 binhtml    => ['html'],
283                 libhtml    => ['html'],
284                },
285      site => {
286               lib        => [@libstyle, 'site_perl'],
287               arch       => [@libstyle, 'site_perl', $version, $arch],
288               bin        => ['bin'],
289               script     => ['bin'],
290               bindoc     => ['man', 'man1'],
291               libdoc     => ['man', 'man3'],
292               binhtml    => ['html'],
293               libhtml    => ['html'],
294              },
295     };
296
297 }
298
299 sub _find_nested_builds {
300   my $self = shift;
301   my $r = $self->recurse_into or return;
302
303   my ($file, @r);
304   if (!ref($r) && $r eq 'auto') {
305     local *DH;
306     opendir DH, $self->base_dir
307       or die "Can't scan directory " . $self->base_dir . " for nested builds: $!";
308     while (defined($file = readdir DH)) {
309       my $subdir = File::Spec->catdir( $self->base_dir, $file );
310       next unless -d $subdir;
311       push @r, $subdir if -e File::Spec->catfile( $subdir, 'Build.PL' );
312     }
313   }
314
315   $self->recurse_into(\@r);
316 }
317
318 sub cwd {
319   require Cwd;
320   return Cwd::cwd();
321 }
322
323 sub _quote_args {
324   # Returns a string that can become [part of] a command line with
325   # proper quoting so that the subprocess sees this same list of args.
326   my ($self, @args) = @_;
327
328   my $return_args = '';
329   my @quoted;
330
331   for (@args) {
332     if ( /^[^\s*?!$<>;\\|'"\[\]\{\}]+$/ ) {
333       # Looks pretty safe
334       push @quoted, $_;
335     } else {
336       # XXX this will obviously have to improve - is there already a
337       # core module lying around that does proper quoting?
338       s/"/"'"'"/g;
339       push @quoted, qq("$_");
340     }
341   }
342
343   return join " ", @quoted;
344 }
345
346 sub _backticks {
347   my ($self, @cmd) = @_;
348   if ($self->have_forkpipe) {
349     local *FH;
350     my $pid = open *FH, "-|";
351     if ($pid) {
352       return wantarray ? <FH> : join '', <FH>;
353     } else {
354       die "Can't execute @cmd: $!\n" unless defined $pid;
355       exec { $cmd[0] } @cmd;
356     }
357   } else {
358     my $cmd = $self->_quote_args(@cmd);
359     return `$cmd`;
360   }
361 }
362
363 sub have_forkpipe { 1 }
364
365 # Determine whether a given binary is the same as the perl
366 # (configuration) that started this process.
367 sub _perl_is_same {
368   my ($self, $perl) = @_;
369
370   my @cmd = ($perl);
371
372   # When run from the perl core, @INC will include the directories
373   # where perl is yet to be installed. We need to reference the
374   # absolute path within the source distribution where it can find
375   # it's Config.pm This also prevents us from picking up a Config.pm
376   # from a different configuration that happens to be already
377   # installed in @INC.
378   if ($ENV{PERL_CORE}) {
379     push @cmd, '-I' . File::Spec->catdir(File::Basename::dirname($perl), 'lib');
380   }
381
382   push @cmd, qw(-MConfig=myconfig -e print -e myconfig);
383   return $self->_backticks(@cmd) eq Config->myconfig;
384 }
385
386 # Returns the absolute path of the perl interperter used to invoke
387 # this process. The path is derived from $^X or $Config{perlpath}. On
388 # some platforms $^X contains the complete absolute path of the
389 # interpreter, on other it may contain a relative path, or simply
390 # 'perl'. This can also vary depending on whether a path was supplied
391 # when perl was invoked. Additionally, the value in $^X may omit the
392 # executable extension on platforms that use one. It's a fatal error
393 # if the interpreter can't be found because it can result in undefined
394 # behavior by routines that depend on it (generating errors or
395 # invoking the wrong perl.
396 sub find_perl_interpreter {
397   my $proto = shift;
398   my $c     = ref($proto) ? $proto->{config} : 'Module::Build::Config';
399
400   my $perl  = $^X;
401   my $perl_basename = File::Basename::basename($perl);
402
403   my @potential_perls;
404
405   # Try 1, Check $^X for absolute path
406   push( @potential_perls, $perl )
407       if File::Spec->file_name_is_absolute($perl);
408
409   # Try 2, Check $^X for a valid relative path
410   my $abs_perl = File::Spec->rel2abs($perl);
411   push( @potential_perls, $abs_perl );
412
413   # Try 3, Last ditch effort: These two option use hackery to try to locate
414   # a suitable perl. The hack varies depending on whether we are running
415   # from an installed perl or an uninstalled perl in the perl source dist.
416   if ($ENV{PERL_CORE}) {
417
418     # Try 3.A, If we are in a perl source tree, running an uninstalled
419     # perl, we can keep moving up the directory tree until we find our
420     # binary. We wouldn't do this under any other circumstances.
421
422     # CBuilder is also in the core, so it should be available here
423     require ExtUtils::CBuilder;
424     my $perl_src = ExtUtils::CBuilder->perl_src;
425     if ( defined($perl_src) && length($perl_src) ) {
426       my $uninstperl =
427         File::Spec->rel2abs(File::Spec->catfile( $perl_src, $perl_basename ));
428       push( @potential_perls, $uninstperl );
429     }
430
431   } else {
432
433     # Try 3.B, First look in $Config{perlpath}, then search the users
434     # PATH. We do not want to do either if we are running from an
435     # uninstalled perl in a perl source tree.
436
437     push( @potential_perls, $c->get('perlpath') );
438
439     push( @potential_perls,
440           map File::Spec->catfile($_, $perl_basename), File::Spec->path() );
441   }
442
443   # Now that we've enumerated the potential perls, it's time to test
444   # them to see if any of them match our configuration, returning the
445   # absolute path of the first successful match.
446   my $exe = $c->get('exe_ext');
447   foreach my $thisperl ( @potential_perls ) {
448
449     if ($proto->os_type eq 'VMS') {
450       # VMS might have a file version at the end
451       $thisperl .= $exe unless $thisperl =~ m/$exe(;\d+)?$/i;
452     } elsif (defined $exe) {
453       $thisperl .= $exe unless $thisperl =~ m/$exe$/i;
454     }
455
456     if ( -f $thisperl && $proto->_perl_is_same($thisperl) ) {
457       return $thisperl;
458     }
459   }
460
461   # We've tried all alternatives, and didn't find a perl that matches
462   # our configuration. Throw an exception, and list alternatives we tried.
463   my @paths = map File::Basename::dirname($_), @potential_perls;
464   die "Can't locate the perl binary used to run this script " .
465       "in (@paths)\n";
466 }
467
468 sub _is_interactive {
469   return -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ;   # Pipe?
470 }
471
472 sub _is_unattended {
473   my $self = shift;
474   return $ENV{PERL_MM_USE_DEFAULT} || ( !$self->_is_interactive && eof STDIN );
475 }
476
477 sub _readline {
478   my $self = shift;
479   return undef if $self->_is_unattended;
480
481   my $answer = <STDIN>;
482   chomp $answer if defined $answer;
483   return $answer;
484 }
485
486 sub prompt {
487   my $self = shift;
488   my $mess = shift
489     or die "prompt() called without a prompt message";
490
491   my $def;
492   if ( $self->_is_unattended && !@_ ) {
493     die <<EOF;
494 ERROR: This build seems to be unattended, but there is no default value
495 for this question.  Aborting.
496 EOF
497   }
498   $def = shift if @_;
499   ($def, my $dispdef) = defined $def ? ($def, "[$def] ") : ('', ' ');
500
501   local $|=1;
502   print "$mess $dispdef";
503
504   my $ans = $self->_readline();
505
506   if ( !defined($ans)        # Ctrl-D or unattended
507        or !length($ans) ) {  # User hit return
508     print "$def\n";
509     $ans = $def;
510   }
511
512   return $ans;
513 }
514
515 sub y_n {
516   my $self = shift;
517   my ($mess, $def)  = @_;
518
519   die "y_n() called without a prompt message" unless $mess;
520   die "Invalid default value: y_n() default must be 'y' or 'n'"
521     if $def && $def !~ /^[yn]/i;
522
523   if ( $self->_is_unattended && !$def ) {
524     die <<EOF;
525 ERROR: This build seems to be unattended, but there is no default value
526 for this question.  Aborting.
527 EOF
528   }
529
530   my $answer;
531   while (1) { # XXX Infinite or a large number followed by an exception ?
532     $answer = $self->prompt(@_);
533     return 1 if $answer =~ /^y/i;
534     return 0 if $answer =~ /^n/i;
535     local $|=1;
536     print "Please answer 'y' or 'n'.\n";
537   }
538 }
539
540 sub current_action { shift->{action} }
541 sub invoked_action { shift->{invoked_action} }
542
543 sub notes        { shift()->{phash}{notes}->access(@_) }
544 sub config_data  { shift()->{phash}{config_data}->access(@_) }
545 sub runtime_params { shift->{phash}{runtime_params}->read( @_ ? shift : () ) }  # Read-only
546 sub auto_features  { shift()->{phash}{auto_features}->access(@_) }
547
548 sub features     {
549   my $self = shift;
550   my $ph = $self->{phash};
551
552   if (@_) {
553     my $key = shift;
554     if ($ph->{features}->exists($key)) {
555       return $ph->{features}->access($key, @_);
556     }
557
558     if (my $info = $ph->{auto_features}->access($key)) {
559       my $failures = $self->prereq_failures($info);
560       my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
561                            keys %$failures ) ? 1 : 0;
562       return !$disabled;
563     }
564
565     return $ph->{features}->access($key, @_);
566   }
567
568   # No args - get the auto_features & overlay the regular features
569   my %features;
570   my %auto_features = $ph->{auto_features}->access();
571   while (my ($name, $info) = each %auto_features) {
572     my $failures = $self->prereq_failures($info);
573     my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
574                          keys %$failures ) ? 1 : 0;
575     $features{$name} = $disabled ? 0 : 1;
576   }
577   %features = (%features, $ph->{features}->access());
578
579   return wantarray ? %features : \%features;
580 }
581 BEGIN { *feature = \&features }
582
583 sub _mb_feature {
584   my $self = shift;
585   
586   if (($self->module_name || '') eq 'Module::Build') {
587     # We're building Module::Build itself, so ...::ConfigData isn't
588     # valid, but $self->features() should be.
589     return $self->feature(@_);
590   } else {
591     require Module::Build::ConfigData;
592     return Module::Build::ConfigData->feature(@_);
593   }
594 }
595
596
597 sub add_build_element {
598     my ($self, $elem) = @_;
599     my $elems = $self->build_elements;
600     push @$elems, $elem unless grep { $_ eq $elem } @$elems;
601 }
602
603 sub ACTION_config_data {
604   my $self = shift;
605   return unless $self->has_config_data;
606   
607   my $module_name = $self->module_name
608     or die "The config_data feature requires that 'module_name' be set";
609   my $notes_name = $module_name . '::ConfigData'; # TODO: Customize name ???
610   my $notes_pm = File::Spec->catfile($self->blib, 'lib', split /::/, "$notes_name.pm");
611
612   return if $self->up_to_date(['Build.PL',
613                                $self->config_file('config_data'),
614                                $self->config_file('features')
615                               ], $notes_pm);
616
617   $self->log_info("Writing config notes to $notes_pm\n");
618   File::Path::mkpath(File::Basename::dirname($notes_pm));
619
620   Module::Build::Notes->write_config_data
621       (
622        file => $notes_pm,
623        module => $module_name,
624        config_module => $notes_name,
625        config_data => scalar $self->config_data,
626        feature => scalar $self->{phash}{features}->access(),
627        auto_features => scalar $self->auto_features,
628       );
629 }
630
631 {
632     my %valid_properties = ( __PACKAGE__,  {} );
633     my %additive_properties;
634
635     sub _mb_classes {
636       my $class = ref($_[0]) || $_[0];
637       return ($class, $class->mb_parents);
638     }
639
640     sub valid_property {
641       my ($class, $prop) = @_;
642       return grep exists( $valid_properties{$_}{$prop} ), $class->_mb_classes;
643     }
644
645     sub valid_properties {
646       return keys %{ shift->valid_properties_defaults() };
647     }
648
649     sub valid_properties_defaults {
650       my %out;
651       for (reverse shift->_mb_classes) {
652         @out{ keys %{ $valid_properties{$_} } } = values %{ $valid_properties{$_} };
653       }
654       return \%out;
655     }
656
657     sub array_properties {
658       for (shift->_mb_classes) {
659         return @{$additive_properties{$_}->{ARRAY}}
660           if exists $additive_properties{$_}->{ARRAY};
661       }
662     }
663
664     sub hash_properties {
665       for (shift->_mb_classes) {
666         return @{$additive_properties{$_}->{'HASH'}}
667           if exists $additive_properties{$_}->{'HASH'};
668       }
669     }
670
671     sub add_property {
672       my ($class, $property, $default) = @_;
673       die "Property '$property' already exists" if $class->valid_property($property);
674
675       $valid_properties{$class}{$property} = $default;
676
677       my $type = ref $default;
678       if ($type) {
679         push @{$additive_properties{$class}->{$type}}, $property;
680       }
681
682       unless ($class->can($property)) {
683         no strict 'refs';
684         if ( $type eq 'HASH' ) {
685           *{"$class\::$property"} = sub {
686             my $self = shift;
687             my $x = $self->{properties};
688             return $x->{$property} unless @_;
689
690             if ( defined($_[0]) && !ref($_[0]) ) {
691               if ( @_ == 1 ) {
692                 return exists( $x->{$property}{$_[0]} ) ?
693                          $x->{$property}{$_[0]} : undef;
694               } elsif ( @_ % 2 == 0 ) {
695                 my %args = @_;
696                 while ( my($k, $v) = each %args ) {
697                   $x->{$property}{$k} = $v;
698                 }
699               } else {
700                 die "Unexpected arguments for property '$property'\n";
701               }
702             } else {
703               $x->{$property} = $_[0];
704             }
705           };
706
707         } else {
708           *{"$class\::$property"} = sub {
709             my $self = shift;
710             $self->{properties}{$property} = shift if @_;
711             return $self->{properties}{$property};
712           }
713         }
714
715       }
716       return $class;
717     }
718
719     sub _set_defaults {
720       my $self = shift;
721
722       # Set the build class.
723       $self->{properties}{build_class} ||= ref $self;
724
725       # If there was no orig_dir, set to the same as base_dir
726       $self->{properties}{orig_dir} ||= $self->{properties}{base_dir};
727
728       my $defaults = $self->valid_properties_defaults;
729       
730       foreach my $prop (keys %$defaults) {
731         $self->{properties}{$prop} = $defaults->{$prop}
732           unless exists $self->{properties}{$prop};
733       }
734       
735       # Copy defaults for arrays any arrays.
736       for my $prop ($self->array_properties) {
737         $self->{properties}{$prop} = [@{$defaults->{$prop}}]
738           unless exists $self->{properties}{$prop};
739       }
740       # Copy defaults for arrays any hashes.
741       for my $prop ($self->hash_properties) {
742         $self->{properties}{$prop} = {%{$defaults->{$prop}}}
743           unless exists $self->{properties}{$prop};
744       }
745     }
746
747 }
748
749 # Add the default properties.
750 __PACKAGE__->add_property(blib => 'blib');
751 __PACKAGE__->add_property(build_class => 'Module::Build');
752 __PACKAGE__->add_property(build_elements => [qw(PL support pm xs pod script)]);
753 __PACKAGE__->add_property(build_script => 'Build');
754 __PACKAGE__->add_property(build_bat => 0);
755 __PACKAGE__->add_property(config_dir => '_build');
756 __PACKAGE__->add_property(include_dirs => []);
757 __PACKAGE__->add_property(installdirs => 'site');
758 __PACKAGE__->add_property(metafile => 'META.yml');
759 __PACKAGE__->add_property(recurse_into => []);
760 __PACKAGE__->add_property(use_rcfile => 1);
761 __PACKAGE__->add_property(create_packlist => 1);
762 __PACKAGE__->add_property(allow_mb_mismatch => 0);
763 __PACKAGE__->add_property(config => undef);
764
765 {
766   my $Is_ActivePerl = eval {require ActivePerl::DocTools};
767   __PACKAGE__->add_property(html_css => $Is_ActivePerl ? 'Active.css' : '');
768 }
769
770 {
771   my @prereq_action_types = qw(requires build_requires conflicts recommends);
772   foreach my $type (@prereq_action_types) {
773     __PACKAGE__->add_property($type => {});
774   }
775   __PACKAGE__->add_property(prereq_action_types => \@prereq_action_types);
776 }
777
778 __PACKAGE__->add_property($_ => {}) for qw(
779   get_options
780   install_base_relpaths
781   install_path
782   install_sets
783   meta_add
784   meta_merge
785   original_prefix
786   prefix_relpaths
787 );
788
789 __PACKAGE__->add_property($_) for qw(
790   PL_files
791   autosplit
792   base_dir
793   bindoc_dirs
794   c_source
795   create_makefile_pl
796   create_readme
797   debugger
798   destdir
799   dist_abstract
800   dist_author
801   dist_name
802   dist_version
803   dist_version_from
804   extra_compiler_flags
805   extra_linker_flags
806   has_config_data
807   install_base
808   libdoc_dirs
809   license
810   magic_number
811   mb_version
812   module_name
813   orig_dir
814   perl
815   pm_files
816   pod_files
817   pollute
818   prefix
819   quiet
820   recursive_test_files
821   script_files
822   scripts
823   test_files
824   verbose
825   xs_files
826 );
827
828 sub config {
829   my $self = shift;
830   my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
831   return $c->all_config unless @_;
832
833   my $key = shift;
834   return $c->get($key) unless @_;
835
836   my $val = shift;
837   return $c->set($key => $val);
838 }
839
840 sub mb_parents {
841     # Code borrowed from Class::ISA.
842     my @in_stack = (shift);
843     my %seen = ($in_stack[0] => 1);
844
845     my ($current, @out);
846     while (@in_stack) {
847         next unless defined($current = shift @in_stack)
848           && $current->isa('Module::Build::Base');
849         push @out, $current;
850         next if $current eq 'Module::Build::Base';
851         no strict 'refs';
852         unshift @in_stack,
853           map {
854               my $c = $_; # copy, to avoid being destructive
855               substr($c,0,2) = "main::" if substr($c,0,2) eq '::';
856               # Canonize the :: -> main::, ::foo -> main::foo thing.
857               # Should I ever canonize the Foo'Bar = Foo::Bar thing?
858               $seen{$c}++ ? () : $c;
859           } @{"$current\::ISA"};
860
861         # I.e., if this class has any parents (at least, ones I've never seen
862         # before), push them, in order, onto the stack of classes I need to
863         # explore.
864     }
865     shift @out;
866     return @out;
867 }
868
869 sub extra_linker_flags   { shift->_list_accessor('extra_linker_flags',   @_) }
870 sub extra_compiler_flags { shift->_list_accessor('extra_compiler_flags', @_) }
871
872 sub _list_accessor {
873   (my $self, local $_) = (shift, shift);
874   my $p = $self->{properties};
875   $p->{$_} = [@_] if @_;
876   $p->{$_} = [] unless exists $p->{$_};
877   return ref($p->{$_}) ? $p->{$_} : [$p->{$_}];
878 }
879
880 # XXX Problem - if Module::Build is loaded from a different directory,
881 # it'll look for (and perhaps destroy/create) a _build directory.
882 sub subclass {
883   my ($pack, %opts) = @_;
884
885   my $build_dir = '_build'; # XXX The _build directory is ostensibly settable by the user.  Shouldn't hard-code here.
886   $pack->delete_filetree($build_dir) if -e $build_dir;
887
888   die "Must provide 'code' or 'class' option to subclass()\n"
889     unless $opts{code} or $opts{class};
890
891   $opts{code}  ||= '';
892   $opts{class} ||= 'MyModuleBuilder';
893   
894   my $filename = File::Spec->catfile($build_dir, 'lib', split '::', $opts{class}) . '.pm';
895   my $filedir  = File::Basename::dirname($filename);
896   $pack->log_info("Creating custom builder $filename in $filedir\n");
897   
898   File::Path::mkpath($filedir);
899   die "Can't create directory $filedir: $!" unless -d $filedir;
900   
901   my $fh = IO::File->new("> $filename") or die "Can't create $filename: $!";
902   print $fh <<EOF;
903 package $opts{class};
904 use $pack;
905 \@ISA = qw($pack);
906 $opts{code}
907 1;
908 EOF
909   close $fh;
910   
911   unshift @INC, File::Spec->catdir(File::Spec->rel2abs($build_dir), 'lib');
912   eval "use $opts{class}";
913   die $@ if $@;
914
915   return $opts{class};
916 }
917
918 sub dist_name {
919   my $self = shift;
920   my $p = $self->{properties};
921   return $p->{dist_name} if defined $p->{dist_name};
922   
923   die "Can't determine distribution name, must supply either 'dist_name' or 'module_name' parameter"
924     unless $self->module_name;
925   
926   ($p->{dist_name} = $self->module_name) =~ s/::/-/g;
927   
928   return $p->{dist_name};
929 }
930
931 sub dist_version_from {
932   my ($self) = @_;
933   my $p = $self->{properties};
934   if ($self->module_name) {
935     $p->{dist_version_from} ||=
936         join( '/', 'lib', split(/::/, $self->module_name) ) . '.pm';
937   }
938   return $p->{dist_version_from} || undef;
939 }
940
941 sub dist_version {
942   my ($self) = @_;
943   my $p = $self->{properties};
944
945   return $p->{dist_version} if defined $p->{dist_version};
946
947   if ( my $dist_version_from = $self->dist_version_from ) {
948     my $version_from = File::Spec->catfile( split( qr{/}, $dist_version_from ) );
949     my $pm_info = Module::Build::ModuleInfo->new_from_file( $version_from )
950       or die "Can't find file $version_from to determine version";
951     $p->{dist_version} = $pm_info->version();
952   }
953
954   die ("Can't determine distribution version, must supply either 'dist_version',\n".
955        "'dist_version_from', or 'module_name' parameter")
956     unless $p->{dist_version};
957
958   return $p->{dist_version};
959 }
960
961 sub dist_author   { shift->_pod_parse('author')   }
962 sub dist_abstract { shift->_pod_parse('abstract') }
963
964 sub _pod_parse {
965   my ($self, $part) = @_;
966   my $p = $self->{properties};
967   my $member = "dist_$part";
968   return $p->{$member} if defined $p->{$member};
969   
970   my $docfile = $self->_main_docfile
971     or return;
972   my $fh = IO::File->new($docfile)
973     or return;
974   
975   require Module::Build::PodParser;
976   my $parser = Module::Build::PodParser->new(fh => $fh);
977   my $method = "get_$part";
978   return $p->{$member} = $parser->$method();
979 }
980
981 sub version_from_file { # Method provided for backwards compatability
982   return Module::Build::ModuleInfo->new_from_file($_[1])->version();
983 }
984
985 sub find_module_by_name { # Method provided for backwards compatability
986   return Module::Build::ModuleInfo->find_module_by_name(@_[1,2]);
987 }
988
989 sub add_to_cleanup {
990   my $self = shift;
991   my %files = map {$self->localize_file_path($_), 1} @_;
992   $self->{phash}{cleanup}->write(\%files);
993 }
994
995 sub cleanup {
996   my $self = shift;
997   my $all = $self->{phash}{cleanup}->read;
998   return keys %$all;
999 }
1000
1001 sub config_file {
1002   my $self = shift;
1003   return unless -d $self->config_dir;
1004   return File::Spec->catfile($self->config_dir, @_);
1005 }
1006
1007 sub read_config {
1008   my ($self) = @_;
1009   
1010   my $file = $self->config_file('build_params')
1011     or die "No build_params?";
1012   my $fh = IO::File->new($file) or die "Can't read '$file': $!";
1013   my $ref = eval do {local $/; <$fh>};
1014   die if $@;
1015   my $c;
1016   ($self->{args}, $c, $self->{properties}) = @$ref;
1017   $self->{config} = Module::Build::Config->new(values => $c);
1018   close $fh;
1019 }
1020
1021 sub has_config_data {
1022   my $self = shift;
1023   return scalar grep $self->{phash}{$_}->has_data(), qw(config_data features auto_features);
1024 }
1025
1026 sub _write_data {
1027   my ($self, $filename, $data) = @_;
1028   
1029   my $file = $self->config_file($filename);
1030   my $fh = IO::File->new("> $file") or die "Can't create '$file': $!";
1031   local $Data::Dumper::Terse = 1;
1032   print $fh ref($data) ? Data::Dumper::Dumper($data) : $data;
1033 }
1034
1035 sub write_config {
1036   my ($self) = @_;
1037   
1038   File::Path::mkpath($self->{properties}{config_dir});
1039   -d $self->{properties}{config_dir} or die "Can't mkdir $self->{properties}{config_dir}: $!";
1040   
1041   my @items = @{ $self->prereq_action_types };
1042   $self->_write_data('prereqs', { map { $_, $self->$_() } @items });
1043   $self->_write_data('build_params', [$self->{args}, $self->{config}->values_set, $self->{properties}]);
1044
1045   # Set a new magic number and write it to a file
1046   $self->_write_data('magicnum', $self->magic_number(int rand 1_000_000));
1047
1048   $self->{phash}{$_}->write() foreach qw(notes cleanup features auto_features config_data runtime_params);
1049 }
1050
1051 sub check_autofeatures {
1052   my ($self) = @_;
1053   my $features = $self->auto_features;
1054   
1055   return unless %$features;
1056
1057   $self->log_info("Checking features:\n");
1058
1059   my $max_name_len;
1060   $max_name_len = ( length($_) > $max_name_len ) ?
1061                     length($_) : $max_name_len
1062     for keys %$features;
1063
1064   while (my ($name, $info) = each %$features) {
1065     $self->log_info("  $name" . '.' x ($max_name_len - length($name) + 4));
1066
1067     if ( my $failures = $self->prereq_failures($info) ) {
1068       my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
1069                            keys %$failures ) ? 1 : 0;
1070       $self->log_info( $disabled ? "disabled\n" : "enabled\n" );
1071
1072       my $log_text;
1073       while (my ($type, $prereqs) = each %$failures) {
1074         while (my ($module, $status) = each %$prereqs) {
1075           my $required =
1076             ($type =~ /^(?:\w+_)?(?:requires|conflicts)$/) ? 1 : 0;
1077           my $prefix = ($required) ? '-' : '*';
1078           $log_text .= "    $prefix $status->{message}\n";
1079         }
1080       }
1081       $self->log_warn("$log_text") unless $self->quiet;
1082     } else {
1083       $self->log_info("enabled\n");
1084     }
1085   }
1086
1087   $self->log_warn("\n");
1088 }
1089
1090 sub prereq_failures {
1091   my ($self, $info) = @_;
1092
1093   my @types = @{ $self->prereq_action_types };
1094   $info ||= {map {$_, $self->$_()} @types};
1095
1096   my $out;
1097
1098   foreach my $type (@types) {
1099     my $prereqs = $info->{$type};
1100     while ( my ($modname, $spec) = each %$prereqs ) {
1101       my $status = $self->check_installed_status($modname, $spec);
1102
1103       if ($type =~ /^(?:\w+_)?conflicts$/) {
1104         next if !$status->{ok};
1105         $status->{conflicts} = delete $status->{need};
1106         $status->{message} = "$modname ($status->{have}) conflicts with this distribution";
1107
1108       } elsif ($type =~ /^(?:\w+_)?recommends$/) {
1109         next if $status->{ok};
1110         $status->{message} = (!ref($status->{have}) && $status->{have} eq '<none>'
1111                               ? "Optional prerequisite $modname is not installed"
1112                               : "$modname ($status->{have}) is installed, but we prefer to have $spec");
1113       } else {
1114         next if $status->{ok};
1115       }
1116
1117       $out->{$type}{$modname} = $status;
1118     }
1119   }
1120
1121   return $out;
1122 }
1123
1124 # returns a hash of defined prerequisites; i.e. only prereq types with values
1125 sub _enum_prereqs {
1126   my $self = shift;
1127   my %prereqs;
1128   foreach my $type ( @{ $self->prereq_action_types } ) {
1129     if ( $self->can( $type ) ) {
1130       my $prereq = $self->$type() || {};
1131       $prereqs{$type} = $prereq if %$prereq;
1132     }
1133   }
1134   return \%prereqs;
1135 }
1136
1137 sub check_prereq {
1138   my $self = shift;
1139
1140   # If we have XS files, make sure we can process them.
1141   my $xs_files = $self->find_xs_files;
1142   if (keys %$xs_files && !$self->_mb_feature('C_support')) {
1143     $self->log_warn("Warning: this distribution contains XS files, ".
1144                     "but Module::Build is not configured with C_support.  ".
1145                     "Please install ExtUtils::CBuilder to enable C_support.\n");
1146   }
1147
1148   # Check to see if there are any prereqs to check
1149   my $info = $self->_enum_prereqs;
1150   return 1 unless $info;
1151
1152   $self->log_info("Checking prerequisites...\n");
1153
1154   my $failures = $self->prereq_failures($info);
1155
1156   if ( $failures ) {
1157
1158     while (my ($type, $prereqs) = each %$failures) {
1159       while (my ($module, $status) = each %$prereqs) {
1160         my $prefix = ($type =~ /^(?:\w+_)?recommends$/) ? '*' : '- ERROR:';
1161         $self->log_warn(" $prefix $status->{message}\n");
1162       }
1163     }
1164
1165     $self->log_warn(<<EOF);
1166
1167 ERRORS/WARNINGS FOUND IN PREREQUISITES.  You may wish to install the versions
1168 of the modules indicated above before proceeding with this installation
1169
1170 EOF
1171     return 0;
1172
1173   } else {
1174
1175     $self->log_info("Looks good\n\n");
1176     return 1;
1177
1178   }
1179 }
1180
1181 sub perl_version {
1182   my ($self) = @_;
1183   # Check the current perl interpreter
1184   # It's much more convenient to use $] here than $^V, but 'man
1185   # perlvar' says I'm not supposed to.  Bloody tyrant.
1186   return $^V ? $self->perl_version_to_float(sprintf "%vd", $^V) : $];
1187 }
1188
1189 sub perl_version_to_float {
1190   my ($self, $version) = @_;
1191   $version =~ s/\./../;
1192   $version =~ s/\.(\d+)/sprintf '%03d', $1/eg;
1193   return $version;
1194 }
1195
1196 sub _parse_conditions {
1197   my ($self, $spec) = @_;
1198
1199   if ($spec =~ /^\s*([\w.]+)\s*$/) { # A plain number, maybe with dots, letters, and underscores
1200     return (">= $spec");
1201   } else {
1202     return split /\s*,\s*/, $spec;
1203   }
1204 }
1205
1206 sub check_installed_status {
1207   my ($self, $modname, $spec) = @_;
1208   my %status = (need => $spec);
1209   
1210   if ($modname eq 'perl') {
1211     $status{have} = $self->perl_version;
1212   
1213   } elsif (eval { no strict; $status{have} = ${"${modname}::VERSION"} }) {
1214     # Don't try to load if it's already loaded
1215     
1216   } else {
1217     my $pm_info = Module::Build::ModuleInfo->new_from_module( $modname );
1218     unless (defined( $pm_info )) {
1219       @status{ qw(have message) } = ('<none>', "$modname is not installed");
1220       return \%status;
1221     }
1222     
1223     $status{have} = $pm_info->version();
1224     if ($spec and !$status{have}) {
1225       @status{ qw(have message) } = (undef, "Couldn't find a \$VERSION in prerequisite $modname");
1226       return \%status;
1227     }
1228   }
1229   
1230   my @conditions = $self->_parse_conditions($spec);
1231   
1232   foreach (@conditions) {
1233     my ($op, $version) = /^\s*  (<=?|>=?|==|!=)  \s*  ([\w.]+)  \s*$/x
1234       or die "Invalid prerequisite condition '$_' for $modname";
1235     
1236     $version = $self->perl_version_to_float($version)
1237       if $modname eq 'perl';
1238     
1239     next if $op eq '>=' and !$version;  # Module doesn't have to actually define a $VERSION
1240     
1241     unless ($self->compare_versions( $status{have}, $op, $version )) {
1242       $status{message} = "$modname ($status{have}) is installed, but we need version $op $version";
1243       return \%status;
1244     }
1245   }
1246   
1247   $status{ok} = 1;
1248   return \%status;
1249 }
1250
1251 sub compare_versions {
1252   my $self = shift;
1253   my ($v1, $op, $v2) = @_;
1254   $v1 = Module::Build::Version->new($v1) 
1255     unless UNIVERSAL::isa($v1,'Module::Build::Version');
1256
1257   my $eval_str = "\$v1 $op \$v2";
1258   my $result   = eval $eval_str;
1259   $self->log_warn("error comparing versions: '$eval_str' $@") if $@;
1260
1261   return $result;
1262 }
1263
1264 # I wish I could set $! to a string, but I can't, so I use $@
1265 sub check_installed_version {
1266   my ($self, $modname, $spec) = @_;
1267   
1268   my $status = $self->check_installed_status($modname, $spec);
1269   
1270   if ($status->{ok}) {
1271     return $status->{have} if $status->{have} and $status->{have} ne '<none>';
1272     return '0 but true';
1273   }
1274   
1275   $@ = $status->{message};
1276   return 0;
1277 }
1278
1279 sub make_executable {
1280   # Perl's chmod() is mapped to useful things on various non-Unix
1281   # platforms, so we use it in the base class even though it looks
1282   # Unixish.
1283
1284   my $self = shift;
1285   foreach (@_) {
1286     my $current_mode = (stat $_)[2];
1287     chmod $current_mode | oct(111), $_;
1288   }
1289 }
1290
1291 sub is_executable {
1292   # We assume this does the right thing on generic platforms, though
1293   # we do some other more specific stuff on Unixish platforms.
1294   my ($self, $file) = @_;
1295   return -x $file;
1296 }
1297
1298 sub _startperl { shift()->config('startperl') }
1299
1300 # Return any directories in @INC which are not in the default @INC for
1301 # this perl.  For example, stuff passed in with -I or loaded with "use lib".
1302 sub _added_to_INC {
1303   my $self = shift;
1304
1305   my %seen;
1306   $seen{$_}++ foreach $self->_default_INC;
1307   return grep !$seen{$_}++, @INC;
1308 }
1309
1310 # Determine the default @INC for this Perl
1311 {
1312   my @default_inc; # Memoize
1313   sub _default_INC {
1314     my $self = shift;
1315     return @default_inc if @default_inc;
1316     
1317     local $ENV{PERL5LIB};  # this is not considered part of the default.
1318     
1319     my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
1320     
1321     my @inc = $self->_backticks($perl, '-le', 'print for @INC');
1322     chomp @inc;
1323     
1324     return @default_inc = @inc;
1325   }
1326 }
1327
1328 sub print_build_script {
1329   my ($self, $fh) = @_;
1330   
1331   my $build_package = $self->build_class;
1332   
1333   my $closedata="";
1334
1335   my %q = map {$_, $self->$_()} qw(config_dir base_dir);
1336
1337   my $case_tolerant = 0+(File::Spec->can('case_tolerant')
1338                          && File::Spec->case_tolerant);
1339   $q{base_dir} = uc $q{base_dir} if $case_tolerant;
1340   $q{base_dir} = Win32::GetShortPathName($q{base_dir}) if $^O eq 'MSWin32';
1341
1342   $q{magic_numfile} = $self->config_file('magicnum');
1343
1344   my @myINC = $self->_added_to_INC;
1345   for (@myINC, values %q) {
1346     $_ = File::Spec->canonpath( $_ );
1347     s/([\\\'])/\\$1/g;
1348   }
1349
1350   my $quoted_INC = join ",\n", map "     '$_'", @myINC;
1351   my $shebang = $self->_startperl;
1352   my $magic_number = $self->magic_number;
1353
1354   print $fh <<EOF;
1355 $shebang
1356
1357 use strict;
1358 use Cwd;
1359 use File::Basename;
1360 use File::Spec;
1361
1362 sub magic_number_matches {
1363   return 0 unless -e '$q{magic_numfile}';
1364   local *FH;
1365   open FH, '$q{magic_numfile}' or return 0;
1366   my \$filenum = <FH>;
1367   close FH;
1368   return \$filenum == $magic_number;
1369 }
1370
1371 my \$progname;
1372 my \$orig_dir;
1373 BEGIN {
1374   \$^W = 1;  # Use warnings
1375   \$progname = basename(\$0);
1376   \$orig_dir = Cwd::cwd();
1377   my \$base_dir = '$q{base_dir}';
1378   if (!magic_number_matches()) {
1379     unless (chdir(\$base_dir)) {
1380       die ("Couldn't chdir(\$base_dir), aborting\\n");
1381     }
1382     unless (magic_number_matches()) {
1383       die ("Configuration seems to be out of date, please re-run 'perl Build.PL' again.\\n");
1384     }
1385   }
1386   unshift \@INC,
1387     (
1388 $quoted_INC
1389     );
1390 }
1391
1392 close(*DATA) unless eof(*DATA); # ensure no open handles to this script
1393
1394 use $build_package;
1395
1396 # Some platforms have problems setting \$^X in shebang contexts, fix it up here
1397 \$^X = Module::Build->find_perl_interpreter;
1398
1399 if (-e 'Build.PL' and not $build_package->up_to_date('Build.PL', \$progname)) {
1400    warn "Warning: Build.PL has been altered.  You may need to run 'perl Build.PL' again.\\n";
1401 }
1402
1403 # This should have just enough arguments to be able to bootstrap the rest.
1404 my \$build = $build_package->resume (
1405   properties => {
1406     config_dir => '$q{config_dir}',
1407     orig_dir => \$orig_dir,
1408   },
1409 );
1410
1411 \$build->dispatch;
1412 EOF
1413 }
1414
1415 sub create_build_script {
1416   my ($self) = @_;
1417   $self->write_config;
1418   
1419   my ($build_script, $dist_name, $dist_version)
1420     = map $self->$_(), qw(build_script dist_name dist_version);
1421   
1422   if ( $self->delete_filetree($build_script) ) {
1423     $self->log_info("Removed previous script '$build_script'\n\n");
1424   }
1425
1426   $self->log_info("Creating new '$build_script' script for ",
1427                   "'$dist_name' version '$dist_version'\n");
1428   my $fh = IO::File->new(">$build_script") or die "Can't create '$build_script': $!";
1429   $self->print_build_script($fh);
1430   close $fh;
1431   
1432   $self->make_executable($build_script);
1433
1434   return 1;
1435 }
1436
1437 sub check_manifest {
1438   my $self = shift;
1439   return unless -e 'MANIFEST';
1440   
1441   # Stolen nearly verbatim from MakeMaker.  But ExtUtils::Manifest
1442   # could easily be re-written into a modern Perl dialect.
1443
1444   require ExtUtils::Manifest;  # ExtUtils::Manifest is not warnings clean.
1445   local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
1446   
1447   $self->log_info("Checking whether your kit is complete...\n");
1448   if (my @missed = ExtUtils::Manifest::manicheck()) {
1449     $self->log_warn("WARNING: the following files are missing in your kit:\n",
1450                     "\t", join("\n\t", @missed), "\n",
1451                     "Please inform the author.\n\n");
1452   } else {
1453     $self->log_info("Looks good\n\n");
1454   }
1455 }
1456
1457 sub dispatch {
1458   my $self = shift;
1459   local $self->{_completed_actions} = {};
1460
1461   if (@_) {
1462     my ($action, %p) = @_;
1463     my $args = $p{args} ? delete($p{args}) : {};
1464
1465     local $self->{invoked_action} = $action;
1466     local $self->{args} = {%{$self->{args}}, %$args};
1467     local $self->{properties} = {%{$self->{properties}}, %p};
1468     return $self->_call_action($action);
1469   }
1470
1471   die "No build action specified" unless $self->{action};
1472   local $self->{invoked_action} = $self->{action};
1473   $self->_call_action($self->{action});
1474 }
1475
1476 sub _call_action {
1477   my ($self, $action) = @_;
1478
1479   return if $self->{_completed_actions}{$action}++;
1480
1481   local $self->{action} = $action;
1482   my $method = "ACTION_$action";
1483   die "No action '$action' defined, try running the 'help' action.\n" unless $self->can($method);
1484   return $self->$method();
1485 }
1486
1487 sub cull_options {
1488     my $self = shift;
1489     my $specs = $self->get_options or return ({}, @_);
1490     require Getopt::Long;
1491     # XXX Should we let Getopt::Long handle M::B's options? That would
1492     # be easy-ish to add to @specs right here, but wouldn't handle options
1493     # passed without "--" as M::B currently allows. We might be able to
1494     # get around this by setting the "prefix_pattern" Configure option.
1495     my @specs;
1496     my $args = {};
1497     # Construct the specifications for GetOptions.
1498     while (my ($k, $v) = each %$specs) {
1499         # Throw an error if specs conflict with our own.
1500         die "Option specification '$k' conflicts with a " . ref $self
1501           . " option of the same name"
1502           if $self->valid_property($k);
1503         push @specs, $k . (defined $v->{type} ? $v->{type} : '');
1504         push @specs, $v->{store} if exists $v->{store};
1505         $args->{$k} = $v->{default} if exists $v->{default};
1506     }
1507
1508     local @ARGV = @_; # No other way to dupe Getopt::Long
1509
1510     # Get the options values and return them.
1511     # XXX Add option to allow users to set options?
1512     if ( @specs ) {
1513       Getopt::Long::Configure('pass_through');
1514       Getopt::Long::GetOptions($args, @specs);
1515     }
1516
1517     return $args, @ARGV;
1518 }
1519
1520 sub unparse_args {
1521   my ($self, $args) = @_;
1522   my @out;
1523   while (my ($k, $v) = each %$args) {
1524     push @out, (UNIVERSAL::isa($v, 'HASH')  ? map {+"--$k", "$_=$v->{$_}"} keys %$v :
1525                 UNIVERSAL::isa($v, 'ARRAY') ? map {+"--$k", $_} @$v :
1526                 ("--$k", $v));
1527   }
1528   return @out;
1529 }
1530
1531 sub args {
1532     my $self = shift;
1533     return wantarray ? %{ $self->{args} } : $self->{args} unless @_;
1534     my $key = shift;
1535     $self->{args}{$key} = shift if @_;
1536     return $self->{args}{$key};
1537 }
1538
1539 sub _translate_option {
1540   my $self = shift;
1541   my $opt  = shift;
1542
1543   (my $tr_opt = $opt) =~ tr/-/_/;
1544
1545   return $tr_opt if grep $tr_opt =~ /^(?:no_?)?$_$/, qw(
1546     create_makefile_pl
1547     create_readme
1548     extra_compiler_flags
1549     extra_linker_flags
1550     html_css
1551     install_base
1552     install_path
1553     meta_add
1554     meta_merge
1555     test_files
1556     use_rcfile
1557   ); # normalize only selected option names
1558
1559   return $opt;
1560 }
1561
1562 sub _read_arg {
1563   my ($self, $args, $key, $val) = @_;
1564
1565   $key = $self->_translate_option($key);
1566
1567   if ( exists $args->{$key} ) {
1568     $args->{$key} = [ $args->{$key} ] unless ref $args->{$key};
1569     push @{$args->{$key}}, $val;
1570   } else {
1571     $args->{$key} = $val;
1572   }
1573 }
1574
1575 sub _optional_arg {
1576   my $self = shift;
1577   my $opt  = shift;
1578   my $argv = shift;
1579
1580   $opt = $self->_translate_option($opt);
1581
1582   my @bool_opts = qw(
1583     build_bat
1584     create_readme
1585     pollute
1586     quiet
1587     uninst
1588     use_rcfile
1589     verbose
1590   );
1591
1592   # inverted boolean options; eg --noverbose or --no-verbose
1593   # converted to proper name & returned with false value (verbose, 0)
1594   if ( grep $opt =~ /^no[-_]?$_$/, @bool_opts ) {
1595     $opt =~ s/^no-?//;
1596     return ($opt, 0);
1597   }
1598
1599   # non-boolean option; return option unchanged along with its argument
1600   return ($opt, shift(@$argv)) unless grep $_ eq $opt, @bool_opts;
1601
1602   # we're punting a bit here, if an option appears followed by a digit
1603   # we take the digit as the argument for the option. If there is
1604   # nothing that looks like a digit, we pretent the option is a flag
1605   # that is being set and has no argument.
1606   my $arg = 1;
1607   $arg = shift(@$argv) if @$argv && $argv->[0] =~ /^\d+$/;
1608
1609   return ($opt, $arg);
1610 }
1611
1612 sub read_args {
1613   my $self = shift;
1614   my ($action, @argv);
1615   (my $args, @_) = $self->cull_options(@_);
1616   my %args = %$args;
1617
1618   my $opt_re = qr/[\w\-]+/;
1619
1620   while (@_) {
1621     local $_ = shift;
1622     if ( /^(?:--)?($opt_re)=(.*)$/ ) {
1623       $self->_read_arg(\%args, $1, $2);
1624     } elsif ( /^--($opt_re)$/ ) {
1625       my($opt, $arg) = $self->_optional_arg($1, \@_);
1626       $self->_read_arg(\%args, $opt, $arg);
1627     } elsif ( /^($opt_re)$/ and !defined($action)) {
1628       $action = $1;
1629     } else {
1630       push @argv, $_;
1631     }
1632   }
1633   $args{ARGV} = \@argv;
1634
1635   # Hashify these parameters
1636   for ($self->hash_properties, 'config') {
1637     next unless exists $args{$_};
1638     my %hash;
1639     $args{$_} ||= [];
1640     $args{$_} = [ $args{$_} ] unless ref $args{$_};
1641     foreach my $arg ( @{$args{$_}} ) {
1642       $arg =~ /(\w+)=(.*)/
1643         or die "Malformed '$_' argument: '$arg' should be something like 'foo=bar'";
1644       $hash{$1} = $2;
1645     }
1646     $args{$_} = \%hash;
1647   }
1648
1649   # De-tilde-ify any path parameters
1650   for my $key (qw(prefix install_base destdir)) {
1651     next if !defined $args{$key};
1652     $args{$key} = _detildefy($args{$key});
1653   }
1654
1655   for my $key (qw(install_path)) {
1656     next if !defined $args{$key};
1657
1658     for my $subkey (keys %{$args{$key}}) {
1659       next if !defined $args{$key}{$subkey};
1660       my $subkey_ext = _detildefy($args{$key}{$subkey});
1661       if ( $subkey eq 'html' ) { # translate for compatability
1662         $args{$key}{binhtml} = $subkey_ext;
1663         $args{$key}{libhtml} = $subkey_ext;
1664       } else {
1665         $args{$key}{$subkey} = $subkey_ext;
1666       }
1667     }
1668   }
1669
1670   if ($args{makefile_env_macros}) {
1671     require Module::Build::Compat;
1672     %args = (%args, Module::Build::Compat->makefile_to_build_macros);
1673   }
1674   
1675   return \%args, $action;
1676 }
1677
1678
1679 sub _detildefy {
1680     my $arg = shift;
1681
1682     return $arg =~ /^~/ ? (glob $arg)[0] : $arg;
1683 }
1684
1685
1686 # merge Module::Build argument lists that have already been parsed
1687 # by read_args(). Takes two references to option hashes and merges
1688 # the contents, giving priority to the first.
1689 sub _merge_arglist {
1690   my( $self, $opts1, $opts2 ) = @_;
1691
1692   my %new_opts = %$opts1;
1693   while (my ($key, $val) = each %$opts2) {
1694     if ( exists( $opts1->{$key} ) ) {
1695       if ( ref( $val ) eq 'HASH' ) {
1696         while (my ($k, $v) = each %$val) {
1697           $new_opts{$key}{$k} = $v unless exists( $opts1->{$key}{$k} );
1698         }
1699       }
1700     } else {
1701       $new_opts{$key} = $val
1702     }
1703   }
1704
1705   return %new_opts;
1706 }
1707
1708 # Look for a home directory on various systems.
1709 sub _home_dir {
1710   my @home_dirs;
1711   push( @home_dirs, $ENV{HOME} ) if $ENV{HOME};
1712
1713   push( @home_dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
1714       if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};
1715
1716   my @other_home_envs = qw( USERPROFILE APPDATA WINDIR SYS$LOGIN );
1717   push( @home_dirs, map $ENV{$_}, grep $ENV{$_}, @other_home_envs );
1718
1719   my @real_home_dirs = grep -d, @home_dirs;
1720
1721   return wantarray ? @real_home_dirs : shift( @real_home_dirs );
1722 }
1723
1724 sub _find_user_config {
1725   my $self = shift;
1726   my $file = shift;
1727   foreach my $dir ( $self->_home_dir ) {
1728     my $path = File::Spec->catfile( $dir, $file );
1729     return $path if -e $path;
1730   }
1731   return undef;
1732 }
1733
1734 # read ~/.modulebuildrc returning global options '*' and
1735 # options specific to the currently executing $action.
1736 sub read_modulebuildrc {
1737   my( $self, $action ) = @_;
1738
1739   return () unless $self->use_rcfile;
1740
1741   my $modulebuildrc;
1742   if ( exists($ENV{MODULEBUILDRC}) && $ENV{MODULEBUILDRC} eq 'NONE' ) {
1743     return ();
1744   } elsif ( exists($ENV{MODULEBUILDRC}) && -e $ENV{MODULEBUILDRC} ) {
1745     $modulebuildrc = $ENV{MODULEBUILDRC};
1746   } elsif ( exists($ENV{MODULEBUILDRC}) ) {
1747     $self->log_warn("WARNING: Can't find resource file " .
1748                     "'$ENV{MODULEBUILDRC}' defined in environment.\n" .
1749                     "No options loaded\n");
1750     return ();
1751   } else {
1752     $modulebuildrc = $self->_find_user_config( '.modulebuildrc' );
1753     return () unless $modulebuildrc;
1754   }
1755
1756   my $fh = IO::File->new( $modulebuildrc )
1757       or die "Can't open $modulebuildrc: $!";
1758
1759   my %options; my $buffer = '';
1760   while (defined( my $line = <$fh> )) {
1761     chomp( $line );
1762     $line =~ s/#.*$//;
1763     next unless length( $line );
1764
1765     if ( $line =~ /^\S/ ) {
1766       if ( $buffer ) {
1767         my( $action, $options ) = split( /\s+/, $buffer, 2 );
1768         $options{$action} .= $options . ' ';
1769         $buffer = '';
1770       }
1771       $buffer = $line;
1772     } else {
1773       $buffer .= $line;
1774     }
1775   }
1776
1777   if ( $buffer ) { # anything left in $buffer ?
1778     my( $action, $options ) = split( /\s+/, $buffer, 2 );
1779     $options{$action} .= $options . ' '; # merge if more than one line
1780   }
1781
1782   my ($global_opts) =
1783     $self->read_args( $self->split_like_shell( $options{'*'} || '' ) );
1784   my ($action_opts) =
1785     $self->read_args( $self->split_like_shell( $options{$action} || '' ) );
1786
1787   # specific $action options take priority over global options '*'
1788   return $self->_merge_arglist( $action_opts, $global_opts );
1789 }
1790
1791 # merge the relevant options in ~/.modulebuildrc into Module::Build's
1792 # option list where they do not conflict with commandline options.
1793 sub merge_modulebuildrc {
1794   my( $self, $action, %cmdline_opts ) = @_;
1795   my %rc_opts = $self->read_modulebuildrc( $action || $self->{action} || 'build' );
1796   my %new_opts = $self->_merge_arglist( \%cmdline_opts, \%rc_opts );
1797   $self->merge_args( $action, %new_opts );
1798 }
1799
1800 sub merge_args {
1801   my ($self, $action, %args) = @_;
1802   $self->{action} = $action if defined $action;
1803
1804   my %additive = map { $_ => 1 } $self->hash_properties;
1805
1806   # Extract our 'properties' from $cmd_args, the rest are put in 'args'.
1807   while (my ($key, $val) = each %args) {
1808     $self->{phash}{runtime_params}->access( $key => $val )
1809       if $self->valid_property($key);
1810
1811     if ($key eq 'config') {
1812       $self->config($_ => $val->{$_}) foreach keys %$val;
1813     } else {
1814       my $add_to = ( $additive{$key} ? $self->{properties}{$key}
1815                      : $self->valid_property($key) ? $self->{properties}
1816                      : $self->{args});
1817
1818       if ($additive{$key}) {
1819         $add_to->{$_} = $val->{$_} foreach keys %$val;
1820       } else {
1821         $add_to->{$key} = $val;
1822       }
1823     }
1824   }
1825 }
1826
1827 sub cull_args {
1828   my $self = shift;
1829   my ($args, $action) = $self->read_args(@_);
1830   $self->merge_args($action, %$args);
1831   $self->merge_modulebuildrc( $action, %$args );
1832 }
1833
1834 sub super_classes {
1835   my ($self, $class, $seen) = @_;
1836   $class ||= ref($self) || $self;
1837   $seen  ||= {};
1838   
1839   no strict 'refs';
1840   my @super = grep {not $seen->{$_}++} $class, @{ $class . '::ISA' };
1841   return @super, map {$self->super_classes($_,$seen)} @super;
1842 }
1843
1844 sub known_actions {
1845   my ($self) = @_;
1846
1847   my %actions;
1848   no strict 'refs';
1849   
1850   foreach my $class ($self->super_classes) {
1851     foreach ( keys %{ $class . '::' } ) {
1852       $actions{$1}++ if /^ACTION_(\w+)/;
1853     }
1854   }
1855
1856   return wantarray ? sort keys %actions : \%actions;
1857 }
1858
1859 sub get_action_docs {
1860   my ($self, $action, $actions) = @_;
1861   $actions ||= $self->known_actions;
1862   $@ = '';
1863   ($@ = "No known action '$action'\n"), return
1864     unless $actions->{$action};
1865   
1866   my ($files_found, @docs) = (0);
1867   foreach my $class ($self->super_classes) {
1868     (my $file = $class) =~ s{::}{/}g;
1869     $file = $INC{$file . '.pm'} or next;
1870     my $fh = IO::File->new("< $file") or next;
1871     $files_found++;
1872     
1873     # Code below modified from /usr/bin/perldoc
1874     
1875     # Skip to ACTIONS section
1876     local $_;
1877     while (<$fh>) {
1878       last if /^=head1 ACTIONS\s/;
1879     }
1880     
1881     # Look for our action
1882     my ($found, $inlist) = (0, 0);
1883     while (<$fh>) {
1884       if (/^=item\s+\Q$action\E\b/)  {
1885         $found = 1;
1886       } elsif (/^=(item|back)/) {
1887         last if $found > 1 and not $inlist;
1888       }
1889       next unless $found;
1890       push @docs, $_;
1891       ++$inlist if /^=over/;
1892       --$inlist if /^=back/;
1893       ++$found  if /^\w/; # Found descriptive text
1894     }
1895   }
1896
1897   unless ($files_found) {
1898     $@ = "Couldn't find any documentation to search";
1899     return;
1900   }
1901   unless (@docs) {
1902     $@ = "Couldn't find any docs for action '$action'";
1903     return;
1904   }
1905   
1906   return join '', @docs;
1907 }
1908
1909 sub ACTION_prereq_report {
1910   my $self = shift;
1911   $self->log_info( $self->prereq_report );
1912 }
1913
1914 sub prereq_report {
1915   my $self = shift;
1916   my @types = @{ $self->prereq_action_types };
1917   my $info = { map { $_ => $self->$_() } @types };
1918
1919   my $output = '';
1920   foreach my $type (@types) {
1921     my $prereqs = $info->{$type};
1922     next unless %$prereqs;
1923     $output .= "\n$type:\n";
1924     my $mod_len = 2;
1925     my $ver_len = 4;
1926     my %mods;
1927     while ( my ($modname, $spec) = each %$prereqs ) {
1928       my $len  = length $modname;
1929       $mod_len = $len if $len > $mod_len;
1930       $spec    ||= '0';
1931       $len     = length $spec;
1932       $ver_len = $len if $len > $ver_len;
1933
1934       my $mod = $self->check_installed_status($modname, $spec);
1935       $mod->{name} = $modname;
1936       $mod->{ok} ||= 0;
1937       $mod->{ok} = ! $mod->{ok} if $type =~ /^(\w+_)?conflicts$/;
1938
1939       $mods{lc $modname} = $mod;
1940     }
1941
1942     my $space  = q{ } x ($mod_len - 3);
1943     my $vspace = q{ } x ($ver_len - 3);
1944     my $sline  = q{-} x ($mod_len - 3);
1945     my $vline  = q{-} x ($ver_len - 3);
1946     my $disposition = ($type =~ /^(\w+_)?conflicts$/) ?
1947                         'Clash' : 'Need';
1948     $output .=
1949       "    Module $space  $disposition $vspace  Have\n".
1950       "    ------$sline+------$vline-+----------\n";
1951
1952
1953     for my $k (sort keys %mods) {
1954       my $mod = $mods{$k};
1955       my $space  = q{ } x ($mod_len - length $k);
1956       my $vspace = q{ } x ($ver_len - length $mod->{need});
1957       my $f = $mod->{ok} ? ' ' : '!';
1958       $output .=
1959         "  $f $mod->{name} $space     $mod->{need}  $vspace   $mod->{have}\n";
1960     }
1961   }
1962   return $output;
1963 }
1964
1965 sub ACTION_help {
1966   my ($self) = @_;
1967   my $actions = $self->known_actions;
1968   
1969   if (@{$self->{args}{ARGV}}) {
1970     my $msg = $self->get_action_docs($self->{args}{ARGV}[0], $actions) || "$@\n";
1971     print $msg;
1972     return;
1973   }
1974
1975   print <<EOF;
1976
1977  Usage: $0 <action> arg1=value arg2=value ...
1978  Example: $0 test verbose=1
1979  
1980  Actions defined:
1981 EOF
1982   
1983   print $self->_action_listing($actions);
1984
1985   print "\nRun `Build help <action>` for details on an individual action.\n";
1986   print "See `perldoc Module::Build` for complete documentation.\n";
1987 }
1988
1989 sub _action_listing {
1990   my ($self, $actions) = @_;
1991
1992   # Flow down columns, not across rows
1993   my @actions = sort keys %$actions;
1994   @actions = map $actions[($_ + ($_ % 2) * @actions) / 2],  0..$#actions;
1995   
1996   my $out = '';
1997   while (my ($one, $two) = splice @actions, 0, 2) {
1998     $out .= sprintf("  %-12s                   %-12s\n", $one, $two||'');
1999   }
2000   return $out;
2001 }
2002
2003 sub ACTION_retest {
2004   my ($self) = @_;
2005   
2006   # Protect others against our @INC changes
2007   local @INC = @INC;
2008
2009   # Filter out nonsensical @INC entries - some versions of
2010   # Test::Harness will really explode the number of entries here
2011   @INC = grep {ref() || -d} @INC if @INC > 100;
2012
2013   $self->do_tests;
2014 }
2015
2016
2017 sub ACTION_test {
2018   my ($self) = @_;
2019   my $p = $self->{properties};
2020   
2021   $self->depends_on('code');
2022   
2023   # Protect others against our @INC changes
2024   local @INC = @INC;
2025
2026   # Make sure we test the module in blib/
2027   unshift @INC, (File::Spec->catdir($p->{base_dir}, $self->blib, 'lib'),
2028                  File::Spec->catdir($p->{base_dir}, $self->blib, 'arch'));
2029
2030   # Filter out nonsensical @INC entries - some versions of
2031   # Test::Harness will really explode the number of entries here
2032   @INC = grep {ref() || -d} @INC if @INC > 100;
2033
2034   $self->do_tests;
2035 }
2036
2037 sub do_tests {
2038   my $self = shift;
2039   my $p = $self->{properties};
2040   require Test::Harness;
2041
2042   # Do everything in our power to work with all versions of Test::Harness
2043   my @harness_switches = $p->{debugger} ? qw(-w -d) : ();
2044   local $Test::Harness::switches    = join ' ', grep defined, $Test::Harness::switches, @harness_switches;
2045   local $Test::Harness::Switches    = join ' ', grep defined, $Test::Harness::Switches, @harness_switches;
2046   local $ENV{HARNESS_PERL_SWITCHES} = join ' ', grep defined, $ENV{HARNESS_PERL_SWITCHES}, @harness_switches;
2047   
2048   $Test::Harness::switches = undef   unless length $Test::Harness::switches;
2049   $Test::Harness::Switches = undef   unless length $Test::Harness::Switches;
2050   delete $ENV{HARNESS_PERL_SWITCHES} unless length $ENV{HARNESS_PERL_SWITCHES};
2051   
2052   local ($Test::Harness::verbose,
2053          $Test::Harness::Verbose,
2054          $ENV{TEST_VERBOSE},
2055          $ENV{HARNESS_VERBOSE}) = ($p->{verbose} || 0) x 4;
2056
2057   my $tests = $self->find_test_files;
2058
2059   if (@$tests) {
2060     # Work around a Test::Harness bug that loses the particular perl
2061     # we're running under.  $self->perl is trustworthy, but $^X isn't.
2062     local $^X = $self->perl;
2063     Test::Harness::runtests(@$tests);
2064   } else {
2065     $self->log_info("No tests defined.\n");
2066   }
2067
2068   # This will get run and the user will see the output.  It doesn't
2069   # emit Test::Harness-style output.
2070   if (-e 'visual.pl') {
2071     $self->run_perl_script('visual.pl', '-Mblib='.$self->blib);
2072   }
2073 }
2074
2075 sub test_files {
2076   my $self = shift;
2077   my $p = $self->{properties};
2078   if (@_) {
2079     return $p->{test_files} = (@_ == 1 ? shift : [@_]);
2080   }
2081   return $self->find_test_files;
2082 }
2083
2084 sub expand_test_dir {
2085   my ($self, $dir) = @_;
2086   return sort @{$self->rscan_dir($dir, qr{^[^.].*\.t$})} if $self->recursive_test_files;
2087   return sort glob File::Spec->catfile($dir, "*.t");
2088 }
2089
2090 sub ACTION_testdb {
2091   my ($self) = @_;
2092   local $self->{properties}{debugger} = 1;
2093   $self->depends_on('test');
2094 }
2095
2096 sub ACTION_testcover {
2097   my ($self) = @_;
2098
2099   unless (Module::Build::ModuleInfo->find_module_by_name('Devel::Cover')) {
2100     warn("Cannot run testcover action unless Devel::Cover is installed.\n");
2101     return;
2102   }
2103
2104   $self->add_to_cleanup('coverage', 'cover_db');
2105   $self->depends_on('code');
2106
2107   # See whether any of the *.pm files have changed since last time
2108   # testcover was run.  If so, start over.
2109   if (-e 'cover_db') {
2110     my $pm_files = $self->rscan_dir(File::Spec->catdir($self->blib, 'lib'), qr{\.pm$} );
2111     my $cover_files = $self->rscan_dir('cover_db', sub {-f $_ and not /\.html$/});
2112     
2113     $self->do_system(qw(cover -delete))
2114       unless $self->up_to_date($pm_files,         $cover_files)
2115           && $self->up_to_date($self->test_files, $cover_files);
2116   }
2117
2118   local $Test::Harness::switches    = 
2119   local $Test::Harness::Switches    = 
2120   local $ENV{HARNESS_PERL_SWITCHES} = "-MDevel::Cover";
2121
2122   $self->depends_on('test');
2123   $self->do_system('cover');
2124 }
2125
2126 sub ACTION_code {
2127   my ($self) = @_;
2128   
2129   # All installable stuff gets created in blib/ .
2130   # Create blib/arch to keep blib.pm happy
2131   my $blib = $self->blib;
2132   $self->add_to_cleanup($blib);
2133   File::Path::mkpath( File::Spec->catdir($blib, 'arch') );
2134   
2135   if (my $split = $self->autosplit) {
2136     $self->autosplit_file($_, $blib) for ref($split) ? @$split : ($split);
2137   }
2138   
2139   foreach my $element (@{$self->build_elements}) {
2140     my $method = "process_${element}_files";
2141     $method = "process_files_by_extension" unless $self->can($method);
2142     $self->$method($element);
2143   }
2144
2145   $self->depends_on('config_data');
2146 }
2147
2148 sub ACTION_build {
2149   my $self = shift;
2150   $self->depends_on('code');
2151   $self->depends_on('docs');
2152 }
2153
2154 sub process_files_by_extension {
2155   my ($self, $ext) = @_;
2156   
2157   my $method = "find_${ext}_files";
2158   my $files = $self->can($method) ? $self->$method() : $self->_find_file_by_type($ext,  'lib');
2159   
2160   while (my ($file, $dest) = each %$files) {
2161     $self->copy_if_modified(from => $file, to => File::Spec->catfile($self->blib, $dest) );
2162   }
2163 }
2164
2165 sub process_support_files {
2166   my $self = shift;
2167   my $p = $self->{properties};
2168   return unless $p->{c_source};
2169   
2170   push @{$p->{include_dirs}}, $p->{c_source};
2171   
2172   my $files = $self->rscan_dir($p->{c_source}, qr{\.c(pp)?$});
2173   foreach my $file (@$files) {
2174     push @{$p->{objects}}, $self->compile_c($file);
2175   }
2176 }
2177
2178 sub process_PL_files {
2179   my ($self) = @_;
2180   my $files = $self->find_PL_files;
2181   
2182   while (my ($file, $to) = each %$files) {
2183     unless ($self->up_to_date( $file, $to )) {
2184       $self->run_perl_script($file, [], [@$to]);
2185       $self->add_to_cleanup(@$to);
2186     }
2187   }
2188 }
2189
2190 sub process_xs_files {
2191   my $self = shift;
2192   my $files = $self->find_xs_files;
2193   while (my ($from, $to) = each %$files) {
2194     unless ($from eq $to) {
2195       $self->add_to_cleanup($to);
2196       $self->copy_if_modified( from => $from, to => $to );
2197     }
2198     $self->process_xs($to);
2199   }
2200 }
2201
2202 sub process_pod_files { shift()->process_files_by_extension(shift()) }
2203 sub process_pm_files  { shift()->process_files_by_extension(shift()) }
2204
2205 sub process_script_files {
2206   my $self = shift;
2207   my $files = $self->find_script_files;
2208   return unless keys %$files;
2209
2210   my $script_dir = File::Spec->catdir($self->blib, 'script');
2211   File::Path::mkpath( $script_dir );
2212   
2213   foreach my $file (keys %$files) {
2214     my $result = $self->copy_if_modified($file, $script_dir, 'flatten') or next;
2215     $self->fix_shebang_line($result) unless $self->os_type eq 'VMS';
2216     $self->make_executable($result);
2217   }
2218 }
2219
2220 sub find_PL_files {
2221   my $self = shift;
2222   if (my $files = $self->{properties}{PL_files}) {
2223     # 'PL_files' is given as a Unix file spec, so we localize_file_path().
2224     
2225     if (UNIVERSAL::isa($files, 'ARRAY')) {
2226       return { map {$_, [/^(.*)\.PL$/]}
2227                map $self->localize_file_path($_),
2228                @$files };
2229
2230     } elsif (UNIVERSAL::isa($files, 'HASH')) {
2231       my %out;
2232       while (my ($file, $to) = each %$files) {
2233         $out{ $self->localize_file_path($file) } = [ map $self->localize_file_path($_),
2234                                                      ref $to ? @$to : ($to) ];
2235       }
2236       return \%out;
2237
2238     } else {
2239       die "'PL_files' must be a hash reference or array reference";
2240     }
2241   }
2242   
2243   return unless -d 'lib';
2244   return { map {$_, [/^(.*)\.PL$/]} @{ $self->rscan_dir('lib', qr{\.PL$}) } };
2245 }
2246
2247 sub find_pm_files  { shift->_find_file_by_type('pm',  'lib') }
2248 sub find_pod_files { shift->_find_file_by_type('pod', 'lib') }
2249 sub find_xs_files  { shift->_find_file_by_type('xs',  'lib') }
2250
2251 sub find_script_files {
2252   my $self = shift;
2253   if (my $files = $self->script_files) {
2254     # Always given as a Unix file spec.  Values in the hash are
2255     # meaningless, but we preserve if present.
2256     return { map {$self->localize_file_path($_), $files->{$_}} keys %$files };
2257   }
2258   
2259   # No default location for script files
2260   return {};
2261 }
2262
2263 sub find_test_files {
2264   my $self = shift;
2265   my $p = $self->{properties};
2266   
2267   if (my $files = $p->{test_files}) {
2268     $files = [keys %$files] if UNIVERSAL::isa($files, 'HASH');
2269     $files = [map { -d $_ ? $self->expand_test_dir($_) : $_ }
2270               map glob,
2271               $self->split_like_shell($files)];
2272     
2273     # Always given as a Unix file spec.
2274     return [ map $self->localize_file_path($_), @$files ];
2275     
2276   } else {
2277     # Find all possible tests in t/ or test.pl
2278     my @tests;
2279     push @tests, 'test.pl'                          if -e 'test.pl';
2280     push @tests, $self->expand_test_dir('t')        if -e 't' and -d _;
2281     return \@tests;
2282   }
2283 }
2284
2285 sub _find_file_by_type {
2286   my ($self, $type, $dir) = @_;
2287   
2288   if (my $files = $self->{properties}{"${type}_files"}) {
2289     # Always given as a Unix file spec
2290     return { map $self->localize_file_path($_), %$files };
2291   }
2292   
2293   return {} unless -d $dir;
2294   return { map {$_, $_}
2295            map $self->localize_file_path($_),
2296            grep !/\.\#/,
2297            @{ $self->rscan_dir($dir, qr{\.$type$}) } };
2298 }
2299
2300 sub localize_file_path {
2301   my ($self, $path) = @_;
2302   $path =~ s/\.\z// if $self->os_type eq 'VMS';
2303   return File::Spec->catfile( split m{/}, $path );
2304 }
2305
2306 sub localize_dir_path {
2307   my ($self, $path) = @_;
2308   return File::Spec->catdir( split m{/}, $path );
2309 }
2310
2311 sub fix_shebang_line { # Adapted from fixin() in ExtUtils::MM_Unix 1.35
2312   my ($self, @files) = @_;
2313   my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
2314   
2315   my ($does_shbang) = $c->get('sharpbang') =~ /^\s*\#\!/;
2316   for my $file (@files) {
2317     my $FIXIN = IO::File->new($file) or die "Can't process '$file': $!";
2318     local $/ = "\n";
2319     chomp(my $line = <$FIXIN>);
2320     next unless $line =~ s/^\s*\#!\s*//;     # Not a shbang file.
2321     
2322     my ($cmd, $arg) = (split(' ', $line, 2), '');
2323     next unless $cmd =~ /perl/i;
2324     my $interpreter = $self->{properties}{perl};
2325     
2326     $self->log_verbose("Changing sharpbang in $file to $interpreter");
2327     my $shb = '';
2328     $shb .= $c->get('sharpbang')."$interpreter $arg\n" if $does_shbang;
2329     
2330     # I'm not smart enough to know the ramifications of changing the
2331     # embedded newlines here to \n, so I leave 'em in.
2332     $shb .= qq{
2333 eval 'exec $interpreter $arg -S \$0 \${1+"\$\@"}'
2334     if 0; # not running under some shell
2335 } unless $self->os_type eq 'Windows'; # this won't work on win32, so don't
2336     
2337     my $FIXOUT = IO::File->new(">$file.new")
2338       or die "Can't create new $file: $!\n";
2339     
2340     # Print out the new #! line (or equivalent).
2341     local $\;
2342     undef $/; # Was localized above
2343     print $FIXOUT $shb, <$FIXIN>;
2344     close $FIXIN;
2345     close $FIXOUT;
2346     
2347     rename($file, "$file.bak")
2348       or die "Can't rename $file to $file.bak: $!";
2349     
2350     rename("$file.new", $file)
2351       or die "Can't rename $file.new to $file: $!";
2352     
2353     unlink "$file.bak"
2354       or $self->log_warn("Couldn't clean up $file.bak, leaving it there");
2355     
2356     $self->do_system($c->get('eunicefix'), $file) if $c->get('eunicefix') ne ':';
2357   }
2358 }
2359
2360
2361 sub ACTION_testpod {
2362   my $self = shift;
2363   $self->depends_on('docs');
2364   
2365   eval q{use Test::Pod 0.95; 1}
2366     or die "The 'testpod' action requires Test::Pod version 0.95";
2367
2368   my @files = sort keys %{$self->_find_pods($self->libdoc_dirs)},
2369                    keys %{$self->_find_pods($self->bindoc_dirs, exclude => [ qr/\.bat$/ ])}
2370     or die "Couldn't find any POD files to test\n";
2371
2372   { package Module::Build::PodTester;  # Don't want to pollute the main namespace
2373     Test::Pod->import( tests => scalar @files );
2374     pod_file_ok($_) foreach @files;
2375   }
2376 }
2377
2378 sub ACTION_testpodcoverage {
2379   my $self = shift;
2380
2381   $self->depends_on('docs');
2382   
2383   eval q{use Test::Pod::Coverage 1.00; 1}
2384     or die "The 'testpodcoverage' action requires ",
2385            "Test::Pod::Coverage version 1.00";
2386
2387   all_pod_coverage_ok();
2388 }
2389
2390 sub ACTION_docs {
2391   my $self = shift;
2392
2393   $self->depends_on('code');
2394   $self->depends_on('manpages', 'html');
2395 }
2396
2397 # Given a file type, will return true if the file type would normally
2398 # be installed when neither install-base nor prefix has been set.
2399 # I.e. it will be true only if the path is set from Config.pm or
2400 # set explicitly by the user via install-path.
2401 sub _is_default_installable {
2402   my $self = shift;
2403   my $type = shift;
2404   return ( $self->install_destination($type) &&
2405            ( $self->install_path($type) ||
2406              $self->install_sets($self->installdirs)->{$type} )
2407          ) ? 1 : 0;
2408 }
2409
2410 sub ACTION_manpages {
2411   my $self = shift;
2412
2413   return unless $self->_mb_feature('manpage_support');
2414
2415   $self->depends_on('code');
2416
2417   foreach my $type ( qw(bin lib) ) {
2418     my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2419                                    exclude => [ qr/\.bat$/ ] );
2420     next unless %$files;
2421
2422     my $sub = $self->can("manify_${type}_pods");
2423     next unless defined( $sub );
2424
2425     if ( $self->invoked_action eq 'manpages' ) {
2426       $self->$sub();
2427     } elsif ( $self->_is_default_installable("${type}doc") ) {
2428       $self->$sub();
2429     }
2430   }
2431
2432 }
2433
2434 sub manify_bin_pods {
2435   my $self    = shift;
2436
2437   my $files   = $self->_find_pods( $self->{properties}{bindoc_dirs},
2438                                    exclude => [ qr/\.bat$/ ] );
2439   return unless keys %$files;
2440
2441   my $mandir = File::Spec->catdir( $self->blib, 'bindoc' );
2442   File::Path::mkpath( $mandir, 0, oct(777) );
2443
2444   require Pod::Man;
2445   foreach my $file (keys %$files) {
2446     # Pod::Simple based parsers only support one document per instance.
2447     # This is expected to change in a future version (Pod::Simple > 3.03).
2448     my $parser  = Pod::Man->new( section => 1 ); # binaries go in section 1
2449     my $manpage = $self->man1page_name( $file ) . '.' .
2450                   $self->config( 'man1ext' );
2451     my $outfile = File::Spec->catfile($mandir, $manpage);
2452     next if $self->up_to_date( $file, $outfile );
2453     $self->log_info("Manifying $file -> $outfile\n");
2454     $parser->parse_from_file( $file, $outfile );
2455     $files->{$file} = $outfile;
2456   }
2457 }
2458
2459 sub manify_lib_pods {
2460   my $self    = shift;
2461
2462   my $files   = $self->_find_pods($self->{properties}{libdoc_dirs});
2463   return unless keys %$files;
2464
2465   my $mandir = File::Spec->catdir( $self->blib, 'libdoc' );
2466   File::Path::mkpath( $mandir, 0, oct(777) );
2467
2468   require Pod::Man;
2469   while (my ($file, $relfile) = each %$files) {
2470     # Pod::Simple based parsers only support one document per instance.
2471     # This is expected to change in a future version (Pod::Simple > 3.03).
2472     my $parser  = Pod::Man->new( section => 3 ); # libraries go in section 3
2473     my $manpage = $self->man3page_name( $relfile ) . '.' .
2474                   $self->config( 'man3ext' );
2475     my $outfile = File::Spec->catfile( $mandir, $manpage);
2476     next if $self->up_to_date( $file, $outfile );
2477     $self->log_info("Manifying $file -> $outfile\n");
2478     $parser->parse_from_file( $file, $outfile );
2479     $files->{$file} = $outfile;
2480   }
2481 }
2482
2483 sub _find_pods {
2484   my ($self, $dirs, %args) = @_;
2485   my %files;
2486   foreach my $spec (@$dirs) {
2487     my $dir = $self->localize_dir_path($spec);
2488     next unless -e $dir;
2489
2490     FILE: foreach my $file ( @{ $self->rscan_dir( $dir ) } ) {
2491       foreach my $regexp ( @{ $args{exclude} } ) {
2492         next FILE if $file =~ $regexp;
2493       }
2494       $files{$file} = File::Spec->abs2rel($file, $dir) if $self->contains_pod( $file )
2495     }
2496   }
2497   return \%files;
2498 }
2499
2500 sub contains_pod {
2501   my ($self, $file) = @_;
2502   return '' unless -T $file;  # Only look at text files
2503   
2504   my $fh = IO::File->new( $file ) or die "Can't open $file: $!";
2505   while (my $line = <$fh>) {
2506     return 1 if $line =~ /^\=(?:head|pod|item)/;
2507   }
2508   
2509   return '';
2510 }
2511
2512 sub ACTION_html {
2513   my $self = shift;
2514
2515   return unless $self->_mb_feature('HTML_support');
2516
2517   $self->depends_on('code');
2518
2519   foreach my $type ( qw(bin lib) ) {
2520     my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2521                                    exclude => [ qr/\.(?:bat|com|html)$/ ] );
2522     next unless %$files;
2523
2524     if ( $self->invoked_action eq 'html' ) {
2525       $self->htmlify_pods( $type );
2526     } elsif ( $self->_is_default_installable("${type}html") ) {
2527       $self->htmlify_pods( $type );
2528     }
2529   }
2530
2531 }
2532
2533
2534 # 1) If it's an ActiveState perl install, we need to run
2535 #    ActivePerl::DocTools->UpdateTOC;
2536 # 2) Links to other modules are not being generated
2537 sub htmlify_pods {
2538   my $self = shift;
2539   my $type = shift;
2540   my $htmldir = shift || File::Spec->catdir($self->blib, "${type}html");
2541
2542   require Module::Build::PodParser;
2543   require Pod::Html;
2544
2545   $self->add_to_cleanup('pod2htm*');
2546
2547   my $pods = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2548                                 exclude => [ qr/\.(?:bat|com|html)$/ ] );
2549   return unless %$pods;  # nothing to do
2550
2551   unless ( -d $htmldir ) {
2552     File::Path::mkpath($htmldir, 0, oct(755))
2553       or die "Couldn't mkdir $htmldir: $!";
2554   }
2555
2556   my @rootdirs = ($type eq 'bin') ? qw(bin) :
2557       $self->installdirs eq 'core' ? qw(lib) : qw(site lib);
2558
2559   my $podpath = join ':',
2560                 map  $_->[1],
2561                 grep -e $_->[0],
2562                 map  [File::Spec->catdir($self->blib, $_), $_],
2563                 qw( script lib );
2564
2565   foreach my $pod ( keys %$pods ) {
2566
2567     my ($name, $path) = File::Basename::fileparse($pods->{$pod},
2568                                                   qr{\.(?:pm|plx?|pod)$});
2569     my @dirs = File::Spec->splitdir( File::Spec->canonpath( $path ) );
2570     pop( @dirs ) if $dirs[-1] eq File::Spec->curdir;
2571
2572     my $fulldir = File::Spec->catfile($htmldir, @rootdirs, @dirs);
2573     my $outfile = File::Spec->catfile($fulldir, "${name}.html");
2574     my $infile  = File::Spec->abs2rel($pod);
2575
2576     next if $self->up_to_date($infile, $outfile);
2577
2578     unless ( -d $fulldir ){
2579       File::Path::mkpath($fulldir, 0, oct(755))
2580         or die "Couldn't mkdir $fulldir: $!";
2581     }
2582
2583     my $path2root = join( '/', ('..') x (@rootdirs+@dirs) );
2584     my $htmlroot = join( '/',
2585                          ($path2root,
2586                           $self->installdirs eq 'core' ? () : qw(site) ) );
2587
2588     my $fh = IO::File->new($infile) or die "Can't read $infile: $!";
2589     my $abstract = Module::Build::PodParser->new(fh => $fh)->get_abstract();
2590
2591     my $title = join( '::', (@dirs, $name) );
2592     $title .= " - $abstract" if $abstract;
2593
2594     my @opts = (
2595                 '--flush',
2596                 "--title=$title",
2597                 "--podpath=$podpath",
2598                 "--infile=$infile",
2599                 "--outfile=$outfile",
2600                 '--podroot=' . $self->blib,
2601                 "--htmlroot=$htmlroot",
2602                );
2603
2604     if ( eval{Pod::Html->VERSION(1.03)} ) {
2605       push( @opts, ('--header', '--backlink=Back to Top') );
2606       push( @opts, "--css=$path2root/" . $self->html_css) if $self->html_css;
2607     }
2608
2609     $self->log_info("HTMLifying $infile -> $outfile\n");
2610     $self->log_verbose("pod2html @opts\n");
2611     Pod::Html::pod2html(@opts); # or warn "pod2html @opts failed: $!";
2612   }
2613
2614 }
2615
2616 # Adapted from ExtUtils::MM_Unix
2617 sub man1page_name {
2618   my $self = shift;
2619   return File::Basename::basename( shift );
2620 }
2621
2622 # Adapted from ExtUtils::MM_Unix and Pod::Man
2623 # Depending on M::B's dependency policy, it might make more sense to refactor
2624 # Pod::Man::begin_pod() to extract a name() methods, and use them...
2625 #    -spurkis
2626 sub man3page_name {
2627   my $self = shift;
2628   my ($vol, $dirs, $file) = File::Spec->splitpath( shift );
2629   my @dirs = File::Spec->splitdir( File::Spec->canonpath($dirs) );
2630   
2631   # Remove known exts from the base name
2632   $file =~ s/\.p(?:od|m|l)\z//i;
2633   
2634   return join( $self->manpage_separator, @dirs, $file );
2635 }
2636
2637 sub manpage_separator {
2638   return '::';
2639 }
2640
2641 # For systems that don't have 'diff' executable, should use Algorithm::Diff
2642 sub ACTION_diff {
2643   my $self = shift;
2644   $self->depends_on('build');
2645   my $local_lib = File::Spec->rel2abs('lib');
2646   my @myINC = grep {$_ ne $local_lib} @INC;
2647
2648   # The actual install destination might not be in @INC, so check there too.
2649   push @myINC, map $self->install_destination($_), qw(lib arch);
2650
2651   my @flags = @{$self->{args}{ARGV}};
2652   @flags = $self->split_like_shell($self->{args}{flags} || '') unless @flags;
2653   
2654   my $installmap = $self->install_map;
2655   delete $installmap->{read};
2656   delete $installmap->{write};
2657
2658   my $text_suffix = qr{\.(pm|pod)$};
2659
2660   while (my $localdir = each %$installmap) {
2661     my @localparts = File::Spec->splitdir($localdir);
2662     my $files = $self->rscan_dir($localdir, sub {-f});
2663     
2664     foreach my $file (@$files) {
2665       my @parts = File::Spec->splitdir($file);
2666       @parts = @parts[@localparts .. $#parts]; # Get rid of blib/lib or similar
2667       
2668       my $installed = Module::Build::ModuleInfo->find_module_by_name(
2669                         join('::', @parts), \@myINC );
2670       if (not $installed) {
2671         print "Only in lib: $file\n";
2672         next;
2673       }
2674       
2675       my $status = File::Compare::compare($installed, $file);
2676       next if $status == 0;  # Files are the same
2677       die "Can't compare $installed and $file: $!" if $status == -1;
2678       
2679       if ($file =~ $text_suffix) {
2680         $self->do_system('diff', @flags, $installed, $file);
2681       } else {
2682         print "Binary files $file and $installed differ\n";
2683       }
2684     }
2685   }
2686 }
2687
2688 sub ACTION_pure_install {
2689   shift()->depends_on('install');
2690 }
2691
2692 sub ACTION_install {
2693   my ($self) = @_;
2694   require ExtUtils::Install;
2695   $self->depends_on('build');
2696   ExtUtils::Install::install($self->install_map, !$self->quiet, 0, $self->{args}{uninst}||0);
2697 }
2698
2699 sub ACTION_fakeinstall {
2700   my ($self) = @_;
2701   require ExtUtils::Install;
2702   $self->depends_on('build');
2703   ExtUtils::Install::install($self->install_map, !$self->quiet, 1, $self->{args}{uninst}||0);
2704 }
2705
2706 sub ACTION_versioninstall {
2707   my ($self) = @_;
2708   
2709   die "You must have only.pm 0.25 or greater installed for this operation: $@\n"
2710     unless eval { require only; 'only'->VERSION(0.25); 1 };
2711   
2712   $self->depends_on('build');
2713   
2714   my %onlyargs = map {exists($self->{args}{$_}) ? ($_ => $self->{args}{$_}) : ()}
2715     qw(version versionlib);
2716   only::install::install(%onlyargs);
2717 }
2718
2719 sub ACTION_clean {
2720   my ($self) = @_;
2721   foreach my $item (map glob($_), $self->cleanup) {
2722     $self->delete_filetree($item);
2723   }
2724 }
2725
2726 sub ACTION_realclean {
2727   my ($self) = @_;
2728   $self->depends_on('clean');
2729   $self->delete_filetree($self->config_dir, $self->build_script);
2730 }
2731
2732 sub ACTION_ppd {
2733   my ($self) = @_;
2734   require Module::Build::PPMMaker;
2735   my $ppd = Module::Build::PPMMaker->new();
2736   my $file = $ppd->make_ppd(%{$self->{args}}, build => $self);
2737   $self->add_to_cleanup($file);
2738 }
2739
2740 sub ACTION_ppmdist {
2741   my ($self) = @_;
2742
2743   $self->depends_on( 'build' );
2744
2745   my $ppm = $self->ppm_name;
2746   $self->delete_filetree( $ppm );
2747   $self->log_info( "Creating $ppm\n" );
2748   $self->add_to_cleanup( $ppm, "$ppm.tar.gz" );
2749
2750   my %types = ( # translate types/dirs to those expected by ppm
2751     lib     => 'lib',
2752     arch    => 'arch',
2753     bin     => 'bin',
2754     script  => 'script',
2755     bindoc  => 'man1',
2756     libdoc  => 'man3',
2757     binhtml => undef,
2758     libhtml => undef,
2759   );
2760
2761   foreach my $type ($self->install_types) {
2762     next if exists( $types{$type} ) && !defined( $types{$type} );
2763
2764     my $dir = File::Spec->catdir( $self->blib, $type );
2765     next unless -e $dir;
2766
2767     my $files = $self->rscan_dir( $dir );
2768     foreach my $file ( @$files ) {
2769       next unless -f $file;
2770       my $rel_file =
2771         File::Spec->abs2rel( File::Spec->rel2abs( $file ),
2772                              File::Spec->rel2abs( $dir  ) );
2773       my $to_file  =
2774         File::Spec->catdir( $ppm, 'blib',
2775                             exists( $types{$type} ) ? $types{$type} : $type,
2776                             $rel_file );
2777       $self->copy_if_modified( from => $file, to => $to_file );
2778     }
2779   }
2780
2781   foreach my $type ( qw(bin lib) ) {
2782     local $self->{properties}{html_css} = 'Active.css';
2783     $self->htmlify_pods( $type, File::Spec->catdir($ppm, 'blib', 'html') );
2784   }
2785
2786   # create a tarball;
2787   # the directory tar'ed must be blib so we need to do a chdir first
2788   my $start_wd = $self->cwd;
2789   chdir( $ppm ) or die "Can't chdir to $ppm";
2790   $self->make_tarball( 'blib', File::Spec->catfile( $start_wd, $ppm ) );
2791   chdir( $start_wd ) or die "Can't chdir to $start_wd";
2792
2793   $self->depends_on( 'ppd' );
2794
2795   $self->delete_filetree( $ppm );
2796 }
2797
2798 sub ACTION_pardist {
2799   my ($self) = @_;
2800
2801   # Need PAR::Dist
2802   if ( not eval { require PAR::Dist; PAR::Dist->VERSION(0.17) } ) {
2803     $self->log_warn(
2804       "In order to create .par distributions, you need to\n"
2805       . "install PAR::Dist first."
2806     );
2807     return();
2808   }
2809   
2810   $self->depends_on( 'build' );
2811
2812   return PAR::Dist::blib_to_par(
2813     name => $self->dist_name,
2814     version => $self->dist_version,
2815   );
2816 }
2817
2818 sub ACTION_dist {
2819   my ($self) = @_;
2820   
2821   $self->depends_on('distdir');
2822   
2823   my $dist_dir = $self->dist_dir;
2824   
2825   $self->make_tarball($dist_dir);
2826   $self->delete_filetree($dist_dir);
2827 }
2828
2829 sub ACTION_distcheck {
2830   my ($self) = @_;
2831
2832   require ExtUtils::Manifest;
2833   local $^W; # ExtUtils::Manifest is not warnings clean.
2834   my ($missing, $extra) = ExtUtils::Manifest::fullcheck();
2835
2836   return unless @$missing || @$extra;
2837
2838   my $msg = "MANIFEST appears to be out of sync with the distribution\n";
2839   if ( $self->invoked_action eq 'distcheck' ) {
2840     die $msg;
2841   } else {
2842     warn $msg;
2843   }
2844 }
2845
2846 sub _add_to_manifest {
2847   my ($self, $manifest, $lines) = @_;
2848   $lines = [$lines] unless ref $lines;
2849
2850   my $existing_files = $self->_read_manifest($manifest);
2851   return unless defined( $existing_files );
2852
2853   @$lines = grep {!exists $existing_files->{$_}} @$lines
2854     or return;
2855
2856   my $mode = (stat $manifest)[2];
2857   chmod($mode | oct(222), $manifest) or die "Can't make $manifest writable: $!";
2858   
2859   my $fh = IO::File->new("< $manifest") or die "Can't read $manifest: $!";
2860   my $last_line = (<$fh>)[-1] || "\n";
2861   my $has_newline = $last_line =~ /\n$/;
2862   $fh->close;
2863
2864   $fh = IO::File->new(">> $manifest") or die "Can't write to $manifest: $!";
2865   print $fh "\n" unless $has_newline;
2866   print $fh map "$_\n", @$lines;
2867   close $fh;
2868   chmod($mode, $manifest);
2869
2870   $self->log_info(map "Added to $manifest: $_\n", @$lines);
2871 }
2872
2873 sub _sign_dir {
2874   my ($self, $dir) = @_;
2875
2876   unless (eval { require Module::Signature; 1 }) {
2877     $self->log_warn("Couldn't load Module::Signature for 'distsign' action:\n $@\n");
2878     return;
2879   }
2880   
2881   # Add SIGNATURE to the MANIFEST
2882   {
2883     my $manifest = File::Spec->catfile($dir, 'MANIFEST');
2884     die "Signing a distribution requires a MANIFEST file" unless -e $manifest;
2885     $self->_add_to_manifest($manifest, "SIGNATURE    Added here by Module::Build");
2886   }
2887   
2888   # We protect the signing with an eval{} to make sure we get back to
2889   # the right directory after a signature failure.  Would be nice if
2890   # Module::Signature took a directory argument.
2891   
2892   my $start_dir = $self->cwd;
2893   chdir $dir or die "Can't chdir() to $dir: $!";
2894   eval {local $Module::Signature::Quiet = 1; Module::Signature::sign()};
2895   my @err = $@ ? ($@) : ();
2896   chdir $start_dir or push @err, "Can't chdir() back to $start_dir: $!";
2897   die join "\n", @err if @err;
2898 }
2899
2900 sub ACTION_distsign {
2901   my ($self) = @_;
2902   {
2903     local $self->{properties}{sign} = 0;  # We'll sign it ourselves
2904     $self->depends_on('distdir') unless -d $self->dist_dir;
2905   }
2906   $self->_sign_dir($self->dist_dir);
2907 }
2908
2909 sub ACTION_skipcheck {
2910   my ($self) = @_;
2911   
2912   require ExtUtils::Manifest;
2913   local $^W; # ExtUtils::Manifest is not warnings clean.
2914   ExtUtils::Manifest::skipcheck();
2915 }
2916
2917 sub ACTION_distclean {
2918   my ($self) = @_;
2919   
2920   $self->depends_on('realclean');
2921   $self->depends_on('distcheck');
2922 }
2923
2924 sub do_create_makefile_pl {
2925   my $self = shift;
2926   require Module::Build::Compat;
2927   $self->delete_filetree('Makefile.PL');
2928   $self->log_info("Creating Makefile.PL\n");
2929   Module::Build::Compat->create_makefile_pl($self->create_makefile_pl, $self, @_);
2930   $self->_add_to_manifest('MANIFEST', 'Makefile.PL');
2931 }
2932
2933 sub do_create_readme {
2934   my $self = shift;
2935   $self->delete_filetree('README');
2936
2937   my $docfile = $self->_main_docfile;
2938   unless ( $docfile ) {
2939     $self->log_warn(<<EOF);
2940 Cannot create README: can't determine which file contains documentation;
2941 Must supply either 'dist_version_from', or 'module_name' parameter.
2942 EOF
2943     return;
2944   }
2945
2946   if ( eval {require Pod::Readme; 1} ) {
2947     $self->log_info("Creating README using Pod::Readme\n");
2948
2949     my $parser = Pod::Readme->new;
2950     $parser->parse_from_file($docfile, 'README', @_);
2951
2952   } elsif ( eval {require Pod::Text; 1} ) {
2953     $self->log_info("Creating README using Pod::Text\n");
2954
2955     my $fh = IO::File->new('> README');
2956     if ( defined($fh) ) {
2957       local $^W = 0;
2958       no strict "refs";
2959
2960       # work around bug in Pod::Text 3.01, which expects
2961       # Pod::Simple::parse_file to take input and output filehandles
2962       # when it actually only takes an input filehandle
2963
2964       my $old_parse_file;
2965       $old_parse_file = \&{"Pod::Simple::parse_file"}
2966         and
2967       local *{"Pod::Simple::parse_file"} = sub {
2968         my $self = shift;
2969         $self->output_fh($_[1]) if $_[1];
2970         $self->$old_parse_file($_[0]);
2971       }
2972         if $Pod::Text::VERSION
2973           == 3.01; # Split line to avoid evil version-finder
2974
2975       Pod::Text::pod2text( $docfile, $fh );
2976
2977       $fh->close;
2978     } else {
2979       $self->log_warn(
2980         "Cannot create 'README' file: Can't open file for writing\n" );
2981       return;
2982     }
2983
2984   } else {
2985     $self->log_warn("Can't load Pod::Readme or Pod::Text to create README\n");
2986     return;
2987   }
2988
2989   $self->_add_to_manifest('MANIFEST', 'README');
2990 }
2991
2992 sub _main_docfile {
2993   my $self = shift;
2994   if ( my $pm_file = $self->dist_version_from ) {
2995     (my $pod_file = $pm_file) =~ s/.pm$/.pod/;
2996     return (-e $pod_file ? $pod_file : $pm_file);
2997   } else {
2998     return undef;
2999   }
3000 }
3001
3002 sub ACTION_distdir {
3003   my ($self) = @_;
3004
3005   $self->depends_on('distmeta');
3006
3007   my $dist_files = $self->_read_manifest('MANIFEST')
3008     or die "Can't create distdir without a MANIFEST file - run 'manifest' action first";
3009   delete $dist_files->{SIGNATURE};  # Don't copy, create a fresh one
3010   die "No files found in MANIFEST - try running 'manifest' action?\n"
3011     unless ($dist_files and keys %$dist_files);
3012   my $metafile = $self->metafile;
3013   $self->log_warn("*** Did you forget to add $metafile to the MANIFEST?\n")
3014     unless exists $dist_files->{$metafile};
3015   
3016   my $dist_dir = $self->dist_dir;
3017   $self->delete_filetree($dist_dir);
3018   $self->log_info("Creating $dist_dir\n");
3019   $self->add_to_cleanup($dist_dir);
3020   
3021   foreach my $file (keys %$dist_files) {
3022     my $new = $self->copy_if_modified(from => $file, to_dir => $dist_dir, verbose => 0);
3023   }
3024   
3025   $self->_sign_dir($dist_dir) if $self->{properties}{sign};
3026 }
3027
3028 sub ACTION_disttest {
3029   my ($self) = @_;
3030
3031   $self->depends_on('distdir');
3032
3033   my $start_dir = $self->cwd;
3034   my $dist_dir = $self->dist_dir;
3035   chdir $dist_dir or die "Cannot chdir to $dist_dir: $!";
3036   # XXX could be different names for scripts
3037
3038   $self->run_perl_script('Build.PL') # XXX Should this be run w/ --nouse-rcfile
3039       or die "Error executing 'Build.PL' in dist directory: $!";
3040   $self->run_perl_script('Build')
3041       or die "Error executing 'Build' in dist directory: $!";
3042   $self->run_perl_script('Build', [], ['test'])
3043       or die "Error executing 'Build test' in dist directory";
3044   chdir $start_dir;
3045 }
3046
3047 sub _write_default_maniskip {
3048   my $self = shift;
3049   my $file = shift || 'MANIFEST.SKIP';
3050   my $fh = IO::File->new("> $file")
3051     or die "Can't open $file: $!";
3052
3053   # This is derived from MakeMaker's default MANIFEST.SKIP file with
3054   # some new entries
3055
3056   print $fh <<'EOF';
3057 # Avoid version control files.
3058 \bRCS\b
3059 \bCVS\b
3060 ,v$
3061 \B\.svn\b
3062 \B\.cvsignore$
3063
3064 # Avoid Makemaker generated and utility files.
3065 \bMakefile$
3066 \bblib
3067 \bMakeMaker-\d
3068 \bpm_to_blib$
3069 \bblibdirs$
3070 ^MANIFEST\.SKIP$
3071
3072 # Avoid Module::Build generated and utility files.
3073 \bBuild$
3074 \bBuild.bat$
3075 \b_build
3076
3077 # Avoid Devel::Cover generated files
3078 \bcover_db
3079
3080 # Avoid temp and backup files.
3081 ~$
3082 \.tmp$
3083 \.old$
3084 \.bak$
3085 \#$
3086 \.#
3087 \.rej$
3088
3089 # Avoid OS-specific files/dirs
3090 #   Mac OSX metadata
3091 \B\.DS_Store
3092 #   Mac OSX SMB mount metadata files
3093 \B\._
3094 # Avoid archives of this distribution
3095 EOF
3096
3097   # Skip, for example, 'Module-Build-0.27.tar.gz'
3098   print $fh '\b'.$self->dist_name.'-[\d\.\_]+'."\n";
3099
3100   $fh->close();
3101 }
3102
3103 sub ACTION_manifest {
3104   my ($self) = @_;
3105
3106   my $maniskip = 'MANIFEST.SKIP';
3107   unless ( -e 'MANIFEST' || -e $maniskip ) {
3108     $self->log_warn("File '$maniskip' does not exist: Creating a default '$maniskip'\n");
3109     $self->_write_default_maniskip($maniskip);
3110   }
3111
3112   require ExtUtils::Manifest;  # ExtUtils::Manifest is not warnings clean.
3113   local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3114   ExtUtils::Manifest::mkmanifest();
3115 }
3116
3117 sub dist_dir {
3118   my ($self) = @_;
3119   return "$self->{properties}{dist_name}-$self->{properties}{dist_version}";
3120 }
3121
3122 sub ppm_name {
3123   my $self = shift;
3124   return 'PPM-' . $self->dist_dir;
3125 }
3126
3127 sub _files_in {
3128   my ($self, $dir) = @_;
3129   return unless -d $dir;
3130
3131   local *DH;
3132   opendir DH, $dir or die "Can't read directory $dir: $!";
3133
3134   my @files;
3135   while (defined (my $file = readdir DH)) {
3136     my $full_path = File::Spec->catfile($dir, $file);
3137     next if -d $full_path;
3138     push @files, $full_path;
3139   }
3140   return @files;
3141 }
3142
3143 sub script_files {
3144   my $self = shift;
3145   
3146   for ($self->{properties}{script_files}) {
3147     $_ = shift if @_;
3148     next unless $_;
3149     
3150     # Always coerce into a hash
3151     return $_ if UNIVERSAL::isa($_, 'HASH');
3152     return $_ = { map {$_,1} @$_ } if UNIVERSAL::isa($_, 'ARRAY');
3153     
3154     die "'script_files' must be a hashref, arrayref, or string" if ref();
3155     
3156     return $_ = { map {$_,1} $self->_files_in( $_ ) } if -d $_;
3157     return $_ = {$_ => 1};
3158   }
3159   
3160   return $_ = { map {$_,1} $self->_files_in( File::Spec->catdir( $self->base_dir, 'bin' ) ) };
3161 }
3162 BEGIN { *scripts = \&script_files; }
3163
3164 {
3165   my %licenses =
3166     (
3167      perl => 'http://dev.perl.org/licenses/',
3168      gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3169      apache => 'http://apache.org/licenses/LICENSE-2.0',
3170      artistic => 'http://opensource.org/licenses/artistic-license.php',
3171      lgpl => 'http://opensource.org/licenses/artistic-license.php',
3172      bsd => 'http://www.opensource.org/licenses/bsd-license.php',
3173      gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3174      mit => 'http://opensource.org/licenses/mit-license.php',
3175      mozilla => 'http://opensource.org/licenses/mozilla1.1.php',
3176      open_source => undef,
3177      unrestricted => undef,
3178      restrictive => undef,
3179      unknown => undef,
3180     );
3181   sub valid_licenses {
3182     return \%licenses;
3183   }
3184 }
3185
3186 sub _hash_merge {
3187   my ($self, $h, $k, $v) = @_;
3188   if (ref $h->{$k} eq 'ARRAY') {
3189     push @{$h->{$k}}, ref $v ? @$v : $v;
3190   } elsif (ref $h->{$k} eq 'HASH') {
3191     $h->{$k}{$_} = $v->{$_} foreach keys %$v;
3192   } else {
3193     $h->{$k} = $v;
3194   }
3195 }
3196
3197 sub ACTION_distmeta {
3198   my ($self) = @_;
3199
3200   $self->do_create_makefile_pl if $self->create_makefile_pl;
3201   $self->do_create_readme if $self->create_readme;
3202   $self->do_create_metafile;
3203 }
3204
3205 sub do_create_metafile {
3206   my $self = shift;
3207   return if $self->{wrote_metadata};
3208   
3209   my $p = $self->{properties};
3210   my $metafile = $self->metafile;
3211   
3212   unless ($p->{license}) {
3213     $self->log_warn("No license specified, setting license = 'unknown'\n");
3214     $p->{license} = 'unknown';
3215   }
3216   unless (exists $self->valid_licenses->{ $p->{license} }) {
3217     die "Unknown license type '$p->{license}'";
3218   }
3219
3220   # If we're in the distdir, the metafile may exist and be non-writable.
3221   $self->delete_filetree($metafile);
3222   $self->log_info("Creating $metafile\n");
3223
3224   # Since we're building ourself, we have to do some special stuff
3225   # here: the ConfigData module is found in blib/lib.
3226   local @INC = @INC;
3227   if (($self->module_name || '') eq 'Module::Build') {
3228     $self->depends_on('config_data');
3229     push @INC, File::Spec->catdir($self->blib, 'lib');
3230   }
3231
3232   $self->write_metafile;
3233 }
3234
3235 sub write_metafile {
3236   my $self = shift;
3237   my $metafile = $self->metafile;
3238
3239   if ($self->_mb_feature('YAML_support')) {
3240     require YAML;
3241     require YAML::Node;
3242
3243     # We use YAML::Node to get the order nice in the YAML file.
3244     $self->prepare_metadata( my $node = YAML::Node->new({}) );
3245     
3246     # YAML API changed after version 0.30
3247     my $yaml_sub = $YAML::VERSION le '0.30' ? \&YAML::StoreFile : \&YAML::DumpFile;
3248     $self->{wrote_metadata} = $yaml_sub->($metafile, $node );
3249
3250   } else {
3251     require Module::Build::YAML;
3252     my (%node, @order_keys);
3253     $self->prepare_metadata(\%node, \@order_keys);
3254     $node{_order} = \@order_keys;
3255     &Module::Build::YAML::DumpFile($metafile, \%node);
3256     $self->{wrote_metadata} = 1;
3257   }
3258
3259   $self->_add_to_manifest('MANIFEST', $metafile);
3260 }
3261
3262 sub prepare_metadata {
3263   my ($self, $node, $keys) = @_;
3264   my $p = $self->{properties};
3265
3266   # A little helper sub
3267   my $add_node = sub {
3268     my ($name, $val) = @_;
3269     $node->{$name} = $val;
3270     push @$keys, $name if $keys;
3271   };
3272
3273   foreach (qw(dist_name dist_version dist_author dist_abstract license)) {
3274     (my $name = $_) =~ s/^dist_//;
3275     $add_node->($name, $self->$_());
3276     die "ERROR: Missing required field '$_' for META.yml\n"
3277       unless defined($node->{$name}) && length($node->{$name});
3278   }
3279   $node->{version} = '' . $node->{version}; # Stringify version objects
3280
3281   if (defined( $self->license ) &&
3282       defined( my $url = $self->valid_licenses->{ $self->license } )) {
3283     $node->{resources}{license} = $url;
3284   }
3285
3286   foreach ( @{$self->prereq_action_types} ) {
3287     if (exists $p->{$_} and keys %{ $p->{$_} }) {
3288       $add_node->($_, $p->{$_});
3289     }
3290   }
3291
3292   if (exists $p->{dynamic_config}) {
3293     $add_node->('dynamic_config', $p->{dynamic_config});
3294   }
3295   my $pkgs = eval { $self->find_dist_packages };
3296   if ($@) {
3297     $self->log_warn("$@\nWARNING: Possible missing or corrupt 'MANIFEST' file.\n" .
3298                     "Nothing to enter for 'provides' field in META.yml\n");
3299   } else {
3300     $node->{provides} = $pkgs if %$pkgs;
3301   }
3302 ;
3303   if (exists $p->{no_index}) {
3304     $add_node->('no_index', $p->{no_index});
3305   }
3306
3307   $add_node->('generated_by', "Module::Build version $Module::Build::VERSION");
3308
3309   $add_node->('meta-spec', 
3310               {version => '1.2',
3311                url     => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
3312               });
3313
3314   while (my($k, $v) = each %{$self->meta_add}) {
3315     $add_node->($k, $v);
3316   }
3317
3318   while (my($k, $v) = each %{$self->meta_merge}) {
3319     $self->_hash_merge($node, $k, $v);
3320   }
3321
3322   return $node;
3323 }
3324
3325 sub _read_manifest {
3326   my ($self, $file) = @_;
3327   return undef unless -e $file;
3328
3329   require ExtUtils::Manifest;  # ExtUtils::Manifest is not warnings clean.
3330   local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3331   return scalar ExtUtils::Manifest::maniread($file);
3332 }
3333
3334 sub find_dist_packages {
3335   my $self = shift;
3336
3337   # Only packages in .pm files are candidates for inclusion here.
3338   # Only include things in the MANIFEST, not things in developer's
3339   # private stock.
3340
3341   my $manifest = $self->_read_manifest('MANIFEST')
3342     or die "Can't find dist packages without a MANIFEST file - run 'manifest' action first";
3343
3344   # Localize
3345   my %dist_files = map { $self->localize_file_path($_) => $_ }
3346                        keys %$manifest;
3347
3348   my @pm_files = grep {exists $dist_files{$_}} keys %{ $self->find_pm_files };
3349
3350   # First, we enumerate all packages & versions,
3351   # seperating into primary & alternative candidates
3352   my( %prime, %alt );
3353   foreach my $file (@pm_files) {
3354     next if $dist_files{$file} =~ m{^t/};  # Skip things in t/
3355
3356     my @path = split( /\//, $dist_files{$file} );
3357     (my $prime_package = join( '::', @path[1..$#path] )) =~ s/\.pm$//;
3358
3359     my $pm_info = Module::Build::ModuleInfo->new_from_file( $file );
3360
3361     foreach my $package ( $pm_info->packages_inside ) {
3362       next if $package eq 'main';  # main can appear numerous times, ignore
3363       next if grep /^_/, split( /::/, $package ); # private package, ignore
3364
3365       my $version = $pm_info->version( $package );
3366
3367       if ( $package eq $prime_package ) {
3368         if ( exists( $prime{$package} ) ) {
3369           # M::B::ModuleInfo will handle this conflict
3370           die "Unexpected conflict in '$package'; multiple versions found.\n";
3371         } else {
3372           $prime{$package}{file} = $dist_files{$file};
3373           $prime{$package}{version} = $version if defined( $version );
3374         }
3375       } else {
3376         push( @{$alt{$package}}, {
3377                                   file    => $dist_files{$file},
3378                                   version => $version,
3379                                  } );
3380       }
3381     }
3382   }
3383
3384   # Then we iterate over all the packages found above, identifying conflicts
3385   # and selecting the "best" candidate for recording the file & version
3386   # for each package.
3387   foreach my $package ( keys( %alt ) ) {
3388     my $result = $self->_resolve_module_versions( $alt{$package} );
3389
3390     if ( exists( $prime{$package} ) ) { # primary package selected
3391
3392       if ( $result->{err} ) {
3393         # Use the selected primary package, but there are conflicting
3394         # errors amoung multiple alternative packages that need to be
3395         # reported
3396         $self->log_warn(
3397           "Found conflicting versions for package '$package'\n" .
3398           "  $prime{$package}{file} ($prime{$package}{version})\n" .
3399           $result->{err}
3400         );
3401
3402       } elsif ( defined( $result->{version} ) ) {
3403         # There is a primary package selected, and exactly one
3404         # alternative package
3405
3406         if ( exists( $prime{$package}{version} ) &&
3407              defined( $prime{$package}{version} ) ) {
3408           # Unless the version of the primary package agrees with the
3409           # version of the alternative package, report a conflict
3410           if ( $self->compare_versions( $prime{$package}{version}, '!=',
3411                                         $result->{version} ) ) {
3412             $self->log_warn(
3413               "Found conflicting versions for package '$package'\n" .
3414               "  $prime{$package}{file} ($prime{$package}{version})\n" .
3415               "  $result->{file} ($result->{version})\n"
3416             );
3417           }
3418
3419         } else {
3420           # The prime package selected has no version so, we choose to
3421           # use any alternative package that does have a version
3422           $prime{$package}{file}    = $result->{file};
3423           $prime{$package}{version} = $result->{version};
3424         }
3425
3426       } else {
3427         # no alt package found with a version, but we have a prime
3428         # package so we use it whether it has a version or not
3429       }
3430
3431     } else { # No primary package was selected, use the best alternative
3432
3433       if ( $result->{err} ) {
3434         $self->log_warn(
3435           "Found conflicting versions for package '$package'\n" .
3436           $result->{err}
3437         );
3438       }
3439
3440       # Despite possible conflicting versions, we choose to record
3441       # something rather than nothing
3442       $prime{$package}{file}    = $result->{file};
3443       $prime{$package}{version} = $result->{version}
3444           if defined( $result->{version} );
3445     }
3446   }
3447
3448   # Stringify versions.  Can't use exists() here because of bug in YAML::Node.
3449   for (grep defined $_->{version}, values %prime) {
3450     $_->{version} = '' . $_->{version};
3451   }
3452
3453   return \%prime;
3454 }
3455
3456 # seperate out some of the conflict resolution logic from
3457 # $self->find_dist_packages(), above, into a helper function.
3458 #
3459 sub _resolve_module_versions {
3460   my $self = shift;
3461
3462   my $packages = shift;
3463
3464   my( $file, $version );
3465   my $err = '';
3466     foreach my $p ( @$packages ) {
3467       if ( defined( $p->{version} ) ) {
3468         if ( defined( $version ) ) {
3469           if ( $self->compare_versions( $version, '!=', $p->{version} ) ) {
3470             $err .= "  $p->{file} ($p->{version})\n";
3471           } else {
3472             # same version declared multiple times, ignore
3473           }
3474         } else {
3475           $file    = $p->{file};
3476           $version = $p->{version};
3477         }
3478       }
3479       $file ||= $p->{file} if defined( $p->{file} );
3480     }
3481
3482   if ( $err ) {
3483     $err = "  $file ($version)\n" . $err;
3484   }
3485
3486   my %result = (
3487     file    => $file,
3488     version => $version,
3489     err     => $err
3490   );
3491
3492   return \%result;
3493 }
3494
3495 sub make_tarball {
3496   my ($self, $dir, $file) = @_;
3497   $file ||= $dir;
3498   
3499   $self->log_info("Creating $file.tar.gz\n");
3500   
3501   if ($self->{args}{tar}) {
3502     my $tar_flags = $self->verbose ? 'cvf' : 'cf';
3503     $self->do_system($self->split_like_shell($self->{args}{tar}), $tar_flags, "$file.tar", $dir);
3504     $self->do_system($self->split_like_shell($self->{args}{gzip}), "$file.tar") if $self->{args}{gzip};
3505   } else {
3506     require Archive::Tar;
3507     # Archive::Tar versions >= 1.09 use the following to enable a compatibility
3508     # hack so that the resulting archive is compatible with older clients.
3509     $Archive::Tar::DO_NOT_USE_PREFIX = 0;
3510     my $files = $self->rscan_dir($dir);
3511     Archive::Tar->create_archive("$file.tar.gz", 1, @$files);
3512   }
3513 }
3514
3515 sub install_path {
3516   my $self = shift;
3517   my( $type, $value ) = ( @_, '<empty>' );
3518
3519   Carp::croak( 'Type argument missing' )
3520     unless defined( $type );
3521
3522   my $map = $self->{properties}{install_path};
3523   return $map unless @_;
3524
3525   # delete existing value if $value is literal undef()
3526   unless ( defined( $value ) ) {
3527     delete( $map->{$type} );
3528     return undef;
3529   }
3530
3531   # return existing value if no new $value is given
3532   if ( $value eq '<empty>' ) {
3533     return undef unless exists $map->{$type};
3534     return $map->{$type};
3535   }
3536
3537   # set value if $value is a valid relative path
3538   return $map->{$type} = $value;
3539 }
3540
3541 sub install_base_relpaths {
3542   # Usage: install_base_relpaths(), install_base_relpaths('lib'),
3543   #   or install_base_relpaths('lib' => $value);
3544   my $self = shift;
3545   my $map = $self->{properties}{install_base_relpaths};
3546   return $map unless @_;
3547   return $self->_relpaths($map, @_);
3548 }
3549
3550
3551 # Translated from ExtUtils::MM_Any::init_INSTALL_from_PREFIX
3552 sub prefix_relative {
3553   my ($self, $type) = @_;
3554   my $installdirs = $self->installdirs;
3555
3556   my $relpath = $self->install_sets($installdirs)->{$type};
3557
3558   return $self->_prefixify($relpath,
3559                            $self->original_prefix($installdirs),
3560                            $type,
3561                           );
3562 }
3563
3564 sub _relpaths {
3565   my $self = shift;
3566   my( $map, $type, $value ) = ( @_, '<empty>' );
3567
3568   Carp::croak( 'Type argument missing' )
3569     unless defined( $type );
3570
3571   my @value = ();
3572
3573   # delete existing value if $value is literal undef()
3574   unless ( defined( $value ) ) {
3575     delete( $map->{$type} );
3576     return undef;
3577   }
3578
3579   # return existing value if no new $value is given
3580   elsif ( $value eq '<empty>' ) {
3581     return undef unless exists $map->{$type};
3582     @value = @{ $map->{$type} };
3583   }
3584
3585   # set value if $value is a valid relative path
3586   else {
3587     Carp::croak( "Value must be a relative path" )
3588       if File::Spec::Unix->file_name_is_absolute($value);
3589
3590     @value = split( /\//, $value );
3591     $map->{$type} = \@value;
3592   }
3593
3594   return File::Spec->catdir( @value );
3595 }
3596
3597 # Defaults to use in case the config install paths cannot be prefixified.
3598 sub prefix_relpaths {
3599   # Usage: prefix_relpaths('site'), prefix_relpaths('site', 'lib'),
3600   #   or prefix_relpaths('site', 'lib' => $value);
3601   my $self = shift;
3602   my $installdirs = shift || $self->installdirs;
3603   my $map = $self->{properties}{prefix_relpaths}{$installdirs};
3604   return $map unless @_;
3605   return $self->_relpaths($map, @_);
3606 }
3607
3608
3609 # Translated from ExtUtils::MM_Unix::prefixify()
3610 sub _prefixify {
3611   my($self, $path, $sprefix, $type) = @_;
3612
3613   my $rprefix = $self->prefix;
3614   $rprefix .= '/' if $sprefix =~ m|/$|;
3615
3616   $self->log_verbose("  prefixify $path from $sprefix to $rprefix\n")
3617     if defined( $path ) && length( $path );
3618
3619   if( !defined( $path ) || ( length( $path ) == 0 ) ) {
3620     $self->log_verbose("  no path to prefixify, falling back to default.\n");
3621     return $self->_prefixify_default( $type, $rprefix );
3622   } elsif( !File::Spec->file_name_is_absolute($path) ) {
3623     $self->log_verbose("    path is relative, not prefixifying.\n");
3624   } elsif( $sprefix eq $rprefix ) {
3625     $self->log_verbose("  no new prefix.\n");
3626   } elsif( $path !~ s{^\Q$sprefix\E\b}{}s ) {
3627     $self->log_verbose("    cannot prefixify, falling back to default.\n");
3628     return $self->_prefixify_default( $type, $rprefix );
3629   }
3630
3631   $self->log_verbose("    now $path in $rprefix\n");
3632
3633   return $path;
3634 }
3635
3636 sub _prefixify_default {
3637   my $self = shift;
3638   my $type = shift;
3639   my $rprefix = shift;
3640
3641   my $default = $self->prefix_relpaths($self->installdirs, $type);
3642   if( !$default ) {
3643     $self->log_verbose("    no default install location for type '$type', using prefix '$rprefix'.\n");
3644     return $rprefix;
3645   } else {
3646     return $default;
3647   }
3648 }
3649
3650 sub install_destination {
3651   my ($self, $type) = @_;
3652
3653   return $self->install_path($type) if $self->install_path($type);
3654
3655   if ( $self->install_base ) {
3656     my $relpath = $self->install_base_relpaths($type);
3657     return $relpath ? File::Spec->catdir($self->install_base, $relpath) : undef;
3658   }
3659
3660   if ( $self->prefix ) {
3661     my $relpath = $self->prefix_relative($type);
3662     return $relpath ? File::Spec->catdir($self->prefix, $relpath) : undef;
3663   }
3664
3665   return $self->install_sets($self->installdirs)->{$type};
3666 }
3667
3668 sub install_types {
3669   my $self = shift;
3670
3671   my %types;
3672   if ( $self->install_base ) {
3673     %types = %{$self->install_base_relpaths};
3674   } elsif ( $self->prefix ) {
3675     %types = %{$self->prefix_relpaths};
3676   } else {
3677     %types = %{$self->install_sets($self->installdirs)};
3678   }
3679
3680   %types = (%types, %{$self->install_path});
3681
3682   return sort keys %types;
3683 }
3684
3685 sub install_map {
3686   my ($self, $blib) = @_;
3687   $blib ||= $self->blib;
3688
3689   my( %map, @skipping );
3690   foreach my $type ($self->install_types) {
3691     my $localdir = File::Spec->catdir( $blib, $type );
3692     next unless -e $localdir;
3693
3694     if (my $dest = $self->install_destination($type)) {
3695       $map{$localdir} = $dest;
3696     } else {
3697       push( @skipping, $type );
3698     }
3699   }
3700
3701   $self->log_warn(
3702     "WARNING: Can't figure out install path for types: @skipping\n" .
3703     "Files will not be installed.\n"
3704   ) if @skipping;
3705
3706   # Write the packlist into the same place as ExtUtils::MakeMaker.
3707   if ($self->create_packlist and my $module_name = $self->module_name) {
3708     my $archdir = $self->install_destination('arch');
3709     my @ext = split /::/, $module_name;
3710     $map{write} = File::Spec->catdir($archdir, 'auto', @ext, '.packlist');
3711   }
3712
3713   # Handle destdir
3714   if (length(my $destdir = $self->destdir || '')) {
3715     foreach (keys %map) {
3716       # Need to remove volume from $map{$_} using splitpath, or else
3717       # we'll create something crazy like C:\Foo\Bar\E:\Baz\Quux
3718       my ($volume, $path) = File::Spec->splitpath( $map{$_}, 1 );
3719       $map{$_} = File::Spec->catdir($destdir, $path);
3720     }
3721   }
3722   
3723   $map{read} = '';  # To keep ExtUtils::Install quiet
3724
3725   return \%map;
3726 }
3727
3728 sub depends_on {
3729   my $self = shift;
3730   foreach my $action (@_) {
3731     $self->_call_action($action);
3732   }
3733 }
3734
3735 sub rscan_dir {
3736   my ($self, $dir, $pattern) = @_;
3737   my @result;
3738   local $_; # find() can overwrite $_, so protect ourselves
3739   my $subr = !$pattern ? sub {push @result, $File::Find::name} :
3740              !ref($pattern) || (ref $pattern eq 'Regexp') ? sub {push @result, $File::Find::name if /$pattern/} :
3741              ref($pattern) eq 'CODE' ? sub {push @result, $File::Find::name if $pattern->()} :
3742              die "Unknown pattern type";
3743   
3744   File::Find::find({wanted => $subr, no_chdir => 1}, $dir);
3745   return \@result;
3746 }
3747
3748 sub delete_filetree {
3749   my $self = shift;
3750   my $deleted = 0;
3751   foreach (@_) {
3752     next unless -e $_;
3753     $self->log_info("Deleting $_\n");
3754     File::Path::rmtree($_, 0, 0);
3755     die "Couldn't remove '$_': $!\n" if -e $_;
3756     $deleted++;
3757   }
3758   return $deleted;
3759 }
3760
3761 sub autosplit_file {
3762   my ($self, $file, $to) = @_;
3763   require AutoSplit;
3764   my $dir = File::Spec->catdir($to, 'lib', 'auto');
3765   AutoSplit::autosplit($file, $dir);
3766 }
3767
3768 sub _cbuilder {
3769   # Returns a CBuilder object
3770
3771   my $self = shift;
3772   my $p = $self->{properties};
3773   return $p->{_cbuilder} if $p->{_cbuilder};
3774   return unless $self->_mb_feature('C_support');
3775
3776   require ExtUtils::CBuilder;
3777   return $p->{_cbuilder} = ExtUtils::CBuilder->new(config => $self->config);
3778 }
3779
3780 sub have_c_compiler {
3781   my ($self) = @_;
3782   
3783   my $p = $self->{properties};
3784   return $p->{have_compiler} if defined $p->{have_compiler};
3785   
3786   $self->log_verbose("Checking if compiler tools configured... ");
3787   my $b = $self->_cbuilder;
3788   my $have = $b && $b->have_compiler;
3789   $self->log_verbose($have ? "ok.\n" : "failed.\n");
3790   return $p->{have_compiler} = $have;
3791 }
3792
3793 sub compile_c {
3794   my ($self, $file, %args) = @_;
3795   my $b = $self->_cbuilder
3796     or die "Module::Build is not configured with C_support";
3797
3798   my $obj_file = $b->object_file($file);
3799   $self->add_to_cleanup($obj_file);
3800   return $obj_file if $self->up_to_date($file, $obj_file);
3801
3802   $b->compile(source => $file,
3803               defines => $args{defines},
3804               object_file => $obj_file,
3805               include_dirs => $self->include_dirs,
3806               extra_compiler_flags => $self->extra_compiler_flags,
3807              );
3808
3809   return $obj_file;
3810 }
3811
3812 sub link_c {
3813   my ($self, $to, $file_base) = @_;
3814   my $p = $self->{properties}; # For convenience
3815
3816   my $spec = $self->_infer_xs_spec($file_base);
3817
3818   $self->add_to_cleanup($spec->{lib_file});
3819
3820   my $objects = $p->{objects} || [];
3821
3822   return $spec->{lib_file}
3823     if $self->up_to_date([$spec->{obj_file}, @$objects],
3824                          $spec->{lib_file});
3825
3826   my $module_name = $self->module_name;
3827   $module_name  ||= $spec->{module_name};
3828
3829   my $b = $self->_cbuilder
3830     or die "Module::Build is not configured with C_support";
3831   $b->link(
3832     module_name => $module_name,
3833     objects     => [$spec->{obj_file}, @$objects],
3834     lib_file    => $spec->{lib_file},
3835     extra_linker_flags => $p->{extra_linker_flags} );
3836
3837   return $spec->{lib_file};
3838 }
3839
3840 sub compile_xs {
3841   my ($self, $file, %args) = @_;
3842   
3843   $self->log_info("$file -> $args{outfile}\n");
3844
3845   if (eval {require ExtUtils::ParseXS; 1}) {
3846     
3847     ExtUtils::ParseXS::process_file(
3848                                     filename => $file,
3849                                     prototypes => 0,
3850                                     output => $args{outfile},
3851                                    );
3852   } else {
3853     # Ok, I give up.  Just use backticks.
3854     
3855     my $xsubpp = Module::Build::ModuleInfo->find_module_by_name('ExtUtils::xsubpp')
3856       or die "Can't find ExtUtils::xsubpp in INC (@INC)";
3857     
3858     my @typemaps;
3859     push @typemaps, Module::Build::ModuleInfo->find_module_by_name('ExtUtils::typemap', \@INC);
3860     my $lib_typemap = Module::Build::ModuleInfo->find_module_by_name('typemap', ['lib']);
3861     if (defined $lib_typemap and -e $lib_typemap) {
3862       push @typemaps, 'typemap';
3863     }
3864     @typemaps = map {+'-typemap', $_} @typemaps;
3865
3866     my $cf = $self->{config};
3867     my $perl = $self->{properties}{perl};
3868     
3869     my @command = ($perl, "-I".$cf->get('installarchlib'), "-I".$cf->get('installprivlib'), $xsubpp, '-noprototypes',
3870                    @typemaps, $file);
3871     
3872     $self->log_info("@command\n");
3873     my $fh = IO::File->new("> $args{outfile}") or die "Couldn't write $args{outfile}: $!";
3874     print {$fh} $self->_backticks(@command);
3875     close $fh;
3876   }
3877 }
3878
3879 sub split_like_shell {
3880   my ($self, $string) = @_;
3881   
3882   return () unless defined($string);
3883   return @$string if UNIVERSAL::isa($string, 'ARRAY');
3884   $string =~ s/^\s+|\s+$//g;
3885   return () unless length($string);
3886   
3887   return Text::ParseWords::shellwords($string);
3888 }
3889
3890 sub run_perl_script {
3891   my ($self, $script, $preargs, $postargs) = @_;
3892   foreach ($preargs, $postargs) {
3893     $_ = [ $self->split_like_shell($_) ] unless ref();
3894   }
3895   return $self->run_perl_command([@$preargs, $script, @$postargs]);
3896 }
3897
3898 sub run_perl_command {
3899   # XXX Maybe we should accept @args instead of $args?  Must resolve
3900   # this before documenting.
3901   my ($self, $args) = @_;
3902   $args = [ $self->split_like_shell($args) ] unless ref($args);
3903   my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
3904
3905   # Make sure our local additions to @INC are propagated to the subprocess
3906   local $ENV{PERL5LIB} = join $self->config('path_sep'), $self->_added_to_INC;
3907
3908   return $self->do_system($perl, @$args);
3909 }
3910
3911 # Infer various data from the path of the input filename
3912 # that is needed to create output files.
3913 # The input filename is expected to be of the form:
3914 #   lib/Module/Name.ext or Module/Name.ext
3915 sub _infer_xs_spec {
3916   my $self = shift;
3917   my $file = shift;
3918
3919   my $cf = $self->{config};
3920
3921   my %spec;
3922
3923   my( $v, $d, $f ) = File::Spec->splitpath( $file );
3924   my @d = File::Spec->splitdir( $d );
3925   (my $file_base = $f) =~ s/\.[^.]+$//i;
3926
3927   $spec{base_name} = $file_base;
3928
3929   $spec{src_dir} = File::Spec->catpath( $v, $d, '' );
3930
3931   # the module name
3932   shift( @d ) while @d && ($d[0] eq 'lib' || $d[0] eq '');
3933   pop( @d ) while @d && $d[-1] eq '';
3934   $spec{module_name} = join( '::', (@d, $file_base) );
3935
3936   $spec{archdir} = File::Spec->catdir($self->blib, 'arch', 'auto',
3937                                       @d, $file_base);
3938
3939   $spec{bs_file} = File::Spec->catfile($spec{archdir}, "${file_base}.bs");
3940
3941   $spec{lib_file} = File::Spec->catfile($spec{archdir},
3942                                         "${file_base}.".$cf->get('dlext'));
3943
3944   $spec{c_file} = File::Spec->catfile( $spec{src_dir},
3945                                        "${file_base}.c" );
3946
3947   $spec{obj_file} = File::Spec->catfile( $spec{src_dir},
3948                                          "${file_base}".$cf->get('obj_ext') );
3949
3950   return \%spec;
3951 }
3952
3953 sub process_xs {
3954   my ($self, $file) = @_;
3955
3956   my $spec = $self->_infer_xs_spec($file);
3957
3958   # File name, minus the suffix
3959   (my $file_base = $file) =~ s/\.[^.]+$//;
3960
3961   # .xs -> .c
3962   $self->add_to_cleanup($spec->{c_file});
3963
3964   unless ($self->up_to_date($file, $spec->{c_file})) {
3965     $self->compile_xs($file, outfile => $spec->{c_file});
3966   }
3967
3968   # .c -> .o
3969   my $v = $self->dist_version;
3970   $self->compile_c($spec->{c_file},
3971                    defines => {VERSION => qq{"$v"}, XS_VERSION => qq{"$v"}});
3972
3973   # archdir
3974   File::Path::mkpath($spec->{archdir}, 0, oct(777)) unless -d $spec->{archdir};
3975
3976   # .xs -> .bs
3977   $self->add_to_cleanup($spec->{bs_file});
3978   unless ($self->up_to_date($file, $spec->{bs_file})) {
3979     require ExtUtils::Mkbootstrap;
3980     $self->log_info("ExtUtils::Mkbootstrap::Mkbootstrap('$spec->{bs_file}')\n");
3981     ExtUtils::Mkbootstrap::Mkbootstrap($spec->{bs_file});  # Original had $BSLOADLIBS - what's that?
3982     {my $fh = IO::File->new(">> $spec->{bs_file}")}  # create
3983     utime((time)x2, $spec->{bs_file});  # touch
3984   }
3985
3986   # .o -> .(a|bundle)
3987   $self->link_c($spec->{archdir}, $file_base);
3988 }
3989
3990 sub do_system {
3991   my ($self, @cmd) = @_;
3992   $self->log_info("@cmd\n");
3993
3994   # Some systems proliferate huge PERL5LIBs, try to ameliorate:
3995   my %seen;
3996   my $sep = $self->config('path_sep');
3997   local $ENV{PERL5LIB} = 
3998     ( length($ENV{PERL5LIB}) < 500
3999       ? $ENV{PERL5LIB}
4000       : join $sep, grep { ! $seen{$_}++ and -d $_ } split($sep, $ENV{PERL5LIB})
4001     );
4002
4003   my $status = system(@cmd);
4004   if ($status and $! =~ /Argument list too long/i) {
4005     my $env_entries = '';
4006     foreach (sort keys %ENV) { $env_entries .= "$_=>".length($ENV{$_})."; " }
4007     warn "'Argument list' was 'too long', env lengths are $env_entries";
4008   }
4009   return !$status;
4010 }
4011
4012 sub copy_if_modified {
4013   my $self = shift;
4014   my %args = (@_ > 3
4015               ? ( @_ )
4016               : ( from => shift, to_dir => shift, flatten => shift )
4017              );
4018   $args{verbose} = !$self->quiet
4019     unless exists $args{verbose};
4020   
4021   my $file = $args{from};
4022   unless (defined $file and length $file) {
4023     die "No 'from' parameter given to copy_if_modified";
4024   }
4025   
4026   my $to_path;
4027   if (defined $args{to} and length $args{to}) {
4028     $to_path = $args{to};
4029   } elsif (defined $args{to_dir} and length $args{to_dir}) {
4030     $to_path = File::Spec->catfile( $args{to_dir}, $args{flatten}
4031                                     ? File::Basename::basename($file)
4032                                     : $file );
4033   } else {
4034     die "No 'to' or 'to_dir' parameter given to copy_if_modified";
4035   }
4036   
4037   return if $self->up_to_date($file, $to_path); # Already fresh
4038
4039   {
4040     local $self->{properties}{quiet} = 1;
4041     $self->delete_filetree($to_path); # delete destination if exists
4042   }
4043
4044   # Create parent directories
4045   File::Path::mkpath(File::Basename::dirname($to_path), 0, oct(777));
4046   
4047   $self->log_info("Copying $file -> $to_path\n") if $args{verbose};
4048   File::Copy::copy($file, $to_path) or die "Can't copy('$file', '$to_path'): $!";
4049   # mode is read-only + (executable if source is executable)
4050   my $mode = oct(444) | ( $self->is_executable($file) ? oct(111) : 0 );
4051   chmod( $mode, $to_path );
4052
4053   return $to_path;
4054 }
4055
4056 sub up_to_date {
4057   my ($self, $source, $derived) = @_;
4058   $source  = [$source]  unless ref $source;
4059   $derived = [$derived] unless ref $derived;
4060
4061   return 0 if grep {not -e} @$derived;
4062
4063   my $most_recent_source = time / (24*60*60);
4064   foreach my $file (@$source) {
4065     unless (-e $file) {
4066       $self->log_warn("Can't find source file $file for up-to-date check");
4067       next;
4068     }
4069     $most_recent_source = -M _ if -M _ < $most_recent_source;
4070   }
4071   
4072   foreach my $derived (@$derived) {
4073     return 0 if -M $derived > $most_recent_source;
4074   }
4075   return 1;
4076 }
4077
4078 sub dir_contains {
4079   my ($self, $first, $second) = @_;
4080   # File::Spec doesn't have an easy way to check whether one directory
4081   # is inside another, unfortunately.
4082   
4083   ($first, $second) = map File::Spec->canonpath($_), ($first, $second);
4084   my @first_dirs = File::Spec->splitdir($first);
4085   my @second_dirs = File::Spec->splitdir($second);
4086
4087   return 0 if @second_dirs < @first_dirs;
4088   
4089   my $is_same = ( File::Spec->case_tolerant
4090                   ? sub {lc(shift()) eq lc(shift())}
4091                   : sub {shift() eq shift()} );
4092   
4093   while (@first_dirs) {
4094     return 0 unless $is_same->(shift @first_dirs, shift @second_dirs);
4095   }
4096   
4097   return 1;
4098 }
4099
4100 1;
4101 __END__
4102
4103
4104 =head1 NAME
4105
4106 Module::Build::Base - Default methods for Module::Build
4107
4108 =head1 SYNOPSIS
4109
4110   Please see the Module::Build documentation.
4111
4112 =head1 DESCRIPTION
4113
4114 The C<Module::Build::Base> module defines the core functionality of
4115 C<Module::Build>.  Its methods may be overridden by any of the
4116 platform-dependent modules in the C<Module::Build::Platform::>
4117 namespace, but the intention here is to make this base module as
4118 platform-neutral as possible.  Nicely enough, Perl has several core
4119 tools available in the C<File::> namespace for doing this, so the task
4120 isn't very difficult.
4121
4122 Please see the C<Module::Build> documentation for more details.
4123
4124 =head1 AUTHOR
4125
4126 Ken Williams <kwilliams@cpan.org>
4127
4128 =head1 COPYRIGHT
4129
4130 Copyright (c) 2001-2006 Ken Williams.  All rights reserved.
4131
4132 This library is free software; you can redistribute it and/or
4133 modify it under the same terms as Perl itself.
4134
4135 =head1 SEE ALSO
4136
4137 perl(1), Module::Build(3)
4138
4139 =cut