Alien-ROOT

 view release on metacpan or  search on metacpan

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

  # from a different configuration that happens to be already
  # installed in @INC.
  if ($ENV{PERL_CORE}) {
    push @cmd, '-I' . File::Spec->catdir(File::Basename::dirname($perl), 'lib');
  }

  push @cmd, qw(-MConfig=myconfig -e print -e myconfig);
  return $self->_backticks(@cmd) eq Config->myconfig;
}

# cache _discover_perl_interpreter() results
{
  my $known_perl;
  sub find_perl_interpreter {
    my $self = shift;

    return $known_perl if defined($known_perl);
    return $known_perl = $self->_discover_perl_interpreter;
  }
}

# Returns the absolute path of the perl interpreter used to invoke
# this process. The path is derived from $^X or $Config{perlpath}. On
# some platforms $^X contains the complete absolute path of the
# interpreter, on other it may contain a relative path, or simply
# 'perl'. This can also vary depending on whether a path was supplied
# when perl was invoked. Additionally, the value in $^X may omit the
# executable extension on platforms that use one. It's a fatal error
# if the interpreter can't be found because it can result in undefined
# behavior by routines that depend on it (generating errors or
# invoking the wrong perl.)
sub _discover_perl_interpreter {
  my $proto = shift;
  my $c     = ref($proto) ? $proto->{config} : 'Module::Build::Config';

  my $perl  = $^X;
  my $perl_basename = File::Basename::basename($perl);

  my @potential_perls;

  # Try 1, Check $^X for absolute path
  push( @potential_perls, $perl )
      if File::Spec->file_name_is_absolute($perl);

  # Try 2, Check $^X for a valid relative path
  my $abs_perl = File::Spec->rel2abs($perl);
  push( @potential_perls, $abs_perl );

  # Try 3, Last ditch effort: These two option use hackery to try to locate
  # a suitable perl. The hack varies depending on whether we are running
  # from an installed perl or an uninstalled perl in the perl source dist.
  if ($ENV{PERL_CORE}) {

    # Try 3.A, If we are in a perl source tree, running an uninstalled
    # perl, we can keep moving up the directory tree until we find our
    # binary. We wouldn't do this under any other circumstances.

    # CBuilder is also in the core, so it should be available here
    require ExtUtils::CBuilder;
    my $perl_src = Cwd::realpath( ExtUtils::CBuilder->perl_src );
    if ( defined($perl_src) && length($perl_src) ) {
      my $uninstperl =
        File::Spec->rel2abs(File::Spec->catfile( $perl_src, $perl_basename ));
      push( @potential_perls, $uninstperl );
    }

  } else {

    # Try 3.B, First look in $Config{perlpath}, then search the user's
    # PATH. We do not want to do either if we are running from an
    # uninstalled perl in a perl source tree.

    push( @potential_perls, $c->get('perlpath') );

    push( @potential_perls,
          map File::Spec->catfile($_, $perl_basename), File::Spec->path() );
  }

  # Now that we've enumerated the potential perls, it's time to test
  # them to see if any of them match our configuration, returning the
  # absolute path of the first successful match.
  my $exe = $c->get('exe_ext');
  foreach my $thisperl ( @potential_perls ) {

    if (defined $exe) {
      $thisperl .= $exe unless $thisperl =~ m/$exe$/i;
    }

    if ( -f $thisperl && $proto->_perl_is_same($thisperl) ) {
      return $thisperl;
    }
  }

  # We've tried all alternatives, and didn't find a perl that matches
  # our configuration. Throw an exception, and list alternatives we tried.
  my @paths = map File::Basename::dirname($_), @potential_perls;
  die "Can't locate the perl binary used to run this script " .
      "in (@paths)\n";
}

# Adapted from IPC::Cmd::can_run()
sub find_command {
  my ($self, $command) = @_;

  if( File::Spec->file_name_is_absolute($command) ) {
    return $self->_maybe_command($command);

  } else {
    for my $dir ( File::Spec->path ) {
      my $abs = File::Spec->catfile($dir, $command);
      return $abs if $abs = $self->_maybe_command($abs);
    }
  }
}

# Copied from ExtUtils::MM_Unix::maybe_command
sub _maybe_command {
  my($self,$file) = @_;
  return $file if -x $file && ! -d $file;
  return;
}

sub _is_interactive {
  return -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)) ;   # Pipe?
}

# NOTE this is a blocking operation if(-t STDIN)
sub _is_unattended {
  my $self = shift;
  return $ENV{PERL_MM_USE_DEFAULT} ||
    ( !$self->_is_interactive && eof STDIN );
}

sub _readline {
  my $self = shift;
  return undef if $self->_is_unattended;

  my $answer = <STDIN>;
  chomp $answer if defined $answer;
  return $answer;
}

sub prompt {
  my $self = shift;
  my $mess = shift
    or die "prompt() called without a prompt message";

  # use a list to distinguish a default of undef() from no default
  my @def;
  @def = (shift) if @_;
  # use dispdef for output
  my @dispdef = scalar(@def) ?
    ('[', (defined($def[0]) ? $def[0] . ' ' : ''), ']') :
    (' ', '');

  local $|=1;
  print "$mess ", @dispdef;

  if ( $self->_is_unattended && !@def ) {
    die <<EOF;
ERROR: This build seems to be unattended, but there is no default value
for this question.  Aborting.
EOF
  }

  my $ans = $self->_readline();

  if ( !defined($ans)        # Ctrl-D or unattended
       or !length($ans) ) {  # User hit return
    print "$dispdef[1]\n";
    $ans = scalar(@def) ? $def[0] : '';
  }

  return $ans;
}

sub y_n {
  my $self = shift;
  my ($mess, $def)  = @_;

  die "y_n() called without a prompt message" unless $mess;
  die "Invalid default value: y_n() default must be 'y' or 'n'"
    if $def && $def !~ /^[yn]/i;

  my $answer;
  while (1) { # XXX Infinite or a large number followed by an exception ?
    $answer = $self->prompt(@_);
    return 1 if $answer =~ /^y/i;
    return 0 if $answer =~ /^n/i;
    local $|=1;
    print "Please answer 'y' or 'n'.\n";
  }
}

sub current_action { shift->{action} }
sub invoked_action { shift->{invoked_action} }

sub notes        { shift()->{phash}{notes}->access(@_) }
sub config_data  { shift()->{phash}{config_data}->access(@_) }
sub runtime_params { shift->{phash}{runtime_params}->read( @_ ? shift : () ) }  # Read-only
sub auto_features  { shift()->{phash}{auto_features}->access(@_) }

