1 package Module::Build::Base;
4 BEGIN { require 5.00503 }
11 use File::Basename ();
12 use File::Spec 0.82 ();
16 use Text::ParseWords ();
18 use Module::Build::ModuleInfo;
19 use Module::Build::Notes;
20 use Module::Build::Config;
23 #################### Constructors ###########################
25 my $self = shift()->_construct(@_);
27 $self->{invoked_action} = $self->{action} ||= 'Build_PL';
28 $self->cull_args(@ARGV);
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';
36 $self->check_manifest;
38 $self->check_autofeatures;
40 $self->_set_install_paths;
41 $self->_find_nested_builds;
48 my $self = $package->_construct(@_);
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': $@";
63 return $build_class->resume(@_);
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");
72 $self->cull_args(@ARGV);
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};
82 $self->{invoked_action} = $self->{action} ||= 'build';
87 sub new_from_context {
88 my ($package, %args) = @_;
90 # XXX Read the META.yml and see whether we need to run the Build.PL?
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).
97 local @ARGV = $package->unparse_args(\%args);
101 return $package->resume;
105 # hmm, wonder what the right thing to do here is
107 return shift()->resume;
111 my ($package, %input) = @_;
113 my $args = delete $input{args} || {};
114 my $config = delete $input{config} || {};
118 config => Module::Build::Config->new(values => $config),
120 base_dir => $package->cwd,
121 mb_version => $Module::Build::VERSION,
127 $self->_set_defaults;
128 my ($p, $ph) = ($self->{properties}, $self->{phash});
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) {
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");
150 my $blibdir = sub { File::Spec->catdir($p->{blib}, @_) };
151 $p->{bindoc_dirs} ||= [ $blibdir->("script") ];
152 $p->{libdoc_dirs} ||= [ $blibdir->("lib"), $blibdir->("arch") ];
154 $p->{dist_author} = [ $p->{dist_author} ] if defined $p->{dist_author} and not ref $p->{dist_author};
157 $p->{requires} = delete $p->{prereq} if defined $p->{prereq};
158 $p->{script_files} = delete $p->{scripts} if defined $p->{scripts};
161 for ('extra_compiler_flags', 'extra_linker_flags') {
162 $p->{$_} = [ $self->split_like_shell($p->{$_}) ] if exists $p->{$_};
165 $self->add_to_cleanup( @{delete $p->{add_to_cleanup}} )
166 if $p->{add_to_cleanup};
171 ################## End constructors #########################
173 sub log_info { print @_ unless shift()->quiet }
174 sub log_verbose { shift()->log_info(@_) if $_[0]->verbose }
176 # Try to make our call stack invisible
178 if (@_ and $_[-1] !~ /\n$/) {
179 my (undef, $file, $line) = caller();
180 warn @_, " at $file line $line.\n";
187 sub _set_install_paths {
189 my $c = $self->{config};
190 my $p = $self->{properties};
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');
197 my $bindoc = $c->get('installman1dir') || undef;
198 my $libdoc = $c->get('installman3dir') || undef;
200 my $binhtml = $c->get('installhtml1dir') || $c->get('installhtmldir') || undef;
201 my $libhtml = $c->get('installhtml3dir') || $c->get('installhtmldir') || undef;
206 lib => $c->get('installprivlib'),
207 arch => $c->get('installarchlib'),
208 bin => $c->get('installbin'),
209 script => $c->get('installscript'),
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,
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,
239 $p->{original_prefix} =
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') : '',
246 $p->{original_prefix}{site} ||= $p->{original_prefix}{core};
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
252 $p->{install_base_relpaths} =
254 lib => ['lib', 'perl5'],
255 arch => ['lib', 'perl5', $arch],
258 bindoc => ['man', 'man1'],
259 libdoc => ['man', 'man3'],
264 $p->{prefix_relpaths} =
268 arch => [@libstyle, $version, $arch],
271 bindoc => ['man', 'man1'],
272 libdoc => ['man', 'man3'],
278 arch => [@libstyle, $version, $arch],
281 bindoc => ['man', 'man1'],
282 libdoc => ['man', 'man3'],
287 lib => [@libstyle, 'site_perl'],
288 arch => [@libstyle, 'site_perl', $version, $arch],
291 bindoc => ['man', 'man1'],
292 libdoc => ['man', 'man3'],
300 sub _find_nested_builds {
302 my $r = $self->recurse_into or return;
305 if (!ref($r) && $r eq 'auto') {
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' );
316 $self->recurse_into(\@r);
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) = @_;
329 my $return_args = '';
333 if ( /^[^\s*?!$<>;\\|'"\[\]\{\}]+$/ ) {
337 # XXX this will obviously have to improve - is there already a
338 # core module lying around that does proper quoting?
340 push @quoted, qq("$_");
344 return join " ", @quoted;
348 my ($self, @cmd) = @_;
349 if ($self->have_forkpipe) {
351 my $pid = open *FH, "-|";
353 return wantarray ? <FH> : join '', <FH>;
355 die "Can't execute @cmd: $!\n" unless defined $pid;
356 exec { $cmd[0] } @cmd;
359 my $cmd = $self->_quote_args(@cmd);
364 sub have_forkpipe { 1 }
366 # Determine whether a given binary is the same as the perl
367 # (configuration) that started this process.
369 my ($self, $perl) = @_;
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
379 if ($ENV{PERL_CORE}) {
380 push @cmd, '-I' . File::Spec->catdir(File::Basename::dirname($perl), 'lib');
383 push @cmd, qw(-MConfig=myconfig -e print -e myconfig);
384 return $self->_backticks(@cmd) eq Config->myconfig;
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 {
399 my $c = ref($proto) ? $proto->{config} : 'Module::Build::Config';
402 my $perl_basename = File::Basename::basename($perl);
406 # Try 1, Check $^X for absolute path
407 push( @potential_perls, $perl )
408 if File::Spec->file_name_is_absolute($perl);
410 # Try 2, Check $^X for a valid relative path
411 my $abs_perl = File::Spec->rel2abs($perl);
412 push( @potential_perls, $abs_perl );
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}) {
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.
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) ) {
428 File::Spec->rel2abs(File::Spec->catfile( $perl_src, $perl_basename ));
429 push( @potential_perls, $uninstperl );
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.
438 push( @potential_perls, $c->get('perlpath') );
440 push( @potential_perls,
441 map File::Spec->catfile($_, $perl_basename), File::Spec->path() );
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 ) {
450 if (defined $exe and $proto->os_type ne 'VMS') {
451 $thisperl .= $exe unless $thisperl =~ m/$exe$/i;
454 if ( -f $thisperl && $proto->_perl_is_same($thisperl) ) {
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 " .
466 sub _is_interactive {
467 return -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ; # Pipe?
470 # NOTE this is a blocking operation if(-t STDIN)
473 return $ENV{PERL_MM_USE_DEFAULT} ||
474 ( !$self->_is_interactive && eof STDIN );
479 return undef if $self->_is_unattended;
481 my $answer = <STDIN>;
482 chomp $answer if defined $answer;
489 or die "prompt() called without a prompt message";
491 # use a list to distinguish a default of undef() from no default
493 @def = (shift) if @_;
494 # use dispdef for output
495 my @dispdef = scalar(@def) ?
496 ('[', (defined($def[0]) ? $def[0] . ' ' : ''), ']') :
500 print "$mess ", @dispdef;
502 if ( $self->_is_unattended && !@def ) {
504 ERROR: This build seems to be unattended, but there is no default value
505 for this question. Aborting.
509 my $ans = $self->_readline();
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] : '';
522 my ($mess, $def) = @_;
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;
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;
534 print "Please answer 'y' or 'n'.\n";
538 sub current_action { shift->{action} }
539 sub invoked_action { shift->{invoked_action} }
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(@_) }
548 my $ph = $self->{phash};
552 if ($ph->{features}->exists($key)) {
553 return $ph->{features}->access($key, @_);
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;
563 return $ph->{features}->access($key, @_);
566 # No args - get the auto_features & overlay the regular 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;
575 %features = (%features, $ph->{features}->access());
577 return wantarray ? %features : \%features;
579 BEGIN { *feature = \&features }
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(@_);
589 require Module::Build::ConfigData;
590 return Module::Build::ConfigData->feature(@_);
595 sub add_build_element {
596 my ($self, $elem) = @_;
597 my $elems = $self->build_elements;
598 push @$elems, $elem unless grep { $_ eq $elem } @$elems;
601 sub ACTION_config_data {
603 return unless $self->has_config_data;
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");
610 return if $self->up_to_date(['Build.PL',
611 $self->config_file('config_data'),
612 $self->config_file('features')
615 $self->log_info("Writing config notes to $notes_pm\n");
616 File::Path::mkpath(File::Basename::dirname($notes_pm));
618 Module::Build::Notes->write_config_data
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,
630 my %valid_properties = ( __PACKAGE__, {} );
631 my %additive_properties;
634 my $class = ref($_[0]) || $_[0];
635 return ($class, $class->mb_parents);
639 my ($class, $prop) = @_;
640 return grep exists( $valid_properties{$_}{$prop} ), $class->_mb_classes;
643 sub valid_properties {
644 return keys %{ shift->valid_properties_defaults() };
647 sub valid_properties_defaults {
649 for (reverse shift->_mb_classes) {
650 @out{ keys %{ $valid_properties{$_} } } = values %{ $valid_properties{$_} };
655 sub array_properties {
656 for (shift->_mb_classes) {
657 return @{$additive_properties{$_}->{ARRAY}}
658 if exists $additive_properties{$_}->{ARRAY};
662 sub hash_properties {
663 for (shift->_mb_classes) {
664 return @{$additive_properties{$_}->{'HASH'}}
665 if exists $additive_properties{$_}->{'HASH'};
670 my ($class, $property, $default) = @_;
671 die "Property '$property' already exists" if $class->valid_property($property);
673 $valid_properties{$class}{$property} = $default;
675 my $type = ref $default;
677 push @{$additive_properties{$class}->{$type}}, $property;
680 unless ($class->can($property)) {
682 if ( $type eq 'HASH' ) {
683 *{"$class\::$property"} = sub {
685 my $x = $self->{properties};
686 return $x->{$property} unless @_;
688 if ( defined($_[0]) && !ref($_[0]) ) {
690 return exists( $x->{$property}{$_[0]} ) ?
691 $x->{$property}{$_[0]} : undef;
692 } elsif ( @_ % 2 == 0 ) {
694 while ( my($k, $v) = each %args ) {
695 $x->{$property}{$k} = $v;
698 die "Unexpected arguments for property '$property'\n";
701 $x->{$property} = $_[0];
706 *{"$class\::$property"} = sub {
708 $self->{properties}{$property} = shift if @_;
709 return $self->{properties}{$property};
720 # Set the build class.
721 $self->{properties}{build_class} ||= ref $self;
723 # If there was no orig_dir, set to the same as base_dir
724 $self->{properties}{orig_dir} ||= $self->{properties}{base_dir};
726 my $defaults = $self->valid_properties_defaults;
728 foreach my $prop (keys %$defaults) {
729 $self->{properties}{$prop} = $defaults->{$prop}
730 unless exists $self->{properties}{$prop};
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};
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};
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);
764 my $Is_ActivePerl = eval {require ActivePerl::DocTools};
765 __PACKAGE__->add_property(html_css => $Is_ActivePerl ? 'Active.css' : '');
769 my @prereq_action_types = qw(requires build_requires conflicts recommends);
770 foreach my $type (@prereq_action_types) {
771 __PACKAGE__->add_property($type => {});
773 __PACKAGE__->add_property(prereq_action_types => \@prereq_action_types);
776 __PACKAGE__->add_property($_ => {}) for qw(
778 install_base_relpaths
787 __PACKAGE__->add_property($_) for qw(
828 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
829 return $c->all_config unless @_;
832 return $c->get($key) unless @_;
835 return $c->set($key => $val);
839 # Code borrowed from Class::ISA.
840 my @in_stack = (shift);
841 my %seen = ($in_stack[0] => 1);
845 next unless defined($current = shift @in_stack)
846 && $current->isa('Module::Build::Base');
848 next if $current eq 'Module::Build::Base';
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"};
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
867 sub extra_linker_flags { shift->_list_accessor('extra_linker_flags', @_) }
868 sub extra_compiler_flags { shift->_list_accessor('extra_compiler_flags', @_) }
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->{$_}];
878 # XXX Problem - if Module::Build is loaded from a different directory,
879 # it'll look for (and perhaps destroy/create) a _build directory.
881 my ($pack, %opts) = @_;
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;
886 die "Must provide 'code' or 'class' option to subclass()\n"
887 unless $opts{code} or $opts{class};
890 $opts{class} ||= 'MyModuleBuilder';
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");
896 File::Path::mkpath($filedir);
897 die "Can't create directory $filedir: $!" unless -d $filedir;
899 my $fh = IO::File->new("> $filename") or die "Can't create $filename: $!";
901 package $opts{class};
909 unshift @INC, File::Spec->catdir(File::Spec->rel2abs($build_dir), 'lib');
910 eval "use $opts{class}";
918 my $p = $self->{properties};
919 return $p->{dist_name} if defined $p->{dist_name};
921 die "Can't determine distribution name, must supply either 'dist_name' or 'module_name' parameter"
922 unless $self->module_name;
924 ($p->{dist_name} = $self->module_name) =~ s/::/-/g;
926 return $p->{dist_name};
929 sub dist_version_from {
931 my $p = $self->{properties};
932 if ($self->module_name) {
933 $p->{dist_version_from} ||=
934 join( '/', 'lib', split(/::/, $self->module_name) ) . '.pm';
936 return $p->{dist_version_from} || undef;
941 my $p = $self->{properties};
943 return $p->{dist_version} if defined $p->{dist_version};
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();
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};
956 return $p->{dist_version};
959 sub dist_author { shift->_pod_parse('author') }
960 sub dist_abstract { shift->_pod_parse('abstract') }
963 my ($self, $part) = @_;
964 my $p = $self->{properties};
965 my $member = "dist_$part";
966 return $p->{$member} if defined $p->{$member};
968 my $docfile = $self->_main_docfile
970 my $fh = IO::File->new($docfile)
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();
979 sub version_from_file { # Method provided for backwards compatability
980 return Module::Build::ModuleInfo->new_from_file($_[1])->version();
983 sub find_module_by_name { # Method provided for backwards compatability
984 return Module::Build::ModuleInfo->find_module_by_name(@_[1,2]);
989 my %files = map {$self->localize_file_path($_), 1} @_;
990 $self->{phash}{cleanup}->write(\%files);
995 my $all = $self->{phash}{cleanup}->read;
1001 return unless -d $self->config_dir;
1002 return File::Spec->catfile($self->config_dir, @_);
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>};
1014 ($self->{args}, $c, $self->{properties}) = @$ref;
1015 $self->{config} = Module::Build::Config->new(values => $c);
1019 sub has_config_data {
1021 return scalar grep $self->{phash}{$_}->has_data(), qw(config_data features auto_features);
1025 my ($self, $filename, $data) = @_;
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;
1036 File::Path::mkpath($self->{properties}{config_dir});
1037 -d $self->{properties}{config_dir} or die "Can't mkdir $self->{properties}{config_dir}: $!";
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}]);
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));
1046 $self->{phash}{$_}->write() foreach qw(notes cleanup features auto_features config_data runtime_params);
1049 sub check_autofeatures {
1051 my $features = $self->auto_features;
1053 return unless %$features;
1055 $self->log_info("Checking features:\n");
1058 $max_name_len = ( length($_) > $max_name_len ) ?
1059 length($_) : $max_name_len
1060 for keys %$features;
1062 while (my ($name, $info) = each %$features) {
1063 $self->log_info(" $name" . '.' x ($max_name_len - length($name) + 4));
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" );
1071 while (my ($type, $prereqs) = each %$failures) {
1072 while (my ($module, $status) = each %$prereqs) {
1074 ($type =~ /^(?:\w+_)?(?:requires|conflicts)$/) ? 1 : 0;
1075 my $prefix = ($required) ? '-' : '*';
1076 $log_text .= " $prefix $status->{message}\n";
1079 $self->log_warn("$log_text") unless $self->quiet;
1081 $self->log_info("enabled\n");
1085 $self->log_warn("\n");
1088 sub prereq_failures {
1089 my ($self, $info) = @_;
1091 my @types = @{ $self->prereq_action_types };
1092 $info ||= {map {$_, $self->$_()} @types};
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);
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";
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");
1112 next if $status->{ok};
1115 $out->{$type}{$modname} = $status;
1122 # returns a hash of defined prerequisites; i.e. only prereq types with values
1126 foreach my $type ( @{ $self->prereq_action_types } ) {
1127 if ( $self->can( $type ) ) {
1128 my $prereq = $self->$type() || {};
1129 $prereqs{$type} = $prereq if %$prereq;
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");
1146 # Check to see if there are any prereqs to check
1147 my $info = $self->_enum_prereqs;
1148 return 1 unless $info;
1150 $self->log_info("Checking prerequisites...\n");
1152 my $failures = $self->prereq_failures($info);
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");
1163 $self->log_warn(<<EOF);
1165 ERRORS/WARNINGS FOUND IN PREREQUISITES. You may wish to install the versions
1166 of the modules indicated above before proceeding with this installation
1173 $self->log_info("Looks good\n\n");
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) : $];
1187 sub perl_version_to_float {
1188 my ($self, $version) = @_;
1189 $version =~ s/\./../;
1190 $version =~ s/\.(\d+)/sprintf '%03d', $1/eg;
1194 sub _parse_conditions {
1195 my ($self, $spec) = @_;
1197 if ($spec =~ /^\s*([\w.]+)\s*$/) { # A plain number, maybe with dots, letters, and underscores
1198 return (">= $spec");
1200 return split /\s*,\s*/, $spec;
1204 sub check_installed_status {
1205 my ($self, $modname, $spec) = @_;
1206 my %status = (need => $spec);
1208 if ($modname eq 'perl') {
1209 $status{have} = $self->perl_version;
1211 } elsif (eval { no strict; $status{have} = ${"${modname}::VERSION"} }) {
1212 # Don't try to load if it's already loaded
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");
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");
1228 my @conditions = $self->_parse_conditions($spec);
1230 foreach (@conditions) {
1231 my ($op, $version) = /^\s* (<=?|>=?|==|!=) \s* ([\w.]+) \s*$/x
1232 or die "Invalid prerequisite condition '$_' for $modname";
1234 $version = $self->perl_version_to_float($version)
1235 if $modname eq 'perl';
1237 next if $op eq '>=' and !$version; # Module doesn't have to actually define a $VERSION
1239 unless ($self->compare_versions( $status{have}, $op, $version )) {
1240 $status{message} = "$modname ($status{have}) is installed, but we need version $op $version";
1249 sub compare_versions {
1251 my ($v1, $op, $v2) = @_;
1252 $v1 = Module::Build::Version->new($v1)
1253 unless UNIVERSAL::isa($v1,'Module::Build::Version');
1255 my $eval_str = "\$v1 $op \$v2";
1256 my $result = eval $eval_str;
1257 $self->log_warn("error comparing versions: '$eval_str' $@") if $@;
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) = @_;
1266 my $status = $self->check_installed_status($modname, $spec);
1268 if ($status->{ok}) {
1269 return $status->{have} if $status->{have} and $status->{have} ne '<none>';
1270 return '0 but true';
1273 $@ = $status->{message};
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
1284 my $current_mode = (stat $_)[2];
1285 chmod $current_mode | oct(111), $_;
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) = @_;
1296 sub _startperl { shift()->config('startperl') }
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".
1304 $seen{$_}++ foreach $self->_default_INC;
1305 return grep !$seen{$_}++, @INC;
1308 # Determine the default @INC for this Perl
1310 my @default_inc; # Memoize
1313 return @default_inc if @default_inc;
1315 local $ENV{PERL5LIB}; # this is not considered part of the default.
1317 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
1319 my @inc = $self->_backticks($perl, '-le', 'print for @INC');
1322 return @default_inc = @inc;
1326 sub print_build_script {
1327 my ($self, $fh) = @_;
1329 my $build_package = $self->build_class;
1333 my %q = map {$_, $self->$_()} qw(config_dir base_dir);
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';
1340 $q{magic_numfile} = $self->config_file('magicnum');
1342 my @myINC = $self->_added_to_INC;
1343 for (@myINC, values %q) {
1344 $_ = File::Spec->canonpath( $_ );
1348 my $quoted_INC = join ",\n", map " '$_'", @myINC;
1349 my $shebang = $self->_startperl;
1350 my $magic_number = $self->magic_number;
1360 sub magic_number_matches {
1361 return 0 unless -e '$q{magic_numfile}';
1363 open FH, '$q{magic_numfile}' or return 0;
1364 my \$filenum = <FH>;
1366 return \$filenum == $magic_number;
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");
1380 unless (magic_number_matches()) {
1381 die ("Configuration seems to be out of date, please re-run 'perl Build.PL' again.\\n");
1390 close(*DATA) unless eof(*DATA); # ensure no open handles to this script
1394 # Some platforms have problems setting \$^X in shebang contexts, fix it up here
1395 \$^X = Module::Build->find_perl_interpreter;
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";
1401 # This should have just enough arguments to be able to bootstrap the rest.
1402 my \$build = $build_package->resume (
1404 config_dir => '$q{config_dir}',
1405 orig_dir => \$orig_dir,
1413 sub create_build_script {
1415 $self->write_config;
1417 my ($build_script, $dist_name, $dist_version)
1418 = map $self->$_(), qw(build_script dist_name dist_version);
1420 if ( $self->delete_filetree($build_script) ) {
1421 $self->log_info("Removed previous script '$build_script'\n\n");
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);
1430 $self->make_executable($build_script);
1435 sub check_manifest {
1437 return unless -e 'MANIFEST';
1439 # Stolen nearly verbatim from MakeMaker. But ExtUtils::Manifest
1440 # could easily be re-written into a modern Perl dialect.
1442 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
1443 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
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");
1451 $self->log_info("Looks good\n\n");
1457 local $self->{_completed_actions} = {};
1460 my ($action, %p) = @_;
1461 my $args = $p{args} ? delete($p{args}) : {};
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);
1469 die "No build action specified" unless $self->{action};
1470 local $self->{invoked_action} = $self->{action};
1471 $self->_call_action($self->{action});
1475 my ($self, $action) = @_;
1477 return if $self->{_completed_actions}{$action}++;
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();
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.
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};
1506 local @ARGV = @_; # No other way to dupe Getopt::Long
1508 # Get the options values and return them.
1509 # XXX Add option to allow users to set options?
1511 Getopt::Long::Configure('pass_through');
1512 Getopt::Long::GetOptions($args, @specs);
1515 return $args, @ARGV;
1519 my ($self, $args) = @_;
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 :
1531 return wantarray ? %{ $self->{args} } : $self->{args} unless @_;
1533 $self->{args}{$key} = shift if @_;
1534 return $self->{args}{$key};
1537 sub _translate_option {
1541 (my $tr_opt = $opt) =~ tr/-/_/;
1543 return $tr_opt if grep $tr_opt =~ /^(?:no_?)?$_$/, qw(
1546 extra_compiler_flags
1555 ); # normalize only selected option names
1561 my ($self, $args, $key, $val) = @_;
1563 $key = $self->_translate_option($key);
1565 if ( exists $args->{$key} ) {
1566 $args->{$key} = [ $args->{$key} ] unless ref $args->{$key};
1567 push @{$args->{$key}}, $val;
1569 $args->{$key} = $val;
1578 $opt = $self->_translate_option($opt);
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 ) {
1597 # non-boolean option; return option unchanged along with its argument
1598 return ($opt, shift(@$argv)) unless grep $_ eq $opt, @bool_opts;
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.
1605 $arg = shift(@$argv) if @$argv && $argv->[0] =~ /^\d+$/;
1607 return ($opt, $arg);
1612 my ($action, @argv);
1613 (my $args, @_) = $self->cull_options(@_);
1616 my $opt_re = qr/[\w\-]+/;
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)) {
1631 $args{ARGV} = \@argv;
1633 for ('extra_compiler_flags', 'extra_linker_flags') {
1634 $args{$_} = [ $self->split_like_shell($args{$_}) ] if exists $args{$_};
1637 # Hashify these parameters
1638 for ($self->hash_properties, 'config') {
1639 next unless exists $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'";
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});
1657 for my $key (qw(install_path)) {
1658 next if !defined $args{$key};
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;
1667 $args{$key}{$subkey} = $subkey_ext;
1672 if ($args{makefile_env_macros}) {
1673 require Module::Build::Compat;
1674 %args = (%args, Module::Build::Compat->makefile_to_build_macros);
1677 return \%args, $action;
1681 # (bash shell won't expand tildes mid-word: "--foo=~/thing")
1682 # TODO: handle ~user/foo
1686 return $arg =~ /^~/ ? (glob $arg)[0] : $arg;
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 ) = @_;
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} );
1705 $new_opts{$key} = $val
1712 # Look for a home directory on various systems.
1715 push( @home_dirs, $ENV{HOME} ) if $ENV{HOME};
1717 push( @home_dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
1718 if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};
1720 my @other_home_envs = qw( USERPROFILE APPDATA WINDIR SYS$LOGIN );
1721 push( @home_dirs, map $ENV{$_}, grep $ENV{$_}, @other_home_envs );
1723 my @real_home_dirs = grep -d, @home_dirs;
1725 return wantarray ? @real_home_dirs : shift( @real_home_dirs );
1728 sub _find_user_config {
1731 foreach my $dir ( $self->_home_dir ) {
1732 my $path = File::Spec->catfile( $dir, $file );
1733 return $path if -e $path;
1738 # read ~/.modulebuildrc returning global options '*' and
1739 # options specific to the currently executing $action.
1740 sub read_modulebuildrc {
1741 my( $self, $action ) = @_;
1743 return () unless $self->use_rcfile;
1746 if ( exists($ENV{MODULEBUILDRC}) && $ENV{MODULEBUILDRC} eq 'NONE' ) {
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");
1756 $modulebuildrc = $self->_find_user_config( '.modulebuildrc' );
1757 return () unless $modulebuildrc;
1760 my $fh = IO::File->new( $modulebuildrc )
1761 or die "Can't open $modulebuildrc: $!";
1763 my %options; my $buffer = '';
1764 while (defined( my $line = <$fh> )) {
1767 next unless length( $line );
1769 if ( $line =~ /^\S/ ) {
1771 my( $action, $options ) = split( /\s+/, $buffer, 2 );
1772 $options{$action} .= $options . ' ';
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
1787 $self->read_args( $self->split_like_shell( $options{'*'} || '' ) );
1789 $self->read_args( $self->split_like_shell( $options{$action} || '' ) );
1791 # specific $action options take priority over global options '*'
1792 return $self->_merge_arglist( $action_opts, $global_opts );
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 );
1805 my ($self, $action, %args) = @_;
1806 $self->{action} = $action if defined $action;
1808 my %additive = map { $_ => 1 } $self->hash_properties;
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);
1815 if ($key eq 'config') {
1816 $self->config($_ => $val->{$_}) foreach keys %$val;
1818 my $add_to = ( $additive{$key} ? $self->{properties}{$key}
1819 : $self->valid_property($key) ? $self->{properties}
1822 if ($additive{$key}) {
1823 $add_to->{$_} = $val->{$_} foreach keys %$val;
1825 $add_to->{$key} = $val;
1833 my ($args, $action) = $self->read_args(@_);
1834 $self->merge_args($action, %$args);
1835 $self->merge_modulebuildrc( $action, %$args );
1839 my ($self, $class, $seen) = @_;
1840 $class ||= ref($self) || $self;
1844 my @super = grep {not $seen->{$_}++} $class, @{ $class . '::ISA' };
1845 return @super, map {$self->super_classes($_,$seen)} @super;
1854 foreach my $class ($self->super_classes) {
1855 foreach ( keys %{ $class . '::' } ) {
1856 $actions{$1}++ if /^ACTION_(\w+)/;
1860 return wantarray ? sort keys %actions : \%actions;
1863 sub get_action_docs {
1864 my ($self, $action) = @_;
1865 my $actions = $self->known_actions;
1866 die "No known action '$action'" unless $actions->{$action};
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;
1876 # Code below modified from /usr/bin/perldoc
1878 # Skip to ACTIONS section
1881 last if /^=head1 ACTIONS\s/;
1884 # Look for our action and determine the style
1889 # only item and head2 are allowed (3&4 are not in 5.005)
1890 if(/^=(item|head2)\s+\Q$action\E\b/) {
1896 $style or next; # not here
1899 if($style eq 'item') {
1900 my ($found, $inlist) = (0, 0);
1902 if (/^=(item|back)/) {
1903 last unless $inlist;
1906 ++$inlist if /^=over/;
1907 --$inlist if /^=back/;
1910 else { # head2 style
1911 # stop at anything equal or greater than the found level
1913 last if(/^=(?:head[12]|cut)/);
1917 # TODO maybe disallow overriding just pod for an action
1918 # TODO and possibly: @docs and last;
1921 unless ($files_found) {
1922 $@ = "Couldn't find any documentation to search";
1926 $@ = "Couldn't find any docs for action '$action'";
1930 return join '', @docs;
1933 sub ACTION_prereq_report {
1935 $self->log_info( $self->prereq_report );
1940 my @types = @{ $self->prereq_action_types };
1941 my $info = { map { $_ => $self->$_() } @types };
1944 foreach my $type (@types) {
1945 my $prereqs = $info->{$type};
1946 next unless %$prereqs;
1947 $output .= "\n$type:\n";
1951 while ( my ($modname, $spec) = each %$prereqs ) {
1952 my $len = length $modname;
1953 $mod_len = $len if $len > $mod_len;
1955 $len = length $spec;
1956 $ver_len = $len if $len > $ver_len;
1958 my $mod = $self->check_installed_status($modname, $spec);
1959 $mod->{name} = $modname;
1961 $mod->{ok} = ! $mod->{ok} if $type =~ /^(\w+_)?conflicts$/;
1963 $mods{lc $modname} = $mod;
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$/) ?
1973 " Module $space $disposition $vspace Have\n".
1974 " ------$sline+------$vline-+----------\n";
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} ? ' ' : '!';
1983 " $f $mod->{name} $space $mod->{need} $vspace $mod->{have}\n";
1991 my $actions = $self->known_actions;
1993 if (@{$self->{args}{ARGV}}) {
1994 my $msg = eval {$self->get_action_docs($self->{args}{ARGV}[0], $actions)};
1995 print $@ ? "$@\n" : $msg;
2001 Usage: $0 <action> arg1=value arg2=value ...
2002 Example: $0 test verbose=1
2007 print $self->_action_listing($actions);
2009 print "\nRun `Build help <action>` for details on an individual action.\n";
2010 print "See `perldoc Module::Build` for complete documentation.\n";
2013 sub _action_listing {
2014 my ($self, $actions) = @_;
2016 # Flow down columns, not across rows
2017 my @actions = sort keys %$actions;
2018 @actions = map $actions[($_ + ($_ % 2) * @actions) / 2], 0..$#actions;
2021 while (my ($one, $two) = splice @actions, 0, 2) {
2022 $out .= sprintf(" %-12s %-12s\n", $one, $two||'');
2030 # Protect others against our @INC changes
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;
2040 sub ACTION_testall {
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" );
2053 $self->generic_test(types => ['default', @types]);
2056 sub get_test_types {
2059 my $t = $self->{properties}->{test_types};
2060 return ( defined $t ? ( keys %$t ) : () );
2066 $self->generic_test(type => 'default');
2071 (@_ % 2) and croak('Odd number of elements in argument hash');
2074 my $p = $self->{properties};
2077 (exists($args{type}) ? $args{type} : ()),
2078 (exists($args{types}) ? @{$args{types}} : ()),
2080 @types or croak "need some types of tests to check";
2084 (defined($p->{test_types}) ? %{$p->{test_types}} : ()),
2087 for my $type (@types) {
2088 croak "$type not defined in test_types!"
2089 unless defined $test_types{ $type };
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');
2096 # Protect others against our @INC changes
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'));
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;
2112 my $p = $self->{properties};
2113 require Test::Harness;
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;
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};
2125 local ($Test::Harness::verbose,
2126 $Test::Harness::Verbose,
2128 $ENV{HARNESS_VERBOSE}) = ($p->{verbose} || 0) x 4;
2130 my $tests = $self->find_test_files;
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);
2138 $self->log_info("No tests defined.\n");
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);
2150 my $p = $self->{properties};
2152 return $p->{test_files} = (@_ == 1 ? shift : [@_]);
2154 return $self->find_test_files;
2157 sub expand_test_dir {
2158 my ($self, $dir) = @_;
2159 my $exts = $self->{properties}{test_file_exts} || ['.t'];
2161 return sort map { @{$self->rscan_dir($dir, qr{^[^.].*\Q$_\E$})} } @$exts
2162 if $self->recursive_test_files;
2164 return sort map { glob File::Spec->catfile($dir, "*$_") } @$exts;
2169 local $self->{properties}{debugger} = 1;
2170 $self->depends_on('test');
2173 sub ACTION_testcover {
2176 unless (Module::Build::ModuleInfo->find_module_by_name('Devel::Cover')) {
2177 warn("Cannot run testcover action unless Devel::Cover is installed.\n");
2181 $self->add_to_cleanup('coverage', 'cover_db');
2182 $self->depends_on('code');
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
2188 (File::Spec->catdir($self->blib, 'lib'), file_qr('\.pm$') );
2189 my $cover_files = $self->rscan_dir('cover_db', sub {-f $_ and not /\.html$/});
2191 $self->do_system(qw(cover -delete))
2192 unless $self->up_to_date($pm_files, $cover_files)
2193 && $self->up_to_date($self->test_files, $cover_files);
2196 local $Test::Harness::switches =
2197 local $Test::Harness::Switches =
2198 local $ENV{HARNESS_PERL_SWITCHES} = "-MDevel::Cover";
2200 $self->depends_on('test');
2201 $self->do_system('cover');
2207 # All installable stuff gets created in blib/ .
2208 # Create blib/arch to keep blib.pm happy
2209 my $blib = $self->blib;
2210 $self->add_to_cleanup($blib);
2211 File::Path::mkpath( File::Spec->catdir($blib, 'arch') );
2213 if (my $split = $self->autosplit) {
2214 $self->autosplit_file($_, $blib) for ref($split) ? @$split : ($split);
2217 foreach my $element (@{$self->build_elements}) {
2218 my $method = "process_${element}_files";
2219 $method = "process_files_by_extension" unless $self->can($method);
2220 $self->$method($element);
2223 $self->depends_on('config_data');
2228 $self->depends_on('code');
2229 $self->depends_on('docs');
2232 sub process_files_by_extension {
2233 my ($self, $ext) = @_;
2235 my $method = "find_${ext}_files";
2236 my $files = $self->can($method) ? $self->$method() : $self->_find_file_by_type($ext, 'lib');
2238 while (my ($file, $dest) = each %$files) {
2239 $self->copy_if_modified(from => $file, to => File::Spec->catfile($self->blib, $dest) );
2243 sub process_support_files {
2245 my $p = $self->{properties};
2246 return unless $p->{c_source};
2248 push @{$p->{include_dirs}}, $p->{c_source};
2250 my $files = $self->rscan_dir($p->{c_source}, qr('\.c(pp)?$'));
2251 foreach my $file (@$files) {
2252 push @{$p->{objects}}, $self->compile_c($file);
2256 sub process_PL_files {
2258 my $files = $self->find_PL_files;
2260 while (my ($file, $to) = each %$files) {
2261 unless ($self->up_to_date( $file, $to )) {
2262 $self->run_perl_script($file, [], [@$to]);
2263 $self->add_to_cleanup(@$to);
2268 sub process_xs_files {
2270 my $files = $self->find_xs_files;
2271 while (my ($from, $to) = each %$files) {
2272 unless ($from eq $to) {
2273 $self->add_to_cleanup($to);
2274 $self->copy_if_modified( from => $from, to => $to );
2276 $self->process_xs($to);
2280 sub process_pod_files { shift()->process_files_by_extension(shift()) }
2281 sub process_pm_files { shift()->process_files_by_extension(shift()) }
2283 sub process_script_files {
2285 my $files = $self->find_script_files;
2286 return unless keys %$files;
2288 my $script_dir = File::Spec->catdir($self->blib, 'script');
2289 File::Path::mkpath( $script_dir );
2291 foreach my $file (keys %$files) {
2292 my $result = $self->copy_if_modified($file, $script_dir, 'flatten') or next;
2293 $self->fix_shebang_line($result) unless $self->is_vmsish;
2294 $self->make_executable($result);
2300 if (my $files = $self->{properties}{PL_files}) {
2301 # 'PL_files' is given as a Unix file spec, so we localize_file_path().
2303 if (UNIVERSAL::isa($files, 'ARRAY')) {
2304 return { map {$_, [/^(.*)\.PL$/]}
2305 map $self->localize_file_path($_),
2308 } elsif (UNIVERSAL::isa($files, 'HASH')) {
2310 while (my ($file, $to) = each %$files) {
2311 $out{ $self->localize_file_path($file) } = [ map $self->localize_file_path($_),
2312 ref $to ? @$to : ($to) ];
2317 die "'PL_files' must be a hash reference or array reference";
2321 return unless -d 'lib';
2322 return { map {$_, [/^(.*)\.PL$/i ]} @{ $self->rscan_dir('lib',
2323 file_qr('\.PL$')) } };
2326 sub find_pm_files { shift->_find_file_by_type('pm', 'lib') }
2327 sub find_pod_files { shift->_find_file_by_type('pod', 'lib') }
2328 sub find_xs_files { shift->_find_file_by_type('xs', 'lib') }
2330 sub find_script_files {
2332 if (my $files = $self->script_files) {
2333 # Always given as a Unix file spec. Values in the hash are
2334 # meaningless, but we preserve if present.
2335 return { map {$self->localize_file_path($_), $files->{$_}} keys %$files };
2338 # No default location for script files
2342 sub find_test_files {
2344 my $p = $self->{properties};
2346 if (my $files = $p->{test_files}) {
2347 $files = [keys %$files] if UNIVERSAL::isa($files, 'HASH');
2348 $files = [map { -d $_ ? $self->expand_test_dir($_) : $_ }
2350 $self->split_like_shell($files)];
2352 # Always given as a Unix file spec.
2353 return [ map $self->localize_file_path($_), @$files ];
2356 # Find all possible tests in t/ or test.pl
2358 push @tests, 'test.pl' if -e 'test.pl';
2359 push @tests, $self->expand_test_dir('t') if -e 't' and -d _;
2364 sub _find_file_by_type {
2365 my ($self, $type, $dir) = @_;
2367 if (my $files = $self->{properties}{"${type}_files"}) {
2368 # Always given as a Unix file spec
2369 return { map $self->localize_file_path($_), %$files };
2372 return {} unless -d $dir;
2373 return { map {$_, $_}
2374 map $self->localize_file_path($_),
2376 @{ $self->rscan_dir($dir, file_qr("\\.$type\$")) } };
2379 sub localize_file_path {
2380 my ($self, $path) = @_;
2381 $path =~ s/\.\z// if $self->is_vmsish;
2382 return File::Spec->catfile( split m{/}, $path );
2385 sub localize_dir_path {
2386 my ($self, $path) = @_;
2387 return File::Spec->catdir( split m{/}, $path );
2390 sub fix_shebang_line { # Adapted from fixin() in ExtUtils::MM_Unix 1.35
2391 my ($self, @files) = @_;
2392 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
2394 my ($does_shbang) = $c->get('sharpbang') =~ /^\s*\#\!/;
2395 for my $file (@files) {
2396 my $FIXIN = IO::File->new($file) or die "Can't process '$file': $!";
2398 chomp(my $line = <$FIXIN>);
2399 next unless $line =~ s/^\s*\#!\s*//; # Not a shbang file.
2401 my ($cmd, $arg) = (split(' ', $line, 2), '');
2402 next unless $cmd =~ /perl/i;
2403 my $interpreter = $self->{properties}{perl};
2405 $self->log_verbose("Changing sharpbang in $file to $interpreter");
2407 $shb .= $c->get('sharpbang')."$interpreter $arg\n" if $does_shbang;
2409 # I'm not smart enough to know the ramifications of changing the
2410 # embedded newlines here to \n, so I leave 'em in.
2412 eval 'exec $interpreter $arg -S \$0 \${1+"\$\@"}'
2413 if 0; # not running under some shell
2414 } unless $self->is_windowsish; # this won't work on win32, so don't
2416 my $FIXOUT = IO::File->new(">$file.new")
2417 or die "Can't create new $file: $!\n";
2419 # Print out the new #! line (or equivalent).
2421 undef $/; # Was localized above
2422 print $FIXOUT $shb, <$FIXIN>;
2426 rename($file, "$file.bak")
2427 or die "Can't rename $file to $file.bak: $!";
2429 rename("$file.new", $file)
2430 or die "Can't rename $file.new to $file: $!";
2432 $self->delete_filetree("$file.bak")
2433 or $self->log_warn("Couldn't clean up $file.bak, leaving it there");
2435 $self->do_system($c->get('eunicefix'), $file) if $c->get('eunicefix') ne ':';
2440 sub ACTION_testpod {
2442 $self->depends_on('docs');
2444 eval q{use Test::Pod 0.95; 1}
2445 or die "The 'testpod' action requires Test::Pod version 0.95";
2447 my @files = sort keys %{$self->_find_pods($self->libdoc_dirs)},
2448 keys %{$self->_find_pods
2449 ($self->bindoc_dirs,
2450 exclude => [ file_qr('\.bat$') ])}
2451 or die "Couldn't find any POD files to test\n";
2453 { package Module::Build::PodTester; # Don't want to pollute the main namespace
2454 Test::Pod->import( tests => scalar @files );
2455 pod_file_ok($_) foreach @files;
2459 sub ACTION_testpodcoverage {
2462 $self->depends_on('docs');
2464 eval q{use Test::Pod::Coverage 1.00; 1}
2465 or die "The 'testpodcoverage' action requires ",
2466 "Test::Pod::Coverage version 1.00";
2468 # TODO this needs test coverage!
2470 # XXX work-around a bug in Test::Pod::Coverage previous to v1.09
2471 # Make sure we test the module in blib/
2473 my $p = $self->{properties};
2475 # XXX any reason to include arch?
2476 File::Spec->catdir($p->{base_dir}, $self->blib, 'lib'),
2477 #File::Spec->catdir($p->{base_dir}, $self->blib, 'arch')
2480 all_pod_coverage_ok();
2486 $self->depends_on('code');
2487 $self->depends_on('manpages', 'html');
2490 # Given a file type, will return true if the file type would normally
2491 # be installed when neither install-base nor prefix has been set.
2492 # I.e. it will be true only if the path is set from Config.pm or
2493 # set explicitly by the user via install-path.
2494 sub _is_default_installable {
2497 return ( $self->install_destination($type) &&
2498 ( $self->install_path($type) ||
2499 $self->install_sets($self->installdirs)->{$type} )
2503 sub ACTION_manpages {
2506 return unless $self->_mb_feature('manpage_support');
2508 $self->depends_on('code');
2510 foreach my $type ( qw(bin lib) ) {
2511 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2512 exclude => [ file_qr('\.bat$') ] );
2513 next unless %$files;
2515 my $sub = $self->can("manify_${type}_pods");
2516 next unless defined( $sub );
2518 if ( $self->invoked_action eq 'manpages' ) {
2520 } elsif ( $self->_is_default_installable("${type}doc") ) {
2527 sub manify_bin_pods {
2530 my $files = $self->_find_pods( $self->{properties}{bindoc_dirs},
2531 exclude => [ file_qr('\.bat$') ] );
2532 return unless keys %$files;
2534 my $mandir = File::Spec->catdir( $self->blib, 'bindoc' );
2535 File::Path::mkpath( $mandir, 0, oct(777) );
2538 foreach my $file (keys %$files) {
2539 # Pod::Simple based parsers only support one document per instance.
2540 # This is expected to change in a future version (Pod::Simple > 3.03).
2541 my $parser = Pod::Man->new( section => 1 ); # binaries go in section 1
2542 my $manpage = $self->man1page_name( $file ) . '.' .
2543 $self->config( 'man1ext' );
2544 my $outfile = File::Spec->catfile($mandir, $manpage);
2545 next if $self->up_to_date( $file, $outfile );
2546 $self->log_info("Manifying $file -> $outfile\n");
2547 $parser->parse_from_file( $file, $outfile );
2548 $files->{$file} = $outfile;
2552 sub manify_lib_pods {
2555 my $files = $self->_find_pods($self->{properties}{libdoc_dirs});
2556 return unless keys %$files;
2558 my $mandir = File::Spec->catdir( $self->blib, 'libdoc' );
2559 File::Path::mkpath( $mandir, 0, oct(777) );
2562 while (my ($file, $relfile) = each %$files) {
2563 # Pod::Simple based parsers only support one document per instance.
2564 # This is expected to change in a future version (Pod::Simple > 3.03).
2565 my $parser = Pod::Man->new( section => 3 ); # libraries go in section 3
2566 my $manpage = $self->man3page_name( $relfile ) . '.' .
2567 $self->config( 'man3ext' );
2568 my $outfile = File::Spec->catfile( $mandir, $manpage);
2569 next if $self->up_to_date( $file, $outfile );
2570 $self->log_info("Manifying $file -> $outfile\n");
2571 $parser->parse_from_file( $file, $outfile );
2572 $files->{$file} = $outfile;
2577 my ($self, $dirs, %args) = @_;
2579 foreach my $spec (@$dirs) {
2580 my $dir = $self->localize_dir_path($spec);
2581 next unless -e $dir;
2583 FILE: foreach my $file ( @{ $self->rscan_dir( $dir ) } ) {
2584 foreach my $regexp ( @{ $args{exclude} } ) {
2585 next FILE if $file =~ $regexp;
2587 $files{$file} = File::Spec->abs2rel($file, $dir) if $self->contains_pod( $file )
2594 my ($self, $file) = @_;
2595 return '' unless -T $file; # Only look at text files
2597 my $fh = IO::File->new( $file ) or die "Can't open $file: $!";
2598 while (my $line = <$fh>) {
2599 return 1 if $line =~ /^\=(?:head|pod|item)/;
2608 return unless $self->_mb_feature('HTML_support');
2610 $self->depends_on('code');
2612 foreach my $type ( qw(bin lib) ) {
2613 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2615 [ file_qr('\.(?:bat|com|html)$') ] );
2616 next unless %$files;
2618 if ( $self->invoked_action eq 'html' ) {
2619 $self->htmlify_pods( $type );
2620 } elsif ( $self->_is_default_installable("${type}html") ) {
2621 $self->htmlify_pods( $type );
2628 # 1) If it's an ActiveState perl install, we need to run
2629 # ActivePerl::DocTools->UpdateTOC;
2630 # 2) Links to other modules are not being generated
2634 my $htmldir = shift || File::Spec->catdir($self->blib, "${type}html");
2636 require Module::Build::PodParser;
2639 $self->add_to_cleanup('pod2htm*');
2641 my $pods = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2642 exclude => [ file_qr('\.(?:bat|com|html)$') ] );
2643 return unless %$pods; # nothing to do
2645 unless ( -d $htmldir ) {
2646 File::Path::mkpath($htmldir, 0, oct(755))
2647 or die "Couldn't mkdir $htmldir: $!";
2650 my @rootdirs = ($type eq 'bin') ? qw(bin) :
2651 $self->installdirs eq 'core' ? qw(lib) : qw(site lib);
2653 my $podpath = join ':',
2656 map [File::Spec->catdir($self->blib, $_), $_],
2659 foreach my $pod ( keys %$pods ) {
2661 my ($name, $path) = File::Basename::fileparse($pods->{$pod},
2662 file_qr('\.(?:pm|plx?|pod)$'));
2663 my @dirs = File::Spec->splitdir( File::Spec->canonpath( $path ) );
2664 pop( @dirs ) if $dirs[-1] eq File::Spec->curdir;
2666 my $fulldir = File::Spec->catfile($htmldir, @rootdirs, @dirs);
2667 my $outfile = File::Spec->catfile($fulldir, "${name}.html");
2668 my $infile = File::Spec->abs2rel($pod);
2670 next if $self->up_to_date($infile, $outfile);
2672 unless ( -d $fulldir ){
2673 File::Path::mkpath($fulldir, 0, oct(755))
2674 or die "Couldn't mkdir $fulldir: $!";
2677 my $path2root = join( '/', ('..') x (@rootdirs+@dirs) );
2678 my $htmlroot = join( '/',
2680 $self->installdirs eq 'core' ? () : qw(site) ) );
2682 my $fh = IO::File->new($infile) or die "Can't read $infile: $!";
2683 my $abstract = Module::Build::PodParser->new(fh => $fh)->get_abstract();
2685 my $title = join( '::', (@dirs, $name) );
2686 $title .= " - $abstract" if $abstract;
2691 "--podpath=$podpath",
2693 "--outfile=$outfile",
2694 '--podroot=' . $self->blib,
2695 "--htmlroot=$htmlroot",
2698 if ( eval{Pod::Html->VERSION(1.03)} ) {
2699 push( @opts, ('--header', '--backlink=Back to Top') );
2700 push( @opts, "--css=$path2root/" . $self->html_css) if $self->html_css;
2703 $self->log_info("HTMLifying $infile -> $outfile\n");
2704 $self->log_verbose("pod2html @opts\n");
2705 Pod::Html::pod2html(@opts); # or warn "pod2html @opts failed: $!";
2710 # Adapted from ExtUtils::MM_Unix
2713 return File::Basename::basename( shift );
2716 # Adapted from ExtUtils::MM_Unix and Pod::Man
2717 # Depending on M::B's dependency policy, it might make more sense to refactor
2718 # Pod::Man::begin_pod() to extract a name() methods, and use them...
2722 my ($vol, $dirs, $file) = File::Spec->splitpath( shift );
2723 my @dirs = File::Spec->splitdir( File::Spec->canonpath($dirs) );
2725 # Remove known exts from the base name
2726 $file =~ s/\.p(?:od|m|l)\z//i;
2728 return join( $self->manpage_separator, @dirs, $file );
2731 sub manpage_separator {
2735 # For systems that don't have 'diff' executable, should use Algorithm::Diff
2738 $self->depends_on('build');
2739 my $local_lib = File::Spec->rel2abs('lib');
2740 my @myINC = grep {$_ ne $local_lib} @INC;
2742 # The actual install destination might not be in @INC, so check there too.
2743 push @myINC, map $self->install_destination($_), qw(lib arch);
2745 my @flags = @{$self->{args}{ARGV}};
2746 @flags = $self->split_like_shell($self->{args}{flags} || '') unless @flags;
2748 my $installmap = $self->install_map;
2749 delete $installmap->{read};
2750 delete $installmap->{write};
2752 my $text_suffix = file_qr('\.(pm|pod)$');
2754 while (my $localdir = each %$installmap) {
2755 my @localparts = File::Spec->splitdir($localdir);
2756 my $files = $self->rscan_dir($localdir, sub {-f});
2758 foreach my $file (@$files) {
2759 my @parts = File::Spec->splitdir($file);
2760 @parts = @parts[@localparts .. $#parts]; # Get rid of blib/lib or similar
2762 my $installed = Module::Build::ModuleInfo->find_module_by_name(
2763 join('::', @parts), \@myINC );
2764 if (not $installed) {
2765 print "Only in lib: $file\n";
2769 my $status = File::Compare::compare($installed, $file);
2770 next if $status == 0; # Files are the same
2771 die "Can't compare $installed and $file: $!" if $status == -1;
2773 if ($file =~ $text_suffix) {
2774 $self->do_system('diff', @flags, $installed, $file);
2776 print "Binary files $file and $installed differ\n";
2782 sub ACTION_pure_install {
2783 shift()->depends_on('install');
2786 sub ACTION_install {
2788 require ExtUtils::Install;
2789 $self->depends_on('build');
2790 ExtUtils::Install::install($self->install_map, !$self->quiet, 0, $self->{args}{uninst}||0);
2793 sub ACTION_fakeinstall {
2795 require ExtUtils::Install;
2796 $self->depends_on('build');
2797 ExtUtils::Install::install($self->install_map, !$self->quiet, 1, $self->{args}{uninst}||0);
2800 sub ACTION_versioninstall {
2803 die "You must have only.pm 0.25 or greater installed for this operation: $@\n"
2804 unless eval { require only; 'only'->VERSION(0.25); 1 };
2806 $self->depends_on('build');
2808 my %onlyargs = map {exists($self->{args}{$_}) ? ($_ => $self->{args}{$_}) : ()}
2809 qw(version versionlib);
2810 only::install::install(%onlyargs);
2815 foreach my $item (map glob($_), $self->cleanup) {
2816 $self->delete_filetree($item);
2820 sub ACTION_realclean {
2822 $self->depends_on('clean');
2823 $self->delete_filetree($self->config_dir, $self->build_script);
2828 require Module::Build::PPMMaker;
2829 my $ppd = Module::Build::PPMMaker->new();
2830 my $file = $ppd->make_ppd(%{$self->{args}}, build => $self);
2831 $self->add_to_cleanup($file);
2834 sub ACTION_ppmdist {
2837 $self->depends_on( 'build' );
2839 my $ppm = $self->ppm_name;
2840 $self->delete_filetree( $ppm );
2841 $self->log_info( "Creating $ppm\n" );
2842 $self->add_to_cleanup( $ppm, "$ppm.tar.gz" );
2844 my %types = ( # translate types/dirs to those expected by ppm
2855 foreach my $type ($self->install_types) {
2856 next if exists( $types{$type} ) && !defined( $types{$type} );
2858 my $dir = File::Spec->catdir( $self->blib, $type );
2859 next unless -e $dir;
2861 my $files = $self->rscan_dir( $dir );
2862 foreach my $file ( @$files ) {
2863 next unless -f $file;
2865 File::Spec->abs2rel( File::Spec->rel2abs( $file ),
2866 File::Spec->rel2abs( $dir ) );
2868 File::Spec->catfile( $ppm, 'blib',
2869 exists( $types{$type} ) ? $types{$type} : $type,
2871 $self->copy_if_modified( from => $file, to => $to_file );
2875 foreach my $type ( qw(bin lib) ) {
2876 local $self->{properties}{html_css} = 'Active.css';
2877 $self->htmlify_pods( $type, File::Spec->catdir($ppm, 'blib', 'html') );
2881 # the directory tar'ed must be blib so we need to do a chdir first
2882 my $start_wd = $self->cwd;
2883 chdir( $ppm ) or die "Can't chdir to $ppm";
2884 $self->make_tarball( 'blib', File::Spec->catfile( $start_wd, $ppm ) );
2885 chdir( $start_wd ) or die "Can't chdir to $start_wd";
2887 $self->depends_on( 'ppd' );
2889 $self->delete_filetree( $ppm );
2892 sub ACTION_pardist {
2896 if ( not eval { require PAR::Dist; PAR::Dist->VERSION(0.17) } ) {
2898 "In order to create .par distributions, you need to\n"
2899 . "install PAR::Dist first."
2904 $self->depends_on( 'build' );
2906 return PAR::Dist::blib_to_par(
2907 name => $self->dist_name,
2908 version => $self->dist_version,
2915 $self->depends_on('distdir');
2917 my $dist_dir = $self->dist_dir;
2919 $self->make_tarball($dist_dir);
2920 $self->delete_filetree($dist_dir);
2923 sub ACTION_distcheck {
2926 require ExtUtils::Manifest;
2927 local $^W; # ExtUtils::Manifest is not warnings clean.
2928 my ($missing, $extra) = ExtUtils::Manifest::fullcheck();
2930 return unless @$missing || @$extra;
2932 my $msg = "MANIFEST appears to be out of sync with the distribution\n";
2933 if ( $self->invoked_action eq 'distcheck' ) {
2940 sub _add_to_manifest {
2941 my ($self, $manifest, $lines) = @_;
2942 $lines = [$lines] unless ref $lines;
2944 my $existing_files = $self->_read_manifest($manifest);
2945 return unless defined( $existing_files );
2947 @$lines = grep {!exists $existing_files->{$_}} @$lines
2950 my $mode = (stat $manifest)[2];
2951 chmod($mode | oct(222), $manifest) or die "Can't make $manifest writable: $!";
2953 my $fh = IO::File->new("< $manifest") or die "Can't read $manifest: $!";
2954 my $last_line = (<$fh>)[-1] || "\n";
2955 my $has_newline = $last_line =~ /\n$/;
2958 $fh = IO::File->new(">> $manifest") or die "Can't write to $manifest: $!";
2959 print $fh "\n" unless $has_newline;
2960 print $fh map "$_\n", @$lines;
2962 chmod($mode, $manifest);
2964 $self->log_info(map "Added to $manifest: $_\n", @$lines);
2968 my ($self, $dir) = @_;
2970 unless (eval { require Module::Signature; 1 }) {
2971 $self->log_warn("Couldn't load Module::Signature for 'distsign' action:\n $@\n");
2975 # Add SIGNATURE to the MANIFEST
2977 my $manifest = File::Spec->catfile($dir, 'MANIFEST');
2978 die "Signing a distribution requires a MANIFEST file" unless -e $manifest;
2979 $self->_add_to_manifest($manifest, "SIGNATURE Added here by Module::Build");
2982 # We protect the signing with an eval{} to make sure we get back to
2983 # the right directory after a signature failure. Would be nice if
2984 # Module::Signature took a directory argument.
2986 my $start_dir = $self->cwd;
2987 chdir $dir or die "Can't chdir() to $dir: $!";
2988 eval {local $Module::Signature::Quiet = 1; Module::Signature::sign()};
2989 my @err = $@ ? ($@) : ();
2990 chdir $start_dir or push @err, "Can't chdir() back to $start_dir: $!";
2991 die join "\n", @err if @err;
2994 sub ACTION_distsign {
2997 local $self->{properties}{sign} = 0; # We'll sign it ourselves
2998 $self->depends_on('distdir') unless -d $self->dist_dir;
3000 $self->_sign_dir($self->dist_dir);
3003 sub ACTION_skipcheck {
3006 require ExtUtils::Manifest;
3007 local $^W; # ExtUtils::Manifest is not warnings clean.
3008 ExtUtils::Manifest::skipcheck();
3011 sub ACTION_distclean {
3014 $self->depends_on('realclean');
3015 $self->depends_on('distcheck');
3018 sub do_create_makefile_pl {
3020 require Module::Build::Compat;
3021 $self->delete_filetree('Makefile.PL');
3022 $self->log_info("Creating Makefile.PL\n");
3023 Module::Build::Compat->create_makefile_pl($self->create_makefile_pl, $self, @_);
3024 $self->_add_to_manifest('MANIFEST', 'Makefile.PL');
3027 sub do_create_readme {
3029 $self->delete_filetree('README');
3031 my $docfile = $self->_main_docfile;
3032 unless ( $docfile ) {
3033 $self->log_warn(<<EOF);
3034 Cannot create README: can't determine which file contains documentation;
3035 Must supply either 'dist_version_from', or 'module_name' parameter.
3040 if ( eval {require Pod::Readme; 1} ) {
3041 $self->log_info("Creating README using Pod::Readme\n");
3043 my $parser = Pod::Readme->new;
3044 $parser->parse_from_file($docfile, 'README', @_);
3046 } elsif ( eval {require Pod::Text; 1} ) {
3047 $self->log_info("Creating README using Pod::Text\n");
3049 my $fh = IO::File->new('> README');
3050 if ( defined($fh) ) {
3054 # work around bug in Pod::Text 3.01, which expects
3055 # Pod::Simple::parse_file to take input and output filehandles
3056 # when it actually only takes an input filehandle
3059 $old_parse_file = \&{"Pod::Simple::parse_file"}
3061 local *{"Pod::Simple::parse_file"} = sub {
3063 $self->output_fh($_[1]) if $_[1];
3064 $self->$old_parse_file($_[0]);
3066 if $Pod::Text::VERSION
3067 == 3.01; # Split line to avoid evil version-finder
3069 Pod::Text::pod2text( $docfile, $fh );
3074 "Cannot create 'README' file: Can't open file for writing\n" );
3079 $self->log_warn("Can't load Pod::Readme or Pod::Text to create README\n");
3083 $self->_add_to_manifest('MANIFEST', 'README');
3088 if ( my $pm_file = $self->dist_version_from ) {
3089 (my $pod_file = $pm_file) =~ s/.pm$/.pod/;
3090 return (-e $pod_file ? $pod_file : $pm_file);
3096 sub ACTION_distdir {
3099 $self->depends_on('distmeta');
3101 my $dist_files = $self->_read_manifest('MANIFEST')
3102 or die "Can't create distdir without a MANIFEST file - run 'manifest' action first";
3103 delete $dist_files->{SIGNATURE}; # Don't copy, create a fresh one
3104 die "No files found in MANIFEST - try running 'manifest' action?\n"
3105 unless ($dist_files and keys %$dist_files);
3106 my $metafile = $self->metafile;
3107 $self->log_warn("*** Did you forget to add $metafile to the MANIFEST?\n")
3108 unless exists $dist_files->{$metafile};
3110 my $dist_dir = $self->dist_dir;
3111 $self->delete_filetree($dist_dir);
3112 $self->log_info("Creating $dist_dir\n");
3113 $self->add_to_cleanup($dist_dir);
3115 foreach my $file (keys %$dist_files) {
3116 my $new = $self->copy_if_modified(from => $file, to_dir => $dist_dir, verbose => 0);
3119 $self->_sign_dir($dist_dir) if $self->{properties}{sign};
3122 sub ACTION_disttest {
3125 $self->depends_on('distdir');
3127 my $start_dir = $self->cwd;
3128 my $dist_dir = $self->dist_dir;
3129 chdir $dist_dir or die "Cannot chdir to $dist_dir: $!";
3130 # XXX could be different names for scripts
3132 $self->run_perl_script('Build.PL') # XXX Should this be run w/ --nouse-rcfile
3133 or die "Error executing 'Build.PL' in dist directory: $!";
3134 $self->run_perl_script('Build')
3135 or die "Error executing 'Build' in dist directory: $!";
3136 $self->run_perl_script('Build', [], ['test'])
3137 or die "Error executing 'Build test' in dist directory";
3141 sub _write_default_maniskip {
3143 my $file = shift || 'MANIFEST.SKIP';
3144 my $fh = IO::File->new("> $file")
3145 or die "Can't open $file: $!";
3147 # This is derived from MakeMaker's default MANIFEST.SKIP file with
3151 # Avoid version control files.
3158 # Avoid Makemaker generated and utility files.
3166 # Avoid Module::Build generated and utility files.
3171 # Avoid Devel::Cover generated files
3174 # Avoid temp and backup files.
3183 # Avoid OS-specific files/dirs
3186 # Mac OSX SMB mount metadata files
3188 # Avoid archives of this distribution
3191 # Skip, for example, 'Module-Build-0.27.tar.gz'
3192 print $fh '\b'.$self->dist_name.'-[\d\.\_]+'."\n";
3197 sub ACTION_manifest {
3200 my $maniskip = 'MANIFEST.SKIP';
3201 unless ( -e 'MANIFEST' || -e $maniskip ) {
3202 $self->log_warn("File '$maniskip' does not exist: Creating a default '$maniskip'\n");
3203 $self->_write_default_maniskip($maniskip);
3206 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3207 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3208 ExtUtils::Manifest::mkmanifest();
3211 # Case insenstive regex for files
3213 return File::Spec->case_tolerant ? qr($_[0])i : qr($_[0]);
3218 return "$self->{properties}{dist_name}-$self->{properties}{dist_version}";
3223 return 'PPM-' . $self->dist_dir;
3227 my ($self, $dir) = @_;
3228 return unless -d $dir;
3231 opendir DH, $dir or die "Can't read directory $dir: $!";
3234 while (defined (my $file = readdir DH)) {
3235 my $full_path = File::Spec->catfile($dir, $file);
3236 next if -d $full_path;
3237 push @files, $full_path;
3245 for ($self->{properties}{script_files}) {
3249 # Always coerce into a hash
3250 return $_ if UNIVERSAL::isa($_, 'HASH');
3251 return $_ = { map {$_,1} @$_ } if UNIVERSAL::isa($_, 'ARRAY');
3253 die "'script_files' must be a hashref, arrayref, or string" if ref();
3255 return $_ = { map {$_,1} $self->_files_in( $_ ) } if -d $_;
3256 return $_ = {$_ => 1};
3259 return $_ = { map {$_,1} $self->_files_in( File::Spec->catdir( $self->base_dir, 'bin' ) ) };
3261 BEGIN { *scripts = \&script_files; }
3266 perl => 'http://dev.perl.org/licenses/',
3267 gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3268 apache => 'http://apache.org/licenses/LICENSE-2.0',
3269 artistic => 'http://opensource.org/licenses/artistic-license.php',
3270 lgpl => 'http://opensource.org/licenses/artistic-license.php',
3271 bsd => 'http://www.opensource.org/licenses/bsd-license.php',
3272 gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3273 mit => 'http://opensource.org/licenses/mit-license.php',
3274 mozilla => 'http://opensource.org/licenses/mozilla1.1.php',
3275 open_source => undef,
3276 unrestricted => undef,
3277 restrictive => undef,
3280 sub valid_licenses {
3286 my ($self, $h, $k, $v) = @_;
3287 if (ref $h->{$k} eq 'ARRAY') {
3288 push @{$h->{$k}}, ref $v ? @$v : $v;
3289 } elsif (ref $h->{$k} eq 'HASH') {
3290 $h->{$k}{$_} = $v->{$_} foreach keys %$v;
3296 sub ACTION_distmeta {
3299 $self->do_create_makefile_pl if $self->create_makefile_pl;
3300 $self->do_create_readme if $self->create_readme;
3301 $self->do_create_metafile;
3304 sub do_create_metafile {
3306 return if $self->{wrote_metadata};
3308 my $p = $self->{properties};
3309 my $metafile = $self->metafile;
3311 unless ($p->{license}) {
3312 $self->log_warn("No license specified, setting license = 'unknown'\n");
3313 $p->{license} = 'unknown';
3315 unless (exists $self->valid_licenses->{ $p->{license} }) {
3316 die "Unknown license type '$p->{license}'";
3319 # If we're in the distdir, the metafile may exist and be non-writable.
3320 $self->delete_filetree($metafile);
3321 $self->log_info("Creating $metafile\n");
3323 # Since we're building ourself, we have to do some special stuff
3324 # here: the ConfigData module is found in blib/lib.
3326 if (($self->module_name || '') eq 'Module::Build') {
3327 $self->depends_on('config_data');
3328 push @INC, File::Spec->catdir($self->blib, 'lib');
3331 $self->write_metafile;
3334 sub write_metafile {
3336 my $metafile = $self->metafile;
3338 if ($self->_mb_feature('YAML_support')) {
3342 # We use YAML::Node to get the order nice in the YAML file.
3343 $self->prepare_metadata( my $node = YAML::Node->new({}) );
3345 # YAML API changed after version 0.30
3346 my $yaml_sub = $YAML::VERSION le '0.30' ? \&YAML::StoreFile : \&YAML::DumpFile;
3347 $self->{wrote_metadata} = $yaml_sub->($metafile, $node );
3350 require Module::Build::YAML;
3351 my (%node, @order_keys);
3352 $self->prepare_metadata(\%node, \@order_keys);
3353 $node{_order} = \@order_keys;
3354 &Module::Build::YAML::DumpFile($metafile, \%node);
3355 $self->{wrote_metadata} = 1;
3358 $self->_add_to_manifest('MANIFEST', $metafile);
3361 sub prepare_metadata {
3362 my ($self, $node, $keys) = @_;
3363 my $p = $self->{properties};
3365 # A little helper sub
3366 my $add_node = sub {
3367 my ($name, $val) = @_;
3368 $node->{$name} = $val;
3369 push @$keys, $name if $keys;
3372 foreach (qw(dist_name dist_version dist_author dist_abstract license)) {
3373 (my $name = $_) =~ s/^dist_//;
3374 $add_node->($name, $self->$_());
3375 die "ERROR: Missing required field '$_' for META.yml\n"
3376 unless defined($node->{$name}) && length($node->{$name});
3378 $node->{version} = '' . $node->{version}; # Stringify version objects
3380 if (defined( $self->license ) &&
3381 defined( my $url = $self->valid_licenses->{ $self->license } )) {
3382 $node->{resources}{license} = $url;
3385 foreach ( @{$self->prereq_action_types} ) {
3386 if (exists $p->{$_} and keys %{ $p->{$_} }) {
3387 $add_node->($_, $p->{$_});
3391 if (exists $p->{dynamic_config}) {
3392 $add_node->('dynamic_config', $p->{dynamic_config});
3394 my $pkgs = eval { $self->find_dist_packages };
3396 $self->log_warn("$@\nWARNING: Possible missing or corrupt 'MANIFEST' file.\n" .
3397 "Nothing to enter for 'provides' field in META.yml\n");
3399 $node->{provides} = $pkgs if %$pkgs;
3402 if (exists $p->{no_index}) {
3403 $add_node->('no_index', $p->{no_index});
3406 $add_node->('generated_by', "Module::Build version $Module::Build::VERSION");
3408 $add_node->('meta-spec',
3410 url => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
3413 while (my($k, $v) = each %{$self->meta_add}) {
3414 $add_node->($k, $v);
3417 while (my($k, $v) = each %{$self->meta_merge}) {
3418 $self->_hash_merge($node, $k, $v);
3424 sub _read_manifest {
3425 my ($self, $file) = @_;
3426 return undef unless -e $file;
3428 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3429 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3430 return scalar ExtUtils::Manifest::maniread($file);
3433 sub find_dist_packages {
3436 # Only packages in .pm files are candidates for inclusion here.
3437 # Only include things in the MANIFEST, not things in developer's
3440 my $manifest = $self->_read_manifest('MANIFEST')
3441 or die "Can't find dist packages without a MANIFEST file - run 'manifest' action first";
3444 my %dist_files = map { $self->localize_file_path($_) => $_ }
3447 my @pm_files = grep {exists $dist_files{$_}} keys %{ $self->find_pm_files };
3449 # First, we enumerate all packages & versions,
3450 # seperating into primary & alternative candidates
3452 foreach my $file (@pm_files) {
3453 next if $dist_files{$file} =~ m{^t/}; # Skip things in t/
3455 my @path = split( /\//, $dist_files{$file} );
3456 (my $prime_package = join( '::', @path[1..$#path] )) =~ s/\.pm$//;
3458 my $pm_info = Module::Build::ModuleInfo->new_from_file( $file );
3460 foreach my $package ( $pm_info->packages_inside ) {
3461 next if $package eq 'main'; # main can appear numerous times, ignore
3462 next if grep /^_/, split( /::/, $package ); # private package, ignore
3464 my $version = $pm_info->version( $package );
3466 if ( $package eq $prime_package ) {
3467 if ( exists( $prime{$package} ) ) {
3468 # M::B::ModuleInfo will handle this conflict
3469 die "Unexpected conflict in '$package'; multiple versions found.\n";
3471 $prime{$package}{file} = $dist_files{$file};
3472 $prime{$package}{version} = $version if defined( $version );
3475 push( @{$alt{$package}}, {
3476 file => $dist_files{$file},
3477 version => $version,
3483 # Then we iterate over all the packages found above, identifying conflicts
3484 # and selecting the "best" candidate for recording the file & version
3486 foreach my $package ( keys( %alt ) ) {
3487 my $result = $self->_resolve_module_versions( $alt{$package} );
3489 if ( exists( $prime{$package} ) ) { # primary package selected
3491 if ( $result->{err} ) {
3492 # Use the selected primary package, but there are conflicting
3493 # errors amoung multiple alternative packages that need to be
3496 "Found conflicting versions for package '$package'\n" .
3497 " $prime{$package}{file} ($prime{$package}{version})\n" .
3501 } elsif ( defined( $result->{version} ) ) {
3502 # There is a primary package selected, and exactly one
3503 # alternative package
3505 if ( exists( $prime{$package}{version} ) &&
3506 defined( $prime{$package}{version} ) ) {
3507 # Unless the version of the primary package agrees with the
3508 # version of the alternative package, report a conflict
3509 if ( $self->compare_versions( $prime{$package}{version}, '!=',
3510 $result->{version} ) ) {
3512 "Found conflicting versions for package '$package'\n" .
3513 " $prime{$package}{file} ($prime{$package}{version})\n" .
3514 " $result->{file} ($result->{version})\n"
3519 # The prime package selected has no version so, we choose to
3520 # use any alternative package that does have a version
3521 $prime{$package}{file} = $result->{file};
3522 $prime{$package}{version} = $result->{version};
3526 # no alt package found with a version, but we have a prime
3527 # package so we use it whether it has a version or not
3530 } else { # No primary package was selected, use the best alternative
3532 if ( $result->{err} ) {
3534 "Found conflicting versions for package '$package'\n" .
3539 # Despite possible conflicting versions, we choose to record
3540 # something rather than nothing
3541 $prime{$package}{file} = $result->{file};
3542 $prime{$package}{version} = $result->{version}
3543 if defined( $result->{version} );
3547 # Stringify versions. Can't use exists() here because of bug in YAML::Node.
3548 for (grep defined $_->{version}, values %prime) {
3549 $_->{version} = '' . $_->{version};
3555 # seperate out some of the conflict resolution logic from
3556 # $self->find_dist_packages(), above, into a helper function.
3558 sub _resolve_module_versions {
3561 my $packages = shift;
3563 my( $file, $version );
3565 foreach my $p ( @$packages ) {
3566 if ( defined( $p->{version} ) ) {
3567 if ( defined( $version ) ) {
3568 if ( $self->compare_versions( $version, '!=', $p->{version} ) ) {
3569 $err .= " $p->{file} ($p->{version})\n";
3571 # same version declared multiple times, ignore
3575 $version = $p->{version};
3578 $file ||= $p->{file} if defined( $p->{file} );
3582 $err = " $file ($version)\n" . $err;
3587 version => $version,
3595 my ($self, $dir, $file) = @_;
3598 $self->log_info("Creating $file.tar.gz\n");
3600 if ($self->{args}{tar}) {
3601 my $tar_flags = $self->verbose ? 'cvf' : 'cf';
3602 $self->do_system($self->split_like_shell($self->{args}{tar}), $tar_flags, "$file.tar", $dir);
3603 $self->do_system($self->split_like_shell($self->{args}{gzip}), "$file.tar") if $self->{args}{gzip};
3605 require Archive::Tar;
3606 # Archive::Tar versions >= 1.09 use the following to enable a compatibility
3607 # hack so that the resulting archive is compatible with older clients.
3608 $Archive::Tar::DO_NOT_USE_PREFIX = 0;
3609 my $files = $self->rscan_dir($dir);
3610 Archive::Tar->create_archive("$file.tar.gz", 1, @$files);
3616 my( $type, $value ) = ( @_, '<empty>' );
3618 Carp::croak( 'Type argument missing' )
3619 unless defined( $type );
3621 my $map = $self->{properties}{install_path};
3622 return $map unless @_;
3624 # delete existing value if $value is literal undef()
3625 unless ( defined( $value ) ) {
3626 delete( $map->{$type} );
3630 # return existing value if no new $value is given
3631 if ( $value eq '<empty>' ) {
3632 return undef unless exists $map->{$type};
3633 return $map->{$type};
3636 # set value if $value is a valid relative path
3637 return $map->{$type} = $value;
3640 sub install_base_relpaths {
3641 # Usage: install_base_relpaths(), install_base_relpaths('lib'),
3642 # or install_base_relpaths('lib' => $value);
3644 my $map = $self->{properties}{install_base_relpaths};
3645 return $map unless @_;
3646 return $self->_relpaths($map, @_);
3650 # Translated from ExtUtils::MM_Any::init_INSTALL_from_PREFIX
3651 sub prefix_relative {
3652 my ($self, $type) = @_;
3653 my $installdirs = $self->installdirs;
3655 my $relpath = $self->install_sets($installdirs)->{$type};
3657 return $self->_prefixify($relpath,
3658 $self->original_prefix($installdirs),
3665 my( $map, $type, $value ) = ( @_, '<empty>' );
3667 Carp::croak( 'Type argument missing' )
3668 unless defined( $type );
3672 # delete existing value if $value is literal undef()
3673 unless ( defined( $value ) ) {
3674 delete( $map->{$type} );
3678 # return existing value if no new $value is given
3679 elsif ( $value eq '<empty>' ) {
3680 return undef unless exists $map->{$type};
3681 @value = @{ $map->{$type} };
3684 # set value if $value is a valid relative path
3686 Carp::croak( "Value must be a relative path" )
3687 if File::Spec::Unix->file_name_is_absolute($value);
3689 @value = split( /\//, $value );
3690 $map->{$type} = \@value;
3693 return File::Spec->catdir( @value );
3696 # Defaults to use in case the config install paths cannot be prefixified.
3697 sub prefix_relpaths {
3698 # Usage: prefix_relpaths('site'), prefix_relpaths('site', 'lib'),
3699 # or prefix_relpaths('site', 'lib' => $value);
3701 my $installdirs = shift || $self->installdirs;
3702 my $map = $self->{properties}{prefix_relpaths}{$installdirs};
3703 return $map unless @_;
3704 return $self->_relpaths($map, @_);
3708 # Translated from ExtUtils::MM_Unix::prefixify()
3710 my($self, $path, $sprefix, $type) = @_;
3712 my $rprefix = $self->prefix;
3713 $rprefix .= '/' if $sprefix =~ m|/$|;
3715 $self->log_verbose(" prefixify $path from $sprefix to $rprefix\n")
3716 if defined( $path ) && length( $path );
3718 if( !defined( $path ) || ( length( $path ) == 0 ) ) {
3719 $self->log_verbose(" no path to prefixify, falling back to default.\n");
3720 return $self->_prefixify_default( $type, $rprefix );
3721 } elsif( !File::Spec->file_name_is_absolute($path) ) {
3722 $self->log_verbose(" path is relative, not prefixifying.\n");
3723 } elsif( $sprefix eq $rprefix ) {
3724 $self->log_verbose(" no new prefix.\n");
3725 } elsif( $path !~ s{^\Q$sprefix\E\b}{}s ) {
3726 $self->log_verbose(" cannot prefixify, falling back to default.\n");
3727 return $self->_prefixify_default( $type, $rprefix );
3730 $self->log_verbose(" now $path in $rprefix\n");
3735 sub _prefixify_default {
3738 my $rprefix = shift;
3740 my $default = $self->prefix_relpaths($self->installdirs, $type);
3742 $self->log_verbose(" no default install location for type '$type', using prefix '$rprefix'.\n");
3749 sub install_destination {
3750 my ($self, $type) = @_;
3752 return $self->install_path($type) if $self->install_path($type);
3754 if ( $self->install_base ) {
3755 my $relpath = $self->install_base_relpaths($type);
3756 return $relpath ? File::Spec->catdir($self->install_base, $relpath) : undef;
3759 if ( $self->prefix ) {
3760 my $relpath = $self->prefix_relative($type);
3761 return $relpath ? File::Spec->catdir($self->prefix, $relpath) : undef;
3764 return $self->install_sets($self->installdirs)->{$type};
3771 if ( $self->install_base ) {
3772 %types = %{$self->install_base_relpaths};
3773 } elsif ( $self->prefix ) {
3774 %types = %{$self->prefix_relpaths};
3776 %types = %{$self->install_sets($self->installdirs)};
3779 %types = (%types, %{$self->install_path});
3781 return sort keys %types;
3785 my ($self, $blib) = @_;
3786 $blib ||= $self->blib;
3788 my( %map, @skipping );
3789 foreach my $type ($self->install_types) {
3790 my $localdir = File::Spec->catdir( $blib, $type );
3791 next unless -e $localdir;
3793 if (my $dest = $self->install_destination($type)) {
3794 $map{$localdir} = $dest;
3796 push( @skipping, $type );
3801 "WARNING: Can't figure out install path for types: @skipping\n" .
3802 "Files will not be installed.\n"
3805 # Write the packlist into the same place as ExtUtils::MakeMaker.
3806 if ($self->create_packlist and my $module_name = $self->module_name) {
3807 my $archdir = $self->install_destination('arch');
3808 my @ext = split /::/, $module_name;
3809 $map{write} = File::Spec->catfile($archdir, 'auto', @ext, '.packlist');
3813 if (length(my $destdir = $self->destdir || '')) {
3814 foreach (keys %map) {
3815 # Need to remove volume from $map{$_} using splitpath, or else
3816 # we'll create something crazy like C:\Foo\Bar\E:\Baz\Quux
3817 # VMS will always have the file separate than the path.
3818 my ($volume, $path, $file) = File::Spec->splitpath( $map{$_}, 1 );
3820 # catdir needs a list of directories, or it will create something
3821 # crazy like volume:[Foo.Bar.volume.Baz.Quux]
3822 my @dirs = File::Spec->splitdir($path);
3824 # First merge the directories
3825 $path = File::Spec->catdir($destdir, @dirs);
3827 # Then put the file back on if there is one.
3829 $map{$_} = File::Spec->catfile($path, $file)
3836 $map{read} = ''; # To keep ExtUtils::Install quiet
3843 foreach my $action (@_) {
3844 $self->_call_action($action);
3849 my ($self, $dir, $pattern) = @_;
3851 local $_; # find() can overwrite $_, so protect ourselves
3852 my $subr = !$pattern ? sub {push @result, $File::Find::name} :
3853 !ref($pattern) || (ref $pattern eq 'Regexp') ? sub {push @result, $File::Find::name if /$pattern/} :
3854 ref($pattern) eq 'CODE' ? sub {push @result, $File::Find::name if $pattern->()} :
3855 die "Unknown pattern type";
3857 File::Find::find({wanted => $subr, no_chdir => 1}, $dir);
3861 sub delete_filetree {
3866 $self->log_info("Deleting $_\n");
3867 File::Path::rmtree($_, 0, 0);
3868 die "Couldn't remove '$_': $!\n" if -e $_;
3874 sub autosplit_file {
3875 my ($self, $file, $to) = @_;
3877 my $dir = File::Spec->catdir($to, 'lib', 'auto');
3878 AutoSplit::autosplit($file, $dir);
3882 # Returns a CBuilder object
3885 my $p = $self->{properties};
3886 return $p->{_cbuilder} if $p->{_cbuilder};
3887 return unless $self->_mb_feature('C_support');
3889 require ExtUtils::CBuilder;
3890 return $p->{_cbuilder} = ExtUtils::CBuilder->new(config => $self->config);
3893 sub have_c_compiler {
3896 my $p = $self->{properties};
3897 return $p->{have_compiler} if defined $p->{have_compiler};
3899 $self->log_verbose("Checking if compiler tools configured... ");
3900 my $b = $self->_cbuilder;
3901 my $have = $b && $b->have_compiler;
3902 $self->log_verbose($have ? "ok.\n" : "failed.\n");
3903 return $p->{have_compiler} = $have;
3907 my ($self, $file, %args) = @_;
3908 my $b = $self->_cbuilder
3909 or die "Module::Build is not configured with C_support";
3911 my $obj_file = $b->object_file($file);
3912 $self->add_to_cleanup($obj_file);
3913 return $obj_file if $self->up_to_date($file, $obj_file);
3915 $b->compile(source => $file,
3916 defines => $args{defines},
3917 object_file => $obj_file,
3918 include_dirs => $self->include_dirs,
3919 extra_compiler_flags => $self->extra_compiler_flags,
3926 my ($self, $to, $file_base) = @_;
3927 my $p = $self->{properties}; # For convenience
3929 my $spec = $self->_infer_xs_spec($file_base);
3931 $self->add_to_cleanup($spec->{lib_file});
3933 my $objects = $p->{objects} || [];
3935 return $spec->{lib_file}
3936 if $self->up_to_date([$spec->{obj_file}, @$objects],
3939 my $module_name = $self->module_name;
3940 $module_name ||= $spec->{module_name};
3942 my $b = $self->_cbuilder
3943 or die "Module::Build is not configured with C_support";
3945 module_name => $module_name,
3946 objects => [$spec->{obj_file}, @$objects],
3947 lib_file => $spec->{lib_file},
3948 extra_linker_flags => $p->{extra_linker_flags} );
3950 return $spec->{lib_file};
3954 my ($self, $file, %args) = @_;
3956 $self->log_info("$file -> $args{outfile}\n");
3958 if (eval {require ExtUtils::ParseXS; 1}) {
3960 ExtUtils::ParseXS::process_file(
3963 output => $args{outfile},
3966 # Ok, I give up. Just use backticks.
3968 my $xsubpp = Module::Build::ModuleInfo->find_module_by_name('ExtUtils::xsubpp')
3969 or die "Can't find ExtUtils::xsubpp in INC (@INC)";
3972 push @typemaps, Module::Build::ModuleInfo->find_module_by_name('ExtUtils::typemap', \@INC);
3973 my $lib_typemap = Module::Build::ModuleInfo->find_module_by_name('typemap', ['lib']);
3974 if (defined $lib_typemap and -e $lib_typemap) {
3975 push @typemaps, 'typemap';
3977 @typemaps = map {+'-typemap', $_} @typemaps;
3979 my $cf = $self->{config};
3980 my $perl = $self->{properties}{perl};
3982 my @command = ($perl, "-I".$cf->get('installarchlib'), "-I".$cf->get('installprivlib'), $xsubpp, '-noprototypes',
3985 $self->log_info("@command\n");
3986 my $fh = IO::File->new("> $args{outfile}") or die "Couldn't write $args{outfile}: $!";
3987 print {$fh} $self->_backticks(@command);
3992 sub split_like_shell {
3993 my ($self, $string) = @_;
3995 return () unless defined($string);
3996 return @$string if UNIVERSAL::isa($string, 'ARRAY');
3997 $string =~ s/^\s+|\s+$//g;
3998 return () unless length($string);
4000 return Text::ParseWords::shellwords($string);
4003 sub run_perl_script {
4004 my ($self, $script, $preargs, $postargs) = @_;
4005 foreach ($preargs, $postargs) {
4006 $_ = [ $self->split_like_shell($_) ] unless ref();
4008 return $self->run_perl_command([@$preargs, $script, @$postargs]);
4011 sub run_perl_command {
4012 # XXX Maybe we should accept @args instead of $args? Must resolve
4013 # this before documenting.
4014 my ($self, $args) = @_;
4015 $args = [ $self->split_like_shell($args) ] unless ref($args);
4016 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
4018 # Make sure our local additions to @INC are propagated to the subprocess
4019 local $ENV{PERL5LIB} = join $self->config('path_sep'), $self->_added_to_INC;
4021 return $self->do_system($perl, @$args);
4024 # Infer various data from the path of the input filename
4025 # that is needed to create output files.
4026 # The input filename is expected to be of the form:
4027 # lib/Module/Name.ext or Module/Name.ext
4028 sub _infer_xs_spec {
4032 my $cf = $self->{config};
4036 my( $v, $d, $f ) = File::Spec->splitpath( $file );
4037 my @d = File::Spec->splitdir( $d );
4038 (my $file_base = $f) =~ s/\.[^.]+$//i;
4040 $spec{base_name} = $file_base;
4042 $spec{src_dir} = File::Spec->catpath( $v, $d, '' );
4045 shift( @d ) while @d && ($d[0] eq 'lib' || $d[0] eq '');
4046 pop( @d ) while @d && $d[-1] eq '';
4047 $spec{module_name} = join( '::', (@d, $file_base) );
4049 $spec{archdir} = File::Spec->catdir($self->blib, 'arch', 'auto',
4052 $spec{bs_file} = File::Spec->catfile($spec{archdir}, "${file_base}.bs");
4054 $spec{lib_file} = File::Spec->catfile($spec{archdir},
4055 "${file_base}.".$cf->get('dlext'));
4057 $spec{c_file} = File::Spec->catfile( $spec{src_dir},
4060 $spec{obj_file} = File::Spec->catfile( $spec{src_dir},
4061 "${file_base}".$cf->get('obj_ext') );
4067 my ($self, $file) = @_;
4069 my $spec = $self->_infer_xs_spec($file);
4071 # File name, minus the suffix
4072 (my $file_base = $file) =~ s/\.[^.]+$//;
4075 $self->add_to_cleanup($spec->{c_file});
4077 unless ($self->up_to_date($file, $spec->{c_file})) {
4078 $self->compile_xs($file, outfile => $spec->{c_file});
4082 my $v = $self->dist_version;
4083 $self->compile_c($spec->{c_file},
4084 defines => {VERSION => qq{"$v"}, XS_VERSION => qq{"$v"}});
4087 File::Path::mkpath($spec->{archdir}, 0, oct(777)) unless -d $spec->{archdir};
4090 $self->add_to_cleanup($spec->{bs_file});
4091 unless ($self->up_to_date($file, $spec->{bs_file})) {
4092 require ExtUtils::Mkbootstrap;
4093 $self->log_info("ExtUtils::Mkbootstrap::Mkbootstrap('$spec->{bs_file}')\n");
4094 ExtUtils::Mkbootstrap::Mkbootstrap($spec->{bs_file}); # Original had $BSLOADLIBS - what's that?
4095 {my $fh = IO::File->new(">> $spec->{bs_file}")} # create
4096 utime((time)x2, $spec->{bs_file}); # touch
4100 $self->link_c($spec->{archdir}, $file_base);
4104 my ($self, @cmd) = @_;
4105 $self->log_info("@cmd\n");
4107 # Some systems proliferate huge PERL5LIBs, try to ameliorate:
4109 my $sep = $self->config('path_sep');
4110 local $ENV{PERL5LIB} =
4111 ( !exists($ENV{PERL5LIB}) ? '' :
4112 length($ENV{PERL5LIB}) < 500
4114 : join $sep, grep { ! $seen{$_}++ and -d $_ } split($sep, $ENV{PERL5LIB})
4117 my $status = system(@cmd);
4118 if ($status and $! =~ /Argument list too long/i) {
4119 my $env_entries = '';
4120 foreach (sort keys %ENV) { $env_entries .= "$_=>".length($ENV{$_})."; " }
4121 warn "'Argument list' was 'too long', env lengths are $env_entries";
4126 sub copy_if_modified {
4130 : ( from => shift, to_dir => shift, flatten => shift )
4132 $args{verbose} = !$self->quiet
4133 unless exists $args{verbose};
4135 my $file = $args{from};
4136 unless (defined $file and length $file) {
4137 die "No 'from' parameter given to copy_if_modified";
4141 if (defined $args{to} and length $args{to}) {
4142 $to_path = $args{to};
4143 } elsif (defined $args{to_dir} and length $args{to_dir}) {
4144 $to_path = File::Spec->catfile( $args{to_dir}, $args{flatten}
4145 ? File::Basename::basename($file)
4148 die "No 'to' or 'to_dir' parameter given to copy_if_modified";
4151 return if $self->up_to_date($file, $to_path); # Already fresh
4154 local $self->{properties}{quiet} = 1;
4155 $self->delete_filetree($to_path); # delete destination if exists
4158 # Create parent directories
4159 File::Path::mkpath(File::Basename::dirname($to_path), 0, oct(777));
4161 $self->log_info("Copying $file -> $to_path\n") if $args{verbose};
4163 if ($^O eq 'os2') {# copy will not overwrite; 0x1 = overwrite
4164 chmod 0666, $to_path;
4165 File::Copy::syscopy($file, $to_path, 0x1) or die "Can't copy('$file', '$to_path'): $!";
4167 File::Copy::copy($file, $to_path) or die "Can't copy('$file', '$to_path'): $!";
4170 # mode is read-only + (executable if source is executable)
4171 my $mode = oct(444) | ( $self->is_executable($file) ? oct(111) : 0 );
4172 chmod( $mode, $to_path );
4178 my ($self, $source, $derived) = @_;
4179 $source = [$source] unless ref $source;
4180 $derived = [$derived] unless ref $derived;
4182 return 0 if grep {not -e} @$derived;
4184 my $most_recent_source = time / (24*60*60);
4185 foreach my $file (@$source) {
4187 $self->log_warn("Can't find source file $file for up-to-date check");
4190 $most_recent_source = -M _ if -M _ < $most_recent_source;
4193 foreach my $derived (@$derived) {
4194 return 0 if -M $derived > $most_recent_source;
4200 my ($self, $first, $second) = @_;
4201 # File::Spec doesn't have an easy way to check whether one directory
4202 # is inside another, unfortunately.
4204 ($first, $second) = map File::Spec->canonpath($_), ($first, $second);
4205 my @first_dirs = File::Spec->splitdir($first);
4206 my @second_dirs = File::Spec->splitdir($second);
4208 return 0 if @second_dirs < @first_dirs;
4210 my $is_same = ( File::Spec->case_tolerant
4211 ? sub {lc(shift()) eq lc(shift())}
4212 : sub {shift() eq shift()} );
4214 while (@first_dirs) {
4215 return 0 unless $is_same->(shift @first_dirs, shift @second_dirs);
4227 Module::Build::Base - Default methods for Module::Build
4231 Please see the Module::Build documentation.
4235 The C<Module::Build::Base> module defines the core functionality of
4236 C<Module::Build>. Its methods may be overridden by any of the
4237 platform-dependent modules in the C<Module::Build::Platform::>
4238 namespace, but the intention here is to make this base module as
4239 platform-neutral as possible. Nicely enough, Perl has several core
4240 tools available in the C<File::> namespace for doing this, so the task
4241 isn't very difficult.
4243 Please see the C<Module::Build> documentation for more details.
4247 Ken Williams <kwilliams@cpan.org>
4251 Copyright (c) 2001-2006 Ken Williams. All rights reserved.
4253 This library is free software; you can redistribute it and/or
4254 modify it under the same terms as Perl itself.
4258 perl(1), Module::Build(3)
4262 # vim:ts=8:sw=2:et:sta:sts=2