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