sub features     {
  my $self = shift;
  my $ph = $self->{phash};

  if (@_) {
    my $key = shift;
    if ($ph->{features}->exists($key)) {
      return $ph->{features}->access($key, @_);
    }

    if (my $info = $ph->{auto_features}->access($key)) {
      my $disabled;
      for my $type ( @{$self->prereq_action_types} ) {
        next if $type eq 'description' || $type eq 'recommends' || ! exists $info->{$type};
        my $prereqs = $info->{$type};
        for my $modname ( sort keys %$prereqs ) {
          my $spec = $prereqs->{$modname};
          my $status = $self->check_installed_status($modname, $spec);
          if ((!$status->{ok}) xor ($type =~ /conflicts$/)) { return 0; }
          if ( ! eval "require $modname; 1" ) { return 0; }
        }
      }
      return 1;
    }

    return $ph->{features}->access($key, @_);
  }

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

    }
    return $packlist ? $lookup : undef;
  }

  sub set_bundle_inc {
    my $self = shift;

    my $bundle_inc = $self->{properties}{bundle_inc};
    my $bundle_inc_preload = $self->{properties}{bundle_inc_preload};
    # We're in author mode if inc::latest is loaded, but not from cwd
    return unless inc::latest->can('loaded_modules');
    require ExtUtils::Installed;
    # ExtUtils::Installed is buggy about finding additions to default @INC
    my $inst = eval { ExtUtils::Installed->new(extra_libs => [@INC]) };
    if ($@) {
      $self->log_warn( << "EUI_ERROR" );
Bundling in inc/ is disabled because ExtUtils::Installed could not
create a list of your installed modules.  Here is the error:
$@
EUI_ERROR
      return;
    }
    my @bundle_list = map { [ $_, 0 ] } inc::latest->loaded_modules;

    # XXX TODO: Need to get ordering of prerequisites correct so they are
    # are loaded in the right order. Use an actual tree?!

    while( @bundle_list ) {
      my ($mod, $prereq) = @{ shift @bundle_list };

      # XXX TODO: Append prereqs to list
      # skip if core or already in bundle or preload lists
      # push @bundle_list, [$_, 1] for prereqs()

      # Locate packlist for bundling
      my $lookup = $self->_find_packlist($inst,$mod);
      if ( ! $lookup ) {
        # XXX Really needs a more helpful error message here
        die << "NO_PACKLIST";
Could not find a packlist for '$mod'.  If it's a core module, try
force installing it from CPAN.
NO_PACKLIST
      }
      else {
        push @{ $prereq ? $bundle_inc_preload : $bundle_inc }, $lookup;
      }
    }
  } # sub check_bundling
}

sub check_autofeatures {
  my ($self) = @_;
  my $features = $self->auto_features;

  return 1 unless %$features;

  # TODO refactor into ::Util
  my $longest = sub {
    my @str = @_ or croak("no strings given");

    my @len = map({length($_)} @str);
    my $max = 0;
    my $longest;
    for my $i (0..$#len) {
      ($max, $longest) = ($len[$i], $str[$i]) if($len[$i] > $max);
    }
    return($longest);
  };
  my $max_name_len = length($longest->(keys %$features));

  my ($num_disabled, $log_text) = (0, "\nChecking optional features...\n");
  for my $name ( sort keys %$features ) {
    $log_text .= $self->_feature_deps_msg($name, $max_name_len);
  }

  $num_disabled = () = $log_text =~ /disabled/g;

  # warn user if features disabled
  if ( $num_disabled ) {
    $self->log_warn( $log_text );
    return 0;
  }
  else {
    $self->log_verbose( $log_text );
    return 1;
  }
}

sub _feature_deps_msg {
  my ($self, $name, $max_name_len) = @_;
    $max_name_len ||= length $name;
    my $features = $self->auto_features;
    my $info = $features->{$name};
    my $feature_text = "$name" . '.' x ($max_name_len - length($name) + 4);

    my ($log_text, $disabled) = ('','');
    if ( my $failures = $self->prereq_failures($info) ) {
      $disabled = grep( /^(?:\w+_)?(?:requires|conflicts)$/,
                  keys %$failures ) ? 1 : 0;
      $feature_text .= $disabled ? "disabled\n" : "enabled\n";

      for my $type ( @{ $self->prereq_action_types } ) {
        next unless exists $failures->{$type};
        $feature_text .= "  $type:\n";
        my $prereqs = $failures->{$type};
        for my $module ( sort keys %$prereqs ) {
          my $status = $prereqs->{$module};
          my $required =
            ($type =~ /^(?:\w+_)?(?:requires|conflicts)$/) ? 1 : 0;
          my $prefix = ($required) ? '!' : '*';
          $feature_text .= "    $prefix $status->{message}\n";
        }
      }
    } else {
      $feature_text .= "enabled\n";
    }
    $log_text .= $feature_text if $disabled || $self->verbose;
    return $log_text;
}

# Automatically detect configure_requires prereqs
sub auto_config_requires {
  my ($self) = @_;
  my $p = $self->{properties};

  # add current Module::Build to configure_requires if there
  # isn't one already specified (but not ourself, so we're not circular)
  if ( $self->dist_name ne 'Module-Build'
    && $self->auto_configure_requires
    && ! exists $p->{configure_requires}{'Module::Build'}
  ) {
    (my $ver = $VERSION) =~ s/^(\d+\.\d\d).*$/$1/; # last major release only
    $self->log_warn(<<EOM);
Module::Build was not found in configure_requires! Adding it now
automatically as: configure_requires => { 'Module::Build' => $ver }
EOM
    $self->_add_prereq('configure_requires', 'Module::Build', $ver);
  }

  # if we're in author mode, add inc::latest modules to
  # configure_requires if not already set.  If we're not in author mode
  # then configure_requires will have been satisfied, or we'll just
  # live with what we've bundled
  if ( inc::latest->can('loaded_module') ) {
    for my $mod ( inc::latest->loaded_modules ) {
      next if exists $p->{configure_requires}{$mod};
      $self->_add_prereq('configure_requires', $mod, $mod->VERSION);
    }
  }

  return;
}

# Automatically detect and add prerequisites based on configuration

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

  }

  return %new_opts;
}

# Look for a home directory on various systems.
sub _home_dir {
  my @home_dirs;
  push( @home_dirs, $ENV{HOME} ) if $ENV{HOME};

  push( @home_dirs, File::Spec->catpath($ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '') )
      if $ENV{HOMEDRIVE} && $ENV{HOMEPATH};

  my @other_home_envs = qw( USERPROFILE APPDATA WINDIR SYS$LOGIN );
  push( @home_dirs, map $ENV{$_}, grep $ENV{$_}, @other_home_envs );

  my @real_home_dirs = grep -d, @home_dirs;

  return wantarray ? @real_home_dirs : shift( @real_home_dirs );
}

sub _find_user_config {
  my $self = shift;
  my $file = shift;
  foreach my $dir ( $self->_home_dir ) {
    my $path = File::Spec->catfile( $dir, $file );
    return $path if -e $path;
  }
  return undef;
}

# read ~/.modulebuildrc returning global options '*' and
# options specific to the currently executing $action.
sub read_modulebuildrc {
  my( $self, $action ) = @_;

  return () unless $self->use_rcfile;

  my $modulebuildrc;
  if ( exists($ENV{MODULEBUILDRC}) && $ENV{MODULEBUILDRC} eq 'NONE' ) {
    return ();
  } elsif ( exists($ENV{MODULEBUILDRC}) && -e $ENV{MODULEBUILDRC} ) {
    $modulebuildrc = $ENV{MODULEBUILDRC};
  } elsif ( exists($ENV{MODULEBUILDRC}) ) {
    $self->log_warn("WARNING: Can't find resource file " .
                    "'$ENV{MODULEBUILDRC}' defined in environment.\n" .
                    "No options loaded\n");
    return ();
  } else {
    $modulebuildrc = $self->_find_user_config( '.modulebuildrc' );
    return () unless $modulebuildrc;
  }

  my $fh = IO::File->new( $modulebuildrc )
      or die "Can't open $modulebuildrc: $!";

  my %options; my $buffer = '';
  while (defined( my $line = <$fh> )) {
    chomp( $line );
    $line =~ s/#.*$//;
    next unless length( $line );

    if ( $line =~ /^\S/ ) {
      if ( $buffer ) {
        my( $action, $options ) = split( /\s+/, $buffer, 2 );
        $options{$action} .= $options . ' ';
        $buffer = '';
      }
      $buffer = $line;
    } else {
      $buffer .= $line;
    }
  }

  if ( $buffer ) { # anything left in $buffer ?
    my( $action, $options ) = split( /\s+/, $buffer, 2 );
    $options{$action} .= $options . ' '; # merge if more than one line
  }

  my ($global_opts) =
    $self->read_args( $self->split_like_shell( $options{'*'} || '' ) );

  # let fakeinstall act like install if not provided
  if ( $action eq 'fakeinstall' && ! exists $options{fakeinstall} ) {
    $action = 'install';
  }
  my ($action_opts) =
    $self->read_args( $self->split_like_shell( $options{$action} || '' ) );

  # specific $action options take priority over global options '*'
  return $self->_merge_arglist( $action_opts, $global_opts );
}

