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 if $mb_version ne $self->{properties}{mb_version};
81 $self->{invoked_action} = $self->{action} ||= 'build';
86 sub new_from_context {
87 my ($package, %args) = @_;
89 # XXX Read the META.yml and see whether we need to run the Build.PL?
91 # Run the Build.PL. We use do() rather than run_perl_script() so
92 # that it runs in this process rather than a subprocess, because we
93 # need to make sure that the environment is the same during Build.PL
94 # as it is during resume() (and thereafter).
96 local @ARGV = $package->unparse_args(\%args);
100 return $package->resume;
104 # hmm, wonder what the right thing to do here is
106 return shift()->resume;
110 my ($package, %input) = @_;
112 my $args = delete $input{args} || {};
113 my $config = delete $input{config} || {};
117 config => Module::Build::Config->new(values => $config),
119 base_dir => $package->cwd,
120 mb_version => $Module::Build::VERSION,
126 $self->_set_defaults;
127 my ($p, $ph) = ($self->{properties}, $self->{phash});
129 foreach (qw(notes config_data features runtime_params cleanup auto_features)) {
130 my $file = File::Spec->catfile($self->config_dir, $_);
131 $ph->{$_} = Module::Build::Notes->new(file => $file);
132 $ph->{$_}->restore if -e $file;
133 if (exists $p->{$_}) {
134 my $vals = delete $p->{$_};
135 while (my ($k, $v) = each %$vals) {
141 # The following warning could be unnecessary if the user is running
142 # an embedded perl, but there aren't too many of those around, and
143 # embedded perls aren't usually used to install modules, and the
144 # installation process sometimes needs to run external scripts
145 # (e.g. to run tests).
146 $p->{perl} = $self->find_perl_interpreter
147 or $self->log_warn("Warning: Can't locate your perl binary");
149 my $blibdir = sub { File::Spec->catdir($p->{blib}, @_) };
150 $p->{bindoc_dirs} ||= [ $blibdir->("script") ];
151 $p->{libdoc_dirs} ||= [ $blibdir->("lib"), $blibdir->("arch") ];
153 $p->{dist_author} = [ $p->{dist_author} ] if defined $p->{dist_author} and not ref $p->{dist_author};
156 $p->{requires} = delete $p->{prereq} if defined $p->{prereq};
157 $p->{script_files} = delete $p->{scripts} if defined $p->{scripts};
160 for ('extra_compiler_flags', 'extra_linker_flags') {
161 $p->{$_} = [ $self->split_like_shell($p->{$_}) ] if exists $p->{$_};
164 $self->add_to_cleanup( @{delete $p->{add_to_cleanup}} )
165 if $p->{add_to_cleanup};
170 ################## End constructors #########################
172 sub log_info { print @_ unless shift()->quiet }
173 sub log_verbose { shift()->log_info(@_) if $_[0]->verbose }
175 # Try to make our call stack invisible
177 if (@_ and $_[-1] !~ /\n$/) {
178 my (undef, $file, $line) = caller();
179 warn @_, " at $file line $line.\n";
186 sub _set_install_paths {
188 my $c = $self->{config};
189 my $p = $self->{properties};
191 my @libstyle = $c->get('installstyle') ?
192 File::Spec->splitdir($c->get('installstyle')) : qw(lib perl5);
193 my $arch = $c->get('archname');
194 my $version = $c->get('version');
196 my $bindoc = $c->get('installman1dir') || undef;
197 my $libdoc = $c->get('installman3dir') || undef;
199 my $binhtml = $c->get('installhtml1dir') || $c->get('installhtmldir') || undef;
200 my $libhtml = $c->get('installhtml3dir') || $c->get('installhtmldir') || undef;
205 lib => $c->get('installprivlib'),
206 arch => $c->get('installarchlib'),
207 bin => $c->get('installbin'),
208 script => $c->get('installscript'),
215 lib => $c->get('installsitelib'),
216 arch => $c->get('installsitearch'),
217 bin => $c->get('installsitebin') || $c->get('installbin'),
218 script => $c->get('installsitescript') ||
219 $c->get('installsitebin') || $c->get('installscript'),
220 bindoc => $c->get('installsiteman1dir') || $bindoc,
221 libdoc => $c->get('installsiteman3dir') || $libdoc,
222 binhtml => $c->get('installsitehtml1dir') || $binhtml,
223 libhtml => $c->get('installsitehtml3dir') || $libhtml,
226 lib => $c->get('installvendorlib'),
227 arch => $c->get('installvendorarch'),
228 bin => $c->get('installvendorbin') || $c->get('installbin'),
229 script => $c->get('installvendorscript') ||
230 $c->get('installvendorbin') || $c->get('installscript'),
231 bindoc => $c->get('installvendorman1dir') || $bindoc,
232 libdoc => $c->get('installvendorman3dir') || $libdoc,
233 binhtml => $c->get('installvendorhtml1dir') || $binhtml,
234 libhtml => $c->get('installvendorhtml3dir') || $libhtml,
238 $p->{original_prefix} =
240 core => $c->get('installprefixexp') || $c->get('installprefix') ||
241 $c->get('prefixexp') || $c->get('prefix') || '',
242 site => $c->get('siteprefixexp'),
243 vendor => $c->get('usevendorprefix') ? $c->get('vendorprefixexp') : '',
245 $p->{original_prefix}{site} ||= $p->{original_prefix}{core};
247 # Note: you might be tempted to use $Config{installstyle} here
248 # instead of hard-coding lib/perl5, but that's been considered and
249 # (at least for now) rejected. `perldoc Config` has some wisdom
251 $p->{install_base_relpaths} =
253 lib => ['lib', 'perl5'],
254 arch => ['lib', 'perl5', $arch],
257 bindoc => ['man', 'man1'],
258 libdoc => ['man', 'man3'],
263 $p->{prefix_relpaths} =
267 arch => [@libstyle, $version, $arch],
270 bindoc => ['man', 'man1'],
271 libdoc => ['man', 'man3'],
277 arch => [@libstyle, $version, $arch],
280 bindoc => ['man', 'man1'],
281 libdoc => ['man', 'man3'],
286 lib => [@libstyle, 'site_perl'],
287 arch => [@libstyle, 'site_perl', $version, $arch],
290 bindoc => ['man', 'man1'],
291 libdoc => ['man', 'man3'],
299 sub _find_nested_builds {
301 my $r = $self->recurse_into or return;
304 if (!ref($r) && $r eq 'auto') {
306 opendir DH, $self->base_dir
307 or die "Can't scan directory " . $self->base_dir . " for nested builds: $!";
308 while (defined($file = readdir DH)) {
309 my $subdir = File::Spec->catdir( $self->base_dir, $file );
310 next unless -d $subdir;
311 push @r, $subdir if -e File::Spec->catfile( $subdir, 'Build.PL' );
315 $self->recurse_into(\@r);
324 # Returns a string that can become [part of] a command line with
325 # proper quoting so that the subprocess sees this same list of args.
326 my ($self, @args) = @_;
328 my $return_args = '';
332 if ( /^[^\s*?!$<>;\\|'"\[\]\{\}]+$/ ) {
336 # XXX this will obviously have to improve - is there already a
337 # core module lying around that does proper quoting?
339 push @quoted, qq("$_");
343 return join " ", @quoted;
347 my ($self, @cmd) = @_;
348 if ($self->have_forkpipe) {
350 my $pid = open *FH, "-|";
352 return wantarray ? <FH> : join '', <FH>;
354 die "Can't execute @cmd: $!\n" unless defined $pid;
355 exec { $cmd[0] } @cmd;
358 my $cmd = $self->_quote_args(@cmd);
363 sub have_forkpipe { 1 }
365 # Determine whether a given binary is the same as the perl
366 # (configuration) that started this process.
368 my ($self, $perl) = @_;
372 # When run from the perl core, @INC will include the directories
373 # where perl is yet to be installed. We need to reference the
374 # absolute path within the source distribution where it can find
375 # it's Config.pm This also prevents us from picking up a Config.pm
376 # from a different configuration that happens to be already
378 if ($ENV{PERL_CORE}) {
379 push @cmd, '-I' . File::Spec->catdir(File::Basename::dirname($perl), 'lib');
382 push @cmd, qw(-MConfig=myconfig -e print -e myconfig);
383 return $self->_backticks(@cmd) eq Config->myconfig;
386 # Returns the absolute path of the perl interperter used to invoke
387 # this process. The path is derived from $^X or $Config{perlpath}. On
388 # some platforms $^X contains the complete absolute path of the
389 # interpreter, on other it may contain a relative path, or simply
390 # 'perl'. This can also vary depending on whether a path was supplied
391 # when perl was invoked. Additionally, the value in $^X may omit the
392 # executable extension on platforms that use one. It's a fatal error
393 # if the interpreter can't be found because it can result in undefined
394 # behavior by routines that depend on it (generating errors or
395 # invoking the wrong perl.
396 sub find_perl_interpreter {
398 my $c = ref($proto) ? $proto->{config} : 'Module::Build::Config';
401 my $perl_basename = File::Basename::basename($perl);
405 # Try 1, Check $^X for absolute path
406 push( @potential_perls, $perl )
407 if File::Spec->file_name_is_absolute($perl);
409 # Try 2, Check $^X for a valid relative path
410 my $abs_perl = File::Spec->rel2abs($perl);
411 push( @potential_perls, $abs_perl );
413 # Try 3, Last ditch effort: These two option use hackery to try to locate
414 # a suitable perl. The hack varies depending on whether we are running
415 # from an installed perl or an uninstalled perl in the perl source dist.
416 if ($ENV{PERL_CORE}) {
418 # Try 3.A, If we are in a perl source tree, running an uninstalled
419 # perl, we can keep moving up the directory tree until we find our
420 # binary. We wouldn't do this under any other circumstances.
422 # CBuilder is also in the core, so it should be available here
423 require ExtUtils::CBuilder;
424 my $perl_src = ExtUtils::CBuilder->perl_src;
425 if ( defined($perl_src) && length($perl_src) ) {
427 File::Spec->rel2abs(File::Spec->catfile( $perl_src, $perl_basename ));
428 push( @potential_perls, $uninstperl );
433 # Try 3.B, First look in $Config{perlpath}, then search the users
434 # PATH. We do not want to do either if we are running from an
435 # uninstalled perl in a perl source tree.
437 push( @potential_perls, $c->get('perlpath') );
439 push( @potential_perls,
440 map File::Spec->catfile($_, $perl_basename), File::Spec->path() );
443 # Now that we've enumerated the potential perls, it's time to test
444 # them to see if any of them match our configuration, returning the
445 # absolute path of the first successful match.
446 my $exe = $c->get('exe_ext');
447 foreach my $thisperl ( @potential_perls ) {
449 if ($proto->os_type eq 'VMS') {
450 # VMS might have a file version at the end
451 $thisperl .= $exe unless $thisperl =~ m/$exe(;\d+)?$/i;
452 } elsif (defined $exe) {
453 $thisperl .= $exe unless $thisperl =~ m/$exe$/i;
456 if ( -f $thisperl && $proto->_perl_is_same($thisperl) ) {
461 # We've tried all alternatives, and didn't find a perl that matches
462 # our configuration. Throw an exception, and list alternatives we tried.
463 my @paths = map File::Basename::dirname($_), @potential_perls;
464 die "Can't locate the perl binary used to run this script " .
468 sub _is_interactive {
469 return -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ; # Pipe?
474 return $ENV{PERL_MM_USE_DEFAULT} || ( !$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";
492 if ( $self->_is_unattended && !@_ ) {
494 ERROR: This build seems to be unattended, but there is no default value
495 for this question. Aborting.
499 ($def, my $dispdef) = defined $def ? ($def, "[$def] ") : ('', ' ');
502 print "$mess $dispdef";
504 my $ans = $self->_readline();
506 if ( !defined($ans) # Ctrl-D or unattended
507 or !length($ans) ) { # User hit return
517 my ($mess, $def) = @_;
519 die "y_n() called without a prompt message" unless $mess;
520 die "Invalid default value: y_n() default must be 'y' or 'n'"
521 if $def && $def !~ /^[yn]/i;
523 if ( $self->_is_unattended && !$def ) {
525 ERROR: This build seems to be unattended, but there is no default value
526 for this question. Aborting.
531 while (1) { # XXX Infinite or a large number followed by an exception ?
532 $answer = $self->prompt(@_);
533 return 1 if $answer =~ /^y/i;
534 return 0 if $answer =~ /^n/i;
536 print "Please answer 'y' or 'n'.\n";
540 sub current_action { shift->{action} }
541 sub invoked_action { shift->{invoked_action} }
543 sub notes { shift()->{phash}{notes}->access(@_) }
544 sub config_data { shift()->{phash}{config_data}->access(@_) }
545 sub runtime_params { shift->{phash}{runtime_params}->read( @_ ? shift : () ) } # Read-only
546 sub auto_features { shift()->{phash}{auto_features}->access(@_) }
550 my $ph = $self->{phash};
554 if ($ph->{features}->exists($key)) {
555 return $ph->{features}->access($key, @_);
558 if (my $info = $ph->{auto_features}->access($key)) {
559 my $failures = $self->prereq_failures($info);
560 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
561 keys %$failures ) ? 1 : 0;
565 return $ph->{features}->access($key, @_);
568 # No args - get the auto_features & overlay the regular features
570 my %auto_features = $ph->{auto_features}->access();
571 while (my ($name, $info) = each %auto_features) {
572 my $failures = $self->prereq_failures($info);
573 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
574 keys %$failures ) ? 1 : 0;
575 $features{$name} = $disabled ? 0 : 1;
577 %features = (%features, $ph->{features}->access());
579 return wantarray ? %features : \%features;
581 BEGIN { *feature = \&features }
586 if (($self->module_name || '') eq 'Module::Build') {
587 # We're building Module::Build itself, so ...::ConfigData isn't
588 # valid, but $self->features() should be.
589 return $self->feature(@_);
591 require Module::Build::ConfigData;
592 return Module::Build::ConfigData->feature(@_);
597 sub add_build_element {
598 my ($self, $elem) = @_;
599 my $elems = $self->build_elements;
600 push @$elems, $elem unless grep { $_ eq $elem } @$elems;
603 sub ACTION_config_data {
605 return unless $self->has_config_data;
607 my $module_name = $self->module_name
608 or die "The config_data feature requires that 'module_name' be set";
609 my $notes_name = $module_name . '::ConfigData'; # TODO: Customize name ???
610 my $notes_pm = File::Spec->catfile($self->blib, 'lib', split /::/, "$notes_name.pm");
612 return if $self->up_to_date(['Build.PL',
613 $self->config_file('config_data'),
614 $self->config_file('features')
617 $self->log_info("Writing config notes to $notes_pm\n");
618 File::Path::mkpath(File::Basename::dirname($notes_pm));
620 Module::Build::Notes->write_config_data
623 module => $module_name,
624 config_module => $notes_name,
625 config_data => scalar $self->config_data,
626 feature => scalar $self->{phash}{features}->access(),
627 auto_features => scalar $self->auto_features,
632 my %valid_properties = ( __PACKAGE__, {} );
633 my %additive_properties;
636 my $class = ref($_[0]) || $_[0];
637 return ($class, $class->mb_parents);
641 my ($class, $prop) = @_;
642 return grep exists( $valid_properties{$_}{$prop} ), $class->_mb_classes;
645 sub valid_properties {
646 return keys %{ shift->valid_properties_defaults() };
649 sub valid_properties_defaults {
651 for (reverse shift->_mb_classes) {
652 @out{ keys %{ $valid_properties{$_} } } = values %{ $valid_properties{$_} };
657 sub array_properties {
658 for (shift->_mb_classes) {
659 return @{$additive_properties{$_}->{ARRAY}}
660 if exists $additive_properties{$_}->{ARRAY};
664 sub hash_properties {
665 for (shift->_mb_classes) {
666 return @{$additive_properties{$_}->{'HASH'}}
667 if exists $additive_properties{$_}->{'HASH'};
672 my ($class, $property, $default) = @_;
673 die "Property '$property' already exists" if $class->valid_property($property);
675 $valid_properties{$class}{$property} = $default;
677 my $type = ref $default;
679 push @{$additive_properties{$class}->{$type}}, $property;
682 unless ($class->can($property)) {
684 if ( $type eq 'HASH' ) {
685 *{"$class\::$property"} = sub {
687 my $x = $self->{properties};
688 return $x->{$property} unless @_;
690 if ( defined($_[0]) && !ref($_[0]) ) {
692 return exists( $x->{$property}{$_[0]} ) ?
693 $x->{$property}{$_[0]} : undef;
694 } elsif ( @_ % 2 == 0 ) {
696 while ( my($k, $v) = each %args ) {
697 $x->{$property}{$k} = $v;
700 die "Unexpected arguments for property '$property'\n";
703 $x->{$property} = $_[0];
708 *{"$class\::$property"} = sub {
710 $self->{properties}{$property} = shift if @_;
711 return $self->{properties}{$property};
722 # Set the build class.
723 $self->{properties}{build_class} ||= ref $self;
725 # If there was no orig_dir, set to the same as base_dir
726 $self->{properties}{orig_dir} ||= $self->{properties}{base_dir};
728 my $defaults = $self->valid_properties_defaults;
730 foreach my $prop (keys %$defaults) {
731 $self->{properties}{$prop} = $defaults->{$prop}
732 unless exists $self->{properties}{$prop};
735 # Copy defaults for arrays any arrays.
736 for my $prop ($self->array_properties) {
737 $self->{properties}{$prop} = [@{$defaults->{$prop}}]
738 unless exists $self->{properties}{$prop};
740 # Copy defaults for arrays any hashes.
741 for my $prop ($self->hash_properties) {
742 $self->{properties}{$prop} = {%{$defaults->{$prop}}}
743 unless exists $self->{properties}{$prop};
749 # Add the default properties.
750 __PACKAGE__->add_property(blib => 'blib');
751 __PACKAGE__->add_property(build_class => 'Module::Build');
752 __PACKAGE__->add_property(build_elements => [qw(PL support pm xs pod script)]);
753 __PACKAGE__->add_property(build_script => 'Build');
754 __PACKAGE__->add_property(build_bat => 0);
755 __PACKAGE__->add_property(config_dir => '_build');
756 __PACKAGE__->add_property(include_dirs => []);
757 __PACKAGE__->add_property(installdirs => 'site');
758 __PACKAGE__->add_property(metafile => 'META.yml');
759 __PACKAGE__->add_property(recurse_into => []);
760 __PACKAGE__->add_property(use_rcfile => 1);
761 __PACKAGE__->add_property(create_packlist => 1);
762 __PACKAGE__->add_property(allow_mb_mismatch => 0);
763 __PACKAGE__->add_property(config => undef);
766 my $Is_ActivePerl = eval {require ActivePerl::DocTools};
767 __PACKAGE__->add_property(html_css => $Is_ActivePerl ? 'Active.css' : '');
771 my @prereq_action_types = qw(requires build_requires conflicts recommends);
772 foreach my $type (@prereq_action_types) {
773 __PACKAGE__->add_property($type => {});
775 __PACKAGE__->add_property(prereq_action_types => \@prereq_action_types);
778 __PACKAGE__->add_property($_ => {}) for qw(
780 install_base_relpaths
789 __PACKAGE__->add_property($_) for qw(
830 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
831 return $c->all_config unless @_;
834 return $c->get($key) unless @_;
837 return $c->set($key => $val);
841 # Code borrowed from Class::ISA.
842 my @in_stack = (shift);
843 my %seen = ($in_stack[0] => 1);
847 next unless defined($current = shift @in_stack)
848 && $current->isa('Module::Build::Base');
850 next if $current eq 'Module::Build::Base';
854 my $c = $_; # copy, to avoid being destructive
855 substr($c,0,2) = "main::" if substr($c,0,2) eq '::';
856 # Canonize the :: -> main::, ::foo -> main::foo thing.
857 # Should I ever canonize the Foo'Bar = Foo::Bar thing?
858 $seen{$c}++ ? () : $c;
859 } @{"$current\::ISA"};
861 # I.e., if this class has any parents (at least, ones I've never seen
862 # before), push them, in order, onto the stack of classes I need to
869 sub extra_linker_flags { shift->_list_accessor('extra_linker_flags', @_) }
870 sub extra_compiler_flags { shift->_list_accessor('extra_compiler_flags', @_) }
873 (my $self, local $_) = (shift, shift);
874 my $p = $self->{properties};
875 $p->{$_} = [@_] if @_;
876 $p->{$_} = [] unless exists $p->{$_};
877 return ref($p->{$_}) ? $p->{$_} : [$p->{$_}];
880 # XXX Problem - if Module::Build is loaded from a different directory,
881 # it'll look for (and perhaps destroy/create) a _build directory.
883 my ($pack, %opts) = @_;
885 my $build_dir = '_build'; # XXX The _build directory is ostensibly settable by the user. Shouldn't hard-code here.
886 $pack->delete_filetree($build_dir) if -e $build_dir;
888 die "Must provide 'code' or 'class' option to subclass()\n"
889 unless $opts{code} or $opts{class};
892 $opts{class} ||= 'MyModuleBuilder';
894 my $filename = File::Spec->catfile($build_dir, 'lib', split '::', $opts{class}) . '.pm';
895 my $filedir = File::Basename::dirname($filename);
896 $pack->log_info("Creating custom builder $filename in $filedir\n");
898 File::Path::mkpath($filedir);
899 die "Can't create directory $filedir: $!" unless -d $filedir;
901 my $fh = IO::File->new("> $filename") or die "Can't create $filename: $!";
903 package $opts{class};
911 unshift @INC, File::Spec->catdir(File::Spec->rel2abs($build_dir), 'lib');
912 eval "use $opts{class}";
920 my $p = $self->{properties};
921 return $p->{dist_name} if defined $p->{dist_name};
923 die "Can't determine distribution name, must supply either 'dist_name' or 'module_name' parameter"
924 unless $self->module_name;
926 ($p->{dist_name} = $self->module_name) =~ s/::/-/g;
928 return $p->{dist_name};
931 sub dist_version_from {
933 my $p = $self->{properties};
934 if ($self->module_name) {
935 $p->{dist_version_from} ||=
936 join( '/', 'lib', split(/::/, $self->module_name) ) . '.pm';
938 return $p->{dist_version_from} || undef;
943 my $p = $self->{properties};
945 return $p->{dist_version} if defined $p->{dist_version};
947 if ( my $dist_version_from = $self->dist_version_from ) {
948 my $version_from = File::Spec->catfile( split( qr{/}, $dist_version_from ) );
949 my $pm_info = Module::Build::ModuleInfo->new_from_file( $version_from )
950 or die "Can't find file $version_from to determine version";
951 $p->{dist_version} = $pm_info->version();
954 die ("Can't determine distribution version, must supply either 'dist_version',\n".
955 "'dist_version_from', or 'module_name' parameter")
956 unless $p->{dist_version};
958 return $p->{dist_version};
961 sub dist_author { shift->_pod_parse('author') }
962 sub dist_abstract { shift->_pod_parse('abstract') }
965 my ($self, $part) = @_;
966 my $p = $self->{properties};
967 my $member = "dist_$part";
968 return $p->{$member} if defined $p->{$member};
970 my $docfile = $self->_main_docfile
972 my $fh = IO::File->new($docfile)
975 require Module::Build::PodParser;
976 my $parser = Module::Build::PodParser->new(fh => $fh);
977 my $method = "get_$part";
978 return $p->{$member} = $parser->$method();
981 sub version_from_file { # Method provided for backwards compatability
982 return Module::Build::ModuleInfo->new_from_file($_[1])->version();
985 sub find_module_by_name { # Method provided for backwards compatability
986 return Module::Build::ModuleInfo->find_module_by_name(@_[1,2]);
991 my %files = map {$self->localize_file_path($_), 1} @_;
992 $self->{phash}{cleanup}->write(\%files);
997 my $all = $self->{phash}{cleanup}->read;
1003 return unless -d $self->config_dir;
1004 return File::Spec->catfile($self->config_dir, @_);
1010 my $file = $self->config_file('build_params')
1011 or die "No build_params?";
1012 my $fh = IO::File->new($file) or die "Can't read '$file': $!";
1013 my $ref = eval do {local $/; <$fh>};
1016 ($self->{args}, $c, $self->{properties}) = @$ref;
1017 $self->{config} = Module::Build::Config->new(values => $c);
1021 sub has_config_data {
1023 return scalar grep $self->{phash}{$_}->has_data(), qw(config_data features auto_features);
1027 my ($self, $filename, $data) = @_;
1029 my $file = $self->config_file($filename);
1030 my $fh = IO::File->new("> $file") or die "Can't create '$file': $!";
1031 local $Data::Dumper::Terse = 1;
1032 print $fh ref($data) ? Data::Dumper::Dumper($data) : $data;
1038 File::Path::mkpath($self->{properties}{config_dir});
1039 -d $self->{properties}{config_dir} or die "Can't mkdir $self->{properties}{config_dir}: $!";
1041 my @items = @{ $self->prereq_action_types };
1042 $self->_write_data('prereqs', { map { $_, $self->$_() } @items });
1043 $self->_write_data('build_params', [$self->{args}, $self->{config}->values_set, $self->{properties}]);
1045 # Set a new magic number and write it to a file
1046 $self->_write_data('magicnum', $self->magic_number(int rand 1_000_000));
1048 $self->{phash}{$_}->write() foreach qw(notes cleanup features auto_features config_data runtime_params);
1051 sub check_autofeatures {
1053 my $features = $self->auto_features;
1055 return unless %$features;
1057 $self->log_info("Checking features:\n");
1060 $max_name_len = ( length($_) > $max_name_len ) ?
1061 length($_) : $max_name_len
1062 for keys %$features;
1064 while (my ($name, $info) = each %$features) {
1065 $self->log_info(" $name" . '.' x ($max_name_len - length($name) + 4));
1067 if ( my $failures = $self->prereq_failures($info) ) {
1068 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
1069 keys %$failures ) ? 1 : 0;
1070 $self->log_info( $disabled ? "disabled\n" : "enabled\n" );
1073 while (my ($type, $prereqs) = each %$failures) {
1074 while (my ($module, $status) = each %$prereqs) {
1076 ($type =~ /^(?:\w+_)?(?:requires|conflicts)$/) ? 1 : 0;
1077 my $prefix = ($required) ? '-' : '*';
1078 $log_text .= " $prefix $status->{message}\n";
1081 $self->log_warn("$log_text") unless $self->quiet;
1083 $self->log_info("enabled\n");
1087 $self->log_warn("\n");
1090 sub prereq_failures {
1091 my ($self, $info) = @_;
1093 my @types = @{ $self->prereq_action_types };
1094 $info ||= {map {$_, $self->$_()} @types};
1098 foreach my $type (@types) {
1099 my $prereqs = $info->{$type};
1100 while ( my ($modname, $spec) = each %$prereqs ) {
1101 my $status = $self->check_installed_status($modname, $spec);
1103 if ($type =~ /^(?:\w+_)?conflicts$/) {
1104 next if !$status->{ok};
1105 $status->{conflicts} = delete $status->{need};
1106 $status->{message} = "$modname ($status->{have}) conflicts with this distribution";
1108 } elsif ($type =~ /^(?:\w+_)?recommends$/) {
1109 next if $status->{ok};
1110 $status->{message} = (!ref($status->{have}) && $status->{have} eq '<none>'
1111 ? "Optional prerequisite $modname is not installed"
1112 : "$modname ($status->{have}) is installed, but we prefer to have $spec");
1114 next if $status->{ok};
1117 $out->{$type}{$modname} = $status;
1124 # returns a hash of defined prerequisites; i.e. only prereq types with values
1128 foreach my $type ( @{ $self->prereq_action_types } ) {
1129 if ( $self->can( $type ) ) {
1130 my $prereq = $self->$type() || {};
1131 $prereqs{$type} = $prereq if %$prereq;
1140 # If we have XS files, make sure we can process them.
1141 my $xs_files = $self->find_xs_files;
1142 if (keys %$xs_files && !$self->_mb_feature('C_support')) {
1143 $self->log_warn("Warning: this distribution contains XS files, ".
1144 "but Module::Build is not configured with C_support. ".
1145 "Please install ExtUtils::CBuilder to enable C_support.\n");
1148 # Check to see if there are any prereqs to check
1149 my $info = $self->_enum_prereqs;
1150 return 1 unless $info;
1152 $self->log_info("Checking prerequisites...\n");
1154 my $failures = $self->prereq_failures($info);
1158 while (my ($type, $prereqs) = each %$failures) {
1159 while (my ($module, $status) = each %$prereqs) {
1160 my $prefix = ($type =~ /^(?:\w+_)?recommends$/) ? '*' : '- ERROR:';
1161 $self->log_warn(" $prefix $status->{message}\n");
1165 $self->log_warn(<<EOF);
1167 ERRORS/WARNINGS FOUND IN PREREQUISITES. You may wish to install the versions
1168 of the modules indicated above before proceeding with this installation
1175 $self->log_info("Looks good\n\n");
1183 # Check the current perl interpreter
1184 # It's much more convenient to use $] here than $^V, but 'man
1185 # perlvar' says I'm not supposed to. Bloody tyrant.
1186 return $^V ? $self->perl_version_to_float(sprintf "%vd", $^V) : $];
1189 sub perl_version_to_float {
1190 my ($self, $version) = @_;
1191 $version =~ s/\./../;
1192 $version =~ s/\.(\d+)/sprintf '%03d', $1/eg;
1196 sub _parse_conditions {
1197 my ($self, $spec) = @_;
1199 if ($spec =~ /^\s*([\w.]+)\s*$/) { # A plain number, maybe with dots, letters, and underscores
1200 return (">= $spec");
1202 return split /\s*,\s*/, $spec;
1206 sub check_installed_status {
1207 my ($self, $modname, $spec) = @_;
1208 my %status = (need => $spec);
1210 if ($modname eq 'perl') {
1211 $status{have} = $self->perl_version;
1213 } elsif (eval { no strict; $status{have} = ${"${modname}::VERSION"} }) {
1214 # Don't try to load if it's already loaded
1217 my $pm_info = Module::Build::ModuleInfo->new_from_module( $modname );
1218 unless (defined( $pm_info )) {
1219 @status{ qw(have message) } = ('<none>', "$modname is not installed");
1223 $status{have} = $pm_info->version();
1224 if ($spec and !$status{have}) {
1225 @status{ qw(have message) } = (undef, "Couldn't find a \$VERSION in prerequisite $modname");
1230 my @conditions = $self->_parse_conditions($spec);
1232 foreach (@conditions) {
1233 my ($op, $version) = /^\s* (<=?|>=?|==|!=) \s* ([\w.]+) \s*$/x
1234 or die "Invalid prerequisite condition '$_' for $modname";
1236 $version = $self->perl_version_to_float($version)
1237 if $modname eq 'perl';
1239 next if $op eq '>=' and !$version; # Module doesn't have to actually define a $VERSION
1241 unless ($self->compare_versions( $status{have}, $op, $version )) {
1242 $status{message} = "$modname ($status{have}) is installed, but we need version $op $version";
1251 sub compare_versions {
1253 my ($v1, $op, $v2) = @_;
1254 $v1 = Module::Build::Version->new($v1)
1255 unless UNIVERSAL::isa($v1,'Module::Build::Version');
1257 my $eval_str = "\$v1 $op \$v2";
1258 my $result = eval $eval_str;
1259 $self->log_warn("error comparing versions: '$eval_str' $@") if $@;
1264 # I wish I could set $! to a string, but I can't, so I use $@
1265 sub check_installed_version {
1266 my ($self, $modname, $spec) = @_;
1268 my $status = $self->check_installed_status($modname, $spec);
1270 if ($status->{ok}) {
1271 return $status->{have} if $status->{have} and $status->{have} ne '<none>';
1272 return '0 but true';
1275 $@ = $status->{message};
1279 sub make_executable {
1280 # Perl's chmod() is mapped to useful things on various non-Unix
1281 # platforms, so we use it in the base class even though it looks
1286 my $current_mode = (stat $_)[2];
1287 chmod $current_mode | oct(111), $_;
1292 # We assume this does the right thing on generic platforms, though
1293 # we do some other more specific stuff on Unixish platforms.
1294 my ($self, $file) = @_;
1298 sub _startperl { shift()->config('startperl') }
1300 # Return any directories in @INC which are not in the default @INC for
1301 # this perl. For example, stuff passed in with -I or loaded with "use lib".
1306 $seen{$_}++ foreach $self->_default_INC;
1307 return grep !$seen{$_}++, @INC;
1310 # Determine the default @INC for this Perl
1312 my @default_inc; # Memoize
1315 return @default_inc if @default_inc;
1317 local $ENV{PERL5LIB}; # this is not considered part of the default.
1319 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
1321 my @inc = $self->_backticks($perl, '-le', 'print for @INC');
1324 return @default_inc = @inc;
1328 sub print_build_script {
1329 my ($self, $fh) = @_;
1331 my $build_package = $self->build_class;
1335 my %q = map {$_, $self->$_()} qw(config_dir base_dir);
1337 my $case_tolerant = 0+(File::Spec->can('case_tolerant')
1338 && File::Spec->case_tolerant);
1339 $q{base_dir} = uc $q{base_dir} if $case_tolerant;
1340 $q{base_dir} = Win32::GetShortPathName($q{base_dir}) if $^O eq 'MSWin32';
1342 $q{magic_numfile} = $self->config_file('magicnum');
1344 my @myINC = $self->_added_to_INC;
1345 for (@myINC, values %q) {
1346 $_ = File::Spec->canonpath( $_ );
1350 my $quoted_INC = join ",\n", map " '$_'", @myINC;
1351 my $shebang = $self->_startperl;
1352 my $magic_number = $self->magic_number;
1362 sub magic_number_matches {
1363 return 0 unless -e '$q{magic_numfile}';
1365 open FH, '$q{magic_numfile}' or return 0;
1366 my \$filenum = <FH>;
1368 return \$filenum == $magic_number;
1374 \$^W = 1; # Use warnings
1375 \$progname = basename(\$0);
1376 \$orig_dir = Cwd::cwd();
1377 my \$base_dir = '$q{base_dir}';
1378 if (!magic_number_matches()) {
1379 unless (chdir(\$base_dir)) {
1380 die ("Couldn't chdir(\$base_dir), aborting\\n");
1382 unless (magic_number_matches()) {
1383 die ("Configuration seems to be out of date, please re-run 'perl Build.PL' again.\\n");
1392 close(*DATA) unless eof(*DATA); # ensure no open handles to this script
1396 # Some platforms have problems setting \$^X in shebang contexts, fix it up here
1397 \$^X = Module::Build->find_perl_interpreter;
1399 if (-e 'Build.PL' and not $build_package->up_to_date('Build.PL', \$progname)) {
1400 warn "Warning: Build.PL has been altered. You may need to run 'perl Build.PL' again.\\n";
1403 # This should have just enough arguments to be able to bootstrap the rest.
1404 my \$build = $build_package->resume (
1406 config_dir => '$q{config_dir}',
1407 orig_dir => \$orig_dir,
1415 sub create_build_script {
1417 $self->write_config;
1419 my ($build_script, $dist_name, $dist_version)
1420 = map $self->$_(), qw(build_script dist_name dist_version);
1422 if ( $self->delete_filetree($build_script) ) {
1423 $self->log_info("Removed previous script '$build_script'\n\n");
1426 $self->log_info("Creating new '$build_script' script for ",
1427 "'$dist_name' version '$dist_version'\n");
1428 my $fh = IO::File->new(">$build_script") or die "Can't create '$build_script': $!";
1429 $self->print_build_script($fh);
1432 $self->make_executable($build_script);
1437 sub check_manifest {
1439 return unless -e 'MANIFEST';
1441 # Stolen nearly verbatim from MakeMaker. But ExtUtils::Manifest
1442 # could easily be re-written into a modern Perl dialect.
1444 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
1445 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
1447 $self->log_info("Checking whether your kit is complete...\n");
1448 if (my @missed = ExtUtils::Manifest::manicheck()) {
1449 $self->log_warn("WARNING: the following files are missing in your kit:\n",
1450 "\t", join("\n\t", @missed), "\n",
1451 "Please inform the author.\n\n");
1453 $self->log_info("Looks good\n\n");
1459 local $self->{_completed_actions} = {};
1462 my ($action, %p) = @_;
1463 my $args = $p{args} ? delete($p{args}) : {};
1465 local $self->{invoked_action} = $action;
1466 local $self->{args} = {%{$self->{args}}, %$args};
1467 local $self->{properties} = {%{$self->{properties}}, %p};
1468 return $self->_call_action($action);
1471 die "No build action specified" unless $self->{action};
1472 local $self->{invoked_action} = $self->{action};
1473 $self->_call_action($self->{action});
1477 my ($self, $action) = @_;
1479 return if $self->{_completed_actions}{$action}++;
1481 local $self->{action} = $action;
1482 my $method = "ACTION_$action";
1483 die "No action '$action' defined, try running the 'help' action.\n" unless $self->can($method);
1484 return $self->$method();
1489 my $specs = $self->get_options or return ({}, @_);
1490 require Getopt::Long;
1491 # XXX Should we let Getopt::Long handle M::B's options? That would
1492 # be easy-ish to add to @specs right here, but wouldn't handle options
1493 # passed without "--" as M::B currently allows. We might be able to
1494 # get around this by setting the "prefix_pattern" Configure option.
1497 # Construct the specifications for GetOptions.
1498 while (my ($k, $v) = each %$specs) {
1499 # Throw an error if specs conflict with our own.
1500 die "Option specification '$k' conflicts with a " . ref $self
1501 . " option of the same name"
1502 if $self->valid_property($k);
1503 push @specs, $k . (defined $v->{type} ? $v->{type} : '');
1504 push @specs, $v->{store} if exists $v->{store};
1505 $args->{$k} = $v->{default} if exists $v->{default};
1508 local @ARGV = @_; # No other way to dupe Getopt::Long
1510 # Get the options values and return them.
1511 # XXX Add option to allow users to set options?
1513 Getopt::Long::Configure('pass_through');
1514 Getopt::Long::GetOptions($args, @specs);
1517 return $args, @ARGV;
1521 my ($self, $args) = @_;
1523 while (my ($k, $v) = each %$args) {
1524 push @out, (UNIVERSAL::isa($v, 'HASH') ? map {+"--$k", "$_=$v->{$_}"} keys %$v :
1525 UNIVERSAL::isa($v, 'ARRAY') ? map {+"--$k", $_} @$v :
1533 return wantarray ? %{ $self->{args} } : $self->{args} unless @_;
1535 $self->{args}{$key} = shift if @_;
1536 return $self->{args}{$key};
1539 sub _translate_option {
1543 (my $tr_opt = $opt) =~ tr/-/_/;
1545 return $tr_opt if grep $tr_opt =~ /^(?:no_?)?$_$/, qw(
1548 extra_compiler_flags
1557 ); # normalize only selected option names
1563 my ($self, $args, $key, $val) = @_;
1565 $key = $self->_translate_option($key);
1567 if ( exists $args->{$key} ) {
1568 $args->{$key} = [ $args->{$key} ] unless ref $args->{$key};
1569 push @{$args->{$key}}, $val;
1571 $args->{$key} = $val;
1580 $opt = $self->_translate_option($opt);
1592 # inverted boolean options; eg --noverbose or --no-verbose
1593 # converted to proper name & returned with false value (verbose, 0)
1594 if ( grep $opt =~ /^no[-_]?$_$/, @bool_opts ) {
1599 # non-boolean option; return option unchanged along with its argument
1600 return ($opt, shift(@$argv)) unless grep $_ eq $opt, @bool_opts;
1602 # we're punting a bit here, if an option appears followed by a digit
1603 # we take the digit as the argument for the option. If there is
1604 # nothing that looks like a digit, we pretent the option is a flag
1605 # that is being set and has no argument.
1607 $arg = shift(@$argv) if @$argv && $argv->[0] =~ /^\d+$/;
1609 return ($opt, $arg);
1614 my ($action, @argv);
1615 (my $args, @_) = $self->cull_options(@_);
1618 my $opt_re = qr/[\w\-]+/;
1622 if ( /^(?:--)?($opt_re)=(.*)$/ ) {
1623 $self->_read_arg(\%args, $1, $2);
1624 } elsif ( /^--($opt_re)$/ ) {
1625 my($opt, $arg) = $self->_optional_arg($1, \@_);
1626 $self->_read_arg(\%args, $opt, $arg);
1627 } elsif ( /^($opt_re)$/ and !defined($action)) {
1633 $args{ARGV} = \@argv;
1635 # Hashify these parameters
1636 for ($self->hash_properties, 'config') {
1637 next unless exists $args{$_};
1640 $args{$_} = [ $args{$_} ] unless ref $args{$_};
1641 foreach my $arg ( @{$args{$_}} ) {
1642 $arg =~ /(\w+)=(.*)/
1643 or die "Malformed '$_' argument: '$arg' should be something like 'foo=bar'";
1649 # De-tilde-ify any path parameters
1650 for my $key (qw(prefix install_base destdir)) {
1651 next if !defined $args{$key};
1652 $args{$key} = _detildefy($args{$key});
1655 for my $key (qw(install_path)) {
1656 next if !defined $args{$key};
1658 for my $subkey (keys %{$args{$key}}) {
1659 next if !defined $args{$key}{$subkey};
1660 my $subkey_ext = _detildefy($args{$key}{$subkey});
1661 if ( $subkey eq 'html' ) { # translate for compatability
1662 $args{$key}{binhtml} = $subkey_ext;
1663 $args{$key}{libhtml} = $subkey_ext;
1665 $args{$key}{$subkey} = $subkey_ext;
1670 if ($args{makefile_env_macros}) {
1671 require Module::Build::Compat;
1672 %args = (%args, Module::Build::Compat->makefile_to_build_macros);
1675 return \%args, $action;
1682 return $arg =~ /^~/ ? (glob $arg)[0] : $arg;
1686 # merge Module::Build argument lists that have already been parsed
1687 # by read_args(). Takes two references to option hashes and merges
1688 # the contents, giving priority to the first.
1689 sub _merge_arglist {
1690 my( $self, $opts1, $opts2 ) = @_;
1692 my %new_opts = %$opts1;
1693 while (my ($key, $val) = each %$opts2) {
1694 if ( exists( $opts1->{$key} ) ) {
1695 if ( ref( $val ) eq 'HASH' ) {
1696 while (my ($k, $v) = each %$val) {
1697 $new_opts{$key}{$k} = $v unless exists( $opts1->{$key}{$k} );
1701 $new_opts{$key} = $val
1708 # Look for a home directory on various systems.
1711 push( @home_dirs, $ENV{HOME} ) if $ENV{HOME};
1713 push( @home_dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
1714 if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};
1716 my @other_home_envs = qw( USERPROFILE APPDATA WINDIR SYS$LOGIN );
1717 push( @home_dirs, map $ENV{$_}, grep $ENV{$_}, @other_home_envs );
1719 my @real_home_dirs = grep -d, @home_dirs;
1721 return wantarray ? @real_home_dirs : shift( @real_home_dirs );
1724 sub _find_user_config {
1727 foreach my $dir ( $self->_home_dir ) {
1728 my $path = File::Spec->catfile( $dir, $file );
1729 return $path if -e $path;
1734 # read ~/.modulebuildrc returning global options '*' and
1735 # options specific to the currently executing $action.
1736 sub read_modulebuildrc {
1737 my( $self, $action ) = @_;
1739 return () unless $self->use_rcfile;
1742 if ( exists($ENV{MODULEBUILDRC}) && $ENV{MODULEBUILDRC} eq 'NONE' ) {
1744 } elsif ( exists($ENV{MODULEBUILDRC}) && -e $ENV{MODULEBUILDRC} ) {
1745 $modulebuildrc = $ENV{MODULEBUILDRC};
1746 } elsif ( exists($ENV{MODULEBUILDRC}) ) {
1747 $self->log_warn("WARNING: Can't find resource file " .
1748 "'$ENV{MODULEBUILDRC}' defined in environment.\n" .
1749 "No options loaded\n");
1752 $modulebuildrc = $self->_find_user_config( '.modulebuildrc' );
1753 return () unless $modulebuildrc;
1756 my $fh = IO::File->new( $modulebuildrc )
1757 or die "Can't open $modulebuildrc: $!";
1759 my %options; my $buffer = '';
1760 while (defined( my $line = <$fh> )) {
1763 next unless length( $line );
1765 if ( $line =~ /^\S/ ) {
1767 my( $action, $options ) = split( /\s+/, $buffer, 2 );
1768 $options{$action} .= $options . ' ';
1777 if ( $buffer ) { # anything left in $buffer ?
1778 my( $action, $options ) = split( /\s+/, $buffer, 2 );
1779 $options{$action} .= $options . ' '; # merge if more than one line
1783 $self->read_args( $self->split_like_shell( $options{'*'} || '' ) );
1785 $self->read_args( $self->split_like_shell( $options{$action} || '' ) );
1787 # specific $action options take priority over global options '*'
1788 return $self->_merge_arglist( $action_opts, $global_opts );
1791 # merge the relevant options in ~/.modulebuildrc into Module::Build's
1792 # option list where they do not conflict with commandline options.
1793 sub merge_modulebuildrc {
1794 my( $self, $action, %cmdline_opts ) = @_;
1795 my %rc_opts = $self->read_modulebuildrc( $action || $self->{action} || 'build' );
1796 my %new_opts = $self->_merge_arglist( \%cmdline_opts, \%rc_opts );
1797 $self->merge_args( $action, %new_opts );
1801 my ($self, $action, %args) = @_;
1802 $self->{action} = $action if defined $action;
1804 my %additive = map { $_ => 1 } $self->hash_properties;
1806 # Extract our 'properties' from $cmd_args, the rest are put in 'args'.
1807 while (my ($key, $val) = each %args) {
1808 $self->{phash}{runtime_params}->access( $key => $val )
1809 if $self->valid_property($key);
1811 if ($key eq 'config') {
1812 $self->config($_ => $val->{$_}) foreach keys %$val;
1814 my $add_to = ( $additive{$key} ? $self->{properties}{$key}
1815 : $self->valid_property($key) ? $self->{properties}
1818 if ($additive{$key}) {
1819 $add_to->{$_} = $val->{$_} foreach keys %$val;
1821 $add_to->{$key} = $val;
1829 my ($args, $action) = $self->read_args(@_);
1830 $self->merge_args($action, %$args);
1831 $self->merge_modulebuildrc( $action, %$args );
1835 my ($self, $class, $seen) = @_;
1836 $class ||= ref($self) || $self;
1840 my @super = grep {not $seen->{$_}++} $class, @{ $class . '::ISA' };
1841 return @super, map {$self->super_classes($_,$seen)} @super;
1850 foreach my $class ($self->super_classes) {
1851 foreach ( keys %{ $class . '::' } ) {
1852 $actions{$1}++ if /^ACTION_(\w+)/;
1856 return wantarray ? sort keys %actions : \%actions;
1859 sub get_action_docs {
1860 my ($self, $action, $actions) = @_;
1861 $actions ||= $self->known_actions;
1863 ($@ = "No known action '$action'\n"), return
1864 unless $actions->{$action};
1866 my ($files_found, @docs) = (0);
1867 foreach my $class ($self->super_classes) {
1868 (my $file = $class) =~ s{::}{/}g;
1869 $file = $INC{$file . '.pm'} or next;
1870 my $fh = IO::File->new("< $file") or next;
1873 # Code below modified from /usr/bin/perldoc
1875 # Skip to ACTIONS section
1878 last if /^=head1 ACTIONS\s/;
1881 # Look for our action
1882 my ($found, $inlist) = (0, 0);
1884 if (/^=item\s+\Q$action\E\b/) {
1886 } elsif (/^=(item|back)/) {
1887 last if $found > 1 and not $inlist;
1891 ++$inlist if /^=over/;
1892 --$inlist if /^=back/;
1893 ++$found if /^\w/; # Found descriptive text
1897 unless ($files_found) {
1898 $@ = "Couldn't find any documentation to search";
1902 $@ = "Couldn't find any docs for action '$action'";
1906 return join '', @docs;
1909 sub ACTION_prereq_report {
1911 $self->log_info( $self->prereq_report );
1916 my @types = @{ $self->prereq_action_types };
1917 my $info = { map { $_ => $self->$_() } @types };
1920 foreach my $type (@types) {
1921 my $prereqs = $info->{$type};
1922 next unless %$prereqs;
1923 $output .= "\n$type:\n";
1927 while ( my ($modname, $spec) = each %$prereqs ) {
1928 my $len = length $modname;
1929 $mod_len = $len if $len > $mod_len;
1931 $len = length $spec;
1932 $ver_len = $len if $len > $ver_len;
1934 my $mod = $self->check_installed_status($modname, $spec);
1935 $mod->{name} = $modname;
1937 $mod->{ok} = ! $mod->{ok} if $type =~ /^(\w+_)?conflicts$/;
1939 $mods{lc $modname} = $mod;
1942 my $space = q{ } x ($mod_len - 3);
1943 my $vspace = q{ } x ($ver_len - 3);
1944 my $sline = q{-} x ($mod_len - 3);
1945 my $vline = q{-} x ($ver_len - 3);
1946 my $disposition = ($type =~ /^(\w+_)?conflicts$/) ?
1949 " Module $space $disposition $vspace Have\n".
1950 " ------$sline+------$vline-+----------\n";
1953 for my $k (sort keys %mods) {
1954 my $mod = $mods{$k};
1955 my $space = q{ } x ($mod_len - length $k);
1956 my $vspace = q{ } x ($ver_len - length $mod->{need});
1957 my $f = $mod->{ok} ? ' ' : '!';
1959 " $f $mod->{name} $space $mod->{need} $vspace $mod->{have}\n";
1967 my $actions = $self->known_actions;
1969 if (@{$self->{args}{ARGV}}) {
1970 my $msg = $self->get_action_docs($self->{args}{ARGV}[0], $actions) || "$@\n";
1977 Usage: $0 <action> arg1=value arg2=value ...
1978 Example: $0 test verbose=1
1983 print $self->_action_listing($actions);
1985 print "\nRun `Build help <action>` for details on an individual action.\n";
1986 print "See `perldoc Module::Build` for complete documentation.\n";
1989 sub _action_listing {
1990 my ($self, $actions) = @_;
1992 # Flow down columns, not across rows
1993 my @actions = sort keys %$actions;
1994 @actions = map $actions[($_ + ($_ % 2) * @actions) / 2], 0..$#actions;
1997 while (my ($one, $two) = splice @actions, 0, 2) {
1998 $out .= sprintf(" %-12s %-12s\n", $one, $two||'');
2006 # Protect others against our @INC changes
2009 # Filter out nonsensical @INC entries - some versions of
2010 # Test::Harness will really explode the number of entries here
2011 @INC = grep {ref() || -d} @INC if @INC > 100;
2019 my $p = $self->{properties};
2021 $self->depends_on('code');
2023 # Protect others against our @INC changes
2026 # Make sure we test the module in blib/
2027 unshift @INC, (File::Spec->catdir($p->{base_dir}, $self->blib, 'lib'),
2028 File::Spec->catdir($p->{base_dir}, $self->blib, 'arch'));
2030 # Filter out nonsensical @INC entries - some versions of
2031 # Test::Harness will really explode the number of entries here
2032 @INC = grep {ref() || -d} @INC if @INC > 100;
2039 my $p = $self->{properties};
2040 require Test::Harness;
2042 # Do everything in our power to work with all versions of Test::Harness
2043 my @harness_switches = $p->{debugger} ? qw(-w -d) : ();
2044 local $Test::Harness::switches = join ' ', grep defined, $Test::Harness::switches, @harness_switches;
2045 local $Test::Harness::Switches = join ' ', grep defined, $Test::Harness::Switches, @harness_switches;
2046 local $ENV{HARNESS_PERL_SWITCHES} = join ' ', grep defined, $ENV{HARNESS_PERL_SWITCHES}, @harness_switches;
2048 $Test::Harness::switches = undef unless length $Test::Harness::switches;
2049 $Test::Harness::Switches = undef unless length $Test::Harness::Switches;
2050 delete $ENV{HARNESS_PERL_SWITCHES} unless length $ENV{HARNESS_PERL_SWITCHES};
2052 local ($Test::Harness::verbose,
2053 $Test::Harness::Verbose,
2055 $ENV{HARNESS_VERBOSE}) = ($p->{verbose} || 0) x 4;
2057 my $tests = $self->find_test_files;
2060 # Work around a Test::Harness bug that loses the particular perl
2061 # we're running under. $self->perl is trustworthy, but $^X isn't.
2062 local $^X = $self->perl;
2063 Test::Harness::runtests(@$tests);
2065 $self->log_info("No tests defined.\n");
2068 # This will get run and the user will see the output. It doesn't
2069 # emit Test::Harness-style output.
2070 if (-e 'visual.pl') {
2071 $self->run_perl_script('visual.pl', '-Mblib='.$self->blib);
2077 my $p = $self->{properties};
2079 return $p->{test_files} = (@_ == 1 ? shift : [@_]);
2081 return $self->find_test_files;
2084 sub expand_test_dir {
2085 my ($self, $dir) = @_;
2086 return sort @{$self->rscan_dir($dir, qr{^[^.].*\.t$})} if $self->recursive_test_files;
2087 return sort glob File::Spec->catfile($dir, "*.t");
2092 local $self->{properties}{debugger} = 1;
2093 $self->depends_on('test');
2096 sub ACTION_testcover {
2099 unless (Module::Build::ModuleInfo->find_module_by_name('Devel::Cover')) {
2100 warn("Cannot run testcover action unless Devel::Cover is installed.\n");
2104 $self->add_to_cleanup('coverage', 'cover_db');
2105 $self->depends_on('code');
2107 # See whether any of the *.pm files have changed since last time
2108 # testcover was run. If so, start over.
2109 if (-e 'cover_db') {
2110 my $pm_files = $self->rscan_dir(File::Spec->catdir($self->blib, 'lib'), qr{\.pm$} );
2111 my $cover_files = $self->rscan_dir('cover_db', sub {-f $_ and not /\.html$/});
2113 $self->do_system(qw(cover -delete))
2114 unless $self->up_to_date($pm_files, $cover_files)
2115 && $self->up_to_date($self->test_files, $cover_files);
2118 local $Test::Harness::switches =
2119 local $Test::Harness::Switches =
2120 local $ENV{HARNESS_PERL_SWITCHES} = "-MDevel::Cover";
2122 $self->depends_on('test');
2123 $self->do_system('cover');
2129 # All installable stuff gets created in blib/ .
2130 # Create blib/arch to keep blib.pm happy
2131 my $blib = $self->blib;
2132 $self->add_to_cleanup($blib);
2133 File::Path::mkpath( File::Spec->catdir($blib, 'arch') );
2135 if (my $split = $self->autosplit) {
2136 $self->autosplit_file($_, $blib) for ref($split) ? @$split : ($split);
2139 foreach my $element (@{$self->build_elements}) {
2140 my $method = "process_${element}_files";
2141 $method = "process_files_by_extension" unless $self->can($method);
2142 $self->$method($element);
2145 $self->depends_on('config_data');
2150 $self->depends_on('code');
2151 $self->depends_on('docs');
2154 sub process_files_by_extension {
2155 my ($self, $ext) = @_;
2157 my $method = "find_${ext}_files";
2158 my $files = $self->can($method) ? $self->$method() : $self->_find_file_by_type($ext, 'lib');
2160 while (my ($file, $dest) = each %$files) {
2161 $self->copy_if_modified(from => $file, to => File::Spec->catfile($self->blib, $dest) );
2165 sub process_support_files {
2167 my $p = $self->{properties};
2168 return unless $p->{c_source};
2170 push @{$p->{include_dirs}}, $p->{c_source};
2172 my $files = $self->rscan_dir($p->{c_source}, qr{\.c(pp)?$});
2173 foreach my $file (@$files) {
2174 push @{$p->{objects}}, $self->compile_c($file);
2178 sub process_PL_files {
2180 my $files = $self->find_PL_files;
2182 while (my ($file, $to) = each %$files) {
2183 unless ($self->up_to_date( $file, $to )) {
2184 $self->run_perl_script($file, [], [@$to]);
2185 $self->add_to_cleanup(@$to);
2190 sub process_xs_files {
2192 my $files = $self->find_xs_files;
2193 while (my ($from, $to) = each %$files) {
2194 unless ($from eq $to) {
2195 $self->add_to_cleanup($to);
2196 $self->copy_if_modified( from => $from, to => $to );
2198 $self->process_xs($to);
2202 sub process_pod_files { shift()->process_files_by_extension(shift()) }
2203 sub process_pm_files { shift()->process_files_by_extension(shift()) }
2205 sub process_script_files {
2207 my $files = $self->find_script_files;
2208 return unless keys %$files;
2210 my $script_dir = File::Spec->catdir($self->blib, 'script');
2211 File::Path::mkpath( $script_dir );
2213 foreach my $file (keys %$files) {
2214 my $result = $self->copy_if_modified($file, $script_dir, 'flatten') or next;
2215 $self->fix_shebang_line($result) unless $self->os_type eq 'VMS';
2216 $self->make_executable($result);
2222 if (my $files = $self->{properties}{PL_files}) {
2223 # 'PL_files' is given as a Unix file spec, so we localize_file_path().
2225 if (UNIVERSAL::isa($files, 'ARRAY')) {
2226 return { map {$_, [/^(.*)\.PL$/]}
2227 map $self->localize_file_path($_),
2230 } elsif (UNIVERSAL::isa($files, 'HASH')) {
2232 while (my ($file, $to) = each %$files) {
2233 $out{ $self->localize_file_path($file) } = [ map $self->localize_file_path($_),
2234 ref $to ? @$to : ($to) ];
2239 die "'PL_files' must be a hash reference or array reference";
2243 return unless -d 'lib';
2244 return { map {$_, [/^(.*)\.PL$/]} @{ $self->rscan_dir('lib', qr{\.PL$}) } };
2247 sub find_pm_files { shift->_find_file_by_type('pm', 'lib') }
2248 sub find_pod_files { shift->_find_file_by_type('pod', 'lib') }
2249 sub find_xs_files { shift->_find_file_by_type('xs', 'lib') }
2251 sub find_script_files {
2253 if (my $files = $self->script_files) {
2254 # Always given as a Unix file spec. Values in the hash are
2255 # meaningless, but we preserve if present.
2256 return { map {$self->localize_file_path($_), $files->{$_}} keys %$files };
2259 # No default location for script files
2263 sub find_test_files {
2265 my $p = $self->{properties};
2267 if (my $files = $p->{test_files}) {
2268 $files = [keys %$files] if UNIVERSAL::isa($files, 'HASH');
2269 $files = [map { -d $_ ? $self->expand_test_dir($_) : $_ }
2271 $self->split_like_shell($files)];
2273 # Always given as a Unix file spec.
2274 return [ map $self->localize_file_path($_), @$files ];
2277 # Find all possible tests in t/ or test.pl
2279 push @tests, 'test.pl' if -e 'test.pl';
2280 push @tests, $self->expand_test_dir('t') if -e 't' and -d _;
2285 sub _find_file_by_type {
2286 my ($self, $type, $dir) = @_;
2288 if (my $files = $self->{properties}{"${type}_files"}) {
2289 # Always given as a Unix file spec
2290 return { map $self->localize_file_path($_), %$files };
2293 return {} unless -d $dir;
2294 return { map {$_, $_}
2295 map $self->localize_file_path($_),
2297 @{ $self->rscan_dir($dir, qr{\.$type$}) } };
2300 sub localize_file_path {
2301 my ($self, $path) = @_;
2302 $path =~ s/\.\z// if $self->os_type eq 'VMS';
2303 return File::Spec->catfile( split m{/}, $path );
2306 sub localize_dir_path {
2307 my ($self, $path) = @_;
2308 return File::Spec->catdir( split m{/}, $path );
2311 sub fix_shebang_line { # Adapted from fixin() in ExtUtils::MM_Unix 1.35
2312 my ($self, @files) = @_;
2313 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
2315 my ($does_shbang) = $c->get('sharpbang') =~ /^\s*\#\!/;
2316 for my $file (@files) {
2317 my $FIXIN = IO::File->new($file) or die "Can't process '$file': $!";
2319 chomp(my $line = <$FIXIN>);
2320 next unless $line =~ s/^\s*\#!\s*//; # Not a shbang file.
2322 my ($cmd, $arg) = (split(' ', $line, 2), '');
2323 next unless $cmd =~ /perl/i;
2324 my $interpreter = $self->{properties}{perl};
2326 $self->log_verbose("Changing sharpbang in $file to $interpreter");
2328 $shb .= $c->get('sharpbang')."$interpreter $arg\n" if $does_shbang;
2330 # I'm not smart enough to know the ramifications of changing the
2331 # embedded newlines here to \n, so I leave 'em in.
2333 eval 'exec $interpreter $arg -S \$0 \${1+"\$\@"}'
2334 if 0; # not running under some shell
2335 } unless $self->os_type eq 'Windows'; # this won't work on win32, so don't
2337 my $FIXOUT = IO::File->new(">$file.new")
2338 or die "Can't create new $file: $!\n";
2340 # Print out the new #! line (or equivalent).
2342 undef $/; # Was localized above
2343 print $FIXOUT $shb, <$FIXIN>;
2347 rename($file, "$file.bak")
2348 or die "Can't rename $file to $file.bak: $!";
2350 rename("$file.new", $file)
2351 or die "Can't rename $file.new to $file: $!";
2354 or $self->log_warn("Couldn't clean up $file.bak, leaving it there");
2356 $self->do_system($c->get('eunicefix'), $file) if $c->get('eunicefix') ne ':';
2361 sub ACTION_testpod {
2363 $self->depends_on('docs');
2365 eval q{use Test::Pod 0.95; 1}
2366 or die "The 'testpod' action requires Test::Pod version 0.95";
2368 my @files = sort keys %{$self->_find_pods($self->libdoc_dirs)},
2369 keys %{$self->_find_pods($self->bindoc_dirs, exclude => [ qr/\.bat$/ ])}
2370 or die "Couldn't find any POD files to test\n";
2372 { package Module::Build::PodTester; # Don't want to pollute the main namespace
2373 Test::Pod->import( tests => scalar @files );
2374 pod_file_ok($_) foreach @files;
2378 sub ACTION_testpodcoverage {
2381 $self->depends_on('docs');
2383 eval q{use Test::Pod::Coverage 1.00; 1}
2384 or die "The 'testpodcoverage' action requires ",
2385 "Test::Pod::Coverage version 1.00";
2387 all_pod_coverage_ok();
2393 $self->depends_on('code');
2394 $self->depends_on('manpages', 'html');
2397 # Given a file type, will return true if the file type would normally
2398 # be installed when neither install-base nor prefix has been set.
2399 # I.e. it will be true only if the path is set from Config.pm or
2400 # set explicitly by the user via install-path.
2401 sub _is_default_installable {
2404 return ( $self->install_destination($type) &&
2405 ( $self->install_path($type) ||
2406 $self->install_sets($self->installdirs)->{$type} )
2410 sub ACTION_manpages {
2413 return unless $self->_mb_feature('manpage_support');
2415 $self->depends_on('code');
2417 foreach my $type ( qw(bin lib) ) {
2418 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2419 exclude => [ qr/\.bat$/ ] );
2420 next unless %$files;
2422 my $sub = $self->can("manify_${type}_pods");
2423 next unless defined( $sub );
2425 if ( $self->invoked_action eq 'manpages' ) {
2427 } elsif ( $self->_is_default_installable("${type}doc") ) {
2434 sub manify_bin_pods {
2437 my $files = $self->_find_pods( $self->{properties}{bindoc_dirs},
2438 exclude => [ qr/\.bat$/ ] );
2439 return unless keys %$files;
2441 my $mandir = File::Spec->catdir( $self->blib, 'bindoc' );
2442 File::Path::mkpath( $mandir, 0, oct(777) );
2445 foreach my $file (keys %$files) {
2446 # Pod::Simple based parsers only support one document per instance.
2447 # This is expected to change in a future version (Pod::Simple > 3.03).
2448 my $parser = Pod::Man->new( section => 1 ); # binaries go in section 1
2449 my $manpage = $self->man1page_name( $file ) . '.' .
2450 $self->config( 'man1ext' );
2451 my $outfile = File::Spec->catfile($mandir, $manpage);
2452 next if $self->up_to_date( $file, $outfile );
2453 $self->log_info("Manifying $file -> $outfile\n");
2454 $parser->parse_from_file( $file, $outfile );
2455 $files->{$file} = $outfile;
2459 sub manify_lib_pods {
2462 my $files = $self->_find_pods($self->{properties}{libdoc_dirs});
2463 return unless keys %$files;
2465 my $mandir = File::Spec->catdir( $self->blib, 'libdoc' );
2466 File::Path::mkpath( $mandir, 0, oct(777) );
2469 while (my ($file, $relfile) = each %$files) {
2470 # Pod::Simple based parsers only support one document per instance.
2471 # This is expected to change in a future version (Pod::Simple > 3.03).
2472 my $parser = Pod::Man->new( section => 3 ); # libraries go in section 3
2473 my $manpage = $self->man3page_name( $relfile ) . '.' .
2474 $self->config( 'man3ext' );
2475 my $outfile = File::Spec->catfile( $mandir, $manpage);
2476 next if $self->up_to_date( $file, $outfile );
2477 $self->log_info("Manifying $file -> $outfile\n");
2478 $parser->parse_from_file( $file, $outfile );
2479 $files->{$file} = $outfile;
2484 my ($self, $dirs, %args) = @_;
2486 foreach my $spec (@$dirs) {
2487 my $dir = $self->localize_dir_path($spec);
2488 next unless -e $dir;
2490 FILE: foreach my $file ( @{ $self->rscan_dir( $dir ) } ) {
2491 foreach my $regexp ( @{ $args{exclude} } ) {
2492 next FILE if $file =~ $regexp;
2494 $files{$file} = File::Spec->abs2rel($file, $dir) if $self->contains_pod( $file )
2501 my ($self, $file) = @_;
2502 return '' unless -T $file; # Only look at text files
2504 my $fh = IO::File->new( $file ) or die "Can't open $file: $!";
2505 while (my $line = <$fh>) {
2506 return 1 if $line =~ /^\=(?:head|pod|item)/;
2515 return unless $self->_mb_feature('HTML_support');
2517 $self->depends_on('code');
2519 foreach my $type ( qw(bin lib) ) {
2520 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2521 exclude => [ qr/\.(?:bat|com|html)$/ ] );
2522 next unless %$files;
2524 if ( $self->invoked_action eq 'html' ) {
2525 $self->htmlify_pods( $type );
2526 } elsif ( $self->_is_default_installable("${type}html") ) {
2527 $self->htmlify_pods( $type );
2534 # 1) If it's an ActiveState perl install, we need to run
2535 # ActivePerl::DocTools->UpdateTOC;
2536 # 2) Links to other modules are not being generated
2540 my $htmldir = shift || File::Spec->catdir($self->blib, "${type}html");
2542 require Module::Build::PodParser;
2545 $self->add_to_cleanup('pod2htm*');
2547 my $pods = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2548 exclude => [ qr/\.(?:bat|com|html)$/ ] );
2549 return unless %$pods; # nothing to do
2551 unless ( -d $htmldir ) {
2552 File::Path::mkpath($htmldir, 0, oct(755))
2553 or die "Couldn't mkdir $htmldir: $!";
2556 my @rootdirs = ($type eq 'bin') ? qw(bin) :
2557 $self->installdirs eq 'core' ? qw(lib) : qw(site lib);
2559 my $podpath = join ':',
2562 map [File::Spec->catdir($self->blib, $_), $_],
2565 foreach my $pod ( keys %$pods ) {
2567 my ($name, $path) = File::Basename::fileparse($pods->{$pod},
2568 qr{\.(?:pm|plx?|pod)$});
2569 my @dirs = File::Spec->splitdir( File::Spec->canonpath( $path ) );
2570 pop( @dirs ) if $dirs[-1] eq File::Spec->curdir;
2572 my $fulldir = File::Spec->catfile($htmldir, @rootdirs, @dirs);
2573 my $outfile = File::Spec->catfile($fulldir, "${name}.html");
2574 my $infile = File::Spec->abs2rel($pod);
2576 next if $self->up_to_date($infile, $outfile);
2578 unless ( -d $fulldir ){
2579 File::Path::mkpath($fulldir, 0, oct(755))
2580 or die "Couldn't mkdir $fulldir: $!";
2583 my $path2root = join( '/', ('..') x (@rootdirs+@dirs) );
2584 my $htmlroot = join( '/',
2586 $self->installdirs eq 'core' ? () : qw(site) ) );
2588 my $fh = IO::File->new($infile) or die "Can't read $infile: $!";
2589 my $abstract = Module::Build::PodParser->new(fh => $fh)->get_abstract();
2591 my $title = join( '::', (@dirs, $name) );
2592 $title .= " - $abstract" if $abstract;
2597 "--podpath=$podpath",
2599 "--outfile=$outfile",
2600 '--podroot=' . $self->blib,
2601 "--htmlroot=$htmlroot",
2604 if ( eval{Pod::Html->VERSION(1.03)} ) {
2605 push( @opts, ('--header', '--backlink=Back to Top') );
2606 push( @opts, "--css=$path2root/" . $self->html_css) if $self->html_css;
2609 $self->log_info("HTMLifying $infile -> $outfile\n");
2610 $self->log_verbose("pod2html @opts\n");
2611 Pod::Html::pod2html(@opts); # or warn "pod2html @opts failed: $!";
2616 # Adapted from ExtUtils::MM_Unix
2619 return File::Basename::basename( shift );
2622 # Adapted from ExtUtils::MM_Unix and Pod::Man
2623 # Depending on M::B's dependency policy, it might make more sense to refactor
2624 # Pod::Man::begin_pod() to extract a name() methods, and use them...
2628 my ($vol, $dirs, $file) = File::Spec->splitpath( shift );
2629 my @dirs = File::Spec->splitdir( File::Spec->canonpath($dirs) );
2631 # Remove known exts from the base name
2632 $file =~ s/\.p(?:od|m|l)\z//i;
2634 return join( $self->manpage_separator, @dirs, $file );
2637 sub manpage_separator {
2641 # For systems that don't have 'diff' executable, should use Algorithm::Diff
2644 $self->depends_on('build');
2645 my $local_lib = File::Spec->rel2abs('lib');
2646 my @myINC = grep {$_ ne $local_lib} @INC;
2648 # The actual install destination might not be in @INC, so check there too.
2649 push @myINC, map $self->install_destination($_), qw(lib arch);
2651 my @flags = @{$self->{args}{ARGV}};
2652 @flags = $self->split_like_shell($self->{args}{flags} || '') unless @flags;
2654 my $installmap = $self->install_map;
2655 delete $installmap->{read};
2656 delete $installmap->{write};
2658 my $text_suffix = qr{\.(pm|pod)$};
2660 while (my $localdir = each %$installmap) {
2661 my @localparts = File::Spec->splitdir($localdir);
2662 my $files = $self->rscan_dir($localdir, sub {-f});
2664 foreach my $file (@$files) {
2665 my @parts = File::Spec->splitdir($file);
2666 @parts = @parts[@localparts .. $#parts]; # Get rid of blib/lib or similar
2668 my $installed = Module::Build::ModuleInfo->find_module_by_name(
2669 join('::', @parts), \@myINC );
2670 if (not $installed) {
2671 print "Only in lib: $file\n";
2675 my $status = File::Compare::compare($installed, $file);
2676 next if $status == 0; # Files are the same
2677 die "Can't compare $installed and $file: $!" if $status == -1;
2679 if ($file =~ $text_suffix) {
2680 $self->do_system('diff', @flags, $installed, $file);
2682 print "Binary files $file and $installed differ\n";
2688 sub ACTION_pure_install {
2689 shift()->depends_on('install');
2692 sub ACTION_install {
2694 require ExtUtils::Install;
2695 $self->depends_on('build');
2696 ExtUtils::Install::install($self->install_map, !$self->quiet, 0, $self->{args}{uninst}||0);
2699 sub ACTION_fakeinstall {
2701 require ExtUtils::Install;
2702 $self->depends_on('build');
2703 ExtUtils::Install::install($self->install_map, !$self->quiet, 1, $self->{args}{uninst}||0);
2706 sub ACTION_versioninstall {
2709 die "You must have only.pm 0.25 or greater installed for this operation: $@\n"
2710 unless eval { require only; 'only'->VERSION(0.25); 1 };
2712 $self->depends_on('build');
2714 my %onlyargs = map {exists($self->{args}{$_}) ? ($_ => $self->{args}{$_}) : ()}
2715 qw(version versionlib);
2716 only::install::install(%onlyargs);
2721 foreach my $item (map glob($_), $self->cleanup) {
2722 $self->delete_filetree($item);
2726 sub ACTION_realclean {
2728 $self->depends_on('clean');
2729 $self->delete_filetree($self->config_dir, $self->build_script);
2734 require Module::Build::PPMMaker;
2735 my $ppd = Module::Build::PPMMaker->new();
2736 my $file = $ppd->make_ppd(%{$self->{args}}, build => $self);
2737 $self->add_to_cleanup($file);
2740 sub ACTION_ppmdist {
2743 $self->depends_on( 'build' );
2745 my $ppm = $self->ppm_name;
2746 $self->delete_filetree( $ppm );
2747 $self->log_info( "Creating $ppm\n" );
2748 $self->add_to_cleanup( $ppm, "$ppm.tar.gz" );
2750 my %types = ( # translate types/dirs to those expected by ppm
2761 foreach my $type ($self->install_types) {
2762 next if exists( $types{$type} ) && !defined( $types{$type} );
2764 my $dir = File::Spec->catdir( $self->blib, $type );
2765 next unless -e $dir;
2767 my $files = $self->rscan_dir( $dir );
2768 foreach my $file ( @$files ) {
2769 next unless -f $file;
2771 File::Spec->abs2rel( File::Spec->rel2abs( $file ),
2772 File::Spec->rel2abs( $dir ) );
2774 File::Spec->catdir( $ppm, 'blib',
2775 exists( $types{$type} ) ? $types{$type} : $type,
2777 $self->copy_if_modified( from => $file, to => $to_file );
2781 foreach my $type ( qw(bin lib) ) {
2782 local $self->{properties}{html_css} = 'Active.css';
2783 $self->htmlify_pods( $type, File::Spec->catdir($ppm, 'blib', 'html') );
2787 # the directory tar'ed must be blib so we need to do a chdir first
2788 my $start_wd = $self->cwd;
2789 chdir( $ppm ) or die "Can't chdir to $ppm";
2790 $self->make_tarball( 'blib', File::Spec->catfile( $start_wd, $ppm ) );
2791 chdir( $start_wd ) or die "Can't chdir to $start_wd";
2793 $self->depends_on( 'ppd' );
2795 $self->delete_filetree( $ppm );
2798 sub ACTION_pardist {
2802 if ( not eval { require PAR::Dist; PAR::Dist->VERSION(0.17) } ) {
2804 "In order to create .par distributions, you need to\n"
2805 . "install PAR::Dist first."
2810 $self->depends_on( 'build' );
2812 return PAR::Dist::blib_to_par(
2813 name => $self->dist_name,
2814 version => $self->dist_version,
2821 $self->depends_on('distdir');
2823 my $dist_dir = $self->dist_dir;
2825 $self->make_tarball($dist_dir);
2826 $self->delete_filetree($dist_dir);
2829 sub ACTION_distcheck {
2832 require ExtUtils::Manifest;
2833 local $^W; # ExtUtils::Manifest is not warnings clean.
2834 my ($missing, $extra) = ExtUtils::Manifest::fullcheck();
2836 return unless @$missing || @$extra;
2838 my $msg = "MANIFEST appears to be out of sync with the distribution\n";
2839 if ( $self->invoked_action eq 'distcheck' ) {
2846 sub _add_to_manifest {
2847 my ($self, $manifest, $lines) = @_;
2848 $lines = [$lines] unless ref $lines;
2850 my $existing_files = $self->_read_manifest($manifest);
2851 return unless defined( $existing_files );
2853 @$lines = grep {!exists $existing_files->{$_}} @$lines
2856 my $mode = (stat $manifest)[2];
2857 chmod($mode | oct(222), $manifest) or die "Can't make $manifest writable: $!";
2859 my $fh = IO::File->new("< $manifest") or die "Can't read $manifest: $!";
2860 my $last_line = (<$fh>)[-1] || "\n";
2861 my $has_newline = $last_line =~ /\n$/;
2864 $fh = IO::File->new(">> $manifest") or die "Can't write to $manifest: $!";
2865 print $fh "\n" unless $has_newline;
2866 print $fh map "$_\n", @$lines;
2868 chmod($mode, $manifest);
2870 $self->log_info(map "Added to $manifest: $_\n", @$lines);
2874 my ($self, $dir) = @_;
2876 unless (eval { require Module::Signature; 1 }) {
2877 $self->log_warn("Couldn't load Module::Signature for 'distsign' action:\n $@\n");
2881 # Add SIGNATURE to the MANIFEST
2883 my $manifest = File::Spec->catfile($dir, 'MANIFEST');
2884 die "Signing a distribution requires a MANIFEST file" unless -e $manifest;
2885 $self->_add_to_manifest($manifest, "SIGNATURE Added here by Module::Build");
2888 # We protect the signing with an eval{} to make sure we get back to
2889 # the right directory after a signature failure. Would be nice if
2890 # Module::Signature took a directory argument.
2892 my $start_dir = $self->cwd;
2893 chdir $dir or die "Can't chdir() to $dir: $!";
2894 eval {local $Module::Signature::Quiet = 1; Module::Signature::sign()};
2895 my @err = $@ ? ($@) : ();
2896 chdir $start_dir or push @err, "Can't chdir() back to $start_dir: $!";
2897 die join "\n", @err if @err;
2900 sub ACTION_distsign {
2903 local $self->{properties}{sign} = 0; # We'll sign it ourselves
2904 $self->depends_on('distdir') unless -d $self->dist_dir;
2906 $self->_sign_dir($self->dist_dir);
2909 sub ACTION_skipcheck {
2912 require ExtUtils::Manifest;
2913 local $^W; # ExtUtils::Manifest is not warnings clean.
2914 ExtUtils::Manifest::skipcheck();
2917 sub ACTION_distclean {
2920 $self->depends_on('realclean');
2921 $self->depends_on('distcheck');
2924 sub do_create_makefile_pl {
2926 require Module::Build::Compat;
2927 $self->delete_filetree('Makefile.PL');
2928 $self->log_info("Creating Makefile.PL\n");
2929 Module::Build::Compat->create_makefile_pl($self->create_makefile_pl, $self, @_);
2930 $self->_add_to_manifest('MANIFEST', 'Makefile.PL');
2933 sub do_create_readme {
2935 $self->delete_filetree('README');
2937 my $docfile = $self->_main_docfile;
2938 unless ( $docfile ) {
2939 $self->log_warn(<<EOF);
2940 Cannot create README: can't determine which file contains documentation;
2941 Must supply either 'dist_version_from', or 'module_name' parameter.
2946 if ( eval {require Pod::Readme; 1} ) {
2947 $self->log_info("Creating README using Pod::Readme\n");
2949 my $parser = Pod::Readme->new;
2950 $parser->parse_from_file($docfile, 'README', @_);
2952 } elsif ( eval {require Pod::Text; 1} ) {
2953 $self->log_info("Creating README using Pod::Text\n");
2955 my $fh = IO::File->new('> README');
2956 if ( defined($fh) ) {
2960 # work around bug in Pod::Text 3.01, which expects
2961 # Pod::Simple::parse_file to take input and output filehandles
2962 # when it actually only takes an input filehandle
2965 $old_parse_file = \&{"Pod::Simple::parse_file"}
2967 local *{"Pod::Simple::parse_file"} = sub {
2969 $self->output_fh($_[1]) if $_[1];
2970 $self->$old_parse_file($_[0]);
2972 if $Pod::Text::VERSION
2973 == 3.01; # Split line to avoid evil version-finder
2975 Pod::Text::pod2text( $docfile, $fh );
2980 "Cannot create 'README' file: Can't open file for writing\n" );
2985 $self->log_warn("Can't load Pod::Readme or Pod::Text to create README\n");
2989 $self->_add_to_manifest('MANIFEST', 'README');
2994 if ( my $pm_file = $self->dist_version_from ) {
2995 (my $pod_file = $pm_file) =~ s/.pm$/.pod/;
2996 return (-e $pod_file ? $pod_file : $pm_file);
3002 sub ACTION_distdir {
3005 $self->depends_on('distmeta');
3007 my $dist_files = $self->_read_manifest('MANIFEST')
3008 or die "Can't create distdir without a MANIFEST file - run 'manifest' action first";
3009 delete $dist_files->{SIGNATURE}; # Don't copy, create a fresh one
3010 die "No files found in MANIFEST - try running 'manifest' action?\n"
3011 unless ($dist_files and keys %$dist_files);
3012 my $metafile = $self->metafile;
3013 $self->log_warn("*** Did you forget to add $metafile to the MANIFEST?\n")
3014 unless exists $dist_files->{$metafile};
3016 my $dist_dir = $self->dist_dir;
3017 $self->delete_filetree($dist_dir);
3018 $self->log_info("Creating $dist_dir\n");
3019 $self->add_to_cleanup($dist_dir);
3021 foreach my $file (keys %$dist_files) {
3022 my $new = $self->copy_if_modified(from => $file, to_dir => $dist_dir, verbose => 0);
3025 $self->_sign_dir($dist_dir) if $self->{properties}{sign};
3028 sub ACTION_disttest {
3031 $self->depends_on('distdir');
3033 my $start_dir = $self->cwd;
3034 my $dist_dir = $self->dist_dir;
3035 chdir $dist_dir or die "Cannot chdir to $dist_dir: $!";
3036 # XXX could be different names for scripts
3038 $self->run_perl_script('Build.PL') # XXX Should this be run w/ --nouse-rcfile
3039 or die "Error executing 'Build.PL' in dist directory: $!";
3040 $self->run_perl_script('Build')
3041 or die "Error executing 'Build' in dist directory: $!";
3042 $self->run_perl_script('Build', [], ['test'])
3043 or die "Error executing 'Build test' in dist directory";
3047 sub _write_default_maniskip {
3049 my $file = shift || 'MANIFEST.SKIP';
3050 my $fh = IO::File->new("> $file")
3051 or die "Can't open $file: $!";
3053 # This is derived from MakeMaker's default MANIFEST.SKIP file with
3057 # Avoid version control files.
3064 # Avoid Makemaker generated and utility files.
3072 # Avoid Module::Build generated and utility files.
3077 # Avoid Devel::Cover generated files
3080 # Avoid temp and backup files.
3089 # Avoid OS-specific files/dirs
3092 # Mac OSX SMB mount metadata files
3094 # Avoid archives of this distribution
3097 # Skip, for example, 'Module-Build-0.27.tar.gz'
3098 print $fh '\b'.$self->dist_name.'-[\d\.\_]+'."\n";
3103 sub ACTION_manifest {
3106 my $maniskip = 'MANIFEST.SKIP';
3107 unless ( -e 'MANIFEST' || -e $maniskip ) {
3108 $self->log_warn("File '$maniskip' does not exist: Creating a default '$maniskip'\n");
3109 $self->_write_default_maniskip($maniskip);
3112 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3113 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3114 ExtUtils::Manifest::mkmanifest();
3119 return "$self->{properties}{dist_name}-$self->{properties}{dist_version}";
3124 return 'PPM-' . $self->dist_dir;
3128 my ($self, $dir) = @_;
3129 return unless -d $dir;
3132 opendir DH, $dir or die "Can't read directory $dir: $!";
3135 while (defined (my $file = readdir DH)) {
3136 my $full_path = File::Spec->catfile($dir, $file);
3137 next if -d $full_path;
3138 push @files, $full_path;
3146 for ($self->{properties}{script_files}) {
3150 # Always coerce into a hash
3151 return $_ if UNIVERSAL::isa($_, 'HASH');
3152 return $_ = { map {$_,1} @$_ } if UNIVERSAL::isa($_, 'ARRAY');
3154 die "'script_files' must be a hashref, arrayref, or string" if ref();
3156 return $_ = { map {$_,1} $self->_files_in( $_ ) } if -d $_;
3157 return $_ = {$_ => 1};
3160 return $_ = { map {$_,1} $self->_files_in( File::Spec->catdir( $self->base_dir, 'bin' ) ) };
3162 BEGIN { *scripts = \&script_files; }
3167 perl => 'http://dev.perl.org/licenses/',
3168 gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3169 apache => 'http://apache.org/licenses/LICENSE-2.0',
3170 artistic => 'http://opensource.org/licenses/artistic-license.php',
3171 lgpl => 'http://opensource.org/licenses/artistic-license.php',
3172 bsd => 'http://www.opensource.org/licenses/bsd-license.php',
3173 gpl => 'http://www.opensource.org/licenses/gpl-license.php',
3174 mit => 'http://opensource.org/licenses/mit-license.php',
3175 mozilla => 'http://opensource.org/licenses/mozilla1.1.php',
3176 open_source => undef,
3177 unrestricted => undef,
3178 restrictive => undef,
3181 sub valid_licenses {
3187 my ($self, $h, $k, $v) = @_;
3188 if (ref $h->{$k} eq 'ARRAY') {
3189 push @{$h->{$k}}, ref $v ? @$v : $v;
3190 } elsif (ref $h->{$k} eq 'HASH') {
3191 $h->{$k}{$_} = $v->{$_} foreach keys %$v;
3197 sub ACTION_distmeta {
3200 $self->do_create_makefile_pl if $self->create_makefile_pl;
3201 $self->do_create_readme if $self->create_readme;
3202 $self->do_create_metafile;
3205 sub do_create_metafile {
3207 return if $self->{wrote_metadata};
3209 my $p = $self->{properties};
3210 my $metafile = $self->metafile;
3212 unless ($p->{license}) {
3213 $self->log_warn("No license specified, setting license = 'unknown'\n");
3214 $p->{license} = 'unknown';
3216 unless (exists $self->valid_licenses->{ $p->{license} }) {
3217 die "Unknown license type '$p->{license}'";
3220 # If we're in the distdir, the metafile may exist and be non-writable.
3221 $self->delete_filetree($metafile);
3222 $self->log_info("Creating $metafile\n");
3224 # Since we're building ourself, we have to do some special stuff
3225 # here: the ConfigData module is found in blib/lib.
3227 if (($self->module_name || '') eq 'Module::Build') {
3228 $self->depends_on('config_data');
3229 push @INC, File::Spec->catdir($self->blib, 'lib');
3232 $self->write_metafile;
3235 sub write_metafile {
3237 my $metafile = $self->metafile;
3239 if ($self->_mb_feature('YAML_support')) {
3243 # We use YAML::Node to get the order nice in the YAML file.
3244 $self->prepare_metadata( my $node = YAML::Node->new({}) );
3246 # YAML API changed after version 0.30
3247 my $yaml_sub = $YAML::VERSION le '0.30' ? \&YAML::StoreFile : \&YAML::DumpFile;
3248 $self->{wrote_metadata} = $yaml_sub->($metafile, $node );
3251 require Module::Build::YAML;
3252 my (%node, @order_keys);
3253 $self->prepare_metadata(\%node, \@order_keys);
3254 $node{_order} = \@order_keys;
3255 &Module::Build::YAML::DumpFile($metafile, \%node);
3256 $self->{wrote_metadata} = 1;
3259 $self->_add_to_manifest('MANIFEST', $metafile);
3262 sub prepare_metadata {
3263 my ($self, $node, $keys) = @_;
3264 my $p = $self->{properties};
3266 # A little helper sub
3267 my $add_node = sub {
3268 my ($name, $val) = @_;
3269 $node->{$name} = $val;
3270 push @$keys, $name if $keys;
3273 foreach (qw(dist_name dist_version dist_author dist_abstract license)) {
3274 (my $name = $_) =~ s/^dist_//;
3275 $add_node->($name, $self->$_());
3276 die "ERROR: Missing required field '$_' for META.yml\n"
3277 unless defined($node->{$name}) && length($node->{$name});
3279 $node->{version} = '' . $node->{version}; # Stringify version objects
3281 if (defined( $self->license ) &&
3282 defined( my $url = $self->valid_licenses->{ $self->license } )) {
3283 $node->{resources}{license} = $url;
3286 foreach ( @{$self->prereq_action_types} ) {
3287 if (exists $p->{$_} and keys %{ $p->{$_} }) {
3288 $add_node->($_, $p->{$_});
3292 if (exists $p->{dynamic_config}) {
3293 $add_node->('dynamic_config', $p->{dynamic_config});
3295 my $pkgs = eval { $self->find_dist_packages };
3297 $self->log_warn("$@\nWARNING: Possible missing or corrupt 'MANIFEST' file.\n" .
3298 "Nothing to enter for 'provides' field in META.yml\n");
3300 $node->{provides} = $pkgs if %$pkgs;
3303 if (exists $p->{no_index}) {
3304 $add_node->('no_index', $p->{no_index});
3307 $add_node->('generated_by', "Module::Build version $Module::Build::VERSION");
3309 $add_node->('meta-spec',
3311 url => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
3314 while (my($k, $v) = each %{$self->meta_add}) {
3315 $add_node->($k, $v);
3318 while (my($k, $v) = each %{$self->meta_merge}) {
3319 $self->_hash_merge($node, $k, $v);
3325 sub _read_manifest {
3326 my ($self, $file) = @_;
3327 return undef unless -e $file;
3329 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3330 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3331 return scalar ExtUtils::Manifest::maniread($file);
3334 sub find_dist_packages {
3337 # Only packages in .pm files are candidates for inclusion here.
3338 # Only include things in the MANIFEST, not things in developer's
3341 my $manifest = $self->_read_manifest('MANIFEST')
3342 or die "Can't find dist packages without a MANIFEST file - run 'manifest' action first";
3345 my %dist_files = map { $self->localize_file_path($_) => $_ }
3348 my @pm_files = grep {exists $dist_files{$_}} keys %{ $self->find_pm_files };
3350 # First, we enumerate all packages & versions,
3351 # seperating into primary & alternative candidates
3353 foreach my $file (@pm_files) {
3354 next if $dist_files{$file} =~ m{^t/}; # Skip things in t/
3356 my @path = split( /\//, $dist_files{$file} );
3357 (my $prime_package = join( '::', @path[1..$#path] )) =~ s/\.pm$//;
3359 my $pm_info = Module::Build::ModuleInfo->new_from_file( $file );
3361 foreach my $package ( $pm_info->packages_inside ) {
3362 next if $package eq 'main'; # main can appear numerous times, ignore
3363 next if grep /^_/, split( /::/, $package ); # private package, ignore
3365 my $version = $pm_info->version( $package );
3367 if ( $package eq $prime_package ) {
3368 if ( exists( $prime{$package} ) ) {
3369 # M::B::ModuleInfo will handle this conflict
3370 die "Unexpected conflict in '$package'; multiple versions found.\n";
3372 $prime{$package}{file} = $dist_files{$file};
3373 $prime{$package}{version} = $version if defined( $version );
3376 push( @{$alt{$package}}, {
3377 file => $dist_files{$file},
3378 version => $version,
3384 # Then we iterate over all the packages found above, identifying conflicts
3385 # and selecting the "best" candidate for recording the file & version
3387 foreach my $package ( keys( %alt ) ) {
3388 my $result = $self->_resolve_module_versions( $alt{$package} );
3390 if ( exists( $prime{$package} ) ) { # primary package selected
3392 if ( $result->{err} ) {
3393 # Use the selected primary package, but there are conflicting
3394 # errors amoung multiple alternative packages that need to be
3397 "Found conflicting versions for package '$package'\n" .
3398 " $prime{$package}{file} ($prime{$package}{version})\n" .
3402 } elsif ( defined( $result->{version} ) ) {
3403 # There is a primary package selected, and exactly one
3404 # alternative package
3406 if ( exists( $prime{$package}{version} ) &&
3407 defined( $prime{$package}{version} ) ) {
3408 # Unless the version of the primary package agrees with the
3409 # version of the alternative package, report a conflict
3410 if ( $self->compare_versions( $prime{$package}{version}, '!=',
3411 $result->{version} ) ) {
3413 "Found conflicting versions for package '$package'\n" .
3414 " $prime{$package}{file} ($prime{$package}{version})\n" .
3415 " $result->{file} ($result->{version})\n"
3420 # The prime package selected has no version so, we choose to
3421 # use any alternative package that does have a version
3422 $prime{$package}{file} = $result->{file};
3423 $prime{$package}{version} = $result->{version};
3427 # no alt package found with a version, but we have a prime
3428 # package so we use it whether it has a version or not
3431 } else { # No primary package was selected, use the best alternative
3433 if ( $result->{err} ) {
3435 "Found conflicting versions for package '$package'\n" .
3440 # Despite possible conflicting versions, we choose to record
3441 # something rather than nothing
3442 $prime{$package}{file} = $result->{file};
3443 $prime{$package}{version} = $result->{version}
3444 if defined( $result->{version} );
3448 # Stringify versions. Can't use exists() here because of bug in YAML::Node.
3449 for (grep defined $_->{version}, values %prime) {
3450 $_->{version} = '' . $_->{version};
3456 # seperate out some of the conflict resolution logic from
3457 # $self->find_dist_packages(), above, into a helper function.
3459 sub _resolve_module_versions {
3462 my $packages = shift;
3464 my( $file, $version );
3466 foreach my $p ( @$packages ) {
3467 if ( defined( $p->{version} ) ) {
3468 if ( defined( $version ) ) {
3469 if ( $self->compare_versions( $version, '!=', $p->{version} ) ) {
3470 $err .= " $p->{file} ($p->{version})\n";
3472 # same version declared multiple times, ignore
3476 $version = $p->{version};
3479 $file ||= $p->{file} if defined( $p->{file} );
3483 $err = " $file ($version)\n" . $err;
3488 version => $version,
3496 my ($self, $dir, $file) = @_;
3499 $self->log_info("Creating $file.tar.gz\n");
3501 if ($self->{args}{tar}) {
3502 my $tar_flags = $self->verbose ? 'cvf' : 'cf';
3503 $self->do_system($self->split_like_shell($self->{args}{tar}), $tar_flags, "$file.tar", $dir);
3504 $self->do_system($self->split_like_shell($self->{args}{gzip}), "$file.tar") if $self->{args}{gzip};
3506 require Archive::Tar;
3507 # Archive::Tar versions >= 1.09 use the following to enable a compatibility
3508 # hack so that the resulting archive is compatible with older clients.
3509 $Archive::Tar::DO_NOT_USE_PREFIX = 0;
3510 my $files = $self->rscan_dir($dir);
3511 Archive::Tar->create_archive("$file.tar.gz", 1, @$files);
3517 my( $type, $value ) = ( @_, '<empty>' );
3519 Carp::croak( 'Type argument missing' )
3520 unless defined( $type );
3522 my $map = $self->{properties}{install_path};
3523 return $map unless @_;
3525 # delete existing value if $value is literal undef()
3526 unless ( defined( $value ) ) {
3527 delete( $map->{$type} );
3531 # return existing value if no new $value is given
3532 if ( $value eq '<empty>' ) {
3533 return undef unless exists $map->{$type};
3534 return $map->{$type};
3537 # set value if $value is a valid relative path
3538 return $map->{$type} = $value;
3541 sub install_base_relpaths {
3542 # Usage: install_base_relpaths(), install_base_relpaths('lib'),
3543 # or install_base_relpaths('lib' => $value);
3545 my $map = $self->{properties}{install_base_relpaths};
3546 return $map unless @_;
3547 return $self->_relpaths($map, @_);
3551 # Translated from ExtUtils::MM_Any::init_INSTALL_from_PREFIX
3552 sub prefix_relative {
3553 my ($self, $type) = @_;
3554 my $installdirs = $self->installdirs;
3556 my $relpath = $self->install_sets($installdirs)->{$type};
3558 return $self->_prefixify($relpath,
3559 $self->original_prefix($installdirs),
3566 my( $map, $type, $value ) = ( @_, '<empty>' );
3568 Carp::croak( 'Type argument missing' )
3569 unless defined( $type );
3573 # delete existing value if $value is literal undef()
3574 unless ( defined( $value ) ) {
3575 delete( $map->{$type} );
3579 # return existing value if no new $value is given
3580 elsif ( $value eq '<empty>' ) {
3581 return undef unless exists $map->{$type};
3582 @value = @{ $map->{$type} };
3585 # set value if $value is a valid relative path
3587 Carp::croak( "Value must be a relative path" )
3588 if File::Spec::Unix->file_name_is_absolute($value);
3590 @value = split( /\//, $value );
3591 $map->{$type} = \@value;
3594 return File::Spec->catdir( @value );
3597 # Defaults to use in case the config install paths cannot be prefixified.
3598 sub prefix_relpaths {
3599 # Usage: prefix_relpaths('site'), prefix_relpaths('site', 'lib'),
3600 # or prefix_relpaths('site', 'lib' => $value);
3602 my $installdirs = shift || $self->installdirs;
3603 my $map = $self->{properties}{prefix_relpaths}{$installdirs};
3604 return $map unless @_;
3605 return $self->_relpaths($map, @_);
3609 # Translated from ExtUtils::MM_Unix::prefixify()
3611 my($self, $path, $sprefix, $type) = @_;
3613 my $rprefix = $self->prefix;
3614 $rprefix .= '/' if $sprefix =~ m|/$|;
3616 $self->log_verbose(" prefixify $path from $sprefix to $rprefix\n")
3617 if defined( $path ) && length( $path );
3619 if( !defined( $path ) || ( length( $path ) == 0 ) ) {
3620 $self->log_verbose(" no path to prefixify, falling back to default.\n");
3621 return $self->_prefixify_default( $type, $rprefix );
3622 } elsif( !File::Spec->file_name_is_absolute($path) ) {
3623 $self->log_verbose(" path is relative, not prefixifying.\n");
3624 } elsif( $sprefix eq $rprefix ) {
3625 $self->log_verbose(" no new prefix.\n");
3626 } elsif( $path !~ s{^\Q$sprefix\E\b}{}s ) {
3627 $self->log_verbose(" cannot prefixify, falling back to default.\n");
3628 return $self->_prefixify_default( $type, $rprefix );
3631 $self->log_verbose(" now $path in $rprefix\n");
3636 sub _prefixify_default {
3639 my $rprefix = shift;
3641 my $default = $self->prefix_relpaths($self->installdirs, $type);
3643 $self->log_verbose(" no default install location for type '$type', using prefix '$rprefix'.\n");
3650 sub install_destination {
3651 my ($self, $type) = @_;
3653 return $self->install_path($type) if $self->install_path($type);
3655 if ( $self->install_base ) {
3656 my $relpath = $self->install_base_relpaths($type);
3657 return $relpath ? File::Spec->catdir($self->install_base, $relpath) : undef;
3660 if ( $self->prefix ) {
3661 my $relpath = $self->prefix_relative($type);
3662 return $relpath ? File::Spec->catdir($self->prefix, $relpath) : undef;
3665 return $self->install_sets($self->installdirs)->{$type};
3672 if ( $self->install_base ) {
3673 %types = %{$self->install_base_relpaths};
3674 } elsif ( $self->prefix ) {
3675 %types = %{$self->prefix_relpaths};
3677 %types = %{$self->install_sets($self->installdirs)};
3680 %types = (%types, %{$self->install_path});
3682 return sort keys %types;
3686 my ($self, $blib) = @_;
3687 $blib ||= $self->blib;
3689 my( %map, @skipping );
3690 foreach my $type ($self->install_types) {
3691 my $localdir = File::Spec->catdir( $blib, $type );
3692 next unless -e $localdir;
3694 if (my $dest = $self->install_destination($type)) {
3695 $map{$localdir} = $dest;
3697 push( @skipping, $type );
3702 "WARNING: Can't figure out install path for types: @skipping\n" .
3703 "Files will not be installed.\n"
3706 # Write the packlist into the same place as ExtUtils::MakeMaker.
3707 if ($self->create_packlist and my $module_name = $self->module_name) {
3708 my $archdir = $self->install_destination('arch');
3709 my @ext = split /::/, $module_name;
3710 $map{write} = File::Spec->catdir($archdir, 'auto', @ext, '.packlist');
3714 if (length(my $destdir = $self->destdir || '')) {
3715 foreach (keys %map) {
3716 # Need to remove volume from $map{$_} using splitpath, or else
3717 # we'll create something crazy like C:\Foo\Bar\E:\Baz\Quux
3718 my ($volume, $path) = File::Spec->splitpath( $map{$_}, 1 );
3719 $map{$_} = File::Spec->catdir($destdir, $path);
3723 $map{read} = ''; # To keep ExtUtils::Install quiet
3730 foreach my $action (@_) {
3731 $self->_call_action($action);
3736 my ($self, $dir, $pattern) = @_;
3738 local $_; # find() can overwrite $_, so protect ourselves
3739 my $subr = !$pattern ? sub {push @result, $File::Find::name} :
3740 !ref($pattern) || (ref $pattern eq 'Regexp') ? sub {push @result, $File::Find::name if /$pattern/} :
3741 ref($pattern) eq 'CODE' ? sub {push @result, $File::Find::name if $pattern->()} :
3742 die "Unknown pattern type";
3744 File::Find::find({wanted => $subr, no_chdir => 1}, $dir);
3748 sub delete_filetree {
3753 $self->log_info("Deleting $_\n");
3754 File::Path::rmtree($_, 0, 0);
3755 die "Couldn't remove '$_': $!\n" if -e $_;
3761 sub autosplit_file {
3762 my ($self, $file, $to) = @_;
3764 my $dir = File::Spec->catdir($to, 'lib', 'auto');
3765 AutoSplit::autosplit($file, $dir);
3769 # Returns a CBuilder object
3772 my $p = $self->{properties};
3773 return $p->{_cbuilder} if $p->{_cbuilder};
3774 return unless $self->_mb_feature('C_support');
3776 require ExtUtils::CBuilder;
3777 return $p->{_cbuilder} = ExtUtils::CBuilder->new(config => $self->config);
3780 sub have_c_compiler {
3783 my $p = $self->{properties};
3784 return $p->{have_compiler} if defined $p->{have_compiler};
3786 $self->log_verbose("Checking if compiler tools configured... ");
3787 my $b = $self->_cbuilder;
3788 my $have = $b && $b->have_compiler;
3789 $self->log_verbose($have ? "ok.\n" : "failed.\n");
3790 return $p->{have_compiler} = $have;
3794 my ($self, $file, %args) = @_;
3795 my $b = $self->_cbuilder
3796 or die "Module::Build is not configured with C_support";
3798 my $obj_file = $b->object_file($file);
3799 $self->add_to_cleanup($obj_file);
3800 return $obj_file if $self->up_to_date($file, $obj_file);
3802 $b->compile(source => $file,
3803 defines => $args{defines},
3804 object_file => $obj_file,
3805 include_dirs => $self->include_dirs,
3806 extra_compiler_flags => $self->extra_compiler_flags,
3813 my ($self, $to, $file_base) = @_;
3814 my $p = $self->{properties}; # For convenience
3816 my $spec = $self->_infer_xs_spec($file_base);
3818 $self->add_to_cleanup($spec->{lib_file});
3820 my $objects = $p->{objects} || [];
3822 return $spec->{lib_file}
3823 if $self->up_to_date([$spec->{obj_file}, @$objects],
3826 my $module_name = $self->module_name;
3827 $module_name ||= $spec->{module_name};
3829 my $b = $self->_cbuilder
3830 or die "Module::Build is not configured with C_support";
3832 module_name => $module_name,
3833 objects => [$spec->{obj_file}, @$objects],
3834 lib_file => $spec->{lib_file},
3835 extra_linker_flags => $p->{extra_linker_flags} );
3837 return $spec->{lib_file};
3841 my ($self, $file, %args) = @_;
3843 $self->log_info("$file -> $args{outfile}\n");
3845 if (eval {require ExtUtils::ParseXS; 1}) {
3847 ExtUtils::ParseXS::process_file(
3850 output => $args{outfile},
3853 # Ok, I give up. Just use backticks.
3855 my $xsubpp = Module::Build::ModuleInfo->find_module_by_name('ExtUtils::xsubpp')
3856 or die "Can't find ExtUtils::xsubpp in INC (@INC)";
3859 push @typemaps, Module::Build::ModuleInfo->find_module_by_name('ExtUtils::typemap', \@INC);
3860 my $lib_typemap = Module::Build::ModuleInfo->find_module_by_name('typemap', ['lib']);
3861 if (defined $lib_typemap and -e $lib_typemap) {
3862 push @typemaps, 'typemap';
3864 @typemaps = map {+'-typemap', $_} @typemaps;
3866 my $cf = $self->{config};
3867 my $perl = $self->{properties}{perl};
3869 my @command = ($perl, "-I".$cf->get('installarchlib'), "-I".$cf->get('installprivlib'), $xsubpp, '-noprototypes',
3872 $self->log_info("@command\n");
3873 my $fh = IO::File->new("> $args{outfile}") or die "Couldn't write $args{outfile}: $!";
3874 print {$fh} $self->_backticks(@command);
3879 sub split_like_shell {
3880 my ($self, $string) = @_;
3882 return () unless defined($string);
3883 return @$string if UNIVERSAL::isa($string, 'ARRAY');
3884 $string =~ s/^\s+|\s+$//g;
3885 return () unless length($string);
3887 return Text::ParseWords::shellwords($string);
3890 sub run_perl_script {
3891 my ($self, $script, $preargs, $postargs) = @_;
3892 foreach ($preargs, $postargs) {
3893 $_ = [ $self->split_like_shell($_) ] unless ref();
3895 return $self->run_perl_command([@$preargs, $script, @$postargs]);
3898 sub run_perl_command {
3899 # XXX Maybe we should accept @args instead of $args? Must resolve
3900 # this before documenting.
3901 my ($self, $args) = @_;
3902 $args = [ $self->split_like_shell($args) ] unless ref($args);
3903 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
3905 # Make sure our local additions to @INC are propagated to the subprocess
3906 local $ENV{PERL5LIB} = join $self->config('path_sep'), $self->_added_to_INC;
3908 return $self->do_system($perl, @$args);
3911 # Infer various data from the path of the input filename
3912 # that is needed to create output files.
3913 # The input filename is expected to be of the form:
3914 # lib/Module/Name.ext or Module/Name.ext
3915 sub _infer_xs_spec {
3919 my $cf = $self->{config};
3923 my( $v, $d, $f ) = File::Spec->splitpath( $file );
3924 my @d = File::Spec->splitdir( $d );
3925 (my $file_base = $f) =~ s/\.[^.]+$//i;
3927 $spec{base_name} = $file_base;
3929 $spec{src_dir} = File::Spec->catpath( $v, $d, '' );
3932 shift( @d ) while @d && ($d[0] eq 'lib' || $d[0] eq '');
3933 pop( @d ) while @d && $d[-1] eq '';
3934 $spec{module_name} = join( '::', (@d, $file_base) );
3936 $spec{archdir} = File::Spec->catdir($self->blib, 'arch', 'auto',
3939 $spec{bs_file} = File::Spec->catfile($spec{archdir}, "${file_base}.bs");
3941 $spec{lib_file} = File::Spec->catfile($spec{archdir},
3942 "${file_base}.".$cf->get('dlext'));
3944 $spec{c_file} = File::Spec->catfile( $spec{src_dir},
3947 $spec{obj_file} = File::Spec->catfile( $spec{src_dir},
3948 "${file_base}".$cf->get('obj_ext') );
3954 my ($self, $file) = @_;
3956 my $spec = $self->_infer_xs_spec($file);
3958 # File name, minus the suffix
3959 (my $file_base = $file) =~ s/\.[^.]+$//;
3962 $self->add_to_cleanup($spec->{c_file});
3964 unless ($self->up_to_date($file, $spec->{c_file})) {
3965 $self->compile_xs($file, outfile => $spec->{c_file});
3969 my $v = $self->dist_version;
3970 $self->compile_c($spec->{c_file},
3971 defines => {VERSION => qq{"$v"}, XS_VERSION => qq{"$v"}});
3974 File::Path::mkpath($spec->{archdir}, 0, oct(777)) unless -d $spec->{archdir};
3977 $self->add_to_cleanup($spec->{bs_file});
3978 unless ($self->up_to_date($file, $spec->{bs_file})) {
3979 require ExtUtils::Mkbootstrap;
3980 $self->log_info("ExtUtils::Mkbootstrap::Mkbootstrap('$spec->{bs_file}')\n");
3981 ExtUtils::Mkbootstrap::Mkbootstrap($spec->{bs_file}); # Original had $BSLOADLIBS - what's that?
3982 {my $fh = IO::File->new(">> $spec->{bs_file}")} # create
3983 utime((time)x2, $spec->{bs_file}); # touch
3987 $self->link_c($spec->{archdir}, $file_base);
3991 my ($self, @cmd) = @_;
3992 $self->log_info("@cmd\n");
3994 # Some systems proliferate huge PERL5LIBs, try to ameliorate:
3996 my $sep = $self->config('path_sep');
3997 local $ENV{PERL5LIB} =
3998 ( length($ENV{PERL5LIB}) < 500
4000 : join $sep, grep { ! $seen{$_}++ and -d $_ } split($sep, $ENV{PERL5LIB})
4003 my $status = system(@cmd);
4004 if ($status and $! =~ /Argument list too long/i) {
4005 my $env_entries = '';
4006 foreach (sort keys %ENV) { $env_entries .= "$_=>".length($ENV{$_})."; " }
4007 warn "'Argument list' was 'too long', env lengths are $env_entries";
4012 sub copy_if_modified {
4016 : ( from => shift, to_dir => shift, flatten => shift )
4018 $args{verbose} = !$self->quiet
4019 unless exists $args{verbose};
4021 my $file = $args{from};
4022 unless (defined $file and length $file) {
4023 die "No 'from' parameter given to copy_if_modified";
4027 if (defined $args{to} and length $args{to}) {
4028 $to_path = $args{to};
4029 } elsif (defined $args{to_dir} and length $args{to_dir}) {
4030 $to_path = File::Spec->catfile( $args{to_dir}, $args{flatten}
4031 ? File::Basename::basename($file)
4034 die "No 'to' or 'to_dir' parameter given to copy_if_modified";
4037 return if $self->up_to_date($file, $to_path); # Already fresh
4040 local $self->{properties}{quiet} = 1;
4041 $self->delete_filetree($to_path); # delete destination if exists
4044 # Create parent directories
4045 File::Path::mkpath(File::Basename::dirname($to_path), 0, oct(777));
4047 $self->log_info("Copying $file -> $to_path\n") if $args{verbose};
4048 File::Copy::copy($file, $to_path) or die "Can't copy('$file', '$to_path'): $!";
4049 # mode is read-only + (executable if source is executable)
4050 my $mode = oct(444) | ( $self->is_executable($file) ? oct(111) : 0 );
4051 chmod( $mode, $to_path );
4057 my ($self, $source, $derived) = @_;
4058 $source = [$source] unless ref $source;
4059 $derived = [$derived] unless ref $derived;
4061 return 0 if grep {not -e} @$derived;
4063 my $most_recent_source = time / (24*60*60);
4064 foreach my $file (@$source) {
4066 $self->log_warn("Can't find source file $file for up-to-date check");
4069 $most_recent_source = -M _ if -M _ < $most_recent_source;
4072 foreach my $derived (@$derived) {
4073 return 0 if -M $derived > $most_recent_source;
4079 my ($self, $first, $second) = @_;
4080 # File::Spec doesn't have an easy way to check whether one directory
4081 # is inside another, unfortunately.
4083 ($first, $second) = map File::Spec->canonpath($_), ($first, $second);
4084 my @first_dirs = File::Spec->splitdir($first);
4085 my @second_dirs = File::Spec->splitdir($second);
4087 return 0 if @second_dirs < @first_dirs;
4089 my $is_same = ( File::Spec->case_tolerant
4090 ? sub {lc(shift()) eq lc(shift())}
4091 : sub {shift() eq shift()} );
4093 while (@first_dirs) {
4094 return 0 unless $is_same->(shift @first_dirs, shift @second_dirs);
4106 Module::Build::Base - Default methods for Module::Build
4110 Please see the Module::Build documentation.
4114 The C<Module::Build::Base> module defines the core functionality of
4115 C<Module::Build>. Its methods may be overridden by any of the
4116 platform-dependent modules in the C<Module::Build::Platform::>
4117 namespace, but the intention here is to make this base module as
4118 platform-neutral as possible. Nicely enough, Perl has several core
4119 tools available in the C<File::> namespace for doing this, so the task
4120 isn't very difficult.
4122 Please see the C<Module::Build> documentation for more details.
4126 Ken Williams <kwilliams@cpan.org>
4130 Copyright (c) 2001-2006 Ken Williams. All rights reserved.
4132 This library is free software; you can redistribute it and/or
4133 modify it under the same terms as Perl itself.
4137 perl(1), Module::Build(3)