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