# merge the relevant options in ~/.modulebuildrc into Module::Build's
# option list where they do not conflict with commandline options.
sub merge_modulebuildrc {
  my( $self, $action, %cmdline_opts ) = @_;
  my %rc_opts = $self->read_modulebuildrc( $action || $self->{action} || 'build' );
  my %new_opts = $self->_merge_arglist( \%cmdline_opts, \%rc_opts );
  $self->merge_args( $action, %new_opts );
}

sub merge_args {
  my ($self, $action, %args) = @_;
  $self->{action} = $action if defined $action;

  my %additive = map { $_ => 1 } $self->hash_properties;

  # Extract our 'properties' from $cmd_args, the rest are put in 'args'.
  while (my ($key, $val) = each %args) {
    $self->{phash}{runtime_params}->access( $key => $val )
      if $self->valid_property($key);

    if ($key eq 'config') {
      $self->config($_ => $val->{$_}) foreach keys %$val;
    } else {
      my $add_to = $additive{$key}             ? $self->{properties}{$key} :
                   $self->valid_property($key) ? $self->{properties}       :
                   $self->{args}               ;

      if ($additive{$key}) {

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

        if (/^=(item|back)/) {
          last unless $inlist;
        }
        push @docs, $_;
        ++$inlist if /^=over/;
        --$inlist if /^=back/;
      }
    }
    else { # head2 style
      # stop at anything equal or greater than the found level
      while (<$fh>) {
        last if(/^=(?:head[12]|cut)/);
        push @docs, $_;
      }
    }
    # TODO maybe disallow overriding just pod for an action
    # TODO and possibly: @docs and last;
  }

  unless ($files_found) {
    $@ = "Couldn't find any documentation to search";
    return;
  }
  unless (@docs) {
    $@ = "Couldn't find any docs for action '$action'";
    return;
  }

  return join '', @docs;
}

sub ACTION_prereq_report {
  my $self = shift;
  $self->log_info( $self->prereq_report );
}

sub ACTION_prereq_data {
  my $self = shift;
  $self->log_info( Module::Build::Dumper->_data_dump( $self->prereq_data ) );
}

sub prereq_data {
  my $self = shift;
  my @types = ('configure_requires', @{ $self->prereq_action_types } );
  my $info = { map { $_ => $self->$_() } grep { %{$self->$_()} } @types };
  return $info;
}

sub prereq_report {
  my $self = shift;
  my $info = $self->prereq_data;

  my $output = '';
  foreach my $type (keys %$info) {
    my $prereqs = $info->{$type};
    $output .= "\n$type:\n";
    my $mod_len = 2;
    my $ver_len = 4;
    my %mods;
    while ( my ($modname, $spec) = each %$prereqs ) {
      my $len  = length $modname;
      $mod_len = $len if $len > $mod_len;
      $spec    ||= '0';
      $len     = length $spec;
      $ver_len = $len if $len > $ver_len;

      my $mod = $self->check_installed_status($modname, $spec);
      $mod->{name} = $modname;
      $mod->{ok} ||= 0;
      $mod->{ok} = ! $mod->{ok} if $type =~ /^(\w+_)?conflicts$/;

      $mods{lc $modname} = $mod;
    }

    my $space  = q{ } x ($mod_len - 3);
    my $vspace = q{ } x ($ver_len - 3);
    my $sline  = q{-} x ($mod_len - 3);
    my $vline  = q{-} x ($ver_len - 3);
    my $disposition = ($type =~ /^(\w+_)?conflicts$/) ?
                        'Clash' : 'Need';
    $output .=
      "    Module $space  $disposition $vspace  Have\n".
      "    ------$sline+------$vline-+----------\n";


    for my $k (sort keys %mods) {
      my $mod = $mods{$k};
      my $space  = q{ } x ($mod_len - length $k);
      my $vspace = q{ } x ($ver_len - length $mod->{need});
      my $f = $mod->{ok} ? ' ' : '!';
      $output .=
        "  $f $mod->{name} $space     $mod->{need}  $vspace   ".
        (defined($mod->{have}) ? $mod->{have} : "")."\n";
    }
  }
  return $output;
}

sub ACTION_help {
  my ($self) = @_;
  my $actions = $self->known_actions;

  if (@{$self->{args}{ARGV}}) {
    my $msg = eval {$self->get_action_docs($self->{args}{ARGV}[0], $actions)};
    print $@ ? "$@\n" : $msg;
    return;
  }

  print <<EOF;

 Usage: $0 <action> arg1=value arg2=value ...
 Example: $0 test verbose=1

 Actions defined:
EOF

  print $self->_action_listing($actions);

  print "\nRun `Build help <action>` for details on an individual action.\n";
  print "See `perldoc Module::Build` for complete documentation.\n";
}

sub _action_listing {
  my ($self, $actions) = @_;

  # Flow down columns, not across rows
  my @actions = sort keys %$actions;
  @actions = map $actions[($_ + ($_ % 2) * @actions) / 2],  0..$#actions;

  my $out = '';
  while (my ($one, $two) = splice @actions, 0, 2) {
    $out .= sprintf("  %-12s                   %-12s\n", $one, $two||'');
  }
  $out =~ s{\s*$}{}mg; # remove trailing spaces
  return $out;
}

sub ACTION_retest {
  my ($self) = @_;

  # Protect others against our @INC changes
  local @INC = @INC;

  # Filter out nonsensical @INC entries - some versions of
  # Test::Harness will really explode the number of entries here
  @INC = grep {ref() || -d} @INC if @INC > 100;

  $self->do_tests;
}

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

# Test::Harness dies on failure but TAP::Harness does not, so we must
# die if running under TAP::Harness
sub do_tests {
  my $self = shift;

  my $tests = $self->find_test_files;

  local $ENV{PERL_DL_NONLAZY} = 1;

  if(@$tests) {
    my $args = $self->tap_harness_args;
    if($self->use_tap_harness or ($args and %$args)) {
      my $aggregate = $self->run_tap_harness($tests);
      if ( $aggregate->has_errors ) {
        die "Errors in testing.  Cannot continue.\n";
      }
    }
    else {
      $self->run_test_harness($tests);
    }
  }
  else {
    $self->log_info("No tests defined.\n");
  }

  $self->run_visual_script;
}

sub run_tap_harness {
  my ($self, $tests) = @_;

  require TAP::Harness;

  # TODO allow the test @INC to be set via our API?

  my $aggregate = TAP::Harness->new({
    lib => [@INC],
    verbosity => $self->{properties}{verbose},
    switches  => [ $self->harness_switches ],
    %{ $self->tap_harness_args },
  })->runtests(@$tests);

  return $aggregate;
}

