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