1 # -*- mode: cperl; tab-width: 8; indent-tabs-mode: nil; basic-offset: 2 -*-
2 # vim:ts=8:sw=2:et:sta:sts=2
3 package Module::Build::Base;
8 $VERSION = eval $VERSION;
9 BEGIN { require 5.00503 }
16 use File::Basename ();
17 use File::Spec 0.82 ();
19 use Module::Build::Dumper ();
21 use Text::ParseWords ();
23 use Module::Build::ModuleInfo;
24 use Module::Build::Notes;
25 use Module::Build::Config;
28 #################### Constructors ###########################
30 my $self = shift()->_construct(@_);
32 $self->{invoked_action} = $self->{action} ||= 'Build_PL';
33 $self->cull_args(@ARGV);
35 die "Too early to specify a build action '$self->{action}'. Do 'Build $self->{action}' instead.\n"
36 if $self->{action} && $self->{action} ne 'Build_PL';
38 $self->check_manifest;
40 $self->check_autofeatures;
45 $self->_set_install_paths;
46 $self->_find_nested_builds;
53 my $self = $package->_construct(@_);
56 # If someone called Module::Build->current() or
57 # Module::Build->new_from_context() and the correct class to use is
58 # actually a *subclass* of Module::Build, we may need to load that
59 # subclass here and re-delegate the resume() method to it.
60 unless ( UNIVERSAL::isa($package, $self->build_class) ) {
61 my $build_class = $self->build_class;
62 my $config_dir = $self->config_dir || '_build';
63 my $build_lib = File::Spec->catdir( $config_dir, 'lib' );
64 unshift( @INC, $build_lib );
65 unless ( $build_class->can('new') ) {
66 eval "require $build_class; 1" or die "Failed to re-load '$build_class': $@";
68 return $build_class->resume(@_);
71 unless ($self->_perl_is_same($self->{properties}{perl})) {
72 my $perl = $self->find_perl_interpreter;
73 $self->log_warn(" * WARNING: Configuration was initially created with '$self->{properties}{perl}',\n".
74 " but we are now using '$perl'.\n");
77 $self->cull_args(@ARGV);
79 unless ($self->allow_mb_mismatch) {
80 my $mb_version = $Module::Build::VERSION;
81 die(" * ERROR: Configuration was initially created with Module::Build version '$self->{properties}{mb_version}',\n".
82 " but we are now using version '$mb_version'. Please re-run the Build.PL or Makefile.PL script,\n".
83 " or use --allow_mb_mismatch 1 to skip this version check.\n")
84 if $mb_version ne $self->{properties}{mb_version};
87 $self->{invoked_action} = $self->{action} ||= 'build';
89 $self->_set_install_paths;
94 sub new_from_context {
95 my ($package, %args) = @_;
97 # XXX Read the META.yml and see whether we need to run the Build.PL?
99 # Run the Build.PL. We use do() rather than run_perl_script() so
100 # that it runs in this process rather than a subprocess, because we
101 # need to make sure that the environment is the same during Build.PL
102 # as it is during resume() (and thereafter).
104 local @ARGV = $package->unparse_args(\%args);
108 return $package->resume;
112 # hmm, wonder what the right thing to do here is
114 return shift()->resume;
118 my ($package, %input) = @_;
120 my $args = delete $input{args} || {};
121 my $config = delete $input{config} || {};
125 config => Module::Build::Config->new(values => $config),
127 base_dir => $package->cwd,
128 mb_version => $Module::Build::VERSION,
134 $self->_set_defaults;
135 my ($p, $ph) = ($self->{properties}, $self->{phash});
137 foreach (qw(notes config_data features runtime_params cleanup auto_features)) {
138 my $file = File::Spec->catfile($self->config_dir, $_);
139 $ph->{$_} = Module::Build::Notes->new(file => $file);
140 $ph->{$_}->restore if -e $file;
141 if (exists $p->{$_}) {
142 my $vals = delete $p->{$_};
143 while (my ($k, $v) = each %$vals) {
149 # The following warning could be unnecessary if the user is running
150 # an embedded perl, but there aren't too many of those around, and
151 # embedded perls aren't usually used to install modules, and the
152 # installation process sometimes needs to run external scripts
153 # (e.g. to run tests).
154 $p->{perl} = $self->find_perl_interpreter
155 or $self->log_warn("Warning: Can't locate your perl binary");
157 my $blibdir = sub { File::Spec->catdir($p->{blib}, @_) };
158 $p->{bindoc_dirs} ||= [ $blibdir->("script") ];
159 $p->{libdoc_dirs} ||= [ $blibdir->("lib"), $blibdir->("arch") ];
161 $p->{dist_author} = [ $p->{dist_author} ] if defined $p->{dist_author} and not ref $p->{dist_author};
164 $p->{requires} = delete $p->{prereq} if defined $p->{prereq};
165 $p->{script_files} = delete $p->{scripts} if defined $p->{scripts};
168 for ('extra_compiler_flags', 'extra_linker_flags') {
169 $p->{$_} = [ $self->split_like_shell($p->{$_}) ] if exists $p->{$_};
172 $self->add_to_cleanup( @{delete $p->{add_to_cleanup}} )
173 if $p->{add_to_cleanup};
178 ################## End constructors #########################
180 sub log_info { print @_ unless shift()->quiet }
181 sub log_verbose { shift()->log_info(@_) if $_[0]->verbose }
183 # Try to make our call stack invisible
185 if (@_ and $_[-1] !~ /\n$/) {
186 my (undef, $file, $line) = caller();
187 warn @_, " at $file line $line.\n";
194 sub _set_install_paths {
196 my $c = $self->{config};
197 my $p = $self->{properties};
199 my @libstyle = $c->get('installstyle') ?
200 File::Spec->splitdir($c->get('installstyle')) : qw(lib perl5);
201 my $arch = $c->get('archname');
202 my $version = $c->get('version');
204 my $bindoc = $c->get('installman1dir') || undef;
205 my $libdoc = $c->get('installman3dir') || undef;
207 my $binhtml = $c->get('installhtml1dir') || $c->get('installhtmldir') || undef;
208 my $libhtml = $c->get('installhtml3dir') || $c->get('installhtmldir') || undef;
213 lib => $c->get('installprivlib'),
214 arch => $c->get('installarchlib'),
215 bin => $c->get('installbin'),
216 script => $c->get('installscript'),
223 lib => $c->get('installsitelib'),
224 arch => $c->get('installsitearch'),
225 bin => $c->get('installsitebin') || $c->get('installbin'),
226 script => $c->get('installsitescript') ||
227 $c->get('installsitebin') || $c->get('installscript'),
228 bindoc => $c->get('installsiteman1dir') || $bindoc,
229 libdoc => $c->get('installsiteman3dir') || $libdoc,
230 binhtml => $c->get('installsitehtml1dir') || $binhtml,
231 libhtml => $c->get('installsitehtml3dir') || $libhtml,
234 lib => $c->get('installvendorlib'),
235 arch => $c->get('installvendorarch'),
236 bin => $c->get('installvendorbin') || $c->get('installbin'),
237 script => $c->get('installvendorscript') ||
238 $c->get('installvendorbin') || $c->get('installscript'),
239 bindoc => $c->get('installvendorman1dir') || $bindoc,
240 libdoc => $c->get('installvendorman3dir') || $libdoc,
241 binhtml => $c->get('installvendorhtml1dir') || $binhtml,
242 libhtml => $c->get('installvendorhtml3dir') || $libhtml,
246 $p->{original_prefix} =
248 core => $c->get('installprefixexp') || $c->get('installprefix') ||
249 $c->get('prefixexp') || $c->get('prefix') || '',
250 site => $c->get('siteprefixexp'),
251 vendor => $c->get('usevendorprefix') ? $c->get('vendorprefixexp') : '',
253 $p->{original_prefix}{site} ||= $p->{original_prefix}{core};
255 # Note: you might be tempted to use $Config{installstyle} here
256 # instead of hard-coding lib/perl5, but that's been considered and
257 # (at least for now) rejected. `perldoc Config` has some wisdom
259 $p->{install_base_relpaths} =
261 lib => ['lib', 'perl5'],
262 arch => ['lib', 'perl5', $arch],
265 bindoc => ['man', 'man1'],
266 libdoc => ['man', 'man3'],
271 $p->{prefix_relpaths} =
275 arch => [@libstyle, $version, $arch],
278 bindoc => ['man', 'man1'],
279 libdoc => ['man', 'man3'],
285 arch => [@libstyle, $version, $arch],
288 bindoc => ['man', 'man1'],
289 libdoc => ['man', 'man3'],
294 lib => [@libstyle, 'site_perl'],
295 arch => [@libstyle, 'site_perl', $version, $arch],
298 bindoc => ['man', 'man1'],
299 libdoc => ['man', 'man3'],
307 sub _find_nested_builds {
309 my $r = $self->recurse_into or return;
312 if (!ref($r) && $r eq 'auto') {
314 opendir DH, $self->base_dir
315 or die "Can't scan directory " . $self->base_dir . " for nested builds: $!";
316 while (defined($file = readdir DH)) {
317 my $subdir = File::Spec->catdir( $self->base_dir, $file );
318 next unless -d $subdir;
319 push @r, $subdir if -e File::Spec->catfile( $subdir, 'Build.PL' );
323 $self->recurse_into(\@r);
331 # Returns a string that can become [part of] a command line with
332 # proper quoting so that the subprocess sees this same list of args.
333 my ($self, @args) = @_;
338 if ( /^[^\s*?!\$<>;\\|'"\[\]\{\}]+$/ ) {
342 # XXX this will obviously have to improve - is there already a
343 # core module lying around that does proper quoting?
345 push @quoted, qq('$_');
349 return join " ", @quoted;
353 my ($self, @cmd) = @_;
354 if ($self->have_forkpipe) {
356 my $pid = open *FH, "-|";
358 return wantarray ? <FH> : join '', <FH>;
360 die "Can't execute @cmd: $!\n" unless defined $pid;
361 exec { $cmd[0] } @cmd;
364 my $cmd = $self->_quote_args(@cmd);
369 # Tells us whether the construct open($fh, '-|', @command) is
370 # supported. It would probably be better to dynamically sense this.
371 sub have_forkpipe { 1 }
373 # Determine whether a given binary is the same as the perl
374 # (configuration) that started this process.
376 my ($self, $perl) = @_;
380 # When run from the perl core, @INC will include the directories
381 # where perl is yet to be installed. We need to reference the
382 # absolute path within the source distribution where it can find
383 # it's Config.pm This also prevents us from picking up a Config.pm
384 # from a different configuration that happens to be already
386 if ($ENV{PERL_CORE}) {
387 push @cmd, '-I' . File::Spec->catdir(File::Basename::dirname($perl), 'lib');
390 push @cmd, qw(-MConfig=myconfig -e print -e myconfig);
391 return $self->_backticks(@cmd) eq Config->myconfig;
394 # cache _discover_perl_interpreter() results
397 sub find_perl_interpreter {
400 return $known_perl if defined($known_perl);
401 return $known_perl = $self->_discover_perl_interpreter;
405 # Returns the absolute path of the perl interperter used to invoke
406 # this process. The path is derived from $^X or $Config{perlpath}. On
407 # some platforms $^X contains the complete absolute path of the
408 # interpreter, on other it may contain a relative path, or simply
409 # 'perl'. This can also vary depending on whether a path was supplied
410 # when perl was invoked. Additionally, the value in $^X may omit the
411 # executable extension on platforms that use one. It's a fatal error
412 # if the interpreter can't be found because it can result in undefined
413 # behavior by routines that depend on it (generating errors or
414 # invoking the wrong perl.)
415 sub _discover_perl_interpreter {
417 my $c = ref($proto) ? $proto->{config} : 'Module::Build::Config';
420 my $perl_basename = File::Basename::basename($perl);
424 # Try 1, Check $^X for absolute path
425 push( @potential_perls, $perl )
426 if File::Spec->file_name_is_absolute($perl);
428 # Try 2, Check $^X for a valid relative path
429 my $abs_perl = File::Spec->rel2abs($perl);
430 push( @potential_perls, $abs_perl );
432 # Try 3, Last ditch effort: These two option use hackery to try to locate
433 # a suitable perl. The hack varies depending on whether we are running
434 # from an installed perl or an uninstalled perl in the perl source dist.
435 if ($ENV{PERL_CORE}) {
437 # Try 3.A, If we are in a perl source tree, running an uninstalled
438 # perl, we can keep moving up the directory tree until we find our
439 # binary. We wouldn't do this under any other circumstances.
441 # CBuilder is also in the core, so it should be available here
442 require ExtUtils::CBuilder;
443 my $perl_src = Cwd::realpath( ExtUtils::CBuilder->perl_src );
444 if ( defined($perl_src) && length($perl_src) ) {
446 File::Spec->rel2abs(File::Spec->catfile( $perl_src, $perl_basename ));
447 push( @potential_perls, $uninstperl );
452 # Try 3.B, First look in $Config{perlpath}, then search the user's
453 # PATH. We do not want to do either if we are running from an
454 # uninstalled perl in a perl source tree.
456 push( @potential_perls, $c->get('perlpath') );
458 push( @potential_perls,
459 map File::Spec->catfile($_, $perl_basename), File::Spec->path() );
462 # Now that we've enumerated the potential perls, it's time to test
463 # them to see if any of them match our configuration, returning the
464 # absolute path of the first successful match.
465 my $exe = $c->get('exe_ext');
466 foreach my $thisperl ( @potential_perls ) {
469 $thisperl .= $exe unless $thisperl =~ m/$exe$/i;
472 if ( -f $thisperl && $proto->_perl_is_same($thisperl) ) {
477 # We've tried all alternatives, and didn't find a perl that matches
478 # our configuration. Throw an exception, and list alternatives we tried.
479 my @paths = map File::Basename::dirname($_), @potential_perls;
480 die "Can't locate the perl binary used to run this script " .
484 sub _is_interactive {
485 return -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ; # Pipe?
488 # NOTE this is a blocking operation if(-t STDIN)
491 return $ENV{PERL_MM_USE_DEFAULT} ||
492 ( !$self->_is_interactive && eof STDIN );
497 return undef if $self->_is_unattended;
499 my $answer = <STDIN>;
500 chomp $answer if defined $answer;
507 or die "prompt() called without a prompt message";
509 # use a list to distinguish a default of undef() from no default
511 @def = (shift) if @_;
512 # use dispdef for output
513 my @dispdef = scalar(@def) ?
514 ('[', (defined($def[0]) ? $def[0] . ' ' : ''), ']') :
518 print "$mess ", @dispdef;
520 if ( $self->_is_unattended && !@def ) {
522 ERROR: This build seems to be unattended, but there is no default value
523 for this question. Aborting.
527 my $ans = $self->_readline();
529 if ( !defined($ans) # Ctrl-D or unattended
530 or !length($ans) ) { # User hit return
531 print "$dispdef[1]\n";
532 $ans = scalar(@def) ? $def[0] : '';
540 my ($mess, $def) = @_;
542 die "y_n() called without a prompt message" unless $mess;
543 die "Invalid default value: y_n() default must be 'y' or 'n'"
544 if $def && $def !~ /^[yn]/i;
547 while (1) { # XXX Infinite or a large number followed by an exception ?
548 $answer = $self->prompt(@_);
549 return 1 if $answer =~ /^y/i;
550 return 0 if $answer =~ /^n/i;
552 print "Please answer 'y' or 'n'.\n";
556 sub current_action { shift->{action} }
557 sub invoked_action { shift->{invoked_action} }
559 sub notes { shift()->{phash}{notes}->access(@_) }
560 sub config_data { shift()->{phash}{config_data}->access(@_) }
561 sub runtime_params { shift->{phash}{runtime_params}->read( @_ ? shift : () ) } # Read-only
562 sub auto_features { shift()->{phash}{auto_features}->access(@_) }
566 my $ph = $self->{phash};
570 if ($ph->{features}->exists($key)) {
571 return $ph->{features}->access($key, @_);
574 if (my $info = $ph->{auto_features}->access($key)) {
575 my $failures = $self->prereq_failures($info);
576 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
577 keys %$failures ) ? 1 : 0;
581 return $ph->{features}->access($key, @_);
584 # No args - get the auto_features & overlay the regular features
586 my %auto_features = $ph->{auto_features}->access();
587 while (my ($name, $info) = each %auto_features) {
588 my $failures = $self->prereq_failures($info);
589 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
590 keys %$failures ) ? 1 : 0;
591 $features{$name} = $disabled ? 0 : 1;
593 %features = (%features, $ph->{features}->access());
595 return wantarray ? %features : \%features;
597 BEGIN { *feature = \&features } # Alias
602 if (($self->module_name || '') eq 'Module::Build') {
603 # We're building Module::Build itself, so ...::ConfigData isn't
604 # valid, but $self->features() should be.
605 return $self->feature(@_);
607 require Module::Build::ConfigData;
608 return Module::Build::ConfigData->feature(@_);
613 sub add_build_element {
614 my ($self, $elem) = @_;
615 my $elems = $self->build_elements;
616 push @$elems, $elem unless grep { $_ eq $elem } @$elems;
619 sub ACTION_config_data {
621 return unless $self->has_config_data;
623 my $module_name = $self->module_name
624 or die "The config_data feature requires that 'module_name' be set";
625 my $notes_name = $module_name . '::ConfigData'; # TODO: Customize name ???
626 my $notes_pm = File::Spec->catfile($self->blib, 'lib', split /::/, "$notes_name.pm");
628 return if $self->up_to_date(['Build.PL',
629 $self->config_file('config_data'),
630 $self->config_file('features')
633 $self->log_info("Writing config notes to $notes_pm\n");
634 File::Path::mkpath(File::Basename::dirname($notes_pm));
636 Module::Build::Notes->write_config_data
639 module => $module_name,
640 config_module => $notes_name,
641 config_data => scalar $self->config_data,
642 feature => scalar $self->{phash}{features}->access(),
643 auto_features => scalar $self->auto_features,
648 my %valid_properties = ( __PACKAGE__, {} );
649 my %additive_properties;
652 my $class = ref($_[0]) || $_[0];
653 return ($class, $class->mb_parents);
657 my ($class, $prop) = @_;
658 return grep exists( $valid_properties{$_}{$prop} ), $class->_mb_classes;
661 sub valid_properties {
662 return keys %{ shift->valid_properties_defaults() };
665 sub valid_properties_defaults {
667 for (reverse shift->_mb_classes) {
668 @out{ keys %{ $valid_properties{$_} } } = values %{ $valid_properties{$_} };
673 sub array_properties {
674 for (shift->_mb_classes) {
675 return @{$additive_properties{$_}->{ARRAY}}
676 if exists $additive_properties{$_}->{ARRAY};
680 sub hash_properties {
681 for (shift->_mb_classes) {
682 return @{$additive_properties{$_}->{'HASH'}}
683 if exists $additive_properties{$_}->{'HASH'};
688 my ($class, $property, $default) = @_;
689 die "Property '$property' already exists" if $class->valid_property($property);
691 $valid_properties{$class}{$property} = $default;
693 my $type = ref $default;
695 push @{$additive_properties{$class}->{$type}}, $property;
698 unless ($class->can($property)) {
700 if ( $type eq 'HASH' ) {
701 *{"$class\::$property"} = sub {
702 # XXX this needs 'use strict' again
704 my $x = $self->{properties};
705 return $x->{$property} unless @_;
707 if ( defined($_[0]) && !ref($_[0]) ) {
709 return exists( $x->{$property}{$_[0]} ) ?
710 $x->{$property}{$_[0]} : undef;
711 } elsif ( @_ % 2 == 0 ) {
713 while ( my($k, $v) = each %args ) {
714 $x->{$property}{$k} = $v;
717 die "Unexpected arguments for property '$property'\n";
720 $x->{$property} = $_[0];
725 *{"$class\::$property"} = sub {
726 # XXX this needs 'use strict' again
728 $self->{properties}{$property} = shift if @_;
729 return $self->{properties}{$property};
740 # Set the build class.
741 $self->{properties}{build_class} ||= ref $self;
743 # If there was no orig_dir, set to the same as base_dir
744 $self->{properties}{orig_dir} ||= $self->{properties}{base_dir};
746 my $defaults = $self->valid_properties_defaults;
748 foreach my $prop (keys %$defaults) {
749 $self->{properties}{$prop} = $defaults->{$prop}
750 unless exists $self->{properties}{$prop};
753 # Copy defaults for arrays any arrays.
754 for my $prop ($self->array_properties) {
755 $self->{properties}{$prop} = [@{$defaults->{$prop}}]
756 unless exists $self->{properties}{$prop};
758 # Copy defaults for arrays any hashes.
759 for my $prop ($self->hash_properties) {
760 $self->{properties}{$prop} = {%{$defaults->{$prop}}}
761 unless exists $self->{properties}{$prop};
767 # Add the default properties.
768 __PACKAGE__->add_property(blib => 'blib');
769 __PACKAGE__->add_property(build_class => 'Module::Build');
770 __PACKAGE__->add_property(build_elements => [qw(PL support pm xs pod script)]);
771 __PACKAGE__->add_property(build_script => 'Build');
772 __PACKAGE__->add_property(build_bat => 0);
773 __PACKAGE__->add_property(config_dir => '_build');
774 __PACKAGE__->add_property(include_dirs => []);
775 __PACKAGE__->add_property(installdirs => 'site');
776 __PACKAGE__->add_property(metafile => 'META.yml');
777 __PACKAGE__->add_property(recurse_into => []);
778 __PACKAGE__->add_property(use_rcfile => 1);
779 __PACKAGE__->add_property(create_packlist => 1);
780 __PACKAGE__->add_property(allow_mb_mismatch => 0);
781 __PACKAGE__->add_property(config => undef);
782 __PACKAGE__->add_property(test_file_exts => ['.t']);
783 __PACKAGE__->add_property(use_tap_harness => 0);
784 __PACKAGE__->add_property(tap_harness_args => {});
787 my $Is_ActivePerl = eval {require ActivePerl::DocTools};
788 __PACKAGE__->add_property(html_css => $Is_ActivePerl ? 'Active.css' : '');
792 my @prereq_action_types = qw(requires build_requires conflicts recommends);
793 foreach my $type (@prereq_action_types) {
794 __PACKAGE__->add_property($type => {});
796 __PACKAGE__->add_property(prereq_action_types => \@prereq_action_types);
799 __PACKAGE__->add_property($_ => {}) for qw(
801 install_base_relpaths
811 __PACKAGE__->add_property($_) for qw(
854 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
855 return $c->all_config unless @_;
858 return $c->get($key) unless @_;
861 return $c->set($key => $val);
865 # Code borrowed from Class::ISA.
866 my @in_stack = (shift);
867 my %seen = ($in_stack[0] => 1);
871 next unless defined($current = shift @in_stack)
872 && $current->isa('Module::Build::Base');
874 next if $current eq 'Module::Build::Base';
878 my $c = $_; # copy, to avoid being destructive
879 substr($c,0,2) = "main::" if substr($c,0,2) eq '::';
880 # Canonize the :: -> main::, ::foo -> main::foo thing.
881 # Should I ever canonize the Foo'Bar = Foo::Bar thing?
882 $seen{$c}++ ? () : $c;
883 } @{"$current\::ISA"};
885 # I.e., if this class has any parents (at least, ones I've never seen
886 # before), push them, in order, onto the stack of classes I need to
893 sub extra_linker_flags { shift->_list_accessor('extra_linker_flags', @_) }
894 sub extra_compiler_flags { shift->_list_accessor('extra_compiler_flags', @_) }
897 (my $self, local $_) = (shift, shift);
898 my $p = $self->{properties};
899 $p->{$_} = [@_] if @_;
900 $p->{$_} = [] unless exists $p->{$_};
901 return ref($p->{$_}) ? $p->{$_} : [$p->{$_}];
904 # XXX Problem - if Module::Build is loaded from a different directory,
905 # it'll look for (and perhaps destroy/create) a _build directory.
907 my ($pack, %opts) = @_;
909 my $build_dir = '_build'; # XXX The _build directory is ostensibly settable by the user. Shouldn't hard-code here.
910 $pack->delete_filetree($build_dir) if -e $build_dir;
912 die "Must provide 'code' or 'class' option to subclass()\n"
913 unless $opts{code} or $opts{class};
916 $opts{class} ||= 'MyModuleBuilder';
918 my $filename = File::Spec->catfile($build_dir, 'lib', split '::', $opts{class}) . '.pm';
919 my $filedir = File::Basename::dirname($filename);
920 $pack->log_info("Creating custom builder $filename in $filedir\n");
922 File::Path::mkpath($filedir);
923 die "Can't create directory $filedir: $!" unless -d $filedir;
925 my $fh = IO::File->new("> $filename") or die "Can't create $filename: $!";
927 package $opts{class};
935 unshift @INC, File::Spec->catdir(File::Spec->rel2abs($build_dir), 'lib');
936 eval "use $opts{class}";
944 my $p = $self->{properties};
945 return $p->{dist_name} if defined $p->{dist_name};
947 die "Can't determine distribution name, must supply either 'dist_name' or 'module_name' parameter"
948 unless $self->module_name;
950 ($p->{dist_name} = $self->module_name) =~ s/::/-/g;
952 return $p->{dist_name};
955 sub dist_version_from {
957 my $p = $self->{properties};
958 if ($self->module_name) {
959 $p->{dist_version_from} ||=
960 join( '/', 'lib', split(/::/, $self->module_name) ) . '.pm';
962 return $p->{dist_version_from} || undef;
967 my $p = $self->{properties};
969 return $p->{dist_version} if defined $p->{dist_version};
971 if ( my $dist_version_from = $self->dist_version_from ) {
972 my $version_from = File::Spec->catfile( split( qr{/}, $dist_version_from ) );
973 my $pm_info = Module::Build::ModuleInfo->new_from_file( $version_from )
974 or die "Can't find file $version_from to determine version";
975 $p->{dist_version} = $pm_info->version();
978 die ("Can't determine distribution version, must supply either 'dist_version',\n".
979 "'dist_version_from', or 'module_name' parameter")
980 unless defined $p->{dist_version};
982 return $p->{dist_version};
985 sub dist_author { shift->_pod_parse('author') }
986 sub dist_abstract { shift->_pod_parse('abstract') }
989 my ($self, $part) = @_;
990 my $p = $self->{properties};
991 my $member = "dist_$part";
992 return $p->{$member} if defined $p->{$member};
994 my $docfile = $self->_main_docfile
996 my $fh = IO::File->new($docfile)
999 require Module::Build::PodParser;
1000 my $parser = Module::Build::PodParser->new(fh => $fh);
1001 my $method = "get_$part";
1002 return $p->{$member} = $parser->$method();
1005 sub version_from_file { # Method provided for backwards compatability
1006 return Module::Build::ModuleInfo->new_from_file($_[1])->version();
1009 sub find_module_by_name { # Method provided for backwards compatability
1010 return Module::Build::ModuleInfo->find_module_by_name(@_[1,2]);
1013 sub add_to_cleanup {
1015 my %files = map {$self->localize_file_path($_), 1} @_;
1016 $self->{phash}{cleanup}->write(\%files);
1021 my $all = $self->{phash}{cleanup}->read;
1027 return unless -d $self->config_dir;
1028 return File::Spec->catfile($self->config_dir, @_);
1034 my $file = $self->config_file('build_params')
1035 or die "Can't find 'build_params' in " . $self->config_dir;
1036 my $fh = IO::File->new($file) or die "Can't read '$file': $!";
1037 my $ref = eval do {local $/; <$fh>};
1040 ($self->{args}, $c, $self->{properties}) = @$ref;
1041 $self->{config} = Module::Build::Config->new(values => $c);
1045 sub has_config_data {
1047 return scalar grep $self->{phash}{$_}->has_data(), qw(config_data features auto_features);
1051 my ($self, $filename, $data) = @_;
1053 my $file = $self->config_file($filename);
1054 my $fh = IO::File->new("> $file") or die "Can't create '$file': $!";
1055 unless (ref($data)) { # e.g. magicnum
1060 print {$fh} Module::Build::Dumper->_data_dump($data);
1066 File::Path::mkpath($self->{properties}{config_dir});
1067 -d $self->{properties}{config_dir} or die "Can't mkdir $self->{properties}{config_dir}: $!";
1069 my @items = @{ $self->prereq_action_types };
1070 $self->_write_data('prereqs', { map { $_, $self->$_() } @items });
1071 $self->_write_data('build_params', [$self->{args}, $self->{config}->values_set, $self->{properties}]);
1073 # Set a new magic number and write it to a file
1074 $self->_write_data('magicnum', $self->magic_number(int rand 1_000_000));
1076 $self->{phash}{$_}->write() foreach qw(notes cleanup features auto_features config_data runtime_params);
1079 sub check_autofeatures {
1081 my $features = $self->auto_features;
1083 return unless %$features;
1085 $self->log_info("Checking features:\n");
1087 my $max_name_len = 0;
1088 $max_name_len = ( length($_) > $max_name_len ) ?
1089 length($_) : $max_name_len
1090 for keys %$features;
1092 while (my ($name, $info) = each %$features) {
1093 $self->log_info(" $name" . '.' x ($max_name_len - length($name) + 4));
1095 if ( my $failures = $self->prereq_failures($info) ) {
1096 my $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
1097 keys %$failures ) ? 1 : 0;
1098 $self->log_info( $disabled ? "disabled\n" : "enabled\n" );
1101 while (my ($type, $prereqs) = each %$failures) {
1102 while (my ($module, $status) = each %$prereqs) {
1104 ($type =~ /^(?:\w+_)?(?:requires|conflicts)$/) ? 1 : 0;
1105 my $prefix = ($required) ? '-' : '*';
1106 $log_text .= " $prefix $status->{message}\n";
1109 $self->log_warn("$log_text") unless $self->quiet;
1111 $self->log_info("enabled\n");
1115 $self->log_warn("\n");
1118 sub prereq_failures {
1119 my ($self, $info) = @_;
1121 my @types = @{ $self->prereq_action_types };
1122 $info ||= {map {$_, $self->$_()} @types};
1126 foreach my $type (@types) {
1127 my $prereqs = $info->{$type};
1128 while ( my ($modname, $spec) = each %$prereqs ) {
1129 my $status = $self->check_installed_status($modname, $spec);
1131 if ($type =~ /^(?:\w+_)?conflicts$/) {
1132 next if !$status->{ok};
1133 $status->{conflicts} = delete $status->{need};
1134 $status->{message} = "$modname ($status->{have}) conflicts with this distribution";
1136 } elsif ($type =~ /^(?:\w+_)?recommends$/) {
1137 next if $status->{ok};
1138 $status->{message} = (!ref($status->{have}) && $status->{have} eq '<none>'
1139 ? "Optional prerequisite $modname is not installed"
1140 : "$modname ($status->{have}) is installed, but we prefer to have $spec");
1142 next if $status->{ok};
1145 $out->{$type}{$modname} = $status;
1152 # returns a hash of defined prerequisites; i.e. only prereq types with values
1156 foreach my $type ( @{ $self->prereq_action_types } ) {
1157 if ( $self->can( $type ) ) {
1158 my $prereq = $self->$type() || {};
1159 $prereqs{$type} = $prereq if %$prereq;
1168 # If we have XS files, make sure we can process them.
1169 my $xs_files = $self->find_xs_files;
1170 if (keys %$xs_files && !$self->_mb_feature('C_support')) {
1171 $self->log_warn("Warning: this distribution contains XS files, ".
1172 "but Module::Build is not configured with C_support. ".
1173 "Please install ExtUtils::CBuilder to enable C_support.\n");
1176 # Check to see if there are any prereqs to check
1177 my $info = $self->_enum_prereqs;
1178 return 1 unless $info;
1180 $self->log_info("Checking prerequisites...\n");
1182 my $failures = $self->prereq_failures($info);
1186 while (my ($type, $prereqs) = each %$failures) {
1187 while (my ($module, $status) = each %$prereqs) {
1188 my $prefix = ($type =~ /^(?:\w+_)?recommends$/) ? '*' : '- ERROR:';
1189 $self->log_warn(" $prefix $status->{message}\n");
1193 $self->log_warn(<<EOF);
1195 ERRORS/WARNINGS FOUND IN PREREQUISITES. You may wish to install the versions
1196 of the modules indicated above before proceeding with this installation
1203 $self->log_info("Looks good\n\n");
1211 # Check the current perl interpreter
1212 # It's much more convenient to use $] here than $^V, but 'man
1213 # perlvar' says I'm not supposed to. Bloody tyrant.
1214 return $^V ? $self->perl_version_to_float(sprintf "%vd", $^V) : $];
1217 sub perl_version_to_float {
1218 my ($self, $version) = @_;
1219 return $version if grep( /\./, $version ) < 2;
1220 $version =~ s/\./../;
1221 $version =~ s/\.(\d+)/sprintf '%03d', $1/eg;
1225 sub _parse_conditions {
1226 my ($self, $spec) = @_;
1228 if ($spec =~ /^\s*([\w.]+)\s*$/) { # A plain number, maybe with dots, letters, and underscores
1229 return (">= $spec");
1231 return split /\s*,\s*/, $spec;
1235 sub check_installed_status {
1236 my ($self, $modname, $spec) = @_;
1237 my %status = (need => $spec);
1239 if ($modname eq 'perl') {
1240 $status{have} = $self->perl_version;
1242 } elsif (eval { no strict; $status{have} = ${"${modname}::VERSION"} }) {
1243 # Don't try to load if it's already loaded
1246 my $pm_info = Module::Build::ModuleInfo->new_from_module( $modname );
1247 unless (defined( $pm_info )) {
1248 @status{ qw(have message) } = ('<none>', "$modname is not installed");
1252 $status{have} = $pm_info->version();
1253 if ($spec and !defined($status{have})) {
1254 @status{ qw(have message) } = (undef, "Couldn't find a \$VERSION in prerequisite $modname");
1259 my @conditions = $self->_parse_conditions($spec);
1261 foreach (@conditions) {
1262 my ($op, $version) = /^\s* (<=?|>=?|==|!=) \s* ([\w.]+) \s*$/x
1263 or die "Invalid prerequisite condition '$_' for $modname";
1265 $version = $self->perl_version_to_float($version)
1266 if $modname eq 'perl';
1268 next if $op eq '>=' and !$version; # Module doesn't have to actually define a $VERSION
1270 unless ($self->compare_versions( $status{have}, $op, $version )) {
1271 $status{message} = "$modname ($status{have}) is installed, but we need version $op $version";
1280 sub compare_versions {
1282 my ($v1, $op, $v2) = @_;
1283 $v1 = Module::Build::Version->new($v1)
1284 unless UNIVERSAL::isa($v1,'Module::Build::Version');
1286 my $eval_str = "\$v1 $op \$v2";
1287 my $result = eval $eval_str;
1288 $self->log_warn("error comparing versions: '$eval_str' $@") if $@;
1293 # I wish I could set $! to a string, but I can't, so I use $@
1294 sub check_installed_version {
1295 my ($self, $modname, $spec) = @_;
1297 my $status = $self->check_installed_status($modname, $spec);
1299 if ($status->{ok}) {
1300 return $status->{have} if $status->{have} and "$status->{have}" ne '<none>';
1301 return '0 but true';
1304 $@ = $status->{message};
1308 sub make_executable {
1309 # Perl's chmod() is mapped to useful things on various non-Unix
1310 # platforms, so we use it in the base class even though it looks
1315 my $current_mode = (stat $_)[2];
1316 chmod $current_mode | oct(111), $_;
1321 # We assume this does the right thing on generic platforms, though
1322 # we do some other more specific stuff on Unixish platforms.
1323 my ($self, $file) = @_;
1327 sub _startperl { shift()->config('startperl') }
1329 # Return any directories in @INC which are not in the default @INC for
1330 # this perl. For example, stuff passed in with -I or loaded with "use lib".
1335 $seen{$_}++ foreach $self->_default_INC;
1336 return grep !$seen{$_}++, @INC;
1339 # Determine the default @INC for this Perl
1341 my @default_inc; # Memoize
1344 return @default_inc if @default_inc;
1346 local $ENV{PERL5LIB}; # this is not considered part of the default.
1348 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
1350 my @inc = $self->_backticks($perl, '-le', 'print for @INC');
1353 return @default_inc = @inc;
1357 sub print_build_script {
1358 my ($self, $fh) = @_;
1360 my $build_package = $self->build_class;
1364 my %q = map {$_, $self->$_()} qw(config_dir base_dir);
1366 my $case_tolerant = 0+(File::Spec->can('case_tolerant')
1367 && File::Spec->case_tolerant);
1368 $q{base_dir} = uc $q{base_dir} if $case_tolerant;
1369 $q{base_dir} = Win32::GetShortPathName($q{base_dir}) if $self->is_windowsish;
1371 $q{magic_numfile} = $self->config_file('magicnum');
1373 my @myINC = $self->_added_to_INC;
1374 for (@myINC, values %q) {
1375 $_ = File::Spec->canonpath( $_ );
1379 my $quoted_INC = join ",\n", map " '$_'", @myINC;
1380 my $shebang = $self->_startperl;
1381 my $magic_number = $self->magic_number;
1391 sub magic_number_matches {
1392 return 0 unless -e '$q{magic_numfile}';
1394 open FH, '$q{magic_numfile}' or return 0;
1395 my \$filenum = <FH>;
1397 return \$filenum == $magic_number;
1403 \$^W = 1; # Use warnings
1404 \$progname = basename(\$0);
1405 \$orig_dir = Cwd::cwd();
1406 my \$base_dir = '$q{base_dir}';
1407 if (!magic_number_matches()) {
1408 unless (chdir(\$base_dir)) {
1409 die ("Couldn't chdir(\$base_dir), aborting\\n");
1411 unless (magic_number_matches()) {
1412 die ("Configuration seems to be out of date, please re-run 'perl Build.PL' again.\\n");
1421 close(*DATA) unless eof(*DATA); # ensure no open handles to this script
1425 # Some platforms have problems setting \$^X in shebang contexts, fix it up here
1426 \$^X = Module::Build->find_perl_interpreter;
1428 if (-e 'Build.PL' and not $build_package->up_to_date('Build.PL', \$progname)) {
1429 warn "Warning: Build.PL has been altered. You may need to run 'perl Build.PL' again.\\n";
1432 # This should have just enough arguments to be able to bootstrap the rest.
1433 my \$build = $build_package->resume (
1435 config_dir => '$q{config_dir}',
1436 orig_dir => \$orig_dir,
1444 sub create_build_script {
1446 $self->write_config;
1448 my ($build_script, $dist_name, $dist_version)
1449 = map $self->$_(), qw(build_script dist_name dist_version);
1451 if ( $self->delete_filetree($build_script) ) {
1452 $self->log_info("Removed previous script '$build_script'\n\n");
1455 $self->log_info("Creating new '$build_script' script for ",
1456 "'$dist_name' version '$dist_version'\n");
1457 my $fh = IO::File->new(">$build_script") or die "Can't create '$build_script': $!";
1458 $self->print_build_script($fh);
1461 $self->make_executable($build_script);
1466 sub check_manifest {
1468 return unless -e 'MANIFEST';
1470 # Stolen nearly verbatim from MakeMaker. But ExtUtils::Manifest
1471 # could easily be re-written into a modern Perl dialect.
1473 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
1474 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
1476 $self->log_info("Checking whether your kit is complete...\n");
1477 if (my @missed = ExtUtils::Manifest::manicheck()) {
1478 $self->log_warn("WARNING: the following files are missing in your kit:\n",
1479 "\t", join("\n\t", @missed), "\n",
1480 "Please inform the author.\n\n");
1482 $self->log_info("Looks good\n\n");
1488 local $self->{_completed_actions} = {};
1491 my ($action, %p) = @_;
1492 my $args = $p{args} ? delete($p{args}) : {};
1494 local $self->{invoked_action} = $action;
1495 local $self->{args} = {%{$self->{args}}, %$args};
1496 local $self->{properties} = {%{$self->{properties}}, %p};
1497 return $self->_call_action($action);
1500 die "No build action specified" unless $self->{action};
1501 local $self->{invoked_action} = $self->{action};
1502 $self->_call_action($self->{action});
1506 my ($self, $action) = @_;
1508 return if $self->{_completed_actions}{$action}++;
1510 local $self->{action} = $action;
1511 my $method = "ACTION_$action";
1512 die "No action '$action' defined, try running the 'help' action.\n" unless $self->can($method);
1513 return $self->$method();
1516 # cuts the user-specified options out of the command-line args
1521 my $specs = $self->get_options;
1522 return({}, @argv) unless($specs and %$specs); # no user options
1524 require Getopt::Long;
1525 # XXX Should we let Getopt::Long handle M::B's options? That would
1526 # be easy-ish to add to @specs right here, but wouldn't handle options
1527 # passed without "--" as M::B currently allows. We might be able to
1528 # get around this by setting the "prefix_pattern" Configure option.
1531 # Construct the specifications for GetOptions.
1532 while (my ($k, $v) = each %$specs) {
1533 # Throw an error if specs conflict with our own.
1534 die "Option specification '$k' conflicts with a " . ref $self
1535 . " option of the same name"
1536 if $self->valid_property($k);
1537 push @specs, $k . (defined $v->{type} ? $v->{type} : '');
1538 push @specs, $v->{store} if exists $v->{store};
1539 $args->{$k} = $v->{default} if exists $v->{default};
1542 local @ARGV = @argv; # No other way to dupe Getopt::Long
1544 # Get the options values and return them.
1545 # XXX Add option to allow users to set options?
1547 Getopt::Long::Configure('pass_through');
1548 Getopt::Long::GetOptions($args, @specs);
1551 return $args, @ARGV;
1555 my ($self, $args) = @_;
1557 while (my ($k, $v) = each %$args) {
1558 push @out, (UNIVERSAL::isa($v, 'HASH') ? map {+"--$k", "$_=$v->{$_}"} keys %$v :
1559 UNIVERSAL::isa($v, 'ARRAY') ? map {+"--$k", $_} @$v :
1567 return wantarray ? %{ $self->{args} } : $self->{args} unless @_;
1569 $self->{args}{$key} = shift if @_;
1570 return $self->{args}{$key};
1573 # allows select parameters (with underscores) to be spoken with dashes
1574 # when used as command-line options
1575 sub _translate_option {
1579 (my $tr_opt = $opt) =~ tr/-/_/;
1581 return $tr_opt if grep $tr_opt =~ /^(?:no_?)?$_$/, qw(
1584 extra_compiler_flags
1595 ); # normalize only selected option names
1601 my ($self, $args, $key, $val) = @_;
1603 $key = $self->_translate_option($key);
1605 if ( exists $args->{$key} ) {
1606 $args->{$key} = [ $args->{$key} ] unless ref $args->{$key};
1607 push @{$args->{$key}}, $val;
1609 $args->{$key} = $val;
1613 # decide whether or not an option requires/has an opterand
1619 $opt = $self->_translate_option($opt);
1633 # inverted boolean options; eg --noverbose or --no-verbose
1634 # converted to proper name & returned with false value (verbose, 0)
1635 if ( grep $opt =~ /^no[-_]?$_$/, @bool_opts ) {
1640 # non-boolean option; return option unchanged along with its argument
1641 return ($opt, shift(@$argv)) unless grep $_ eq $opt, @bool_opts;
1643 # we're punting a bit here, if an option appears followed by a digit
1644 # we take the digit as the argument for the option. If there is
1645 # nothing that looks like a digit, we pretend the option is a flag
1646 # that is being set and has no argument.
1648 $arg = shift(@$argv) if @$argv && $argv->[0] =~ /^\d+$/;
1650 return ($opt, $arg);
1656 (my $args, @_) = $self->cull_options(@_);
1659 my $opt_re = qr/[\w\-]+/;
1661 my ($action, @argv);
1664 if ( /^(?:--)?($opt_re)=(.*)$/ ) {
1665 $self->_read_arg(\%args, $1, $2);
1666 } elsif ( /^--($opt_re)$/ ) {
1667 my($opt, $arg) = $self->_optional_arg($1, \@_);
1668 $self->_read_arg(\%args, $opt, $arg);
1669 } elsif ( /^($opt_re)$/ and !defined($action)) {
1675 $args{ARGV} = \@argv;
1677 for ('extra_compiler_flags', 'extra_linker_flags') {
1678 $args{$_} = [ $self->split_like_shell($args{$_}) ] if exists $args{$_};
1681 # Hashify these parameters
1682 for ($self->hash_properties, 'config') {
1683 next unless exists $args{$_};
1686 $args{$_} = [ $args{$_} ] unless ref $args{$_};
1687 foreach my $arg ( @{$args{$_}} ) {
1688 $arg =~ /(\w+)=(.*)/
1689 or die "Malformed '$_' argument: '$arg' should be something like 'foo=bar'";
1695 # De-tilde-ify any path parameters
1696 for my $key (qw(prefix install_base destdir)) {
1697 next if !defined $args{$key};
1698 $args{$key} = $self->_detildefy($args{$key});
1701 for my $key (qw(install_path)) {
1702 next if !defined $args{$key};
1704 for my $subkey (keys %{$args{$key}}) {
1705 next if !defined $args{$key}{$subkey};
1706 my $subkey_ext = $self->_detildefy($args{$key}{$subkey});
1707 if ( $subkey eq 'html' ) { # translate for compatability
1708 $args{$key}{binhtml} = $subkey_ext;
1709 $args{$key}{libhtml} = $subkey_ext;
1711 $args{$key}{$subkey} = $subkey_ext;
1716 if ($args{makefile_env_macros}) {
1717 require Module::Build::Compat;
1718 %args = (%args, Module::Build::Compat->makefile_to_build_macros);
1721 return \%args, $action;
1724 # Default: do nothing. Overridden for Unix & Windows.
1728 # merge Module::Build argument lists that have already been parsed
1729 # by read_args(). Takes two references to option hashes and merges
1730 # the contents, giving priority to the first.
1731 sub _merge_arglist {
1732 my( $self, $opts1, $opts2 ) = @_;
1734 my %new_opts = %$opts1;
1735 while (my ($key, $val) = each %$opts2) {
1736 if ( exists( $opts1->{$key} ) ) {
1737 if ( ref( $val ) eq 'HASH' ) {
1738 while (my ($k, $v) = each %$val) {
1739 $new_opts{$key}{$k} = $v unless exists( $opts1->{$key}{$k} );
1743 $new_opts{$key} = $val
1750 # Look for a home directory on various systems.
1753 push( @home_dirs, $ENV{HOME} ) if $ENV{HOME};
1755 push( @home_dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
1756 if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};
1758 my @other_home_envs = qw( USERPROFILE APPDATA WINDIR SYS$LOGIN );
1759 push( @home_dirs, map $ENV{$_}, grep $ENV{$_}, @other_home_envs );
1761 my @real_home_dirs = grep -d, @home_dirs;
1763 return wantarray ? @real_home_dirs : shift( @real_home_dirs );
1766 sub _find_user_config {
1769 foreach my $dir ( $self->_home_dir ) {
1770 my $path = File::Spec->catfile( $dir, $file );
1771 return $path if -e $path;
1776 # read ~/.modulebuildrc returning global options '*' and
1777 # options specific to the currently executing $action.
1778 sub read_modulebuildrc {
1779 my( $self, $action ) = @_;
1781 return () unless $self->use_rcfile;
1784 if ( exists($ENV{MODULEBUILDRC}) && $ENV{MODULEBUILDRC} eq 'NONE' ) {
1786 } elsif ( exists($ENV{MODULEBUILDRC}) && -e $ENV{MODULEBUILDRC} ) {
1787 $modulebuildrc = $ENV{MODULEBUILDRC};
1788 } elsif ( exists($ENV{MODULEBUILDRC}) ) {
1789 $self->log_warn("WARNING: Can't find resource file " .
1790 "'$ENV{MODULEBUILDRC}' defined in environment.\n" .
1791 "No options loaded\n");
1794 $modulebuildrc = $self->_find_user_config( '.modulebuildrc' );
1795 return () unless $modulebuildrc;
1798 my $fh = IO::File->new( $modulebuildrc )
1799 or die "Can't open $modulebuildrc: $!";
1801 my %options; my $buffer = '';
1802 while (defined( my $line = <$fh> )) {
1805 next unless length( $line );
1807 if ( $line =~ /^\S/ ) {
1809 my( $action, $options ) = split( /\s+/, $buffer, 2 );
1810 $options{$action} .= $options . ' ';
1819 if ( $buffer ) { # anything left in $buffer ?
1820 my( $action, $options ) = split( /\s+/, $buffer, 2 );
1821 $options{$action} .= $options . ' '; # merge if more than one line
1825 $self->read_args( $self->split_like_shell( $options{'*'} || '' ) );
1827 $self->read_args( $self->split_like_shell( $options{$action} || '' ) );
1829 # specific $action options take priority over global options '*'
1830 return $self->_merge_arglist( $action_opts, $global_opts );
1833 # merge the relevant options in ~/.modulebuildrc into Module::Build's
1834 # option list where they do not conflict with commandline options.
1835 sub merge_modulebuildrc {
1836 my( $self, $action, %cmdline_opts ) = @_;
1837 my %rc_opts = $self->read_modulebuildrc( $action || $self->{action} || 'build' );
1838 my %new_opts = $self->_merge_arglist( \%cmdline_opts, \%rc_opts );
1839 $self->merge_args( $action, %new_opts );
1843 my ($self, $action, %args) = @_;
1844 $self->{action} = $action if defined $action;
1846 my %additive = map { $_ => 1 } $self->hash_properties;
1848 # Extract our 'properties' from $cmd_args, the rest are put in 'args'.
1849 while (my ($key, $val) = each %args) {
1850 $self->{phash}{runtime_params}->access( $key => $val )
1851 if $self->valid_property($key);
1853 if ($key eq 'config') {
1854 $self->config($_ => $val->{$_}) foreach keys %$val;
1856 my $add_to = $additive{$key} ? $self->{properties}{$key} :
1857 $self->valid_property($key) ? $self->{properties} :
1860 if ($additive{$key}) {
1861 $add_to->{$_} = $val->{$_} foreach keys %$val;
1863 $add_to->{$key} = $val;
1871 my ($args, $action) = $self->read_args(@_);
1872 $self->merge_args($action, %$args);
1873 $self->merge_modulebuildrc( $action, %$args );
1877 my ($self, $class, $seen) = @_;
1878 $class ||= ref($self) || $self;
1882 my @super = grep {not $seen->{$_}++} $class, @{ $class . '::ISA' };
1883 return @super, map {$self->super_classes($_,$seen)} @super;
1892 foreach my $class ($self->super_classes) {
1893 foreach ( keys %{ $class . '::' } ) {
1894 $actions{$1}++ if /^ACTION_(\w+)/;
1898 return wantarray ? sort keys %actions : \%actions;
1901 sub get_action_docs {
1902 my ($self, $action) = @_;
1903 my $actions = $self->known_actions;
1904 die "No known action '$action'" unless $actions->{$action};
1906 my ($files_found, @docs) = (0);
1907 foreach my $class ($self->super_classes) {
1908 (my $file = $class) =~ s{::}{/}g;
1909 # NOTE: silently skipping relative paths if any chdir() happened
1910 $file = $INC{$file . '.pm'} or next;
1911 my $fh = IO::File->new("< $file") or next;
1914 # Code below modified from /usr/bin/perldoc
1916 # Skip to ACTIONS section
1919 last if /^=head1 ACTIONS\s/;
1922 # Look for our action and determine the style
1927 # only item and head2 are allowed (3&4 are not in 5.005)
1928 if(/^=(item|head2)\s+\Q$action\E\b/) {
1934 $style or next; # not here
1937 if($style eq 'item') {
1938 my ($found, $inlist) = (0, 0);
1940 if (/^=(item|back)/) {
1941 last unless $inlist;
1944 ++$inlist if /^=over/;
1945 --$inlist if /^=back/;
1948 else { # head2 style
1949 # stop at anything equal or greater than the found level
1951 last if(/^=(?:head[12]|cut)/);
1955 # TODO maybe disallow overriding just pod for an action
1956 # TODO and possibly: @docs and last;
1959 unless ($files_found) {
1960 $@ = "Couldn't find any documentation to search";
1964 $@ = "Couldn't find any docs for action '$action'";
1968 return join '', @docs;
1971 sub ACTION_prereq_report {
1973 $self->log_info( $self->prereq_report );
1978 my @types = @{ $self->prereq_action_types };
1979 my $info = { map { $_ => $self->$_() } @types };
1982 foreach my $type (@types) {
1983 my $prereqs = $info->{$type};
1984 next unless %$prereqs;
1985 $output .= "\n$type:\n";
1989 while ( my ($modname, $spec) = each %$prereqs ) {
1990 my $len = length $modname;
1991 $mod_len = $len if $len > $mod_len;
1993 $len = length $spec;
1994 $ver_len = $len if $len > $ver_len;
1996 my $mod = $self->check_installed_status($modname, $spec);
1997 $mod->{name} = $modname;
1999 $mod->{ok} = ! $mod->{ok} if $type =~ /^(\w+_)?conflicts$/;
2001 $mods{lc $modname} = $mod;
2004 my $space = q{ } x ($mod_len - 3);
2005 my $vspace = q{ } x ($ver_len - 3);
2006 my $sline = q{-} x ($mod_len - 3);
2007 my $vline = q{-} x ($ver_len - 3);
2008 my $disposition = ($type =~ /^(\w+_)?conflicts$/) ?
2011 " Module $space $disposition $vspace Have\n".
2012 " ------$sline+------$vline-+----------\n";
2015 for my $k (sort keys %mods) {
2016 my $mod = $mods{$k};
2017 my $space = q{ } x ($mod_len - length $k);
2018 my $vspace = q{ } x ($ver_len - length $mod->{need});
2019 my $f = $mod->{ok} ? ' ' : '!';
2021 " $f $mod->{name} $space $mod->{need} $vspace ".
2022 (defined($mod->{have}) ? $mod->{have} : "")."\n";
2030 my $actions = $self->known_actions;
2032 if (@{$self->{args}{ARGV}}) {
2033 my $msg = eval {$self->get_action_docs($self->{args}{ARGV}[0], $actions)};
2034 print $@ ? "$@\n" : $msg;
2040 Usage: $0 <action> arg1=value arg2=value ...
2041 Example: $0 test verbose=1
2046 print $self->_action_listing($actions);
2048 print "\nRun `Build help <action>` for details on an individual action.\n";
2049 print "See `perldoc Module::Build` for complete documentation.\n";
2052 sub _action_listing {
2053 my ($self, $actions) = @_;
2055 # Flow down columns, not across rows
2056 my @actions = sort keys %$actions;
2057 @actions = map $actions[($_ + ($_ % 2) * @actions) / 2], 0..$#actions;
2060 while (my ($one, $two) = splice @actions, 0, 2) {
2061 $out .= sprintf(" %-12s %-12s\n", $one, $two||'');
2069 # Protect others against our @INC changes
2072 # Filter out nonsensical @INC entries - some versions of
2073 # Test::Harness will really explode the number of entries here
2074 @INC = grep {ref() || -d} @INC if @INC > 100;
2079 sub ACTION_testall {
2083 for my $action (grep { $_ ne 'all' } $self->get_test_types) {
2084 # XXX We can't just dispatch because we get multiple summaries but
2085 # we'll need to dispatch to support custom setup/teardown in the
2086 # action. To support that, we'll need to call something besides
2087 # Harness::runtests() because we'll need to collect the results in
2088 # parts, then run the summary.
2089 push(@types, $action);
2090 #$self->_call_action( "test$action" );
2092 $self->generic_test(types => ['default', @types]);
2095 sub get_test_types {
2098 my $t = $self->{properties}->{test_types};
2099 return ( defined $t ? ( keys %$t ) : () );
2105 $self->generic_test(type => 'default');
2110 (@_ % 2) and croak('Odd number of elements in argument hash');
2113 my $p = $self->{properties};
2116 (exists($args{type}) ? $args{type} : ()),
2117 (exists($args{types}) ? @{$args{types}} : ()),
2119 @types or croak "need some types of tests to check";
2122 default => $p->{test_file_exts},
2123 (defined($p->{test_types}) ? %{$p->{test_types}} : ()),
2126 for my $type (@types) {
2127 croak "$type not defined in test_types!"
2128 unless defined $test_types{ $type };
2131 # we use local here because it ends up two method calls deep
2132 local $p->{test_file_exts} = [ map { ref $_ ? @$_ : $_ } @test_types{@types} ];
2133 $self->depends_on('code');
2135 # Protect others against our @INC changes
2138 # Make sure we test the module in blib/
2139 unshift @INC, (File::Spec->catdir($p->{base_dir}, $self->blib, 'lib'),
2140 File::Spec->catdir($p->{base_dir}, $self->blib, 'arch'));
2142 # Filter out nonsensical @INC entries - some versions of
2143 # Test::Harness will really explode the number of entries here
2144 @INC = grep {ref() || -d} @INC if @INC > 100;
2152 my $tests = $self->find_test_files;
2155 my $args = $self->tap_harness_args;
2156 if($self->use_tap_harness or ($args and %$args)) {
2157 $self->run_tap_harness($tests);
2160 $self->run_test_harness($tests);
2164 $self->log_info("No tests defined.\n");
2167 $self->run_visual_script;
2170 sub run_tap_harness {
2171 my ($self, $tests) = @_;
2173 require TAP::Harness;
2175 # TODO allow the test @INC to be set via our API?
2179 verbosity => $self->{properties}{verbose},
2180 switches => [ $self->harness_switches ],
2181 %{ $self->tap_harness_args },
2182 })->runtests(@$tests);
2185 sub run_test_harness {
2186 my ($self, $tests) = @_;
2187 require Test::Harness;
2188 my $p = $self->{properties};
2189 my @harness_switches = $self->harness_switches;
2191 # Work around a Test::Harness bug that loses the particular perl
2192 # we're running under. $self->perl is trustworthy, but $^X isn't.
2193 local $^X = $self->perl;
2195 # Do everything in our power to work with all versions of Test::Harness
2196 local $Test::Harness::switches = join ' ', grep defined, $Test::Harness::switches, @harness_switches;
2197 local $Test::Harness::Switches = join ' ', grep defined, $Test::Harness::Switches, @harness_switches;
2198 local $ENV{HARNESS_PERL_SWITCHES} = join ' ', grep defined, $ENV{HARNESS_PERL_SWITCHES}, @harness_switches;
2200 $Test::Harness::switches = undef unless length $Test::Harness::switches;
2201 $Test::Harness::Switches = undef unless length $Test::Harness::Switches;
2202 delete $ENV{HARNESS_PERL_SWITCHES} unless length $ENV{HARNESS_PERL_SWITCHES};
2204 local ($Test::Harness::verbose,
2205 $Test::Harness::Verbose,
2207 $ENV{HARNESS_VERBOSE}) = ($p->{verbose} || 0) x 4;
2209 Test::Harness::runtests(@$tests);
2212 sub run_visual_script {
2214 # This will get run and the user will see the output. It doesn't
2215 # emit Test::Harness-style output.
2216 $self->run_perl_script('visual.pl', '-Mblib='.$self->blib)
2220 sub harness_switches {
2221 shift->{properties}{debugger} ? qw(-w -d) : ();
2226 my $p = $self->{properties};
2228 return $p->{test_files} = (@_ == 1 ? shift : [@_]);
2230 return $self->find_test_files;
2233 sub expand_test_dir {
2234 my ($self, $dir) = @_;
2235 my $exts = $self->{properties}{test_file_exts};
2237 return sort map { @{$self->rscan_dir($dir, qr{^[^.].*\Q$_\E$})} } @$exts
2238 if $self->recursive_test_files;
2240 return sort map { glob File::Spec->catfile($dir, "*$_") } @$exts;
2245 local $self->{properties}{debugger} = 1;
2246 $self->depends_on('test');
2249 sub ACTION_testcover {
2252 unless (Module::Build::ModuleInfo->find_module_by_name('Devel::Cover')) {
2253 warn("Cannot run testcover action unless Devel::Cover is installed.\n");
2257 $self->add_to_cleanup('coverage', 'cover_db');
2258 $self->depends_on('code');
2260 # See whether any of the *.pm files have changed since last time
2261 # testcover was run. If so, start over.
2262 if (-e 'cover_db') {
2263 my $pm_files = $self->rscan_dir
2264 (File::Spec->catdir($self->blib, 'lib'), file_qr('\.pm$') );
2265 my $cover_files = $self->rscan_dir('cover_db', sub {-f $_ and not /\.html$/});
2267 $self->do_system(qw(cover -delete))
2268 unless $self->up_to_date($pm_files, $cover_files)
2269 && $self->up_to_date($self->test_files, $cover_files);
2272 local $Test::Harness::switches =
2273 local $Test::Harness::Switches =
2274 local $ENV{HARNESS_PERL_SWITCHES} = "-MDevel::Cover";
2276 $self->depends_on('test');
2277 $self->do_system('cover');
2283 # All installable stuff gets created in blib/ .
2284 # Create blib/arch to keep blib.pm happy
2285 my $blib = $self->blib;
2286 $self->add_to_cleanup($blib);
2287 File::Path::mkpath( File::Spec->catdir($blib, 'arch') );
2289 if (my $split = $self->autosplit) {
2290 $self->autosplit_file($_, $blib) for ref($split) ? @$split : ($split);
2293 foreach my $element (@{$self->build_elements}) {
2294 my $method = "process_${element}_files";
2295 $method = "process_files_by_extension" unless $self->can($method);
2296 $self->$method($element);
2299 $self->depends_on('config_data');
2304 $self->depends_on('code');
2305 $self->depends_on('docs');
2308 sub process_files_by_extension {
2309 my ($self, $ext) = @_;
2311 my $method = "find_${ext}_files";
2312 my $files = $self->can($method) ? $self->$method() : $self->_find_file_by_type($ext, 'lib');
2314 while (my ($file, $dest) = each %$files) {
2315 $self->copy_if_modified(from => $file, to => File::Spec->catfile($self->blib, $dest) );
2319 sub process_support_files {
2321 my $p = $self->{properties};
2322 return unless $p->{c_source};
2324 push @{$p->{include_dirs}}, $p->{c_source};
2326 my $files = $self->rscan_dir($p->{c_source}, file_qr('\.c(pp)?$'));
2327 foreach my $file (@$files) {
2328 push @{$p->{objects}}, $self->compile_c($file);
2332 sub process_PL_files {
2334 my $files = $self->find_PL_files;
2336 while (my ($file, $to) = each %$files) {
2337 unless ($self->up_to_date( $file, $to )) {
2338 $self->run_perl_script($file, [], [@$to]) or die "$file failed";
2339 $self->add_to_cleanup(@$to);
2344 sub process_xs_files {
2346 my $files = $self->find_xs_files;
2347 while (my ($from, $to) = each %$files) {
2348 unless ($from eq $to) {
2349 $self->add_to_cleanup($to);
2350 $self->copy_if_modified( from => $from, to => $to );
2352 $self->process_xs($to);
2356 sub process_pod_files { shift()->process_files_by_extension(shift()) }
2357 sub process_pm_files { shift()->process_files_by_extension(shift()) }
2359 sub process_script_files {
2361 my $files = $self->find_script_files;
2362 return unless keys %$files;
2364 my $script_dir = File::Spec->catdir($self->blib, 'script');
2365 File::Path::mkpath( $script_dir );
2367 foreach my $file (keys %$files) {
2368 my $result = $self->copy_if_modified($file, $script_dir, 'flatten') or next;
2369 $self->fix_shebang_line($result) unless $self->is_vmsish;
2370 $self->make_executable($result);
2376 if (my $files = $self->{properties}{PL_files}) {
2377 # 'PL_files' is given as a Unix file spec, so we localize_file_path().
2379 if (UNIVERSAL::isa($files, 'ARRAY')) {
2380 return { map {$_, [/^(.*)\.PL$/]}
2381 map $self->localize_file_path($_),
2384 } elsif (UNIVERSAL::isa($files, 'HASH')) {
2386 while (my ($file, $to) = each %$files) {
2387 $out{ $self->localize_file_path($file) } = [ map $self->localize_file_path($_),
2388 ref $to ? @$to : ($to) ];
2393 die "'PL_files' must be a hash reference or array reference";
2397 return unless -d 'lib';
2398 return { map {$_, [/^(.*)\.PL$/i ]} @{ $self->rscan_dir('lib',
2399 file_qr('\.PL$')) } };
2402 sub find_pm_files { shift->_find_file_by_type('pm', 'lib') }
2403 sub find_pod_files { shift->_find_file_by_type('pod', 'lib') }
2404 sub find_xs_files { shift->_find_file_by_type('xs', 'lib') }
2406 sub find_script_files {
2408 if (my $files = $self->script_files) {
2409 # Always given as a Unix file spec. Values in the hash are
2410 # meaningless, but we preserve if present.
2411 return { map {$self->localize_file_path($_), $files->{$_}} keys %$files };
2414 # No default location for script files
2418 sub find_test_files {
2420 my $p = $self->{properties};
2422 if (my $files = $p->{test_files}) {
2423 $files = [keys %$files] if UNIVERSAL::isa($files, 'HASH');
2424 $files = [map { -d $_ ? $self->expand_test_dir($_) : $_ }
2426 $self->split_like_shell($files)];
2428 # Always given as a Unix file spec.
2429 return [ map $self->localize_file_path($_), @$files ];
2432 # Find all possible tests in t/ or test.pl
2434 push @tests, 'test.pl' if -e 'test.pl';
2435 push @tests, $self->expand_test_dir('t') if -e 't' and -d _;
2440 sub _find_file_by_type {
2441 my ($self, $type, $dir) = @_;
2443 if (my $files = $self->{properties}{"${type}_files"}) {
2444 # Always given as a Unix file spec
2445 return { map $self->localize_file_path($_), %$files };
2448 return {} unless -d $dir;
2449 return { map {$_, $_}
2450 map $self->localize_file_path($_),
2452 @{ $self->rscan_dir($dir, file_qr("\\.$type\$")) } };
2455 sub localize_file_path {
2456 my ($self, $path) = @_;
2457 return File::Spec->catfile( split m{/}, $path );
2460 sub localize_dir_path {
2461 my ($self, $path) = @_;
2462 return File::Spec->catdir( split m{/}, $path );
2465 sub fix_shebang_line { # Adapted from fixin() in ExtUtils::MM_Unix 1.35
2466 my ($self, @files) = @_;
2467 my $c = ref($self) ? $self->{config} : 'Module::Build::Config';
2469 my ($does_shbang) = $c->get('sharpbang') =~ /^\s*\#\!/;
2470 for my $file (@files) {
2471 my $FIXIN = IO::File->new($file) or die "Can't process '$file': $!";
2473 chomp(my $line = <$FIXIN>);
2474 next unless $line =~ s/^\s*\#!\s*//; # Not a shbang file.
2476 my ($cmd, $arg) = (split(' ', $line, 2), '');
2477 next unless $cmd =~ /perl/i;
2478 my $interpreter = $self->{properties}{perl};
2480 $self->log_verbose("Changing sharpbang in $file to $interpreter");
2482 $shb .= $c->get('sharpbang')."$interpreter $arg\n" if $does_shbang;
2484 # I'm not smart enough to know the ramifications of changing the
2485 # embedded newlines here to \n, so I leave 'em in.
2487 eval 'exec $interpreter $arg -S \$0 \${1+"\$\@"}'
2488 if 0; # not running under some shell
2489 } unless $self->is_windowsish; # this won't work on win32, so don't
2491 my $FIXOUT = IO::File->new(">$file.new")
2492 or die "Can't create new $file: $!\n";
2494 # Print out the new #! line (or equivalent).
2496 undef $/; # Was localized above
2497 print $FIXOUT $shb, <$FIXIN>;
2501 rename($file, "$file.bak")
2502 or die "Can't rename $file to $file.bak: $!";
2504 rename("$file.new", $file)
2505 or die "Can't rename $file.new to $file: $!";
2507 $self->delete_filetree("$file.bak")
2508 or $self->log_warn("Couldn't clean up $file.bak, leaving it there");
2510 $self->do_system($c->get('eunicefix'), $file) if $c->get('eunicefix') ne ':';
2515 sub ACTION_testpod {
2517 $self->depends_on('docs');
2519 eval q{use Test::Pod 0.95; 1}
2520 or die "The 'testpod' action requires Test::Pod version 0.95";
2522 my @files = sort keys %{$self->_find_pods($self->libdoc_dirs)},
2523 keys %{$self->_find_pods
2524 ($self->bindoc_dirs,
2525 exclude => [ file_qr('\.bat$') ])}
2526 or die "Couldn't find any POD files to test\n";
2528 { package Module::Build::PodTester; # Don't want to pollute the main namespace
2529 Test::Pod->import( tests => scalar @files );
2530 pod_file_ok($_) foreach @files;
2534 sub ACTION_testpodcoverage {
2537 $self->depends_on('docs');
2539 eval q{use Test::Pod::Coverage 1.00; 1}
2540 or die "The 'testpodcoverage' action requires ",
2541 "Test::Pod::Coverage version 1.00";
2543 # TODO this needs test coverage!
2545 # XXX work-around a bug in Test::Pod::Coverage previous to v1.09
2546 # Make sure we test the module in blib/
2548 my $p = $self->{properties};
2550 # XXX any reason to include arch?
2551 File::Spec->catdir($p->{base_dir}, $self->blib, 'lib'),
2552 #File::Spec->catdir($p->{base_dir}, $self->blib, 'arch')
2555 all_pod_coverage_ok();
2561 $self->depends_on('code');
2562 $self->depends_on('manpages', 'html');
2565 # Given a file type, will return true if the file type would normally
2566 # be installed when neither install-base nor prefix has been set.
2567 # I.e. it will be true only if the path is set from Config.pm or
2568 # set explicitly by the user via install-path.
2569 sub _is_default_installable {
2572 return ( $self->install_destination($type) &&
2573 ( $self->install_path($type) ||
2574 $self->install_sets($self->installdirs)->{$type} )
2578 sub ACTION_manpages {
2581 return unless $self->_mb_feature('manpage_support');
2583 $self->depends_on('code');
2585 foreach my $type ( qw(bin lib) ) {
2586 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2587 exclude => [ file_qr('\.bat$') ] );
2588 next unless %$files;
2590 my $sub = $self->can("manify_${type}_pods");
2591 next unless defined( $sub );
2593 if ( $self->invoked_action eq 'manpages' ) {
2595 } elsif ( $self->_is_default_installable("${type}doc") ) {
2602 sub manify_bin_pods {
2605 my $files = $self->_find_pods( $self->{properties}{bindoc_dirs},
2606 exclude => [ file_qr('\.bat$') ] );
2607 return unless keys %$files;
2609 my $mandir = File::Spec->catdir( $self->blib, 'bindoc' );
2610 File::Path::mkpath( $mandir, 0, oct(777) );
2613 foreach my $file (keys %$files) {
2614 # Pod::Simple based parsers only support one document per instance.
2615 # This is expected to change in a future version (Pod::Simple > 3.03).
2616 my $parser = Pod::Man->new( section => 1 ); # binaries go in section 1
2617 my $manpage = $self->man1page_name( $file ) . '.' .
2618 $self->config( 'man1ext' );
2619 my $outfile = File::Spec->catfile($mandir, $manpage);
2620 next if $self->up_to_date( $file, $outfile );
2621 $self->log_info("Manifying $file -> $outfile\n");
2622 $parser->parse_from_file( $file, $outfile );
2623 $files->{$file} = $outfile;
2627 sub manify_lib_pods {
2630 my $files = $self->_find_pods($self->{properties}{libdoc_dirs});
2631 return unless keys %$files;
2633 my $mandir = File::Spec->catdir( $self->blib, 'libdoc' );
2634 File::Path::mkpath( $mandir, 0, oct(777) );
2637 while (my ($file, $relfile) = each %$files) {
2638 # Pod::Simple based parsers only support one document per instance.
2639 # This is expected to change in a future version (Pod::Simple > 3.03).
2640 my $parser = Pod::Man->new( section => 3 ); # libraries go in section 3
2641 my $manpage = $self->man3page_name( $relfile ) . '.' .
2642 $self->config( 'man3ext' );
2643 my $outfile = File::Spec->catfile( $mandir, $manpage);
2644 next if $self->up_to_date( $file, $outfile );
2645 $self->log_info("Manifying $file -> $outfile\n");
2646 $parser->parse_from_file( $file, $outfile );
2647 $files->{$file} = $outfile;
2652 my ($self, $dirs, %args) = @_;
2654 foreach my $spec (@$dirs) {
2655 my $dir = $self->localize_dir_path($spec);
2656 next unless -e $dir;
2658 FILE: foreach my $file ( @{ $self->rscan_dir( $dir ) } ) {
2659 foreach my $regexp ( @{ $args{exclude} } ) {
2660 next FILE if $file =~ $regexp;
2662 $files{$file} = File::Spec->abs2rel($file, $dir) if $self->contains_pod( $file )
2669 my ($self, $file) = @_;
2670 return '' unless -T $file; # Only look at text files
2672 my $fh = IO::File->new( $file ) or die "Can't open $file: $!";
2673 while (my $line = <$fh>) {
2674 return 1 if $line =~ /^\=(?:head|pod|item)/;
2683 return unless $self->_mb_feature('HTML_support');
2685 $self->depends_on('code');
2687 foreach my $type ( qw(bin lib) ) {
2688 my $files = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2690 [ file_qr('\.(?:bat|com|html)$') ] );
2691 next unless %$files;
2693 if ( $self->invoked_action eq 'html' ) {
2694 $self->htmlify_pods( $type );
2695 } elsif ( $self->_is_default_installable("${type}html") ) {
2696 $self->htmlify_pods( $type );
2703 # 1) If it's an ActiveState perl install, we need to run
2704 # ActivePerl::DocTools->UpdateTOC;
2705 # 2) Links to other modules are not being generated
2709 my $htmldir = shift || File::Spec->catdir($self->blib, "${type}html");
2711 require Module::Build::PodParser;
2714 $self->add_to_cleanup('pod2htm*');
2716 my $pods = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
2717 exclude => [ file_qr('\.(?:bat|com|html)$') ] );
2718 return unless %$pods; # nothing to do
2720 unless ( -d $htmldir ) {
2721 File::Path::mkpath($htmldir, 0, oct(755))
2722 or die "Couldn't mkdir $htmldir: $!";
2725 my @rootdirs = ($type eq 'bin') ? qw(bin) :
2726 $self->installdirs eq 'core' ? qw(lib) : qw(site lib);
2728 my $podpath = join ':',
2731 map [File::Spec->catdir($self->blib, $_), $_],
2734 foreach my $pod ( keys %$pods ) {
2736 my ($name, $path) = File::Basename::fileparse($pods->{$pod},
2737 file_qr('\.(?:pm|plx?|pod)$'));
2738 my @dirs = File::Spec->splitdir( File::Spec->canonpath( $path ) );
2739 pop( @dirs ) if $dirs[-1] eq File::Spec->curdir;
2741 my $fulldir = File::Spec->catfile($htmldir, @rootdirs, @dirs);
2742 my $outfile = File::Spec->catfile($fulldir, "${name}.html");
2743 my $infile = File::Spec->abs2rel($pod);
2745 next if $self->up_to_date($infile, $outfile);
2747 unless ( -d $fulldir ){
2748 File::Path::mkpath($fulldir, 0, oct(755))
2749 or die "Couldn't mkdir $fulldir: $!";
2752 my $path2root = join( '/', ('..') x (@rootdirs+@dirs) );
2753 my $htmlroot = join( '/',
2755 $self->installdirs eq 'core' ? () : qw(site) ) );
2757 my $fh = IO::File->new($infile) or die "Can't read $infile: $!";
2758 my $abstract = Module::Build::PodParser->new(fh => $fh)->get_abstract();
2760 my $title = join( '::', (@dirs, $name) );
2761 $title .= " - $abstract" if $abstract;
2766 "--podpath=$podpath",
2768 "--outfile=$outfile",
2769 '--podroot=' . $self->blib,
2770 "--htmlroot=$htmlroot",
2773 if ( eval{Pod::Html->VERSION(1.03)} ) {
2774 push( @opts, ('--header', '--backlink=Back to Top') );
2775 push( @opts, "--css=$path2root/" . $self->html_css) if $self->html_css;
2778 $self->log_info("HTMLifying $infile -> $outfile\n");
2779 $self->log_verbose("pod2html @opts\n");
2780 Pod::Html::pod2html(@opts); # or warn "pod2html @opts failed: $!";
2785 # Adapted from ExtUtils::MM_Unix
2788 return File::Basename::basename( shift );
2791 # Adapted from ExtUtils::MM_Unix and Pod::Man
2792 # Depending on M::B's dependency policy, it might make more sense to refactor
2793 # Pod::Man::begin_pod() to extract a name() methods, and use them...
2797 my ($vol, $dirs, $file) = File::Spec->splitpath( shift );
2798 my @dirs = File::Spec->splitdir( File::Spec->canonpath($dirs) );
2800 # Remove known exts from the base name
2801 $file =~ s/\.p(?:od|m|l)\z//i;
2803 return join( $self->manpage_separator, @dirs, $file );
2806 sub manpage_separator {
2810 # For systems that don't have 'diff' executable, should use Algorithm::Diff
2813 $self->depends_on('build');
2814 my $local_lib = File::Spec->rel2abs('lib');
2815 my @myINC = grep {$_ ne $local_lib} @INC;
2817 # The actual install destination might not be in @INC, so check there too.
2818 push @myINC, map $self->install_destination($_), qw(lib arch);
2820 my @flags = @{$self->{args}{ARGV}};
2821 @flags = $self->split_like_shell($self->{args}{flags} || '') unless @flags;
2823 my $installmap = $self->install_map;
2824 delete $installmap->{read};
2825 delete $installmap->{write};
2827 my $text_suffix = file_qr('\.(pm|pod)$');
2829 while (my $localdir = each %$installmap) {
2830 my @localparts = File::Spec->splitdir($localdir);
2831 my $files = $self->rscan_dir($localdir, sub {-f});
2833 foreach my $file (@$files) {
2834 my @parts = File::Spec->splitdir($file);
2835 @parts = @parts[@localparts .. $#parts]; # Get rid of blib/lib or similar
2837 my $installed = Module::Build::ModuleInfo->find_module_by_name(
2838 join('::', @parts), \@myINC );
2839 if (not $installed) {
2840 print "Only in lib: $file\n";
2844 my $status = File::Compare::compare($installed, $file);
2845 next if $status == 0; # Files are the same
2846 die "Can't compare $installed and $file: $!" if $status == -1;
2848 if ($file =~ $text_suffix) {
2849 $self->do_system('diff', @flags, $installed, $file);
2851 print "Binary files $file and $installed differ\n";
2857 sub ACTION_pure_install {
2858 shift()->depends_on('install');
2861 sub ACTION_install {
2863 require ExtUtils::Install;
2864 $self->depends_on('build');
2865 ExtUtils::Install::install($self->install_map, !$self->quiet, 0, $self->{args}{uninst}||0);
2868 sub ACTION_fakeinstall {
2870 require ExtUtils::Install;
2871 $self->depends_on('build');
2872 ExtUtils::Install::install($self->install_map, !$self->quiet, 1, $self->{args}{uninst}||0);
2875 sub ACTION_versioninstall {
2878 die "You must have only.pm 0.25 or greater installed for this operation: $@\n"
2879 unless eval { require only; 'only'->VERSION(0.25); 1 };
2881 $self->depends_on('build');
2883 my %onlyargs = map {exists($self->{args}{$_}) ? ($_ => $self->{args}{$_}) : ()}
2884 qw(version versionlib);
2885 only::install::install(%onlyargs);
2890 foreach my $item (map glob($_), $self->cleanup) {
2891 $self->delete_filetree($item);
2895 sub ACTION_realclean {
2897 $self->depends_on('clean');
2898 $self->delete_filetree($self->config_dir, $self->build_script);
2903 require Module::Build::PPMMaker;
2904 my $ppd = Module::Build::PPMMaker->new();
2905 my $file = $ppd->make_ppd(%{$self->{args}}, build => $self);
2906 $self->add_to_cleanup($file);
2909 sub ACTION_ppmdist {
2912 $self->depends_on( 'build' );
2914 my $ppm = $self->ppm_name;
2915 $self->delete_filetree( $ppm );
2916 $self->log_info( "Creating $ppm\n" );
2917 $self->add_to_cleanup( $ppm, "$ppm.tar.gz" );
2919 my %types = ( # translate types/dirs to those expected by ppm
2930 foreach my $type ($self->install_types) {
2931 next if exists( $types{$type} ) && !defined( $types{$type} );
2933 my $dir = File::Spec->catdir( $self->blib, $type );
2934 next unless -e $dir;
2936 my $files = $self->rscan_dir( $dir );
2937 foreach my $file ( @$files ) {
2938 next unless -f $file;
2940 File::Spec->abs2rel( File::Spec->rel2abs( $file ),
2941 File::Spec->rel2abs( $dir ) );
2943 File::Spec->catfile( $ppm, 'blib',
2944 exists( $types{$type} ) ? $types{$type} : $type,
2946 $self->copy_if_modified( from => $file, to => $to_file );
2950 foreach my $type ( qw(bin lib) ) {
2951 local $self->{properties}{html_css} = 'Active.css';
2952 $self->htmlify_pods( $type, File::Spec->catdir($ppm, 'blib', 'html') );
2956 # the directory tar'ed must be blib so we need to do a chdir first
2957 my $target = File::Spec->catfile( File::Spec->updir, $ppm );
2958 $self->_do_in_dir( $ppm, sub { $self->make_tarball( 'blib', $target ) } );
2960 $self->depends_on( 'ppd' );
2962 $self->delete_filetree( $ppm );
2965 sub ACTION_pardist {
2969 if ( not eval { require PAR::Dist; PAR::Dist->VERSION(0.17) } ) {
2971 "In order to create .par distributions, you need to\n"
2972 . "install PAR::Dist first."
2977 $self->depends_on( 'build' );
2979 return PAR::Dist::blib_to_par(
2980 name => $self->dist_name,
2981 version => $self->dist_version,
2988 $self->depends_on('distdir');
2990 my $dist_dir = $self->dist_dir;
2992 $self->make_tarball($dist_dir);
2993 $self->delete_filetree($dist_dir);
2996 sub ACTION_distcheck {
2999 require ExtUtils::Manifest;
3000 local $^W; # ExtUtils::Manifest is not warnings clean.
3001 my ($missing, $extra) = ExtUtils::Manifest::fullcheck();
3003 return unless @$missing || @$extra;
3005 my $msg = "MANIFEST appears to be out of sync with the distribution\n";
3006 if ( $self->invoked_action eq 'distcheck' ) {
3013 sub _add_to_manifest {
3014 my ($self, $manifest, $lines) = @_;
3015 $lines = [$lines] unless ref $lines;
3017 my $existing_files = $self->_read_manifest($manifest);
3018 return unless defined( $existing_files );
3020 @$lines = grep {!exists $existing_files->{$_}} @$lines
3023 my $mode = (stat $manifest)[2];
3024 chmod($mode | oct(222), $manifest) or die "Can't make $manifest writable: $!";
3026 my $fh = IO::File->new("< $manifest") or die "Can't read $manifest: $!";
3027 my $last_line = (<$fh>)[-1] || "\n";
3028 my $has_newline = $last_line =~ /\n$/;
3031 $fh = IO::File->new(">> $manifest") or die "Can't write to $manifest: $!";
3032 print $fh "\n" unless $has_newline;
3033 print $fh map "$_\n", @$lines;
3035 chmod($mode, $manifest);
3037 $self->log_info(map "Added to $manifest: $_\n", @$lines);
3041 my ($self, $dir) = @_;
3043 unless (eval { require Module::Signature; 1 }) {
3044 $self->log_warn("Couldn't load Module::Signature for 'distsign' action:\n $@\n");
3048 # Add SIGNATURE to the MANIFEST
3050 my $manifest = File::Spec->catfile($dir, 'MANIFEST');
3051 die "Signing a distribution requires a MANIFEST file" unless -e $manifest;
3052 $self->_add_to_manifest($manifest, "SIGNATURE Added here by Module::Build");
3055 # Would be nice if Module::Signature took a directory argument.
3057 $self->_do_in_dir($dir, sub {local $Module::Signature::Quiet = 1; Module::Signature::sign()});
3061 my ($self, $dir, $do) = @_;
3063 my $start_dir = $self->cwd;
3064 chdir $dir or die "Can't chdir() to $dir: $!";
3066 my @err = $@ ? ($@) : ();
3067 chdir $start_dir or push @err, "Can't chdir() back to $start_dir: $!";
3068 die join "\n", @err if @err;
3071 sub ACTION_distsign {
3074 local $self->{properties}{sign} = 0; # We'll sign it ourselves
3075 $self->depends_on('distdir') unless -d $self->dist_dir;
3077 $self->_sign_dir($self->dist_dir);
3080 sub ACTION_skipcheck {
3083 require ExtUtils::Manifest;
3084 local $^W; # ExtUtils::Manifest is not warnings clean.
3085 ExtUtils::Manifest::skipcheck();
3088 sub ACTION_distclean {
3091 $self->depends_on('realclean');
3092 $self->depends_on('distcheck');
3095 sub do_create_makefile_pl {
3097 require Module::Build::Compat;
3098 $self->log_info("Creating Makefile.PL\n");
3099 Module::Build::Compat->create_makefile_pl($self->create_makefile_pl, $self, @_);
3100 $self->_add_to_manifest('MANIFEST', 'Makefile.PL');
3103 sub do_create_readme {
3105 $self->delete_filetree('README');
3107 my $docfile = $self->_main_docfile;
3108 unless ( $docfile ) {
3109 $self->log_warn(<<EOF);
3110 Cannot create README: can't determine which file contains documentation;
3111 Must supply either 'dist_version_from', or 'module_name' parameter.
3116 if ( eval {require Pod::Readme; 1} ) {
3117 $self->log_info("Creating README using Pod::Readme\n");
3119 my $parser = Pod::Readme->new;
3120 $parser->parse_from_file($docfile, 'README', @_);
3122 } elsif ( eval {require Pod::Text; 1} ) {
3123 $self->log_info("Creating README using Pod::Text\n");
3125 my $fh = IO::File->new('> README');
3126 if ( defined($fh) ) {
3130 # work around bug in Pod::Text 3.01, which expects
3131 # Pod::Simple::parse_file to take input and output filehandles
3132 # when it actually only takes an input filehandle
3135 $old_parse_file = \&{"Pod::Simple::parse_file"}
3137 local *{"Pod::Simple::parse_file"} = sub {
3139 $self->output_fh($_[1]) if $_[1];
3140 $self->$old_parse_file($_[0]);
3142 if $Pod::Text::VERSION
3143 == 3.01; # Split line to avoid evil version-finder
3145 Pod::Text::pod2text( $docfile, $fh );
3150 "Cannot create 'README' file: Can't open file for writing\n" );
3155 $self->log_warn("Can't load Pod::Readme or Pod::Text to create README\n");
3159 $self->_add_to_manifest('MANIFEST', 'README');
3164 if ( my $pm_file = $self->dist_version_from ) {
3165 (my $pod_file = $pm_file) =~ s/.pm$/.pod/;
3166 return (-e $pod_file ? $pod_file : $pm_file);
3172 sub ACTION_distdir {
3175 $self->depends_on('distmeta');
3177 my $dist_files = $self->_read_manifest('MANIFEST')
3178 or die "Can't create distdir without a MANIFEST file - run 'manifest' action first";
3179 delete $dist_files->{SIGNATURE}; # Don't copy, create a fresh one
3180 die "No files found in MANIFEST - try running 'manifest' action?\n"
3181 unless ($dist_files and keys %$dist_files);
3182 my $metafile = $self->metafile;
3183 $self->log_warn("*** Did you forget to add $metafile to the MANIFEST?\n")
3184 unless exists $dist_files->{$metafile};
3186 my $dist_dir = $self->dist_dir;
3187 $self->delete_filetree($dist_dir);
3188 $self->log_info("Creating $dist_dir\n");
3189 $self->add_to_cleanup($dist_dir);
3191 foreach my $file (keys %$dist_files) {
3192 my $new = $self->copy_if_modified(from => $file, to_dir => $dist_dir, verbose => 0);
3195 $self->_sign_dir($dist_dir) if $self->{properties}{sign};
3198 sub ACTION_disttest {
3201 $self->depends_on('distdir');
3206 # XXX could be different names for scripts
3208 $self->run_perl_script('Build.PL') # XXX Should this be run w/ --nouse-rcfile
3209 or die "Error executing 'Build.PL' in dist directory: $!";
3210 $self->run_perl_script('Build')
3211 or die "Error executing 'Build' in dist directory: $!";
3212 $self->run_perl_script('Build', [], ['test'])
3213 or die "Error executing 'Build test' in dist directory";
3217 sub _write_default_maniskip {
3219 my $file = shift || 'MANIFEST.SKIP';
3220 my $fh = IO::File->new("> $file")
3221 or die "Can't open $file: $!";
3223 # This is derived from MakeMaker's default MANIFEST.SKIP file with
3227 # Avoid version control files.
3234 # Avoid Makemaker generated and utility files.
3242 # Avoid VMS specific Makmaker generated files
3247 # Avoid Module::Build generated and utility files.
3255 # Avoid Devel::Cover generated files
3258 # Avoid temp and backup files.
3267 # Avoid OS-specific files/dirs
3270 # Mac OSX SMB mount metadata files
3272 # Avoid archives of this distribution
3275 # Skip, for example, 'Module-Build-0.27.tar.gz'
3276 print $fh '\b'.$self->dist_name.'-[\d\.\_]+'."\n";
3281 sub ACTION_manifest {
3284 my $maniskip = 'MANIFEST.SKIP';
3285 unless ( -e 'MANIFEST' || -e $maniskip ) {
3286 $self->log_warn("File '$maniskip' does not exist: Creating a default '$maniskip'\n");
3287 $self->_write_default_maniskip($maniskip);
3290 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3291 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3292 ExtUtils::Manifest::mkmanifest();
3295 # Case insenstive regex for files
3297 return File::Spec->case_tolerant ? qr($_[0])i : qr($_[0]);
3302 return "$self->{properties}{dist_name}-$self->{properties}{dist_version}";
3307 return 'PPM-' . $self->dist_dir;
3311 my ($self, $dir) = @_;
3312 return unless -d $dir;
3315 opendir DH, $dir or die "Can't read directory $dir: $!";
3318 while (defined (my $file = readdir DH)) {
3319 my $full_path = File::Spec->catfile($dir, $file);
3320 next if -d $full_path;
3321 push @files, $full_path;
3329 for ($self->{properties}{script_files}) {
3333 # Always coerce into a hash
3334 return $_ if UNIVERSAL::isa($_, 'HASH');
3335 return $_ = { map {$_,1} @$_ } if UNIVERSAL::isa($_, 'ARRAY');
3337 die "'script_files' must be a hashref, arrayref, or string" if ref();
3339 return $_ = { map {$_,1} $self->_files_in( $_ ) } if -d $_;
3340 return $_ = {$_ => 1};
3343 return $_ = { map {$_,1} $self->_files_in('bin') };
3345 BEGIN { *scripts = \&script_files; }
3349 perl => 'http://dev.perl.org/licenses/',
3350 apache => 'http://apache.org/licenses/LICENSE-2.0',
3351 artistic => 'http://opensource.org/licenses/artistic-license.php',
3352 artistic_2 => 'http://opensource.org/licenses/artistic-license-2.0.php',
3353 lgpl => 'http://opensource.org/licenses/lgpl-license.php',
3354 bsd => 'http://opensource.org/licenses/bsd-license.php',
3355 gpl => 'http://opensource.org/licenses/gpl-license.php',
3356 gpl2 => 'http://opensource.org/licenses/gpl-2.0.php',
3357 gpl3 => 'http://opensource.org/licenses/gpl-3.0.html',
3358 mit => 'http://opensource.org/licenses/mit-license.php',
3359 mozilla => 'http://opensource.org/licenses/mozilla1.1.php',
3360 open_source => undef,
3361 unrestricted => undef,
3362 restrictive => undef,
3365 sub valid_licenses {
3371 my ($self, $h, $k, $v) = @_;
3372 if (ref $h->{$k} eq 'ARRAY') {
3373 push @{$h->{$k}}, ref $v ? @$v : $v;
3374 } elsif (ref $h->{$k} eq 'HASH') {
3375 $h->{$k}{$_} = $v->{$_} foreach keys %$v;
3381 sub ACTION_distmeta {
3384 $self->do_create_makefile_pl if $self->create_makefile_pl;
3385 $self->do_create_readme if $self->create_readme;
3386 $self->do_create_metafile;
3389 sub do_create_metafile {
3391 return if $self->{wrote_metadata};
3393 my $p = $self->{properties};
3394 my $metafile = $self->metafile;
3396 unless ($p->{license}) {
3397 $self->log_warn("No license specified, setting license = 'unknown'\n");
3398 $p->{license} = 'unknown';
3400 unless (exists $self->valid_licenses->{ $p->{license} }) {
3401 die "Unknown license type '$p->{license}'";
3404 # If we're in the distdir, the metafile may exist and be non-writable.
3405 $self->delete_filetree($metafile);
3406 $self->log_info("Creating $metafile\n");
3408 # Since we're building ourself, we have to do some special stuff
3409 # here: the ConfigData module is found in blib/lib.
3411 if (($self->module_name || '') eq 'Module::Build') {
3412 $self->depends_on('config_data');
3413 push @INC, File::Spec->catdir($self->blib, 'lib');
3416 $self->write_metafile;
3419 sub write_metafile {
3421 my $metafile = $self->metafile;
3423 if ($self->_mb_feature('YAML_support')) {
3427 # We use YAML::Node to get the order nice in the YAML file.
3428 $self->prepare_metadata( my $node = YAML::Node->new({}) );
3430 # YAML API changed after version 0.30
3431 my $yaml_sub = $YAML::VERSION le '0.30' ? \&YAML::StoreFile : \&YAML::DumpFile;
3432 $self->{wrote_metadata} = $yaml_sub->($metafile, $node );
3435 require Module::Build::YAML;
3436 my (%node, @order_keys);
3437 $self->prepare_metadata(\%node, \@order_keys);
3438 $node{_order} = \@order_keys;
3439 &Module::Build::YAML::DumpFile($metafile, \%node);
3440 $self->{wrote_metadata} = 1;
3443 $self->_add_to_manifest('MANIFEST', $metafile);
3446 sub prepare_metadata {
3447 my ($self, $node, $keys) = @_;
3448 my $p = $self->{properties};
3450 # A little helper sub
3451 my $add_node = sub {
3452 my ($name, $val) = @_;
3453 $node->{$name} = $val;
3454 push @$keys, $name if $keys;
3457 foreach (qw(dist_name dist_version dist_author dist_abstract license)) {
3458 (my $name = $_) =~ s/^dist_//;
3459 $add_node->($name, $self->$_());
3460 die "ERROR: Missing required field '$_' for META.yml\n"
3461 unless defined($node->{$name}) && length($node->{$name});
3463 $node->{version} = '' . $node->{version}; # Stringify version objects
3465 if (defined( $self->license ) &&
3466 defined( my $url = $self->valid_licenses->{ $self->license } )) {
3467 $node->{resources}{license} = $url;
3470 if (exists $p->{configure_requires}) {
3471 foreach my $spec (keys %{$p->{configure_requires}}) {
3472 warn ("Warning: $spec is listed in 'configure_requires', but ".
3473 "it is not found in any of the other prereq fields.\n")
3474 unless grep exists $p->{$_}{$spec},
3475 grep !/conflicts$/, @{$self->prereq_action_types};
3479 foreach ( 'configure_requires', @{$self->prereq_action_types} ) {
3480 if (exists $p->{$_} and keys %{ $p->{$_} }) {
3481 $add_node->($_, $p->{$_});
3485 if (exists $p->{dynamic_config}) {
3486 $add_node->('dynamic_config', $p->{dynamic_config});
3488 my $pkgs = eval { $self->find_dist_packages };
3490 $self->log_warn("$@\nWARNING: Possible missing or corrupt 'MANIFEST' file.\n" .
3491 "Nothing to enter for 'provides' field in META.yml\n");
3493 $node->{provides} = $pkgs if %$pkgs;
3496 if (exists $p->{no_index}) {
3497 $add_node->('no_index', $p->{no_index});
3500 $add_node->('generated_by', "Module::Build version $Module::Build::VERSION");
3502 $add_node->('meta-spec',
3504 url => 'http://module-build.sourceforge.net/META-spec-v1.2.html',
3507 while (my($k, $v) = each %{$self->meta_add}) {
3508 $add_node->($k, $v);
3511 while (my($k, $v) = each %{$self->meta_merge}) {
3512 $self->_hash_merge($node, $k, $v);
3518 sub _read_manifest {
3519 my ($self, $file) = @_;
3520 return undef unless -e $file;
3522 require ExtUtils::Manifest; # ExtUtils::Manifest is not warnings clean.
3523 local ($^W, $ExtUtils::Manifest::Quiet) = (0,1);
3524 return scalar ExtUtils::Manifest::maniread($file);
3527 sub find_dist_packages {
3530 # Only packages in .pm files are candidates for inclusion here.
3531 # Only include things in the MANIFEST, not things in developer's
3534 my $manifest = $self->_read_manifest('MANIFEST')
3535 or die "Can't find dist packages without a MANIFEST file - run 'manifest' action first";
3538 my %dist_files = map { $self->localize_file_path($_) => $_ }
3541 my @pm_files = grep {exists $dist_files{$_}} keys %{ $self->find_pm_files };
3543 # First, we enumerate all packages & versions,
3544 # seperating into primary & alternative candidates
3546 foreach my $file (@pm_files) {
3547 next if $dist_files{$file} =~ m{^t/}; # Skip things in t/
3549 my @path = split( /\//, $dist_files{$file} );
3550 (my $prime_package = join( '::', @path[1..$#path] )) =~ s/\.pm$//;
3552 my $pm_info = Module::Build::ModuleInfo->new_from_file( $file );
3554 foreach my $package ( $pm_info->packages_inside ) {
3555 next if $package eq 'main'; # main can appear numerous times, ignore
3556 next if grep /^_/, split( /::/, $package ); # private package, ignore
3558 my $version = $pm_info->version( $package );
3560 if ( $package eq $prime_package ) {
3561 if ( exists( $prime{$package} ) ) {
3562 # M::B::ModuleInfo will handle this conflict
3563 die "Unexpected conflict in '$package'; multiple versions found.\n";
3565 $prime{$package}{file} = $dist_files{$file};
3566 $prime{$package}{version} = $version if defined( $version );
3569 push( @{$alt{$package}}, {
3570 file => $dist_files{$file},
3571 version => $version,
3577 # Then we iterate over all the packages found above, identifying conflicts
3578 # and selecting the "best" candidate for recording the file & version
3580 foreach my $package ( keys( %alt ) ) {
3581 my $result = $self->_resolve_module_versions( $alt{$package} );
3583 if ( exists( $prime{$package} ) ) { # primary package selected
3585 if ( $result->{err} ) {
3586 # Use the selected primary package, but there are conflicting
3587 # errors amoung multiple alternative packages that need to be
3590 "Found conflicting versions for package '$package'\n" .
3591 " $prime{$package}{file} ($prime{$package}{version})\n" .
3595 } elsif ( defined( $result->{version} ) ) {
3596 # There is a primary package selected, and exactly one
3597 # alternative package
3599 if ( exists( $prime{$package}{version} ) &&
3600 defined( $prime{$package}{version} ) ) {
3601 # Unless the version of the primary package agrees with the
3602 # version of the alternative package, report a conflict
3603 if ( $self->compare_versions( $prime{$package}{version}, '!=',
3604 $result->{version} ) ) {
3606 "Found conflicting versions for package '$package'\n" .
3607 " $prime{$package}{file} ($prime{$package}{version})\n" .
3608 " $result->{file} ($result->{version})\n"
3613 # The prime package selected has no version so, we choose to
3614 # use any alternative package that does have a version
3615 $prime{$package}{file} = $result->{file};
3616 $prime{$package}{version} = $result->{version};
3620 # no alt package found with a version, but we have a prime
3621 # package so we use it whether it has a version or not
3624 } else { # No primary package was selected, use the best alternative
3626 if ( $result->{err} ) {
3628 "Found conflicting versions for package '$package'\n" .
3633 # Despite possible conflicting versions, we choose to record
3634 # something rather than nothing
3635 $prime{$package}{file} = $result->{file};
3636 $prime{$package}{version} = $result->{version}
3637 if defined( $result->{version} );
3641 # Stringify versions. Can't use exists() here because of bug in YAML::Node.
3642 for (grep defined $_->{version}, values %prime) {
3643 $_->{version} = '' . $_->{version};
3649 # seperate out some of the conflict resolution logic from
3650 # $self->find_dist_packages(), above, into a helper function.
3652 sub _resolve_module_versions {
3655 my $packages = shift;
3657 my( $file, $version );
3659 foreach my $p ( @$packages ) {
3660 if ( defined( $p->{version} ) ) {
3661 if ( defined( $version ) ) {
3662 if ( $self->compare_versions( $version, '!=', $p->{version} ) ) {
3663 $err .= " $p->{file} ($p->{version})\n";
3665 # same version declared multiple times, ignore
3669 $version = $p->{version};
3672 $file ||= $p->{file} if defined( $p->{file} );
3676 $err = " $file ($version)\n" . $err;
3681 version => $version,
3689 my ($self, $dir, $file) = @_;
3692 $self->log_info("Creating $file.tar.gz\n");
3694 if ($self->{args}{tar}) {
3695 my $tar_flags = $self->verbose ? 'cvf' : 'cf';
3696 $self->do_system($self->split_like_shell($self->{args}{tar}), $tar_flags, "$file.tar", $dir);
3697 $self->do_system($self->split_like_shell($self->{args}{gzip}), "$file.tar") if $self->{args}{gzip};
3699 require Archive::Tar;
3700 # Archive::Tar versions >= 1.09 use the following to enable a compatibility
3701 # hack so that the resulting archive is compatible with older clients.
3702 $Archive::Tar::DO_NOT_USE_PREFIX = 0;
3703 my $files = $self->rscan_dir($dir);
3704 Archive::Tar->create_archive("$file.tar.gz", 1, @$files);
3710 my( $type, $value ) = ( @_, '<empty>' );
3712 Carp::croak( 'Type argument missing' )
3713 unless defined( $type );
3715 my $map = $self->{properties}{install_path};
3716 return $map unless @_;
3718 # delete existing value if $value is literal undef()
3719 unless ( defined( $value ) ) {
3720 delete( $map->{$type} );
3724 # return existing value if no new $value is given
3725 if ( $value eq '<empty>' ) {
3726 return undef unless exists $map->{$type};
3727 return $map->{$type};
3730 # set value if $value is a valid relative path
3731 return $map->{$type} = $value;
3734 sub install_base_relpaths {
3735 # Usage: install_base_relpaths(), install_base_relpaths('lib'),
3736 # or install_base_relpaths('lib' => $value);
3738 my $map = $self->{properties}{install_base_relpaths};
3739 return $map unless @_;
3740 return $self->_relpaths($map, @_);
3744 # Translated from ExtUtils::MM_Any::init_INSTALL_from_PREFIX
3745 sub prefix_relative {
3746 my ($self, $type) = @_;
3747 my $installdirs = $self->installdirs;
3749 my $relpath = $self->install_sets($installdirs)->{$type};
3751 return $self->_prefixify($relpath,
3752 $self->original_prefix($installdirs),
3759 my( $map, $type, $value ) = ( @_, '<empty>' );
3761 Carp::croak( 'Type argument missing' )
3762 unless defined( $type );
3766 # delete existing value if $value is literal undef()
3767 unless ( defined( $value ) ) {
3768 delete( $map->{$type} );
3772 # return existing value if no new $value is given
3773 elsif ( $value eq '<empty>' ) {
3774 return undef unless exists $map->{$type};
3775 @value = @{ $map->{$type} };
3778 # set value if $value is a valid relative path
3780 Carp::croak( "Value must be a relative path" )
3781 if File::Spec::Unix->file_name_is_absolute($value);
3783 @value = split( /\//, $value );
3784 $map->{$type} = \@value;
3787 return File::Spec->catdir( @value );
3790 # Defaults to use in case the config install paths cannot be prefixified.
3791 sub prefix_relpaths {
3792 # Usage: prefix_relpaths('site'), prefix_relpaths('site', 'lib'),
3793 # or prefix_relpaths('site', 'lib' => $value);
3795 my $installdirs = shift || $self->installdirs;
3796 my $map = $self->{properties}{prefix_relpaths}{$installdirs};
3797 return $map unless @_;
3798 return $self->_relpaths($map, @_);
3802 # Translated from ExtUtils::MM_Unix::prefixify()
3804 my($self, $path, $sprefix, $type) = @_;
3806 my $rprefix = $self->prefix;
3807 $rprefix .= '/' if $sprefix =~ m|/$|;
3809 $self->log_verbose(" prefixify $path from $sprefix to $rprefix\n")
3810 if defined( $path ) && length( $path );
3812 if( !defined( $path ) || ( length( $path ) == 0 ) ) {
3813 $self->log_verbose(" no path to prefixify, falling back to default.\n");
3814 return $self->_prefixify_default( $type, $rprefix );
3815 } elsif( !File::Spec->file_name_is_absolute($path) ) {
3816 $self->log_verbose(" path is relative, not prefixifying.\n");
3817 } elsif( $sprefix eq $rprefix ) {
3818 $self->log_verbose(" no new prefix.\n");
3819 } elsif( $path !~ s{^\Q$sprefix\E\b}{}s ) {
3820 $self->log_verbose(" cannot prefixify, falling back to default.\n");
3821 return $self->_prefixify_default( $type, $rprefix );
3824 $self->log_verbose(" now $path in $rprefix\n");
3829 sub _prefixify_default {
3832 my $rprefix = shift;
3834 my $default = $self->prefix_relpaths($self->installdirs, $type);
3836 $self->log_verbose(" no default install location for type '$type', using prefix '$rprefix'.\n");
3843 sub install_destination {
3844 my ($self, $type) = @_;
3846 return $self->install_path($type) if $self->install_path($type);
3848 if ( $self->install_base ) {
3849 my $relpath = $self->install_base_relpaths($type);
3850 return $relpath ? File::Spec->catdir($self->install_base, $relpath) : undef;
3853 if ( $self->prefix ) {
3854 my $relpath = $self->prefix_relative($type);
3855 return $relpath ? File::Spec->catdir($self->prefix, $relpath) : undef;
3858 return $self->install_sets($self->installdirs)->{$type};
3865 if ( $self->install_base ) {
3866 %types = %{$self->install_base_relpaths};
3867 } elsif ( $self->prefix ) {
3868 %types = %{$self->prefix_relpaths};
3870 %types = %{$self->install_sets($self->installdirs)};
3873 %types = (%types, %{$self->install_path});
3875 return sort keys %types;
3879 my ($self, $blib) = @_;
3880 $blib ||= $self->blib;
3882 my( %map, @skipping );
3883 foreach my $type ($self->install_types) {
3884 my $localdir = File::Spec->catdir( $blib, $type );
3885 next unless -e $localdir;
3887 if (my $dest = $self->install_destination($type)) {
3888 $map{$localdir} = $dest;
3890 push( @skipping, $type );
3895 "WARNING: Can't figure out install path for types: @skipping\n" .
3896 "Files will not be installed.\n"
3899 # Write the packlist into the same place as ExtUtils::MakeMaker.
3900 if ($self->create_packlist and my $module_name = $self->module_name) {
3901 my $archdir = $self->install_destination('arch');
3902 my @ext = split /::/, $module_name;
3903 $map{write} = File::Spec->catfile($archdir, 'auto', @ext, '.packlist');
3907 if (length(my $destdir = $self->destdir || '')) {
3908 foreach (keys %map) {
3909 # Need to remove volume from $map{$_} using splitpath, or else
3910 # we'll create something crazy like C:\Foo\Bar\E:\Baz\Quux
3911 # VMS will always have the file separate than the path.
3912 my ($volume, $path, $file) = File::Spec->splitpath( $map{$_}, 1 );
3914 # catdir needs a list of directories, or it will create something
3915 # crazy like volume:[Foo.Bar.volume.Baz.Quux]
3916 my @dirs = File::Spec->splitdir($path);
3918 # First merge the directories
3919 $path = File::Spec->catdir($destdir, @dirs);
3921 # Then put the file back on if there is one.
3923 $map{$_} = File::Spec->catfile($path, $file)
3930 $map{read} = ''; # To keep ExtUtils::Install quiet
3937 foreach my $action (@_) {
3938 $self->_call_action($action);
3943 my ($self, $dir, $pattern) = @_;
3945 local $_; # find() can overwrite $_, so protect ourselves
3946 my $subr = !$pattern ? sub {push @result, $File::Find::name} :
3947 !ref($pattern) || (ref $pattern eq 'Regexp') ? sub {push @result, $File::Find::name if /$pattern/} :
3948 ref($pattern) eq 'CODE' ? sub {push @result, $File::Find::name if $pattern->()} :
3949 die "Unknown pattern type";
3951 File::Find::find({wanted => $subr, no_chdir => 1}, $dir);
3955 sub delete_filetree {
3960 $self->log_info("Deleting $_\n");
3961 File::Path::rmtree($_, 0, 0);
3962 die "Couldn't remove '$_': $!\n" if -e $_;
3968 sub autosplit_file {
3969 my ($self, $file, $to) = @_;
3971 my $dir = File::Spec->catdir($to, 'lib', 'auto');
3972 AutoSplit::autosplit($file, $dir);
3976 # Returns a CBuilder object
3979 my $p = $self->{properties};
3980 return $p->{_cbuilder} if $p->{_cbuilder};
3981 die "Module::Build is not configured with C_support"
3982 unless $self->_mb_feature('C_support');
3984 require ExtUtils::CBuilder;
3985 return $p->{_cbuilder} = ExtUtils::CBuilder->new(
3986 config => $self->config,
3987 ($self->quiet ? (quiet => 1 ) : ()),
3991 sub have_c_compiler {
3994 my $p = $self->{properties};
3995 return $p->{have_compiler} if defined $p->{have_compiler};
3997 $self->log_verbose("Checking if compiler tools configured... ");
3998 my $b = eval { $self->cbuilder };
3999 my $have = $b && $b->have_compiler;
4000 $self->log_verbose($have ? "ok.\n" : "failed.\n");
4001 return $p->{have_compiler} = $have;
4005 my ($self, $file, %args) = @_;
4006 my $b = $self->cbuilder;
4008 my $obj_file = $b->object_file($file);
4009 $self->add_to_cleanup($obj_file);
4010 return $obj_file if $self->up_to_date($file, $obj_file);
4012 $b->compile(source => $file,
4013 defines => $args{defines},
4014 object_file => $obj_file,
4015 include_dirs => $self->include_dirs,
4016 extra_compiler_flags => $self->extra_compiler_flags,
4023 my ($self, $to, $file_base) = @_;
4024 my $p = $self->{properties}; # For convenience
4026 my $spec = $self->_infer_xs_spec($file_base);
4028 $self->add_to_cleanup($spec->{lib_file});
4030 my $objects = $p->{objects} || [];
4032 return $spec->{lib_file}
4033 if $self->up_to_date([$spec->{obj_file}, @$objects],
4036 my $module_name = $self->module_name;
4037 $module_name ||= $spec->{module_name};
4039 $self->cbuilder->link(
4040 module_name => $module_name,
4041 objects => [$spec->{obj_file}, @$objects],
4042 lib_file => $spec->{lib_file},
4043 extra_linker_flags => $p->{extra_linker_flags} );
4045 return $spec->{lib_file};
4049 my ($self, $file, %args) = @_;
4051 $self->log_info("$file -> $args{outfile}\n");
4053 if (eval {require ExtUtils::ParseXS; 1}) {
4055 ExtUtils::ParseXS::process_file(
4058 output => $args{outfile},
4061 # Ok, I give up. Just use backticks.
4063 my $xsubpp = Module::Build::ModuleInfo->find_module_by_name('ExtUtils::xsubpp')
4064 or die "Can't find ExtUtils::xsubpp in INC (@INC)";
4067 push @typemaps, Module::Build::ModuleInfo->find_module_by_name(
4068 'ExtUtils::typemap', \@INC
4070 my $lib_typemap = Module::Build::ModuleInfo->find_module_by_name(
4071 'typemap', [File::Basename::dirname($file)]
4073 push @typemaps, $lib_typemap if $lib_typemap;
4074 @typemaps = map {+'-typemap', $_} @typemaps;
4076 my $cf = $self->{config};
4077 my $perl = $self->{properties}{perl};
4079 my @command = ($perl, "-I".$cf->get('installarchlib'), "-I".$cf->get('installprivlib'), $xsubpp, '-noprototypes',
4082 $self->log_info("@command\n");
4083 my $fh = IO::File->new("> $args{outfile}") or die "Couldn't write $args{outfile}: $!";
4084 print {$fh} $self->_backticks(@command);
4089 sub split_like_shell {
4090 my ($self, $string) = @_;
4092 return () unless defined($string);
4093 return @$string if UNIVERSAL::isa($string, 'ARRAY');
4094 $string =~ s/^\s+|\s+$//g;
4095 return () unless length($string);
4097 return Text::ParseWords::shellwords($string);
4101 # Returns a string that the shell can evaluate as a perl command.
4102 # This should be avoided whenever possible, since "the shell" really
4103 # means zillions of shells on zillions of platforms and it's really
4104 # hard to get it right all the time.
4106 # Some of this code is stolen with permission from ExtUtils::MakeMaker.
4108 my($self, $cmd, $switches, $args) = @_;
4109 $switches = [] unless defined $switches;
4110 $args = [] unless defined $args;
4112 # Strip leading and trailing newlines
4116 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
4117 return $self->_quote_args($perl, @$switches, '-e', $cmd, @$args);
4120 sub run_perl_script {
4121 my ($self, $script, $preargs, $postargs) = @_;
4122 foreach ($preargs, $postargs) {
4123 $_ = [ $self->split_like_shell($_) ] unless ref();
4125 return $self->run_perl_command([@$preargs, $script, @$postargs]);
4128 sub run_perl_command {
4129 # XXX Maybe we should accept @args instead of $args? Must resolve
4130 # this before documenting.
4131 my ($self, $args) = @_;
4132 $args = [ $self->split_like_shell($args) ] unless ref($args);
4133 my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
4135 # Make sure our local additions to @INC are propagated to the subprocess
4136 local $ENV{PERL5LIB} = join $self->config('path_sep'), $self->_added_to_INC;
4138 return $self->do_system($perl, @$args);
4141 # Infer various data from the path of the input filename
4142 # that is needed to create output files.
4143 # The input filename is expected to be of the form:
4144 # lib/Module/Name.ext or Module/Name.ext
4145 sub _infer_xs_spec {
4149 my $cf = $self->{config};
4153 my( $v, $d, $f ) = File::Spec->splitpath( $file );
4154 my @d = File::Spec->splitdir( $d );
4155 (my $file_base = $f) =~ s/\.[^.]+$//i;
4157 $spec{base_name} = $file_base;
4159 $spec{src_dir} = File::Spec->catpath( $v, $d, '' );
4162 shift( @d ) while @d && ($d[0] eq 'lib' || $d[0] eq '');
4163 pop( @d ) while @d && $d[-1] eq '';
4164 $spec{module_name} = join( '::', (@d, $file_base) );
4166 $spec{archdir} = File::Spec->catdir($self->blib, 'arch', 'auto',
4169 $spec{bs_file} = File::Spec->catfile($spec{archdir}, "${file_base}.bs");
4171 $spec{lib_file} = File::Spec->catfile($spec{archdir},
4172 "${file_base}.".$cf->get('dlext'));
4174 $spec{c_file} = File::Spec->catfile( $spec{src_dir},
4177 $spec{obj_file} = File::Spec->catfile( $spec{src_dir},
4178 "${file_base}".$cf->get('obj_ext') );
4184 my ($self, $file) = @_;
4186 my $spec = $self->_infer_xs_spec($file);
4188 # File name, minus the suffix
4189 (my $file_base = $file) =~ s/\.[^.]+$//;
4192 $self->add_to_cleanup($spec->{c_file});
4194 unless ($self->up_to_date($file, $spec->{c_file})) {
4195 $self->compile_xs($file, outfile => $spec->{c_file});
4199 my $v = $self->dist_version;
4200 $self->compile_c($spec->{c_file},
4201 defines => {VERSION => qq{"$v"}, XS_VERSION => qq{"$v"}});
4204 File::Path::mkpath($spec->{archdir}, 0, oct(777)) unless -d $spec->{archdir};
4207 $self->add_to_cleanup($spec->{bs_file});
4208 unless ($self->up_to_date($file, $spec->{bs_file})) {
4209 require ExtUtils::Mkbootstrap;
4210 $self->log_info("ExtUtils::Mkbootstrap::Mkbootstrap('$spec->{bs_file}')\n");
4211 ExtUtils::Mkbootstrap::Mkbootstrap($spec->{bs_file}); # Original had $BSLOADLIBS - what's that?
4212 {my $fh = IO::File->new(">> $spec->{bs_file}")} # create
4213 utime((time)x2, $spec->{bs_file}); # touch
4217 $self->link_c($spec->{archdir}, $file_base);
4221 my ($self, @cmd) = @_;
4222 $self->log_info("@cmd\n");
4224 # Some systems proliferate huge PERL5LIBs, try to ameliorate:
4226 my $sep = $self->config('path_sep');
4227 local $ENV{PERL5LIB} =
4228 ( !exists($ENV{PERL5LIB}) ? '' :
4229 length($ENV{PERL5LIB}) < 500
4231 : join $sep, grep { ! $seen{$_}++ and -d $_ } split($sep, $ENV{PERL5LIB})
4234 my $status = system(@cmd);
4235 if ($status and $! =~ /Argument list too long/i) {
4236 my $env_entries = '';
4237 foreach (sort keys %ENV) { $env_entries .= "$_=>".length($ENV{$_})."; " }
4238 warn "'Argument list' was 'too long', env lengths are $env_entries";
4243 sub copy_if_modified {
4247 : ( from => shift, to_dir => shift, flatten => shift )
4249 $args{verbose} = !$self->quiet
4250 unless exists $args{verbose};
4252 my $file = $args{from};
4253 unless (defined $file and length $file) {
4254 die "No 'from' parameter given to copy_if_modified";
4258 if (defined $args{to} and length $args{to}) {
4259 $to_path = $args{to};
4260 } elsif (defined $args{to_dir} and length $args{to_dir}) {
4261 $to_path = File::Spec->catfile( $args{to_dir}, $args{flatten}
4262 ? File::Basename::basename($file)
4265 die "No 'to' or 'to_dir' parameter given to copy_if_modified";
4268 return if $self->up_to_date($file, $to_path); # Already fresh
4271 local $self->{properties}{quiet} = 1;
4272 $self->delete_filetree($to_path); # delete destination if exists
4275 # Create parent directories
4276 File::Path::mkpath(File::Basename::dirname($to_path), 0, oct(777));
4278 $self->log_info("Copying $file -> $to_path\n") if $args{verbose};
4280 if ($^O eq 'os2') {# copy will not overwrite; 0x1 = overwrite
4281 chmod 0666, $to_path;
4282 File::Copy::syscopy($file, $to_path, 0x1) or die "Can't copy('$file', '$to_path'): $!";
4284 File::Copy::copy($file, $to_path) or die "Can't copy('$file', '$to_path'): $!";
4287 # mode is read-only + (executable if source is executable)
4288 my $mode = oct(444) | ( $self->is_executable($file) ? oct(111) : 0 );
4289 chmod( $mode, $to_path );
4295 my ($self, $source, $derived) = @_;
4296 $source = [$source] unless ref $source;
4297 $derived = [$derived] unless ref $derived;
4299 return 0 if grep {not -e} @$derived;
4301 my $most_recent_source = time / (24*60*60);
4302 foreach my $file (@$source) {
4304 $self->log_warn("Can't find source file $file for up-to-date check");
4307 $most_recent_source = -M _ if -M _ < $most_recent_source;
4310 foreach my $derived (@$derived) {
4311 return 0 if -M $derived > $most_recent_source;
4317 my ($self, $first, $second) = @_;
4318 # File::Spec doesn't have an easy way to check whether one directory
4319 # is inside another, unfortunately.
4321 ($first, $second) = map File::Spec->canonpath($_), ($first, $second);
4322 my @first_dirs = File::Spec->splitdir($first);
4323 my @second_dirs = File::Spec->splitdir($second);
4325 return 0 if @second_dirs < @first_dirs;
4327 my $is_same = ( File::Spec->case_tolerant
4328 ? sub {lc(shift()) eq lc(shift())}
4329 : sub {shift() eq shift()} );
4331 while (@first_dirs) {
4332 return 0 unless $is_same->(shift @first_dirs, shift @second_dirs);
4344 Module::Build::Base - Default methods for Module::Build
4348 Please see the Module::Build documentation.
4352 The C<Module::Build::Base> module defines the core functionality of
4353 C<Module::Build>. Its methods may be overridden by any of the
4354 platform-dependent modules in the C<Module::Build::Platform::>
4355 namespace, but the intention here is to make this base module as
4356 platform-neutral as possible. Nicely enough, Perl has several core
4357 tools available in the C<File::> namespace for doing this, so the task
4358 isn't very difficult.
4360 Please see the C<Module::Build> documentation for more details.
4364 Ken Williams <kwilliams@cpan.org>
4368 Copyright (c) 2001-2006 Ken Williams. All rights reserved.
4370 This library is free software; you can redistribute it and/or
4371 modify it under the same terms as Perl itself.
4375 perl(1), Module::Build(3)