sub run_test_harness {
    my ($self, $tests) = @_;
    require Test::Harness;
    my $p = $self->{properties};
    my @harness_switches = $self->harness_switches;

    # Work around a Test::Harness bug that loses the particular perl
    # we're running under.  $self->perl is trustworthy, but $^X isn't.
    local $^X = $self->perl;

    # Do everything in our power to work with all versions of Test::Harness
    local $Test::Harness::switches    = join ' ', grep defined, $Test::Harness::switches, @harness_switches;
    local $Test::Harness::Switches    = join ' ', grep defined, $Test::Harness::Switches, @harness_switches;
    local $ENV{HARNESS_PERL_SWITCHES} = join ' ', grep defined, $ENV{HARNESS_PERL_SWITCHES}, @harness_switches;

    $Test::Harness::switches = undef   unless length $Test::Harness::switches;
    $Test::Harness::Switches = undef   unless length $Test::Harness::Switches;
    delete $ENV{HARNESS_PERL_SWITCHES} unless length $ENV{HARNESS_PERL_SWITCHES};

    local ($Test::Harness::verbose,
           $Test::Harness::Verbose,
           $ENV{TEST_VERBOSE},
           $ENV{HARNESS_VERBOSE}) = ($p->{verbose} || 0) x 4;

    Test::Harness::runtests(@$tests);
}

sub run_visual_script {
    my $self = shift;
    # This will get run and the user will see the output.  It doesn't
    # emit Test::Harness-style output.
    $self->run_perl_script('visual.pl', '-Mblib='.$self->blib)
        if -e 'visual.pl';
}

sub harness_switches {
    shift->{properties}{debugger} ? qw(-w -d) : ();
}

sub test_files {
  my $self = shift;
  my $p = $self->{properties};
  if (@_) {
    return $p->{test_files} = (@_ == 1 ? shift : [@_]);
  }
  return $self->find_test_files;
}

sub expand_test_dir {
  my ($self, $dir) = @_;
  my $exts = $self->{properties}{test_file_exts};

  return sort map { @{$self->rscan_dir($dir, qr{^[^.].*\Q$_\E$})} } @$exts
    if $self->recursive_test_files;

  return sort map { glob File::Spec->catfile($dir, "*$_") } @$exts;
}

sub ACTION_testdb {
  my ($self) = @_;
  local $self->{properties}{debugger} = 1;
  $self->depends_on('test');
}

sub ACTION_testcover {
  my ($self) = @_;

  unless (Module::Build::ModuleInfo->find_module_by_name('Devel::Cover')) {
    warn("Cannot run testcover action unless Devel::Cover is installed.\n");
    return;
  }

  $self->add_to_cleanup('coverage', 'cover_db');
  $self->depends_on('code');

  # See whether any of the *.pm files have changed since last time
  # testcover was run.  If so, start over.
  if (-e 'cover_db') {

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

sub ACTION_html {
  my $self = shift;

  return unless $self->_mb_feature('HTML_support');

  $self->depends_on('code');

  foreach my $type ( qw(bin lib) ) {
    next unless ( $self->invoked_action eq 'html' || $self->_is_default_installable("${type}html"));
    $self->htmlify_pods( $type );
  }
}

# 1) If it's an ActiveState perl install, we need to run
#    ActivePerl::DocTools->UpdateTOC;
# 2) Links to other modules are not being generated
sub htmlify_pods {
  my $self = shift;
  my $type = shift;
  my $htmldir = shift || File::Spec->catdir($self->blib, "${type}html");

  $self->add_to_cleanup('pod2htm*');

  my $pods = $self->_find_pods( $self->{properties}{"${type}doc_dirs"},
                                exclude => [ $self->file_qr('\.(?:bat|com|html)$') ] );
  return unless %$pods;  # nothing to do

  unless ( -d $htmldir ) {
    File::Path::mkpath($htmldir, 0, oct(755))
      or die "Couldn't mkdir $htmldir: $!";
  }

  my @rootdirs = ($type eq 'bin') ? qw(bin) :
      $self->installdirs eq 'core' ? qw(lib) : qw(site lib);
  my $podroot = $ENV{PERL_CORE}
              ? File::Basename::dirname($ENV{PERL_CORE})
              : $self->original_prefix('core');

  my $htmlroot = $self->install_sets('core')->{libhtml};
  my @podpath = (map { File::Spec->abs2rel($_ ,$podroot) } grep { -d  }
    ( $self->install_sets('core', 'lib'), # lib
      $self->install_sets('core', 'bin'), # bin
      $self->install_sets('site', 'lib'), # site/lib
    ) ), File::Spec->rel2abs($self->blib);

  my $podpath = $ENV{PERL_CORE}
              ? File::Spec->catdir($podroot, 'lib')
              : join(":", map { tr,:\\,|/,; $_ } @podpath);

  my $blibdir = join('/', File::Spec->splitdir(
    (File::Spec->splitpath(File::Spec->rel2abs($htmldir),1))[1]),''
  );

  my ($with_ActiveState, $htmltool);

  if ( $with_ActiveState = $self->_is_ActivePerl
    && eval { require ActivePerl::DocTools::Pod; 1 }
  ) {
    my $tool_v = ActiveState::DocTools::Pod->VERSION;
    $htmltool = "ActiveState::DocTools::Pod";
    $htmltool .= " $tool_v" if $tool_v && length $tool_v;
  }
  else {
      require Module::Build::PodParser;
      require Pod::Html;
    $htmltool = "Pod::Html " .  Pod::Html->VERSION;
  }
  $self->log_verbose("Converting Pod to HTML with $htmltool\n");

  my $errors = 0;

  POD:
  foreach my $pod ( keys %$pods ) {

    my ($name, $path) = File::Basename::fileparse($pods->{$pod},
      $self->file_qr('\.(?:pm|plx?|pod)$')
    );
    my @dirs = File::Spec->splitdir( File::Spec->canonpath( $path ) );
    pop( @dirs ) if scalar(@dirs) && $dirs[-1] eq File::Spec->curdir;

    my $fulldir = File::Spec->catdir($htmldir, @rootdirs, @dirs);
    my $tmpfile = File::Spec->catfile($fulldir, "${name}.tmp");
    my $outfile = File::Spec->catfile($fulldir, "${name}.html");
    my $infile  = File::Spec->abs2rel($pod);

    next if $self->up_to_date($infile, $outfile);

    unless ( -d $fulldir ){
      File::Path::mkpath($fulldir, 0, oct(755))
        or die "Couldn't mkdir $fulldir: $!";
    }

    $self->log_verbose("HTMLifying $infile -> $outfile\n");
    if ( $with_ActiveState ) {
      my $depth = @rootdirs + @dirs;
      my %opts = ( infile => $infile,
        outfile => $tmpfile,
        podpath => $podpath,
        podroot => $podroot,
        index => 1,
        depth => $depth,
      );
      eval {
        ActivePerl::DocTools::Pod::pod2html(%opts);
        1;
      } or $self->log_warn("[$htmltool] pod2html (" .
        join(", ", map { "q{$_} => q{$opts{$_}}" } (keys %opts)) . ") failed: $@");
    } else {
      my $path2root = join( '/', ('..') x (@rootdirs+@dirs) );
      my $fh = IO::File->new($infile) or die "Can't read $infile: $!";
      my $abstract = Module::Build::PodParser->new(fh => $fh)->get_abstract();

      my $title = join( '::', (@dirs, $name) );
      $title .= " - $abstract" if $abstract;

      my @opts = (
        "--title=$title",
        "--podpath=$podpath",
        "--infile=$infile",
        "--outfile=$tmpfile",
        "--podroot=$podroot",

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

=cut

sub _default_maniskip {
    my $self = shift;

    my $default_maniskip;
    for my $dir (@INC) {
        $default_maniskip = File::Spec->catfile($dir, "ExtUtils", "MANIFEST.SKIP");
        last if -r $default_maniskip;
    }

    return $default_maniskip;
}


=begin private

  my $content = $build->_slurp($file);

Reads $file and returns the $content.

=end private

=cut

sub _slurp {
    my $self = shift;
    my $file = shift;
    my $mode = shift || "";
    open my $fh, "<$mode", $file or croak "Can't open $file for reading: $!";
    local $/;
    return <$fh>;
}

sub _spew {
    my $self = shift;
    my $file = shift;
    my $content = shift || "";
    my $mode = shift || "";
    open my $fh, ">$mode", $file or croak "Can't open $file for writing: $!";
    print {$fh} $content;
    close $fh;
}

sub _case_tolerant {
  my $self = shift;
  if ( ref $self ) {
    $self->{_case_tolerant} = File::Spec->case_tolerant
      unless defined($self->{_case_tolerant});
    return $self->{_case_tolerant};
  }
  else {
    return File::Spec->case_tolerant;
  }
}

sub _append_maniskip {
  my $self = shift;
  my $skip = shift;
  my $file = shift || 'MANIFEST.SKIP';
  return unless defined $skip && length $skip;
  my $fh = IO::File->new(">> $file")
    or die "Can't open $file: $!";

  print $fh "$skip\n";
  $fh->close();
}

sub _write_default_maniskip {
  my $self = shift;
  my $file = shift || 'MANIFEST.SKIP';
  my $fh = IO::File->new("> $file")
    or die "Can't open $file: $!";

  my $content = $self->_eumanifest_has_include ? "#!include_default\n"
                                               : $self->_slurp( $self->_default_maniskip );

  $content .= <<'EOF';
# Avoid configuration metadata file
^MYMETA\.

# Avoid Module::Build generated and utility files.
\bBuild$
\bBuild.bat$
\b_build
\bBuild.COM$
\bBUILD.COM$
\bbuild.com$
^MANIFEST\.SKIP

# Avoid archives of this distribution
EOF

  # Skip, for example, 'Module-Build-0.27.tar.gz'
  $content .= '\b'.$self->dist_name.'-[\d\.\_]+'."\n";

  print $fh $content;

  return;
}

sub _check_manifest_skip {
  my ($self) = @_;

  my $maniskip = 'MANIFEST.SKIP';

  if ( ! -e $maniskip ) {
    $self->log_warn("File '$maniskip' does not exist: Creating a temporary '$maniskip'\n");
    $self->_write_default_maniskip($maniskip);
    $self->_unlink_on_exit($maniskip);
  }
  else {
    # MYMETA must not be added to MANIFEST, so always confirm the skip
    $self->_check_mymeta_skip( $maniskip );
  }

  return;
}

sub ACTION_manifest {
  my ($self) = @_;

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

  push @created, "$file\.yml"
    if $meta && $meta->save( "$file\.yml", {version => "1.4"} );
  push @created, "$file\.json"
    if $meta && $meta->save( "$file\.json" );

  if ( @created ) {
    $self->log_info("Created " . join(" and ", @created) . "\n");
  }
  return @created;
}

sub _get_meta_object {
  my $self = shift;
  my %args = @_;
  return unless $self->try_require("CPAN::Meta", "2.110420");

  my $meta;
  eval {
    my $data = $self->get_metadata(
      fatal => $args{fatal},
      auto => $args{auto},
    );
    $data->{dynamic_config} = $args{dynamic} if defined $args{dynamic};
    $meta = CPAN::Meta->create( $data );
  };
  if ($@ && ! $args{quiet}) {
    $self->log_warn(
      "Could not get valid metadata. Error is: $@\n"
    );
  }

  return $meta;
}

# We return a version 1.4 structure for backwards compatibility
sub read_metafile {
  my $self = shift;
  my ($metafile) = @_;

  return unless $self->try_require("CPAN::Meta", "2.110420");
  my $meta = CPAN::Meta->load_file($metafile);
  return $meta->as_struct( {version => "1.4"} );
}

# For legacy compatibility, we upconvert a 1.4 data structure, ensuring
# validity, and then downconvert it back to save it.
#
# generally, this code should no longer be used
sub write_metafile {
  my $self = shift;
  my ($metafile, $struct) = @_;

  return unless $self->try_require("CPAN::Meta", "2.110420");

  my $meta = CPAN::Meta->new( $struct );
  return $meta->save( $metafile, { version => "1.4" } );
}

sub normalize_version {
  my ($self, $version) = @_;
  $version = 0 unless defined $version and length $version;

  if ( $version =~ /[=<>!,]/ ) { # logic, not just version
    # take as is without modification
  }
  elsif ( ref $version eq 'version' ||
          ref $version eq 'Module::Build::Version' ) { # version objects
    $version = $version->is_qv ? $version->normal : $version->stringify;
  }
  elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots
    # normalize string tuples without "v": "1.2.3" -> "v1.2.3"
    $version = "v$version";
  }
  else {
    # leave alone
  }
  return $version;
}

sub _normalize_prereqs {
  my ($self) = @_;
  my $p = $self->{properties};

  # copy prereq data structures so we can modify them before writing to META
  my %prereq_types;
  for my $type ( 'configure_requires', @{$self->prereq_action_types} ) {
    if (exists $p->{$type}) {
      for my $mod ( keys %{ $p->{$type} } ) {
        $prereq_types{$type}{$mod} =
          $self->normalize_version($p->{$type}{$mod});
      }
    }
  }
  return \%prereq_types;
}

# wrapper around old prepare_metadata API;
sub get_metadata {
  my ($self, %args) = @_;
  my $metadata = {};
  $self->prepare_metadata( $metadata, undef, \%args );
  return $metadata;
}

# To preserve compatibility with old API, $node *must* be a hashref
# passed in to prepare_metadata.  $keys is an arrayref holding a
# list of keys -- it's use is optional and generally no longer needed
# but kept for back compatibility.  $args is an optional parameter to
# support the new 'fatal' toggle

sub prepare_metadata {
  my ($self, $node, $keys, $args) = @_;
  unless ( ref $node eq 'HASH' ) {
    croak "prepare_metadata() requires a hashref argument to hold output\n";
  }
  my $fatal = $args->{fatal} || 0;
  my $p = $self->{properties};

  $self->auto_config_requires if $args->{auto};

  # A little helper sub
  my $add_node = sub {
    my ($name, $val) = @_;
    $node->{$name} = $val;
    push @$keys, $name if $keys;
  };

  # validate required fields
  foreach my $f (qw(dist_name dist_version dist_author dist_abstract license)) {
    my $field = $self->$f();
    unless ( defined $field and length $field ) {
      my $err = "ERROR: Missing required field '$f' for metafile\n";
      if ( $fatal ) {
        die $err;
      }
      else {
        $self->log_warn($err);
      }
    }
  }


  # add dist_* fields
  foreach my $f (qw(dist_name dist_version dist_author dist_abstract)) {
    (my $name = $f) =~ s/^dist_//;
    $add_node->($name, $self->$f());
  }

  # normalize version
  $node->{version} = $self->normalize_version($node->{version});

  # validate license information
  my $license = $self->license;
  my ($meta_license, $meta_license_url);

  # XXX this is still meta spec version 1 stuff

  # if Software::License::* exists, then we can use it to get normalized name
  # for META files

  if ( my $sl = $self->_software_license_object ) {
    $meta_license = $sl->meta_name;
    $meta_license_url = $sl->url;
  }
  elsif ( exists $self->valid_licenses()->{$license} ) {
    $meta_license = $license;
    $meta_license_url = $self->_license_url( $license );
  }
  else {
  # if we didn't find a license from a Software::License class,
  # then treat it as unknown
    $self->log_warn( "Can not determine license type for '" . $self->license
      . "'\nSetting META license field to 'unknown'.\n");
    $meta_license = 'unknown';
  }

  $node->{license} = $meta_license;
  $node->{resources}{license} = $meta_license_url if defined $meta_license_url;

  # add prerequisite data
  my $prereqs = $self->_normalize_prereqs;
  for my $t ( keys %$prereqs ) {
      $add_node->($t, $prereqs->{$t});
  }

  if (exists $p->{dynamic_config}) {
    $add_node->('dynamic_config', $p->{dynamic_config});
  }
  my $pkgs = eval { $self->find_dist_packages };
  if ($@) {
    $self->log_warn("$@\nWARNING: Possible missing or corrupt 'MANIFEST' file.\n" .

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

sub _resolve_module_versions {
  my $self = shift;

  my $packages = shift;

  my( $file, $version );
  my $err = '';
    foreach my $p ( @$packages ) {
      if ( defined( $p->{version} ) ) {
        if ( defined( $version ) ) {
          if ( $self->compare_versions( $version, '!=', $p->{version} ) ) {
            $err .= "  $p->{file} ($p->{version})\n";
          } else {
            # same version declared multiple times, ignore
          }
        } else {
          $file    = $p->{file};
          $version = $p->{version};
        }
      }
      $file ||= $p->{file} if defined( $p->{file} );
    }

  if ( $err ) {
    $err = "  $file ($version)\n" . $err;
  }

  my %result = (
    file    => $file,
    version => $version,
    err     => $err
  );

  return \%result;
}

sub make_tarball {
  my ($self, $dir, $file) = @_;
  $file ||= $dir;

  $self->log_info("Creating $file.tar.gz\n");

  if ($self->{args}{tar}) {
    my $tar_flags = $self->verbose ? 'cvf' : 'cf';
    $self->do_system($self->split_like_shell($self->{args}{tar}), $tar_flags, "$file.tar", $dir);
    $self->do_system($self->split_like_shell($self->{args}{gzip}), "$file.tar") if $self->{args}{gzip};
  } else {
    eval { require Archive::Tar && Archive::Tar->VERSION(1.09); 1 }
      or die "You must install Archive::Tar 1.09+ to make a distribution tarball\n".
             "or specify a binary tar program with the '--tar' option.\n".
             "See the documentation for the 'dist' action.\n";

    my $files = $self->rscan_dir($dir);

    # Archive::Tar versions >= 1.09 use the following to enable a compatibility
    # hack so that the resulting archive is compatible with older clients.
    # If no file path is 100 chars or longer, we disable the prefix field
    # for maximum compatibility.  If there are any long file paths then we
    # need the prefix field after all.
    $Archive::Tar::DO_NOT_USE_PREFIX =
      (grep { length($_) >= 100 } @$files) ? 0 : 1;

    my $tar   = Archive::Tar->new;
    $tar->add_files(@$files);
    for my $f ($tar->get_files) {
      $f->mode($f->mode & ~022); # chmod go-w
    }
    $tar->write("$file.tar.gz", 1);
  }
}

sub install_path {
  my $self = shift;
  my( $type, $value ) = ( @_, '<empty>' );

  Carp::croak( 'Type argument missing' )
    unless defined( $type );

  my $map = $self->{properties}{install_path};
  return $map unless @_;

  # delete existing value if $value is literal undef()
  unless ( defined( $value ) ) {
    delete( $map->{$type} );
    return undef;
  }

  # return existing value if no new $value is given
  if ( $value eq '<empty>' ) {
    return undef unless exists $map->{$type};
    return $map->{$type};
  }

  # set value if $value is a valid relative path
  return $map->{$type} = $value;
}

sub install_sets {
  # Usage: install_sets('site'), install_sets('site', 'lib'),
  #   or install_sets('site', 'lib' => $value);
  my ($self, $dirs, $key, $value) = @_;
  $dirs = $self->installdirs unless defined $dirs;
  # update property before merging with defaults
  if ( @_ == 4 && defined $dirs && defined $key) {
    # $value can be undef; will mask default
    $self->{properties}{install_sets}{$dirs}{$key} = $value;
  }
  my $map = { $self->_merge_arglist(
    $self->{properties}{install_sets},
    $self->_default_install_paths->{install_sets}
  )};
  if ( defined $dirs && defined $key ) {
    return $map->{$dirs}{$key};
  }
  elsif ( defined $dirs ) {
    return $map->{$dirs};
  }
  else {
    croak "Can't determine installdirs for install_sets()";
  }
}

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

  #   or prefix_relpaths('site', 'lib' => $value);
  my $self = shift;
  my $installdirs = shift || $self->installdirs
    or croak "Can't determine installdirs for prefix_relpaths()";
  if ( @_ > 1 ) { # change values before merge
    $self->{properties}{prefix_relpaths}{$installdirs} ||= {};
    $self->_set_relpaths($self->{properties}{prefix_relpaths}{$installdirs}, @_);
  }
  my $map = {$self->_merge_arglist(
    $self->{properties}{prefix_relpaths}{$installdirs},
    $self->_default_install_paths->{prefix_relpaths}{$installdirs}
  )};
  return $map unless @_;
  my $relpath = $map->{$_[0]};
  return defined $relpath ? File::Spec->catdir( @$relpath ) : undef;
}

sub _set_relpaths {
  my $self = shift;
  my( $map, $type, $value ) = @_;

  Carp::croak( 'Type argument missing' )
    unless defined( $type );

  # set undef if $value is literal undef()
  if ( ! defined( $value ) ) {
    $map->{$type} = undef;
    return;
  }
  # set value if $value is a valid relative path
  else {
    Carp::croak( "Value must be a relative path" )
      if File::Spec::Unix->file_name_is_absolute($value);

    my @value = split( /\//, $value );
    $map->{$type} = \@value;
  }
}

# Translated from ExtUtils::MM_Any::init_INSTALL_from_PREFIX
sub prefix_relative {
  my ($self, $type) = @_;
  my $installdirs = $self->installdirs;

  my $relpath = $self->install_sets($installdirs)->{$type};

  return $self->_prefixify($relpath,
                           $self->original_prefix($installdirs),
                           $type,
                          );
}

# Translated from ExtUtils::MM_Unix::prefixify()
sub _prefixify {
  my($self, $path, $sprefix, $type) = @_;

  my $rprefix = $self->prefix;
  $rprefix .= '/' if $sprefix =~ m|/$|;

  $self->log_verbose("  prefixify $path from $sprefix to $rprefix\n")
    if defined( $path ) && length( $path );

  if( !defined( $path ) || ( length( $path ) == 0 ) ) {
    $self->log_verbose("  no path to prefixify, falling back to default.\n");
    return $self->_prefixify_default( $type, $rprefix );
  } elsif( !File::Spec->file_name_is_absolute($path) ) {
    $self->log_verbose("    path is relative, not prefixifying.\n");
  } elsif( $path !~ s{^\Q$sprefix\E\b}{}s ) {
    $self->log_verbose("    cannot prefixify, falling back to default.\n");
    return $self->_prefixify_default( $type, $rprefix );
  }

  $self->log_verbose("    now $path in $rprefix\n");

  return $path;
}

sub _prefixify_default {
  my $self = shift;
  my $type = shift;
  my $rprefix = shift;

  my $default = $self->prefix_relpaths($self->installdirs, $type);
  if( !$default ) {
    $self->log_verbose("    no default install location for type '$type', using prefix '$rprefix'.\n");
    return $rprefix;
  } else {
    return $default;
  }
}

sub install_destination {
  my ($self, $type) = @_;

  return $self->install_path($type) if $self->install_path($type);

  if ( $self->install_base ) {
    my $relpath = $self->install_base_relpaths($type);
    return $relpath ? File::Spec->catdir($self->install_base, $relpath) : undef;
  }

  if ( $self->prefix ) {
    my $relpath = $self->prefix_relative($type);
    return $relpath ? File::Spec->catdir($self->prefix, $relpath) : undef;
  }

  return $self->install_sets($self->installdirs)->{$type};
}

sub install_types {
  my $self = shift;

  my %types;
  if ( $self->install_base ) {
    %types = %{$self->install_base_relpaths};
  } elsif ( $self->prefix ) {
    %types = %{$self->prefix_relpaths};
  } else {
    %types = %{$self->install_sets($self->installdirs)};
  }

  %types = (%types, %{$self->install_path});

  return sort keys %types;
}

sub install_map {
  my ($self, $blib) = @_;
  $blib ||= $self->blib;

  my( %map, @skipping );
  foreach my $type ($self->install_types) {
    my $localdir = File::Spec->catdir( $blib, $type );
    next unless -e $localdir;

    # the line "...next if (($type eq 'bindoc'..." was one of many changes introduced for
    # improving HTML generation on ActivePerl, see https://rt.cpan.org/Public/Bug/Display.html?id=53478
    # Most changes were ok, but this particular line caused test failures in t/manifypods.t on windows,
    # therefore it is commented out.

    # ********* next if (($type eq 'bindoc' || $type eq 'libdoc') && not $self->is_unixish);

    if (my $dest = $self->install_destination($type)) {
      $map{$localdir} = $dest;
    } else {
      push( @skipping, $type );
    }
  }

  $self->log_warn(
    "WARNING: Can't figure out install path for types: @skipping\n" .
    "Files will not be installed.\n"
  ) if @skipping;

  # Write the packlist into the same place as ExtUtils::MakeMaker.
  if ($self->create_packlist and my $module_name = $self->module_name) {
    my $archdir = $self->install_destination('arch');
    my @ext = split /::/, $module_name;
    $map{write} = File::Spec->catfile($archdir, 'auto', @ext, '.packlist');
  }

  # Handle destdir
  if (length(my $destdir = $self->destdir || '')) {
    foreach (keys %map) {
      # Need to remove volume from $map{$_} using splitpath, or else
      # we'll create something crazy like C:\Foo\Bar\E:\Baz\Quux
      # VMS will always have the file separate than the path.
      my ($volume, $path, $file) = File::Spec->splitpath( $map{$_}, 0 );

      # catdir needs a list of directories, or it will create something
      # crazy like volume:[Foo.Bar.volume.Baz.Quux]
      my @dirs = File::Spec->splitdir($path);

      # First merge the directories
      $path = File::Spec->catdir($destdir, @dirs);

      # Then put the file back on if there is one.
      if ($file ne '') {
          $map{$_} = File::Spec->catfile($path, $file)
      } else {
          $map{$_} = $path;
      }
    }
  }

  $map{read} = '';  # To keep ExtUtils::Install quiet

  return \%map;
}

sub depends_on {
  my $self = shift;
  foreach my $action (@_) {
    $self->_call_action($action);
  }
}

sub rscan_dir {
  my ($self, $dir, $pattern) = @_;
  my @result;
  local $_; # find() can overwrite $_, so protect ourselves
  my $subr = !$pattern ? sub {push @result, $File::Find::name} :
             !ref($pattern) || (ref $pattern eq 'Regexp') ? sub {push @result, $File::Find::name if /$pattern/} :
             ref($pattern) eq 'CODE' ? sub {push @result, $File::Find::name if $pattern->()} :
             die "Unknown pattern type";

  File::Find::find({wanted => $subr, no_chdir => 1}, $dir);
  return \@result;
}

sub delete_filetree {
  my $self = shift;
  my $deleted = 0;
  foreach (@_) {
    next unless -e $_;
    $self->log_verbose("Deleting $_\n");
    File::Path::rmtree($_, 0, 0);
    die "Couldn't remove '$_': $!\n" if -e $_;
    $deleted++;
  }
  return $deleted;
}

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

                         $spec->{lib_file});

  my $module_name = $spec->{module_name} || $self->module_name;

  $self->cbuilder->link(
    module_name => $module_name,
    objects     => [$spec->{obj_file}, @$objects],
    lib_file    => $spec->{lib_file},
    extra_linker_flags => $p->{extra_linker_flags} );

  return $spec->{lib_file};
}

sub compile_xs {
  my ($self, $file, %args) = @_;

  $self->log_verbose("$file -> $args{outfile}\n");

  if (eval {require ExtUtils::ParseXS; 1}) {

    ExtUtils::ParseXS::process_file(
                                    filename => $file,
                                    prototypes => 0,
                                    output => $args{outfile},
                                   );
  } else {
    # Ok, I give up.  Just use backticks.

    my $xsubpp = Module::Build::ModuleInfo->find_module_by_name('ExtUtils::xsubpp')
      or die "Can't find ExtUtils::xsubpp in INC (@INC)";

    my @typemaps;
    push @typemaps, Module::Build::ModuleInfo->find_module_by_name(
        'ExtUtils::typemap', \@INC
    );
    my $lib_typemap = Module::Build::ModuleInfo->find_module_by_name(
        'typemap', [File::Basename::dirname($file), File::Spec->rel2abs('.')]
    );
    push @typemaps, $lib_typemap if $lib_typemap;
    @typemaps = map {+'-typemap', $_} @typemaps;

    my $cf = $self->{config};
    my $perl = $self->{properties}{perl};

    my @command = ($perl, "-I".$cf->get('installarchlib'), "-I".$cf->get('installprivlib'), $xsubpp, '-noprototypes',
                   @typemaps, $file);

    $self->log_info("@command\n");
    my $fh = IO::File->new("> $args{outfile}") or die "Couldn't write $args{outfile}: $!";
    print {$fh} $self->_backticks(@command);
    close $fh;
  }
}

sub split_like_shell {
  my ($self, $string) = @_;

  return () unless defined($string);
  return @$string if UNIVERSAL::isa($string, 'ARRAY');
  $string =~ s/^\s+|\s+$//g;
  return () unless length($string);

  return Text::ParseWords::shellwords($string);
}

sub oneliner {
  # Returns a string that the shell can evaluate as a perl command.
  # This should be avoided whenever possible, since "the shell" really
  # means zillions of shells on zillions of platforms and it's really
  # hard to get it right all the time.

  # Some of this code is stolen with permission from ExtUtils::MakeMaker.

  my($self, $cmd, $switches, $args) = @_;
  $switches = [] unless defined $switches;
  $args = [] unless defined $args;

  # Strip leading and trailing newlines
  $cmd =~ s{^\n+}{};
  $cmd =~ s{\n+$}{};

  my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;
  return $self->_quote_args($perl, @$switches, '-e', $cmd, @$args);
}

sub run_perl_script {
  my ($self, $script, $preargs, $postargs) = @_;
  foreach ($preargs, $postargs) {
    $_ = [ $self->split_like_shell($_) ] unless ref();
  }
  return $self->run_perl_command([@$preargs, $script, @$postargs]);
}

sub run_perl_command {
  # XXX Maybe we should accept @args instead of $args?  Must resolve
  # this before documenting.
  my ($self, $args) = @_;
  $args = [ $self->split_like_shell($args) ] unless ref($args);
  my $perl = ref($self) ? $self->perl : $self->find_perl_interpreter;

  # Make sure our local additions to @INC are propagated to the subprocess
  local $ENV{PERL5LIB} = join $self->config('path_sep'), $self->_added_to_INC;

  return $self->do_system($perl, @$args);
}

# Infer various data from the path of the input filename
# that is needed to create output files.
# The input filename is expected to be of the form:
#   lib/Module/Name.ext or Module/Name.ext
sub _infer_xs_spec {
  my $self = shift;
  my $file = shift;

  my $cf = $self->{config};

  my %spec;

  my( $v, $d, $f ) = File::Spec->splitpath( $file );
  my @d = File::Spec->splitdir( $d );
  (my $file_base = $f) =~ s/\.[^.]+$//i;

inc/inc_Module-Build/Module/Build/Base.pm  view on Meta::CPAN

  $spec{bs_file} = File::Spec->catfile($spec{archdir}, "${file_base}.bs");

  $spec{lib_file} = File::Spec->catfile($spec{archdir},
                                        "${file_base}.".$cf->get('dlext'));

  $spec{c_file} = File::Spec->catfile( $spec{src_dir},
                                       "${file_base}.c" );

  $spec{obj_file} = File::Spec->catfile( $spec{src_dir},
                                         "${file_base}".$cf->get('obj_ext') );

  return \%spec;
}

sub process_xs {
  my ($self, $file) = @_;

  my $spec = $self->_infer_xs_spec($file);

  # File name, minus the suffix
  (my $file_base = $file) =~ s/\.[^.]+$//;

  # .xs -> .c
  $self->add_to_cleanup($spec->{c_file});

  unless ($self->up_to_date($file, $spec->{c_file})) {
    $self->compile_xs($file, outfile => $spec->{c_file});
  }

  # .c -> .o
  my $v = $self->dist_version;
  $self->compile_c($spec->{c_file},
                   defines => {VERSION => qq{"$v"}, XS_VERSION => qq{"$v"}});

  # archdir
  File::Path::mkpath($spec->{archdir}, 0, oct(777)) unless -d $spec->{archdir};

  # .xs -> .bs
  $self->add_to_cleanup($spec->{bs_file});
  unless ($self->up_to_date($file, $spec->{bs_file})) {
    require ExtUtils::Mkbootstrap;
    $self->log_info("ExtUtils::Mkbootstrap::Mkbootstrap('$spec->{bs_file}')\n");
    ExtUtils::Mkbootstrap::Mkbootstrap($spec->{bs_file});  # Original had $BSLOADLIBS - what's that?
    {my $fh = IO::File->new(">> $spec->{bs_file}")}  # create
    utime((time)x2, $spec->{bs_file});  # touch
  }

  # .o -> .(a|bundle)
  $self->link_c($spec);
}

sub do_system {
  my ($self, @cmd) = @_;
  $self->log_verbose("@cmd\n");

  # Some systems proliferate huge PERL5LIBs, try to ameliorate:
  my %seen;
  my $sep = $self->config('path_sep');
  local $ENV{PERL5LIB} =
    ( !exists($ENV{PERL5LIB}) ? '' :
      length($ENV{PERL5LIB}) < 500
      ? $ENV{PERL5LIB}
      : join $sep, grep { ! $seen{$_}++ and -d $_ } split($sep, $ENV{PERL5LIB})
    );

  my $status = system(@cmd);
  if ($status and $! =~ /Argument list too long/i) {
    my $env_entries = '';
    foreach (sort keys %ENV) { $env_entries .= "$_=>".length($ENV{$_})."; " }
    warn "'Argument list' was 'too long', env lengths are $env_entries";
  }
  return !$status;
}

sub copy_if_modified {
  my $self = shift;
  my %args = (@_ > 3
              ? ( @_ )
              : ( from => shift, to_dir => shift, flatten => shift )
             );
  $args{verbose} = !$self->quiet
    unless exists $args{verbose};

  my $file = $args{from};
  unless (defined $file and length $file) {
    die "No 'from' parameter given to copy_if_modified";
  }

  # makes no sense to replicate an absolute path, so assume flatten
  $args{flatten} = 1 if File::Spec->file_name_is_absolute( $file );

  my $to_path;
  if (defined $args{to} and length $args{to}) {
    $to_path = $args{to};
  } elsif (defined $args{to_dir} and length $args{to_dir}) {
    $to_path = File::Spec->catfile( $args{to_dir}, $args{flatten}
                                    ? File::Basename::basename($file)
                                    : $file );
  } else {
    die "No 'to' or 'to_dir' parameter given to copy_if_modified";
  }

  return if $self->up_to_date($file, $to_path); # Already fresh

  {
    local $self->{properties}{quiet} = 1;
    $self->delete_filetree($to_path); # delete destination if exists
  }

  # Create parent directories
  File::Path::mkpath(File::Basename::dirname($to_path), 0, oct(777));

  $self->log_verbose("Copying $file -> $to_path\n");

  if ($^O eq 'os2') {# copy will not overwrite; 0x1 = overwrite
    chmod 0666, $to_path;
    File::Copy::syscopy($file, $to_path, 0x1) or die "Can't copy('$file', '$to_path'): $!";
  } else {
    File::Copy::copy($file, $to_path) or die "Can't copy('$file', '$to_path'): $!";
  }

  # mode is read-only + (executable if source is executable)
  my $mode = oct(444) | ( $self->is_executable($file) ? oct(111) : 0 );
  chmod( $mode, $to_path );

  return $to_path;
}

sub up_to_date {
  my ($self, $source, $derived) = @_;
  $source  = [$source]  unless ref $source;
  $derived = [$derived] unless ref $derived;

  # empty $derived means $source should always run
  return 0 if @$source && !@$derived || grep {not -e} @$derived;

  my $most_recent_source = time / (24*60*60);
  foreach my $file (@$source) {
    unless (-e $file) {
      $self->log_warn("Can't find source file $file for up-to-date check");
      next;
    }
    $most_recent_source = -M _ if -M _ < $most_recent_source;
  }

  foreach my $derived (@$derived) {
    return 0 if -M $derived > $most_recent_source;
  }
  return 1;
}

sub dir_contains {
  my ($self, $first, $second) = @_;
  # File::Spec doesn't have an easy way to check whether one directory
  # is inside another, unfortunately.



( run in 0.725 second using v1.01-cache-2.11-cpan-172d661cebc )