This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
backport EUMM commits
[perl5.git] / cpan / ExtUtils-MakeMaker / lib / ExtUtils / MM_Any.pm
1 package ExtUtils::MM_Any;
2
3 use strict;
4 our $VERSION = '7.10_01';
5
6 use Carp;
7 use File::Spec;
8 use File::Basename;
9 BEGIN { our @ISA = qw(File::Spec); }
10
11 # We need $Verbose
12 use ExtUtils::MakeMaker qw($Verbose);
13
14 use ExtUtils::MakeMaker::Config;
15
16
17 # So we don't have to keep calling the methods over and over again,
18 # we have these globals to cache the values.  Faster and shrtr.
19 my $Curdir  = __PACKAGE__->curdir;
20 my $Rootdir = __PACKAGE__->rootdir;
21 my $Updir   = __PACKAGE__->updir;
22
23
24 =head1 NAME
25
26 ExtUtils::MM_Any - Platform-agnostic MM methods
27
28 =head1 SYNOPSIS
29
30   FOR INTERNAL USE ONLY!
31
32   package ExtUtils::MM_SomeOS;
33
34   # Temporarily, you have to subclass both.  Put MM_Any first.
35   require ExtUtils::MM_Any;
36   require ExtUtils::MM_Unix;
37   @ISA = qw(ExtUtils::MM_Any ExtUtils::Unix);
38
39 =head1 DESCRIPTION
40
41 B<FOR INTERNAL USE ONLY!>
42
43 ExtUtils::MM_Any is a superclass for the ExtUtils::MM_* set of
44 modules.  It contains methods which are either inherently
45 cross-platform or are written in a cross-platform manner.
46
47 Subclass off of ExtUtils::MM_Any I<and> ExtUtils::MM_Unix.  This is a
48 temporary solution.
49
50 B<THIS MAY BE TEMPORARY!>
51
52
53 =head1 METHODS
54
55 Any methods marked I<Abstract> must be implemented by subclasses.
56
57
58 =head2 Cross-platform helper methods
59
60 These are methods which help writing cross-platform code.
61
62
63
64 =head3 os_flavor  I<Abstract>
65
66     my @os_flavor = $mm->os_flavor;
67
68 @os_flavor is the style of operating system this is, usually
69 corresponding to the MM_*.pm file we're using.
70
71 The first element of @os_flavor is the major family (ie. Unix,
72 Windows, VMS, OS/2, etc...) and the rest are sub families.
73
74 Some examples:
75
76     Cygwin98       ('Unix',  'Cygwin', 'Cygwin9x')
77     Windows        ('Win32')
78     Win98          ('Win32', 'Win9x')
79     Linux          ('Unix',  'Linux')
80     MacOS X        ('Unix',  'Darwin', 'MacOS', 'MacOS X')
81     OS/2           ('OS/2')
82
83 This is used to write code for styles of operating system.
84 See os_flavor_is() for use.
85
86
87 =head3 os_flavor_is
88
89     my $is_this_flavor = $mm->os_flavor_is($this_flavor);
90     my $is_this_flavor = $mm->os_flavor_is(@one_of_these_flavors);
91
92 Checks to see if the current operating system is one of the given flavors.
93
94 This is useful for code like:
95
96     if( $mm->os_flavor_is('Unix') ) {
97         $out = `foo 2>&1`;
98     }
99     else {
100         $out = `foo`;
101     }
102
103 =cut
104
105 sub os_flavor_is {
106     my $self = shift;
107     my %flavors = map { ($_ => 1) } $self->os_flavor;
108     return (grep { $flavors{$_} } @_) ? 1 : 0;
109 }
110
111
112 =head3 can_load_xs
113
114     my $can_load_xs = $self->can_load_xs;
115
116 Returns true if we have the ability to load XS.
117
118 This is important because miniperl, used to build XS modules in the
119 core, can not load XS.
120
121 =cut
122
123 sub can_load_xs {
124     return defined &DynaLoader::boot_DynaLoader ? 1 : 0;
125 }
126
127
128 =head3 can_run
129
130   use ExtUtils::MM;
131   my $runnable = MM->can_run($Config{make});
132
133 If called in a scalar context it will return the full path to the binary
134 you asked for if it was found, or C<undef> if it was not.
135
136 If called in a list context, it will return a list of the full paths to instances
137 of the binary where found in C<PATH>, or an empty list if it was not found.
138
139 Copied from L<IPC::Cmd|IPC::Cmd/"$path = can_run( PROGRAM );">, but modified into
140 a method (and removed C<$INSTANCES> capability).
141
142 =cut
143
144 sub can_run {
145     my ($self, $command) = @_;
146
147     # a lot of VMS executables have a symbol defined
148     # check those first
149     if ( $^O eq 'VMS' ) {
150         require VMS::DCLsym;
151         my $syms = VMS::DCLsym->new;
152         return $command if scalar $syms->getsym( uc $command );
153     }
154
155     my @possibles;
156
157     if( File::Spec->file_name_is_absolute($command) ) {
158         return $self->maybe_command($command);
159
160     } else {
161         for my $dir (
162             File::Spec->path,
163             File::Spec->curdir
164         ) {
165             next if ! $dir || ! -d $dir;
166             my $abs = File::Spec->catfile($self->os_flavor_is('Win32') ? Win32::GetShortPathName( $dir ) : $dir, $command);
167             push @possibles, $abs if $abs = $self->maybe_command($abs);
168         }
169     }
170     return @possibles if wantarray;
171     return shift @possibles;
172 }
173
174
175 =head3 can_redirect_error
176
177   $useredirect = MM->can_redirect_error;
178
179 True if on an OS where qx operator (or backticks) can redirect C<STDERR>
180 onto C<STDOUT>.
181
182 =cut
183
184 sub can_redirect_error {
185   my $self = shift;
186   $self->os_flavor_is('Unix')
187       or ($self->os_flavor_is('Win32') and !$self->os_flavor_is('Win9x'))
188       or $self->os_flavor_is('OS/2')
189 }
190
191
192 =head3 is_make_type
193
194     my $is_dmake = $self->is_make_type('dmake');
195
196 Returns true if C<<$self->make>> is the given type; possibilities are:
197
198   gmake    GNU make
199   dmake
200   nmake
201   bsdmake  BSD pmake-derived
202
203 =cut
204
205 my %maketype2true;
206 # undocumented - so t/cd.t can still do its thing
207 sub _clear_maketype_cache { %maketype2true = () }
208
209 sub is_make_type {
210     my($self, $type) = @_;
211     return $maketype2true{$type} if defined $maketype2true{$type};
212     (undef, undef, my $make_basename) = $self->splitpath($self->make);
213     return $maketype2true{$type} = 1
214         if $make_basename =~ /\b$type\b/i; # executable's filename
215     return $maketype2true{$type} = 0
216         if $make_basename =~ /\b[gdn]make\b/i; # Never fall through for dmake/nmake/gmake
217     # now have to run with "-v" and guess
218     my $redirect = $self->can_redirect_error ? '2>&1' : '';
219     my $make = $self->make || $self->{MAKE};
220     my $minus_v = `"$make" -v $redirect`;
221     return $maketype2true{$type} = 1
222         if $type eq 'gmake' and $minus_v =~ /GNU make/i;
223     return $maketype2true{$type} = 1
224         if $type eq 'bsdmake'
225       and $minus_v =~ /^usage: make \[-BeikNnqrstWwX\]/im;
226     $maketype2true{$type} = 0; # it wasn't whatever you asked
227 }
228
229
230 =head3 can_dep_space
231
232     my $can_dep_space = $self->can_dep_space;
233
234 Returns true if C<make> can handle (probably by quoting)
235 dependencies that contain a space. Currently known true for GNU make,
236 false for BSD pmake derivative.
237
238 =cut
239
240 my $cached_dep_space;
241 sub can_dep_space {
242     my $self = shift;
243     return $cached_dep_space if defined $cached_dep_space;
244     return $cached_dep_space = 1 if $self->is_make_type('gmake');
245     return $cached_dep_space = 0 if $self->is_make_type('dmake'); # only on W32
246     return $cached_dep_space = 0 if $self->is_make_type('bsdmake');
247     return $cached_dep_space = 0; # assume no
248 }
249
250
251 =head3 quote_dep
252
253   $text = $mm->quote_dep($text);
254
255 Method that protects Makefile single-value constants (mainly filenames),
256 so that make will still treat them as single values even if they
257 inconveniently have spaces in. If the make program being used cannot
258 achieve such protection and the given text would need it, throws an
259 exception.
260
261 =cut
262
263 sub quote_dep {
264     my ($self, $arg) = @_;
265     die <<EOF if $arg =~ / / and not $self->can_dep_space;
266 Tried to use make dependency with space for make that can't:
267   '$arg'
268 EOF
269     $arg =~ s/( )/\\$1/g; # how GNU make does it
270     return $arg;
271 }
272
273
274 =head3 split_command
275
276     my @cmds = $MM->split_command($cmd, @args);
277
278 Most OS have a maximum command length they can execute at once.  Large
279 modules can easily generate commands well past that limit.  Its
280 necessary to split long commands up into a series of shorter commands.
281
282 C<split_command> will return a series of @cmds each processing part of
283 the args.  Collectively they will process all the arguments.  Each
284 individual line in @cmds will not be longer than the
285 $self->max_exec_len being careful to take into account macro expansion.
286
287 $cmd should include any switches and repeated initial arguments.
288
289 If no @args are given, no @cmds will be returned.
290
291 Pairs of arguments will always be preserved in a single command, this
292 is a heuristic for things like pm_to_blib and pod2man which work on
293 pairs of arguments.  This makes things like this safe:
294
295     $self->split_command($cmd, %pod2man);
296
297
298 =cut
299
300 sub split_command {
301     my($self, $cmd, @args) = @_;
302
303     my @cmds = ();
304     return(@cmds) unless @args;
305
306     # If the command was given as a here-doc, there's probably a trailing
307     # newline.
308     chomp $cmd;
309
310     # set aside 30% for macro expansion.
311     my $len_left = int($self->max_exec_len * 0.70);
312     $len_left -= length $self->_expand_macros($cmd);
313
314     do {
315         my $arg_str = '';
316         my @next_args;
317         while( @next_args = splice(@args, 0, 2) ) {
318             # Two at a time to preserve pairs.
319             my $next_arg_str = "\t  ". join ' ', @next_args, "\n";
320
321             if( !length $arg_str ) {
322                 $arg_str .= $next_arg_str
323             }
324             elsif( length($arg_str) + length($next_arg_str) > $len_left ) {
325                 unshift @args, @next_args;
326                 last;
327             }
328             else {
329                 $arg_str .= $next_arg_str;
330             }
331         }
332         chop $arg_str;
333
334         push @cmds, $self->escape_newlines("$cmd \n$arg_str");
335     } while @args;
336
337     return @cmds;
338 }
339
340
341 sub _expand_macros {
342     my($self, $cmd) = @_;
343
344     $cmd =~ s{\$\((\w+)\)}{
345         defined $self->{$1} ? $self->{$1} : "\$($1)"
346     }e;
347     return $cmd;
348 }
349
350
351 =head3 echo
352
353     my @commands = $MM->echo($text);
354     my @commands = $MM->echo($text, $file);
355     my @commands = $MM->echo($text, $file, \%opts);
356
357 Generates a set of @commands which print the $text to a $file.
358
359 If $file is not given, output goes to STDOUT.
360
361 If $opts{append} is true the $file will be appended to rather than
362 overwritten.  Default is to overwrite.
363
364 If $opts{allow_variables} is true, make variables of the form
365 C<$(...)> will not be escaped.  Other C<$> will.  Default is to escape
366 all C<$>.
367
368 Example of use:
369
370     my $make = map "\t$_\n", $MM->echo($text, $file);
371
372 =cut
373
374 sub echo {
375     my($self, $text, $file, $opts) = @_;
376
377     # Compatibility with old options
378     if( !ref $opts ) {
379         my $append = $opts;
380         $opts = { append => $append || 0 };
381     }
382     $opts->{allow_variables} = 0 unless defined $opts->{allow_variables};
383
384     my $ql_opts = { allow_variables => $opts->{allow_variables} };
385     my @cmds = map { '$(NOECHO) $(ECHO) '.$self->quote_literal($_, $ql_opts) }
386                split /\n/, $text;
387     if( $file ) {
388         my $redirect = $opts->{append} ? '>>' : '>';
389         $cmds[0] .= " $redirect $file";
390         $_ .= " >> $file" foreach @cmds[1..$#cmds];
391     }
392
393     return @cmds;
394 }
395
396
397 =head3 wraplist
398
399   my $args = $mm->wraplist(@list);
400
401 Takes an array of items and turns them into a well-formatted list of
402 arguments.  In most cases this is simply something like:
403
404     FOO \
405     BAR \
406     BAZ
407
408 =cut
409
410 sub wraplist {
411     my $self = shift;
412     return join " \\\n\t", @_;
413 }
414
415
416 =head3 maketext_filter
417
418     my $filter_make_text = $mm->maketext_filter($make_text);
419
420 The text of the Makefile is run through this method before writing to
421 disk.  It allows systems a chance to make portability fixes to the
422 Makefile.
423
424 By default it does nothing.
425
426 This method is protected and not intended to be called outside of
427 MakeMaker.
428
429 =cut
430
431 sub maketext_filter { return $_[1] }
432
433
434 =head3 cd  I<Abstract>
435
436   my $subdir_cmd = $MM->cd($subdir, @cmds);
437
438 This will generate a make fragment which runs the @cmds in the given
439 $dir.  The rough equivalent to this, except cross platform.
440
441   cd $subdir && $cmd
442
443 Currently $dir can only go down one level.  "foo" is fine.  "foo/bar" is
444 not.  "../foo" is right out.
445
446 The resulting $subdir_cmd has no leading tab nor trailing newline.  This
447 makes it easier to embed in a make string.  For example.
448
449       my $make = sprintf <<'CODE', $subdir_cmd;
450   foo :
451       $(ECHO) what
452       %s
453       $(ECHO) mouche
454   CODE
455
456
457 =head3 oneliner  I<Abstract>
458
459   my $oneliner = $MM->oneliner($perl_code);
460   my $oneliner = $MM->oneliner($perl_code, \@switches);
461
462 This will generate a perl one-liner safe for the particular platform
463 you're on based on the given $perl_code and @switches (a -e is
464 assumed) suitable for using in a make target.  It will use the proper
465 shell quoting and escapes.
466
467 $(PERLRUN) will be used as perl.
468
469 Any newlines in $perl_code will be escaped.  Leading and trailing
470 newlines will be stripped.  Makes this idiom much easier:
471
472     my $code = $MM->oneliner(<<'CODE', [...switches...]);
473 some code here
474 another line here
475 CODE
476
477 Usage might be something like:
478
479     # an echo emulation
480     $oneliner = $MM->oneliner('print "Foo\n"');
481     $make = '$oneliner > somefile';
482
483 All dollar signs must be doubled in the $perl_code if you expect them
484 to be interpreted normally, otherwise it will be considered a make
485 macro.  Also remember to quote make macros else it might be used as a
486 bareword.  For example:
487
488     # Assign the value of the $(VERSION_FROM) make macro to $vf.
489     $oneliner = $MM->oneliner('$$vf = "$(VERSION_FROM)"');
490
491 Its currently very simple and may be expanded sometime in the figure
492 to include more flexible code and switches.
493
494
495 =head3 quote_literal  I<Abstract>
496
497     my $safe_text = $MM->quote_literal($text);
498     my $safe_text = $MM->quote_literal($text, \%options);
499
500 This will quote $text so it is interpreted literally in the shell.
501
502 For example, on Unix this would escape any single-quotes in $text and
503 put single-quotes around the whole thing.
504
505 If $options{allow_variables} is true it will leave C<'$(FOO)'> make
506 variables untouched.  If false they will be escaped like any other
507 C<$>.  Defaults to true.
508
509 =head3 escape_dollarsigns
510
511     my $escaped_text = $MM->escape_dollarsigns($text);
512
513 Escapes stray C<$> so they are not interpreted as make variables.
514
515 It lets by C<$(...)>.
516
517 =cut
518
519 sub escape_dollarsigns {
520     my($self, $text) = @_;
521
522     # Escape dollar signs which are not starting a variable
523     $text =~ s{\$ (?!\() }{\$\$}gx;
524
525     return $text;
526 }
527
528
529 =head3 escape_all_dollarsigns
530
531     my $escaped_text = $MM->escape_all_dollarsigns($text);
532
533 Escapes all C<$> so they are not interpreted as make variables.
534
535 =cut
536
537 sub escape_all_dollarsigns {
538     my($self, $text) = @_;
539
540     # Escape dollar signs
541     $text =~ s{\$}{\$\$}gx;
542
543     return $text;
544 }
545
546
547 =head3 escape_newlines  I<Abstract>
548
549     my $escaped_text = $MM->escape_newlines($text);
550
551 Shell escapes newlines in $text.
552
553
554 =head3 max_exec_len  I<Abstract>
555
556     my $max_exec_len = $MM->max_exec_len;
557
558 Calculates the maximum command size the OS can exec.  Effectively,
559 this is the max size of a shell command line.
560
561 =for _private
562 $self->{_MAX_EXEC_LEN} is set by this method, but only for testing purposes.
563
564
565 =head3 make
566
567     my $make = $MM->make;
568
569 Returns the make variant we're generating the Makefile for.  This attempts
570 to do some normalization on the information from %Config or the user.
571
572 =cut
573
574 sub make {
575     my $self = shift;
576
577     my $make = lc $self->{MAKE};
578
579     # Truncate anything like foomake6 to just foomake.
580     $make =~ s/^(\w+make).*/$1/;
581
582     # Turn gnumake into gmake.
583     $make =~ s/^gnu/g/;
584
585     return $make;
586 }
587
588
589 =head2 Targets
590
591 These are methods which produce make targets.
592
593
594 =head3 all_target
595
596 Generate the default target 'all'.
597
598 =cut
599
600 sub all_target {
601     my $self = shift;
602
603     return <<'MAKE_EXT';
604 all :: pure_all
605         $(NOECHO) $(NOOP)
606 MAKE_EXT
607
608 }
609
610
611 =head3 blibdirs_target
612
613     my $make_frag = $mm->blibdirs_target;
614
615 Creates the blibdirs target which creates all the directories we use
616 in blib/.
617
618 The blibdirs.ts target is deprecated.  Depend on blibdirs instead.
619
620
621 =cut
622
623 sub blibdirs_target {
624     my $self = shift;
625
626     my @dirs = map { uc "\$(INST_$_)" } qw(libdir archlib
627                                            autodir archautodir
628                                            bin script
629                                            man1dir man3dir
630                                           );
631
632     my @exists = map { $_.'$(DFSEP).exists' } @dirs;
633
634     my $make = sprintf <<'MAKE', join(' ', @exists);
635 blibdirs : %s
636         $(NOECHO) $(NOOP)
637
638 # Backwards compat with 6.18 through 6.25
639 blibdirs.ts : blibdirs
640         $(NOECHO) $(NOOP)
641
642 MAKE
643
644     $make .= $self->dir_target(@dirs);
645
646     return $make;
647 }
648
649
650 =head3 clean (o)
651
652 Defines the clean target.
653
654 =cut
655
656 sub clean {
657 # --- Cleanup and Distribution Sections ---
658
659     my($self, %attribs) = @_;
660     my @m;
661     push(@m, '
662 # Delete temporary files but do not touch installed files. We don\'t delete
663 # the Makefile here so a later make realclean still has a makefile to use.
664
665 clean :: clean_subdirs
666 ');
667
668     my @files = sort values %{$self->{XS}}; # .c files from *.xs files
669     my @dirs  = qw(blib);
670
671     # Normally these are all under blib but they might have been
672     # redefined.
673     # XXX normally this would be a good idea, but the Perl core sets
674     # INST_LIB = ../../lib rather than actually installing the files.
675     # So a "make clean" in an ext/ directory would blow away lib.
676     # Until the core is adjusted let's leave this out.
677 #     push @dirs, qw($(INST_ARCHLIB) $(INST_LIB)
678 #                    $(INST_BIN) $(INST_SCRIPT)
679 #                    $(INST_MAN1DIR) $(INST_MAN3DIR)
680 #                    $(INST_LIBDIR) $(INST_ARCHLIBDIR) $(INST_AUTODIR)
681 #                    $(INST_STATIC) $(INST_DYNAMIC)
682 #                 );
683
684
685     if( $attribs{FILES} ) {
686         # Use @dirs because we don't know what's in here.
687         push @dirs, ref $attribs{FILES}                ?
688                         @{$attribs{FILES}}             :
689                         split /\s+/, $attribs{FILES}   ;
690     }
691
692     push(@files, qw[$(MAKE_APERL_FILE)
693                     MYMETA.json MYMETA.yml perlmain.c tmon.out mon.out so_locations
694                     blibdirs.ts pm_to_blib pm_to_blib.ts
695                     *$(OBJ_EXT) *$(LIB_EXT) perl.exe perl perl$(EXE_EXT)
696                     $(BOOTSTRAP) $(BASEEXT).bso
697                     $(BASEEXT).def lib$(BASEEXT).def
698                     $(BASEEXT).exp $(BASEEXT).x
699                    ]);
700
701     push(@files, $self->catfile('$(INST_ARCHAUTODIR)','extralibs.all'));
702     push(@files, $self->catfile('$(INST_ARCHAUTODIR)','extralibs.ld'));
703
704     # core files
705     if ($^O eq 'vos') {
706         push(@files, qw[perl*.kp]);
707     }
708     else {
709         push(@files, qw[core core.*perl.*.? *perl.core]);
710     }
711
712     push(@files, map { "core." . "[0-9]"x$_ } (1..5));
713
714     # OS specific things to clean up.  Use @dirs since we don't know
715     # what might be in here.
716     push @dirs, $self->extra_clean_files;
717
718     # Occasionally files are repeated several times from different sources
719     { my(%f) = map { ($_ => 1) } @files; @files = sort keys %f; }
720     { my(%d) = map { ($_ => 1) } @dirs;  @dirs  = sort keys %d; }
721
722     push @m, map "\t$_\n", $self->split_command('- $(RM_F)',  @files);
723     push @m, map "\t$_\n", $self->split_command('- $(RM_RF)', @dirs);
724
725     # Leave Makefile.old around for realclean
726     push @m, <<'MAKE';
727           $(NOECHO) $(RM_F) $(MAKEFILE_OLD)
728         - $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) $(DEV_NULL)
729 MAKE
730
731     push(@m, "\t$attribs{POSTOP}\n")   if $attribs{POSTOP};
732
733     join("", @m);
734 }
735
736
737 =head3 clean_subdirs_target
738
739   my $make_frag = $MM->clean_subdirs_target;
740
741 Returns the clean_subdirs target.  This is used by the clean target to
742 call clean on any subdirectories which contain Makefiles.
743
744 =cut
745
746 sub clean_subdirs_target {
747     my($self) = shift;
748
749     # No subdirectories, no cleaning.
750     return <<'NOOP_FRAG' unless @{$self->{DIR}};
751 clean_subdirs :
752         $(NOECHO) $(NOOP)
753 NOOP_FRAG
754
755
756     my $clean = "clean_subdirs :\n";
757
758     for my $dir (@{$self->{DIR}}) {
759         my $subclean = $self->oneliner(sprintf <<'CODE', $dir);
760 exit 0 unless chdir '%s';  system '$(MAKE) clean' if -f '$(FIRST_MAKEFILE)';
761 CODE
762
763         $clean .= "\t$subclean\n";
764     }
765
766     return $clean;
767 }
768
769
770 =head3 dir_target
771
772     my $make_frag = $mm->dir_target(@directories);
773
774 Generates targets to create the specified directories and set its
775 permission to PERM_DIR.
776
777 Because depending on a directory to just ensure it exists doesn't work
778 too well (the modified time changes too often) dir_target() creates a
779 .exists file in the created directory.  It is this you should depend on.
780 For portability purposes you should use the $(DIRFILESEP) macro rather
781 than a '/' to separate the directory from the file.
782
783     yourdirectory$(DIRFILESEP).exists
784
785 =cut
786
787 sub dir_target {
788     my($self, @dirs) = @_;
789
790     my $make = '';
791     foreach my $dir (@dirs) {
792         $make .= sprintf <<'MAKE', ($dir) x 4;
793 %s$(DFSEP).exists :: Makefile.PL
794         $(NOECHO) $(MKPATH) %s
795         $(NOECHO) $(CHMOD) $(PERM_DIR) %s
796         $(NOECHO) $(TOUCH) %s$(DFSEP).exists
797
798 MAKE
799
800     }
801
802     return $make;
803 }
804
805
806 =head3 distdir
807
808 Defines the scratch directory target that will hold the distribution
809 before tar-ing (or shar-ing).
810
811 =cut
812
813 # For backwards compatibility.
814 *dist_dir = *distdir;
815
816 sub distdir {
817     my($self) = shift;
818
819     my $meta_target = $self->{NO_META} ? '' : 'distmeta';
820     my $sign_target = !$self->{SIGN}   ? '' : 'distsignature';
821
822     return sprintf <<'MAKE_FRAG', $meta_target, $sign_target;
823 create_distdir :
824         $(RM_RF) $(DISTVNAME)
825         $(PERLRUN) "-MExtUtils::Manifest=manicopy,maniread" \
826                 -e "manicopy(maniread(),'$(DISTVNAME)', '$(DIST_CP)');"
827
828 distdir : create_distdir %s %s
829         $(NOECHO) $(NOOP)
830
831 MAKE_FRAG
832
833 }
834
835
836 =head3 dist_test
837
838 Defines a target that produces the distribution in the
839 scratch directory, and runs 'perl Makefile.PL; make ;make test' in that
840 subdirectory.
841
842 =cut
843
844 sub dist_test {
845     my($self) = shift;
846
847     my $mpl_args = join " ", map qq["$_"], @ARGV;
848
849     my $test = $self->cd('$(DISTVNAME)',
850                          '$(ABSPERLRUN) Makefile.PL '.$mpl_args,
851                          '$(MAKE) $(PASTHRU)',
852                          '$(MAKE) test $(PASTHRU)'
853                         );
854
855     return sprintf <<'MAKE_FRAG', $test;
856 disttest : distdir
857         %s
858
859 MAKE_FRAG
860
861
862 }
863
864
865 =head3 dynamic (o)
866
867 Defines the dynamic target.
868
869 =cut
870
871 sub dynamic {
872 # --- Dynamic Loading Sections ---
873
874     my($self) = shift;
875     '
876 dynamic :: $(FIRST_MAKEFILE) $(BOOTSTRAP) $(INST_DYNAMIC)
877         $(NOECHO) $(NOOP)
878 ';
879 }
880
881
882 =head3 makemakerdflt_target
883
884   my $make_frag = $mm->makemakerdflt_target
885
886 Returns a make fragment with the makemakerdeflt_target specified.
887 This target is the first target in the Makefile, is the default target
888 and simply points off to 'all' just in case any make variant gets
889 confused or something gets snuck in before the real 'all' target.
890
891 =cut
892
893 sub makemakerdflt_target {
894     return <<'MAKE_FRAG';
895 makemakerdflt : all
896         $(NOECHO) $(NOOP)
897 MAKE_FRAG
898
899 }
900
901
902 =head3 manifypods_target
903
904   my $manifypods_target = $self->manifypods_target;
905
906 Generates the manifypods target.  This target generates man pages from
907 all POD files in MAN1PODS and MAN3PODS.
908
909 =cut
910
911 sub manifypods_target {
912     my($self) = shift;
913
914     my $man1pods      = '';
915     my $man3pods      = '';
916     my $dependencies  = '';
917
918     # populate manXpods & dependencies:
919     foreach my $name (sort keys %{$self->{MAN1PODS}}, sort keys %{$self->{MAN3PODS}}) {
920         $dependencies .= " \\\n\t$name";
921     }
922
923     my $manify = <<END;
924 manifypods : pure_all $dependencies
925 END
926
927     my @man_cmds;
928     foreach my $section (qw(1 3)) {
929         my $pods = $self->{"MAN${section}PODS"};
930         my $p2m = sprintf <<CMD, $] > 5.008 ? " -u" : "";
931         \$(NOECHO) \$(POD2MAN) --section=$section --perm_rw=\$(PERM_RW)%s
932 CMD
933         push @man_cmds, $self->split_command($p2m, map {($_,$pods->{$_})} sort keys %$pods);
934     }
935
936     $manify .= "\t\$(NOECHO) \$(NOOP)\n" unless @man_cmds;
937     $manify .= join '', map { "$_\n" } @man_cmds;
938
939     return $manify;
940 }
941
942 sub _has_cpan_meta {
943     return eval {
944       require CPAN::Meta;
945       CPAN::Meta->VERSION(2.112150);
946       1;
947     };
948 }
949
950 =head3 metafile_target
951
952     my $target = $mm->metafile_target;
953
954 Generate the metafile target.
955
956 Writes the file META.yml (YAML encoded meta-data) and META.json
957 (JSON encoded meta-data) about the module in the distdir.
958 The format follows Module::Build's as closely as possible.
959
960 =cut
961
962 sub metafile_target {
963     my $self = shift;
964     return <<'MAKE_FRAG' if $self->{NO_META} or ! _has_cpan_meta();
965 metafile :
966         $(NOECHO) $(NOOP)
967 MAKE_FRAG
968
969     my %metadata   = $self->metafile_data(
970         $self->{META_ADD}   || {},
971         $self->{META_MERGE} || {},
972     );
973
974     _fix_metadata_before_conversion( \%metadata );
975
976     # paper over validation issues, but still complain, necessary because
977     # there's no guarantee that the above will fix ALL errors
978     my $meta = eval { CPAN::Meta->create( \%metadata, { lazy_validation => 1 } ) };
979     warn $@ if $@ and
980                $@ !~ /encountered CODE.*, but JSON can only represent references to arrays or hashes/;
981
982     # use the original metadata straight if the conversion failed
983     # or if it can't be stringified.
984     if( !$meta                                                  ||
985         !eval { $meta->as_string( { version => "1.4" } ) }      ||
986         !eval { $meta->as_string }
987     )
988     {
989         $meta = bless \%metadata, 'CPAN::Meta';
990     }
991
992     my @write_metayml = $self->echo(
993       $meta->as_string({version => "1.4"}), 'META_new.yml'
994     );
995     my @write_metajson = $self->echo(
996       $meta->as_string(), 'META_new.json'
997     );
998
999     my $metayml = join("\n\t", @write_metayml);
1000     my $metajson = join("\n\t", @write_metajson);
1001     return sprintf <<'MAKE_FRAG', $metayml, $metajson;
1002 metafile : create_distdir
1003         $(NOECHO) $(ECHO) Generating META.yml
1004         %s
1005         -$(NOECHO) $(MV) META_new.yml $(DISTVNAME)/META.yml
1006         $(NOECHO) $(ECHO) Generating META.json
1007         %s
1008         -$(NOECHO) $(MV) META_new.json $(DISTVNAME)/META.json
1009 MAKE_FRAG
1010
1011 }
1012
1013 =begin private
1014
1015 =head3 _fix_metadata_before_conversion
1016
1017     _fix_metadata_before_conversion( \%metadata );
1018
1019 Fixes errors in the metadata before it's handed off to CPAN::Meta for
1020 conversion. This hopefully results in something that can be used further
1021 on, no guarantee is made though.
1022
1023 =end private
1024
1025 =cut
1026
1027 sub _fix_metadata_before_conversion {
1028     my ( $metadata ) = @_;
1029
1030     # we should never be called unless this already passed but
1031     # prefer to be defensive in case somebody else calls this
1032
1033     return unless _has_cpan_meta;
1034
1035     my $bad_version = $metadata->{version} &&
1036                       !CPAN::Meta::Validator->new->version( 'version', $metadata->{version} );
1037
1038     # just delete all invalid versions
1039     if( $bad_version ) {
1040         warn "Can't parse version '$metadata->{version}'\n";
1041         $metadata->{version} = '';
1042     }
1043
1044     my $validator = CPAN::Meta::Validator->new( $metadata );
1045     return if $validator->is_valid;
1046
1047     # fix non-camelcase custom resource keys (only other trick we know)
1048     for my $error ( $validator->errors ) {
1049         my ( $key ) = ( $error =~ /Custom resource '(.*)' must be in CamelCase./ );
1050         next if !$key;
1051
1052         # first try to remove all non-alphabetic chars
1053         ( my $new_key = $key ) =~ s/[^_a-zA-Z]//g;
1054
1055         # if that doesn't work, uppercase first one
1056         $new_key = ucfirst $new_key if !$validator->custom_1( $new_key );
1057
1058         # copy to new key if that worked
1059         $metadata->{resources}{$new_key} = $metadata->{resources}{$key}
1060           if $validator->custom_1( $new_key );
1061
1062         # and delete old one in any case
1063         delete $metadata->{resources}{$key};
1064     }
1065
1066     return;
1067 }
1068
1069
1070 =begin private
1071
1072 =head3 _sort_pairs
1073
1074     my @pairs = _sort_pairs($sort_sub, \%hash);
1075
1076 Sorts the pairs of a hash based on keys ordered according
1077 to C<$sort_sub>.
1078
1079 =end private
1080
1081 =cut
1082
1083 sub _sort_pairs {
1084     my $sort  = shift;
1085     my $pairs = shift;
1086     return map  { $_ => $pairs->{$_} }
1087            sort $sort
1088            keys %$pairs;
1089 }
1090
1091
1092 # Taken from Module::Build::Base
1093 sub _hash_merge {
1094     my ($self, $h, $k, $v) = @_;
1095     if (ref $h->{$k} eq 'ARRAY') {
1096         push @{$h->{$k}}, ref $v ? @$v : $v;
1097     } elsif (ref $h->{$k} eq 'HASH') {
1098         $self->_hash_merge($h->{$k}, $_, $v->{$_}) foreach keys %$v;
1099     } else {
1100         $h->{$k} = $v;
1101     }
1102 }
1103
1104
1105 =head3 metafile_data
1106
1107     my @metadata_pairs = $mm->metafile_data(\%meta_add, \%meta_merge);
1108
1109 Returns the data which MakeMaker turns into the META.yml file 
1110 and the META.json file.
1111
1112 Values of %meta_add will overwrite any existing metadata in those
1113 keys.  %meta_merge will be merged with them.
1114
1115 =cut
1116
1117 sub metafile_data {
1118     my $self = shift;
1119     my($meta_add, $meta_merge) = @_;
1120
1121     my %meta = (
1122         # required
1123         name         => $self->{DISTNAME},
1124         version      => _normalize_version($self->{VERSION}),
1125         abstract     => $self->{ABSTRACT} || 'unknown',
1126         license      => $self->{LICENSE} || 'unknown',
1127         dynamic_config => 1,
1128
1129         # optional
1130         distribution_type => $self->{PM} ? 'module' : 'script',
1131
1132         no_index     => {
1133             directory   => [qw(t inc)]
1134         },
1135
1136         generated_by => "ExtUtils::MakeMaker version $ExtUtils::MakeMaker::VERSION",
1137         'meta-spec'  => {
1138             url         => 'http://module-build.sourceforge.net/META-spec-v1.4.html',
1139             version     => 1.4
1140         },
1141     );
1142
1143     # The author key is required and it takes a list.
1144     $meta{author}   = defined $self->{AUTHOR}    ? $self->{AUTHOR} : [];
1145
1146     {
1147       my $vers = _metaspec_version( $meta_add, $meta_merge );
1148       my $method = $vers =~ m!^2!
1149                ? '_add_requirements_to_meta_v2'
1150                : '_add_requirements_to_meta_v1_4';
1151       %meta = $self->$method( %meta );
1152     }
1153
1154     while( my($key, $val) = each %$meta_add ) {
1155         $meta{$key} = $val;
1156     }
1157
1158     while( my($key, $val) = each %$meta_merge ) {
1159         $self->_hash_merge(\%meta, $key, $val);
1160     }
1161
1162     return %meta;
1163 }
1164
1165
1166 =begin private
1167
1168 =cut
1169
1170 sub _metaspec_version {
1171   my ( $meta_add, $meta_merge ) = @_;
1172   return $meta_add->{'meta-spec'}->{version}
1173     if defined $meta_add->{'meta-spec'}
1174        and defined $meta_add->{'meta-spec'}->{version};
1175   return $meta_merge->{'meta-spec'}->{version}
1176     if defined $meta_merge->{'meta-spec'}
1177        and  defined $meta_merge->{'meta-spec'}->{version};
1178   return '1.4';
1179 }
1180
1181 sub _add_requirements_to_meta_v1_4 {
1182     my ( $self, %meta ) = @_;
1183
1184     # Check the original args so we can tell between the user setting it
1185     # to an empty hash and it just being initialized.
1186     if( $self->{ARGS}{CONFIGURE_REQUIRES} ) {
1187         $meta{configure_requires} = $self->{CONFIGURE_REQUIRES};
1188     } else {
1189         $meta{configure_requires} = {
1190             'ExtUtils::MakeMaker'       => 0,
1191         };
1192     }
1193
1194     if( $self->{ARGS}{BUILD_REQUIRES} ) {
1195         $meta{build_requires} = $self->{BUILD_REQUIRES};
1196     } else {
1197         $meta{build_requires} = {
1198             'ExtUtils::MakeMaker'       => 0,
1199         };
1200     }
1201
1202     if( $self->{ARGS}{TEST_REQUIRES} ) {
1203         $meta{build_requires} = {
1204           %{ $meta{build_requires} },
1205           %{ $self->{TEST_REQUIRES} },
1206         };
1207     }
1208
1209     $meta{requires} = $self->{PREREQ_PM}
1210         if defined $self->{PREREQ_PM};
1211     $meta{requires}{perl} = _normalize_version($self->{MIN_PERL_VERSION})
1212         if $self->{MIN_PERL_VERSION};
1213
1214     return %meta;
1215 }
1216
1217 sub _add_requirements_to_meta_v2 {
1218     my ( $self, %meta ) = @_;
1219
1220     # Check the original args so we can tell between the user setting it
1221     # to an empty hash and it just being initialized.
1222     if( $self->{ARGS}{CONFIGURE_REQUIRES} ) {
1223         $meta{prereqs}{configure}{requires} = $self->{CONFIGURE_REQUIRES};
1224     } else {
1225         $meta{prereqs}{configure}{requires} = {
1226             'ExtUtils::MakeMaker'       => 0,
1227         };
1228     }
1229
1230     if( $self->{ARGS}{BUILD_REQUIRES} ) {
1231         $meta{prereqs}{build}{requires} = $self->{BUILD_REQUIRES};
1232     } else {
1233         $meta{prereqs}{build}{requires} = {
1234             'ExtUtils::MakeMaker'       => 0,
1235         };
1236     }
1237
1238     if( $self->{ARGS}{TEST_REQUIRES} ) {
1239         $meta{prereqs}{test}{requires} = $self->{TEST_REQUIRES};
1240     }
1241
1242     $meta{prereqs}{runtime}{requires} = $self->{PREREQ_PM}
1243         if $self->{ARGS}{PREREQ_PM};
1244     $meta{prereqs}{runtime}{requires}{perl} = _normalize_version($self->{MIN_PERL_VERSION})
1245         if $self->{MIN_PERL_VERSION};
1246
1247     return %meta;
1248 }
1249
1250 # Adapted from Module::Build::Base
1251 sub _normalize_version {
1252   my ($version) = @_;
1253   $version = 0 unless defined $version;
1254
1255   if ( ref $version eq 'version' ) { # version objects
1256     $version = $version->is_qv ? $version->normal : $version->stringify;
1257   }
1258   elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots
1259     # normalize string tuples without "v": "1.2.3" -> "v1.2.3"
1260     $version = "v$version";
1261   }
1262   else {
1263     # leave alone
1264   }
1265   return $version;
1266 }
1267
1268 =head3 _dump_hash
1269
1270     $yaml = _dump_hash(\%options, %hash);
1271
1272 Implements a fake YAML dumper for a hash given
1273 as a list of pairs. No quoting/escaping is done. Keys
1274 are supposed to be strings. Values are undef, strings,
1275 hash refs or array refs of strings.
1276
1277 Supported options are:
1278
1279     delta => STR - indentation delta
1280     use_header => BOOL - whether to include a YAML header
1281     indent => STR - a string of spaces
1282           default: ''
1283
1284     max_key_length => INT - maximum key length used to align
1285         keys and values of the same hash
1286         default: 20
1287     key_sort => CODE - a sort sub
1288             It may be undef, which means no sorting by keys
1289         default: sub { lc $a cmp lc $b }
1290
1291     customs => HASH - special options for certain keys
1292            (whose values are hashes themselves)
1293         may contain: max_key_length, key_sort, customs
1294
1295 =end private
1296
1297 =cut
1298
1299 sub _dump_hash {
1300     croak "first argument should be a hash ref" unless ref $_[0] eq 'HASH';
1301     my $options = shift;
1302     my %hash = @_;
1303
1304     # Use a list to preserve order.
1305     my @pairs;
1306
1307     my $k_sort
1308         = exists $options->{key_sort} ? $options->{key_sort}
1309                                       : sub { lc $a cmp lc $b };
1310     if ($k_sort) {
1311         croak "'key_sort' should be a coderef" unless ref $k_sort eq 'CODE';
1312         @pairs = _sort_pairs($k_sort, \%hash);
1313     } else { # list of pairs, no sorting
1314         @pairs = @_;
1315     }
1316
1317     my $yaml     = $options->{use_header} ? "--- #YAML:1.0\n" : '';
1318     my $indent   = $options->{indent} || '';
1319     my $k_length = min(
1320         ($options->{max_key_length} || 20),
1321         max(map { length($_) + 1 } grep { !ref $hash{$_} } keys %hash)
1322     );
1323     my $customs  = $options->{customs} || {};
1324
1325     # printf format for key
1326     my $k_format = "%-${k_length}s";
1327
1328     while( @pairs ) {
1329         my($key, $val) = splice @pairs, 0, 2;
1330         $val = '~' unless defined $val;
1331         if(ref $val eq 'HASH') {
1332             if ( keys %$val ) {
1333                 my %k_options = ( # options for recursive call
1334                     delta => $options->{delta},
1335                     use_header => 0,
1336                     indent => $indent . $options->{delta},
1337                 );
1338                 if (exists $customs->{$key}) {
1339                     my %k_custom = %{$customs->{$key}};
1340                     foreach my $k (qw(key_sort max_key_length customs)) {
1341                         $k_options{$k} = $k_custom{$k} if exists $k_custom{$k};
1342                     }
1343                 }
1344                 $yaml .= $indent . "$key:\n"
1345                   . _dump_hash(\%k_options, %$val);
1346             }
1347             else {
1348                 $yaml .= $indent . "$key:  {}\n";
1349             }
1350         }
1351         elsif (ref $val eq 'ARRAY') {
1352             if( @$val ) {
1353                 $yaml .= $indent . "$key:\n";
1354
1355                 for (@$val) {
1356                     croak "only nested arrays of non-refs are supported" if ref $_;
1357                     $yaml .= $indent . $options->{delta} . "- $_\n";
1358                 }
1359             }
1360             else {
1361                 $yaml .= $indent . "$key:  []\n";
1362             }
1363         }
1364         elsif( ref $val and !blessed($val) ) {
1365             croak "only nested hashes, arrays and objects are supported";
1366         }
1367         else {  # if it's an object, just stringify it
1368             $yaml .= $indent . sprintf "$k_format  %s\n", "$key:", $val;
1369         }
1370     };
1371
1372     return $yaml;
1373
1374 }
1375
1376 sub blessed {
1377     return eval { $_[0]->isa("UNIVERSAL"); };
1378 }
1379
1380 sub max {
1381     return (sort { $b <=> $a } @_)[0];
1382 }
1383
1384 sub min {
1385     return (sort { $a <=> $b } @_)[0];
1386 }
1387
1388 =head3 metafile_file
1389
1390     my $meta_yml = $mm->metafile_file(@metadata_pairs);
1391
1392 Turns the @metadata_pairs into YAML.
1393
1394 This method does not implement a complete YAML dumper, being limited
1395 to dump a hash with values which are strings, undef's or nested hashes
1396 and arrays of strings. No quoting/escaping is done.
1397
1398 =cut
1399
1400 sub metafile_file {
1401     my $self = shift;
1402
1403     my %dump_options = (
1404         use_header => 1,
1405         delta      => ' ' x 4,
1406         key_sort   => undef,
1407     );
1408     return _dump_hash(\%dump_options, @_);
1409
1410 }
1411
1412
1413 =head3 distmeta_target
1414
1415     my $make_frag = $mm->distmeta_target;
1416
1417 Generates the distmeta target to add META.yml and META.json to the MANIFEST
1418 in the distdir.
1419
1420 =cut
1421
1422 sub distmeta_target {
1423     my $self = shift;
1424
1425     my @add_meta = (
1426       $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd']),
1427 exit unless -e q{META.yml};
1428 eval { maniadd({q{META.yml} => q{Module YAML meta-data (added by MakeMaker)}}) }
1429     or print "Could not add META.yml to MANIFEST: $${'@'}\n"
1430 CODE
1431       $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd'])
1432 exit unless -f q{META.json};
1433 eval { maniadd({q{META.json} => q{Module JSON meta-data (added by MakeMaker)}}) }
1434     or print "Could not add META.json to MANIFEST: $${'@'}\n"
1435 CODE
1436     );
1437
1438     my @add_meta_to_distdir = map { $self->cd('$(DISTVNAME)', $_) } @add_meta;
1439
1440     return sprintf <<'MAKE', @add_meta_to_distdir;
1441 distmeta : create_distdir metafile
1442         $(NOECHO) %s
1443         $(NOECHO) %s
1444
1445 MAKE
1446
1447 }
1448
1449
1450 =head3 mymeta
1451
1452     my $mymeta = $mm->mymeta;
1453
1454 Generate MYMETA information as a hash either from an existing CPAN Meta file
1455 (META.json or META.yml) or from internal data.
1456
1457 =cut
1458
1459 sub mymeta {
1460     my $self = shift;
1461     my $file = shift || ''; # for testing
1462
1463     my $mymeta = $self->_mymeta_from_meta($file);
1464     my $v2 = 1;
1465
1466     unless ( $mymeta ) {
1467         my @metadata = $self->metafile_data(
1468             $self->{META_ADD}   || {},
1469             $self->{META_MERGE} || {},
1470         );
1471         $mymeta = {@metadata};
1472         $v2 = 0;
1473     }
1474
1475     # Overwrite the non-configure dependency hashes
1476
1477     my $method = $v2
1478                ? '_add_requirements_to_meta_v2'
1479                : '_add_requirements_to_meta_v1_4';
1480
1481     $mymeta = { $self->$method( %$mymeta ) };
1482
1483     $mymeta->{dynamic_config} = 0;
1484
1485     return $mymeta;
1486 }
1487
1488
1489 sub _mymeta_from_meta {
1490     my $self = shift;
1491     my $metafile = shift || ''; # for testing
1492
1493     return unless _has_cpan_meta();
1494
1495     my $meta;
1496     for my $file ( $metafile, "META.json", "META.yml" ) {
1497       next unless -e $file;
1498       eval {
1499           $meta = CPAN::Meta->load_file($file)->as_struct( { version => 2 } );
1500       };
1501       last if $meta;
1502     }
1503     return unless $meta;
1504
1505     # META.yml before 6.25_01 cannot be trusted.  META.yml lived in the source directory.
1506     # There was a good chance the author accidentally uploaded a stale META.yml if they
1507     # rolled their own tarball rather than using "make dist".
1508     if ($meta->{generated_by} &&
1509         $meta->{generated_by} =~ /ExtUtils::MakeMaker version ([\d\._]+)/) {
1510         my $eummv = do { local $^W = 0; $1+0; };
1511         if ($eummv < 6.2501) {
1512             return;
1513         }
1514     }
1515
1516     return $meta;
1517 }
1518
1519 =head3 write_mymeta
1520
1521     $self->write_mymeta( $mymeta );
1522
1523 Write MYMETA information to MYMETA.json and MYMETA.yml.
1524
1525 =cut
1526
1527 sub write_mymeta {
1528     my $self = shift;
1529     my $mymeta = shift;
1530
1531     return unless _has_cpan_meta();
1532
1533     _fix_metadata_before_conversion( $mymeta );
1534
1535     # this can still blow up
1536     # not sure if i should just eval this and skip file creation if it
1537     # blows up
1538     my $meta_obj = CPAN::Meta->new( $mymeta, { lazy_validation => 1 } );
1539     $meta_obj->save( 'MYMETA.json' );
1540     $meta_obj->save( 'MYMETA.yml', { version => "1.4" } );
1541     return 1;
1542 }
1543
1544 =head3 realclean (o)
1545
1546 Defines the realclean target.
1547
1548 =cut
1549
1550 sub realclean {
1551     my($self, %attribs) = @_;
1552
1553     my @dirs  = qw($(DISTVNAME));
1554     my @files = qw($(FIRST_MAKEFILE) $(MAKEFILE_OLD));
1555
1556     # Special exception for the perl core where INST_* is not in blib.
1557     # This cleans up the files built from the ext/ directory (all XS).
1558     if( $self->{PERL_CORE} ) {
1559         push @dirs, qw($(INST_AUTODIR) $(INST_ARCHAUTODIR));
1560         push @files, values %{$self->{PM}};
1561     }
1562
1563     if( $self->has_link_code ){
1564         push @files, qw($(OBJECT));
1565     }
1566
1567     if( $attribs{FILES} ) {
1568         if( ref $attribs{FILES} ) {
1569             push @dirs, @{ $attribs{FILES} };
1570         }
1571         else {
1572             push @dirs, split /\s+/, $attribs{FILES};
1573         }
1574     }
1575
1576     # Occasionally files are repeated several times from different sources
1577     { my(%f) = map { ($_ => 1) } @files;  @files = keys %f; }
1578     { my(%d) = map { ($_ => 1) } @dirs;   @dirs  = keys %d; }
1579
1580     my $rm_cmd  = join "\n\t", map { "$_" }
1581                     $self->split_command('- $(RM_F)',  @files);
1582     my $rmf_cmd = join "\n\t", map { "$_" }
1583                     $self->split_command('- $(RM_RF)', @dirs);
1584
1585     my $m = sprintf <<'MAKE', $rm_cmd, $rmf_cmd;
1586 # Delete temporary files (via clean) and also delete dist files
1587 realclean purge ::  clean realclean_subdirs
1588         %s
1589         %s
1590 MAKE
1591
1592     $m .= "\t$attribs{POSTOP}\n" if $attribs{POSTOP};
1593
1594     return $m;
1595 }
1596
1597
1598 =head3 realclean_subdirs_target
1599
1600   my $make_frag = $MM->realclean_subdirs_target;
1601
1602 Returns the realclean_subdirs target.  This is used by the realclean
1603 target to call realclean on any subdirectories which contain Makefiles.
1604
1605 =cut
1606
1607 sub realclean_subdirs_target {
1608     my $self = shift;
1609
1610     return <<'NOOP_FRAG' unless @{$self->{DIR}};
1611 realclean_subdirs :
1612         $(NOECHO) $(NOOP)
1613 NOOP_FRAG
1614
1615     my $rclean = "realclean_subdirs :\n";
1616
1617     foreach my $dir (@{$self->{DIR}}) {
1618         foreach my $makefile ('$(MAKEFILE_OLD)', '$(FIRST_MAKEFILE)' ) {
1619             my $subrclean .= $self->oneliner(sprintf <<'CODE', $dir, ($makefile) x 2);
1620 chdir '%s';  system '$(MAKE) $(USEMAKEFILE) %s realclean' if -f '%s';
1621 CODE
1622
1623             $rclean .= sprintf <<'RCLEAN', $subrclean;
1624         - %s
1625 RCLEAN
1626
1627         }
1628     }
1629
1630     return $rclean;
1631 }
1632
1633
1634 =head3 signature_target
1635
1636     my $target = $mm->signature_target;
1637
1638 Generate the signature target.
1639
1640 Writes the file SIGNATURE with "cpansign -s".
1641
1642 =cut
1643
1644 sub signature_target {
1645     my $self = shift;
1646
1647     return <<'MAKE_FRAG';
1648 signature :
1649         cpansign -s
1650 MAKE_FRAG
1651
1652 }
1653
1654
1655 =head3 distsignature_target
1656
1657     my $make_frag = $mm->distsignature_target;
1658
1659 Generates the distsignature target to add SIGNATURE to the MANIFEST in the
1660 distdir.
1661
1662 =cut
1663
1664 sub distsignature_target {
1665     my $self = shift;
1666
1667     my $add_sign = $self->oneliner(<<'CODE', ['-MExtUtils::Manifest=maniadd']);
1668 eval { maniadd({q{SIGNATURE} => q{Public-key signature (added by MakeMaker)}}) }
1669     or print "Could not add SIGNATURE to MANIFEST: $${'@'}\n"
1670 CODE
1671
1672     my $sign_dist        = $self->cd('$(DISTVNAME)' => 'cpansign -s');
1673
1674     # cpansign -s complains if SIGNATURE is in the MANIFEST yet does not
1675     # exist
1676     my $touch_sig        = $self->cd('$(DISTVNAME)' => '$(TOUCH) SIGNATURE');
1677     my $add_sign_to_dist = $self->cd('$(DISTVNAME)' => $add_sign );
1678
1679     return sprintf <<'MAKE', $add_sign_to_dist, $touch_sig, $sign_dist
1680 distsignature : distmeta
1681         $(NOECHO) %s
1682         $(NOECHO) %s
1683         %s
1684
1685 MAKE
1686
1687 }
1688
1689
1690 =head3 special_targets
1691
1692   my $make_frag = $mm->special_targets
1693
1694 Returns a make fragment containing any targets which have special
1695 meaning to make.  For example, .SUFFIXES and .PHONY.
1696
1697 =cut
1698
1699 sub special_targets {
1700     my $make_frag = <<'MAKE_FRAG';
1701 .SUFFIXES : .xs .c .C .cpp .i .s .cxx .cc $(OBJ_EXT)
1702
1703 .PHONY: all config static dynamic test linkext manifest blibdirs clean realclean disttest distdir
1704
1705 MAKE_FRAG
1706
1707     $make_frag .= <<'MAKE_FRAG' if $ENV{CLEARCASE_ROOT};
1708 .NO_CONFIG_REC: Makefile
1709
1710 MAKE_FRAG
1711
1712     return $make_frag;
1713 }
1714
1715
1716
1717
1718 =head2 Init methods
1719
1720 Methods which help initialize the MakeMaker object and macros.
1721
1722
1723 =head3 init_ABSTRACT
1724
1725     $mm->init_ABSTRACT
1726
1727 =cut
1728
1729 sub init_ABSTRACT {
1730     my $self = shift;
1731
1732     if( $self->{ABSTRACT_FROM} and $self->{ABSTRACT} ) {
1733         warn "Both ABSTRACT_FROM and ABSTRACT are set.  ".
1734              "Ignoring ABSTRACT_FROM.\n";
1735         return;
1736     }
1737
1738     if ($self->{ABSTRACT_FROM}){
1739         $self->{ABSTRACT} = $self->parse_abstract($self->{ABSTRACT_FROM}) or
1740             carp "WARNING: Setting ABSTRACT via file ".
1741                  "'$self->{ABSTRACT_FROM}' failed\n";
1742     }
1743
1744     if ($self->{ABSTRACT} && $self->{ABSTRACT} =~ m![[:cntrl:]]+!) {
1745             warn "WARNING: ABSTRACT contains control character(s),".
1746                  " they will be removed\n";
1747             $self->{ABSTRACT} =~ s![[:cntrl:]]+!!g;
1748             return;
1749     }
1750 }
1751
1752 =head3 init_INST
1753
1754     $mm->init_INST;
1755
1756 Called by init_main.  Sets up all INST_* variables except those related
1757 to XS code.  Those are handled in init_xs.
1758
1759 =cut
1760
1761 sub init_INST {
1762     my($self) = shift;
1763
1764     $self->{INST_ARCHLIB} ||= $self->catdir($Curdir,"blib","arch");
1765     $self->{INST_BIN}     ||= $self->catdir($Curdir,'blib','bin');
1766
1767     # INST_LIB typically pre-set if building an extension after
1768     # perl has been built and installed. Setting INST_LIB allows
1769     # you to build directly into, say $Config{privlibexp}.
1770     unless ($self->{INST_LIB}){
1771         if ($self->{PERL_CORE}) {
1772             $self->{INST_LIB} = $self->{INST_ARCHLIB} = $self->{PERL_LIB};
1773         } else {
1774             $self->{INST_LIB} = $self->catdir($Curdir,"blib","lib");
1775         }
1776     }
1777
1778     my @parentdir = split(/::/, $self->{PARENT_NAME});
1779     $self->{INST_LIBDIR}      = $self->catdir('$(INST_LIB)',     @parentdir);
1780     $self->{INST_ARCHLIBDIR}  = $self->catdir('$(INST_ARCHLIB)', @parentdir);
1781     $self->{INST_AUTODIR}     = $self->catdir('$(INST_LIB)', 'auto',
1782                                               '$(FULLEXT)');
1783     $self->{INST_ARCHAUTODIR} = $self->catdir('$(INST_ARCHLIB)', 'auto',
1784                                               '$(FULLEXT)');
1785
1786     $self->{INST_SCRIPT}  ||= $self->catdir($Curdir,'blib','script');
1787
1788     $self->{INST_MAN1DIR} ||= $self->catdir($Curdir,'blib','man1');
1789     $self->{INST_MAN3DIR} ||= $self->catdir($Curdir,'blib','man3');
1790
1791     return 1;
1792 }
1793
1794
1795 =head3 init_INSTALL
1796
1797     $mm->init_INSTALL;
1798
1799 Called by init_main.  Sets up all INSTALL_* variables (except
1800 INSTALLDIRS) and *PREFIX.
1801
1802 =cut
1803
1804 sub init_INSTALL {
1805     my($self) = shift;
1806
1807     if( $self->{ARGS}{INSTALL_BASE} and $self->{ARGS}{PREFIX} ) {
1808         die "Only one of PREFIX or INSTALL_BASE can be given.  Not both.\n";
1809     }
1810
1811     if( $self->{ARGS}{INSTALL_BASE} ) {
1812         $self->init_INSTALL_from_INSTALL_BASE;
1813     }
1814     else {
1815         $self->init_INSTALL_from_PREFIX;
1816     }
1817 }
1818
1819
1820 =head3 init_INSTALL_from_PREFIX
1821
1822   $mm->init_INSTALL_from_PREFIX;
1823
1824 =cut
1825
1826 sub init_INSTALL_from_PREFIX {
1827     my $self = shift;
1828
1829     $self->init_lib2arch;
1830
1831     # There are often no Config.pm defaults for these new man variables so
1832     # we fall back to the old behavior which is to use installman*dir
1833     foreach my $num (1, 3) {
1834         my $k = 'installsiteman'.$num.'dir';
1835
1836         $self->{uc $k} ||= uc "\$(installman${num}dir)"
1837           unless $Config{$k};
1838     }
1839
1840     foreach my $num (1, 3) {
1841         my $k = 'installvendorman'.$num.'dir';
1842
1843         unless( $Config{$k} ) {
1844             $self->{uc $k}  ||= $Config{usevendorprefix}
1845                               ? uc "\$(installman${num}dir)"
1846                               : '';
1847         }
1848     }
1849
1850     $self->{INSTALLSITEBIN} ||= '$(INSTALLBIN)'
1851       unless $Config{installsitebin};
1852     $self->{INSTALLSITESCRIPT} ||= '$(INSTALLSCRIPT)'
1853       unless $Config{installsitescript};
1854
1855     unless( $Config{installvendorbin} ) {
1856         $self->{INSTALLVENDORBIN} ||= $Config{usevendorprefix}
1857                                     ? $Config{installbin}
1858                                     : '';
1859     }
1860     unless( $Config{installvendorscript} ) {
1861         $self->{INSTALLVENDORSCRIPT} ||= $Config{usevendorprefix}
1862                                        ? $Config{installscript}
1863                                        : '';
1864     }
1865
1866
1867     my $iprefix = $Config{installprefixexp} || $Config{installprefix} ||
1868                   $Config{prefixexp}        || $Config{prefix} || '';
1869     my $vprefix = $Config{usevendorprefix}  ? $Config{vendorprefixexp} : '';
1870     my $sprefix = $Config{siteprefixexp}    || '';
1871
1872     # 5.005_03 doesn't have a siteprefix.
1873     $sprefix = $iprefix unless $sprefix;
1874
1875
1876     $self->{PREFIX}       ||= '';
1877
1878     if( $self->{PREFIX} ) {
1879         @{$self}{qw(PERLPREFIX SITEPREFIX VENDORPREFIX)} =
1880           ('$(PREFIX)') x 3;
1881     }
1882     else {
1883         $self->{PERLPREFIX}   ||= $iprefix;
1884         $self->{SITEPREFIX}   ||= $sprefix;
1885         $self->{VENDORPREFIX} ||= $vprefix;
1886
1887         # Lots of MM extension authors like to use $(PREFIX) so we
1888         # put something sensible in there no matter what.
1889         $self->{PREFIX} = '$('.uc $self->{INSTALLDIRS}.'PREFIX)';
1890     }
1891
1892     my $arch    = $Config{archname};
1893     my $version = $Config{version};
1894
1895     # default style
1896     my $libstyle = $Config{installstyle} || 'lib/perl5';
1897     my $manstyle = '';
1898
1899     if( $self->{LIBSTYLE} ) {
1900         $libstyle = $self->{LIBSTYLE};
1901         $manstyle = $self->{LIBSTYLE} eq 'lib/perl5' ? 'lib/perl5' : '';
1902     }
1903
1904     # Some systems, like VOS, set installman*dir to '' if they can't
1905     # read man pages.
1906     for my $num (1, 3) {
1907         $self->{'INSTALLMAN'.$num.'DIR'} ||= 'none'
1908           unless $Config{'installman'.$num.'dir'};
1909     }
1910
1911     my %bin_layouts =
1912     (
1913         bin         => { s => $iprefix,
1914                          t => 'perl',
1915                          d => 'bin' },
1916         vendorbin   => { s => $vprefix,
1917                          t => 'vendor',
1918                          d => 'bin' },
1919         sitebin     => { s => $sprefix,
1920                          t => 'site',
1921                          d => 'bin' },
1922         script      => { s => $iprefix,
1923                          t => 'perl',
1924                          d => 'bin' },
1925         vendorscript=> { s => $vprefix,
1926                          t => 'vendor',
1927                          d => 'bin' },
1928         sitescript  => { s => $sprefix,
1929                          t => 'site',
1930                          d => 'bin' },
1931     );
1932
1933     my %man_layouts =
1934     (
1935         man1dir         => { s => $iprefix,
1936                              t => 'perl',
1937                              d => 'man/man1',
1938                              style => $manstyle, },
1939         siteman1dir     => { s => $sprefix,
1940                              t => 'site',
1941                              d => 'man/man1',
1942                              style => $manstyle, },
1943         vendorman1dir   => { s => $vprefix,
1944                              t => 'vendor',
1945                              d => 'man/man1',
1946                              style => $manstyle, },
1947
1948         man3dir         => { s => $iprefix,
1949                              t => 'perl',
1950                              d => 'man/man3',
1951                              style => $manstyle, },
1952         siteman3dir     => { s => $sprefix,
1953                              t => 'site',
1954                              d => 'man/man3',
1955                              style => $manstyle, },
1956         vendorman3dir   => { s => $vprefix,
1957                              t => 'vendor',
1958                              d => 'man/man3',
1959                              style => $manstyle, },
1960     );
1961
1962     my %lib_layouts =
1963     (
1964         privlib     => { s => $iprefix,
1965                          t => 'perl',
1966                          d => '',
1967                          style => $libstyle, },
1968         vendorlib   => { s => $vprefix,
1969                          t => 'vendor',
1970                          d => '',
1971                          style => $libstyle, },
1972         sitelib     => { s => $sprefix,
1973                          t => 'site',
1974                          d => 'site_perl',
1975                          style => $libstyle, },
1976
1977         archlib     => { s => $iprefix,
1978                          t => 'perl',
1979                          d => "$version/$arch",
1980                          style => $libstyle },
1981         vendorarch  => { s => $vprefix,
1982                          t => 'vendor',
1983                          d => "$version/$arch",
1984                          style => $libstyle },
1985         sitearch    => { s => $sprefix,
1986                          t => 'site',
1987                          d => "site_perl/$version/$arch",
1988                          style => $libstyle },
1989     );
1990
1991
1992     # Special case for LIB.
1993     if( $self->{LIB} ) {
1994         foreach my $var (keys %lib_layouts) {
1995             my $Installvar = uc "install$var";
1996
1997             if( $var =~ /arch/ ) {
1998                 $self->{$Installvar} ||=
1999                   $self->catdir($self->{LIB}, $Config{archname});
2000             }
2001             else {
2002                 $self->{$Installvar} ||= $self->{LIB};
2003             }
2004         }
2005     }
2006
2007     my %type2prefix = ( perl    => 'PERLPREFIX',
2008                         site    => 'SITEPREFIX',
2009                         vendor  => 'VENDORPREFIX'
2010                       );
2011
2012     my %layouts = (%bin_layouts, %man_layouts, %lib_layouts);
2013     while( my($var, $layout) = each(%layouts) ) {
2014         my($s, $t, $d, $style) = @{$layout}{qw(s t d style)};
2015         my $r = '$('.$type2prefix{$t}.')';
2016
2017         warn "Prefixing $var\n" if $Verbose >= 2;
2018
2019         my $installvar = "install$var";
2020         my $Installvar = uc $installvar;
2021         next if $self->{$Installvar};
2022
2023         $d = "$style/$d" if $style;
2024         $self->prefixify($installvar, $s, $r, $d);
2025
2026         warn "  $Installvar == $self->{$Installvar}\n"
2027           if $Verbose >= 2;
2028     }
2029
2030     # Generate these if they weren't figured out.
2031     $self->{VENDORARCHEXP} ||= $self->{INSTALLVENDORARCH};
2032     $self->{VENDORLIBEXP}  ||= $self->{INSTALLVENDORLIB};
2033
2034     return 1;
2035 }
2036
2037
2038 =head3 init_from_INSTALL_BASE
2039
2040     $mm->init_from_INSTALL_BASE
2041
2042 =cut
2043
2044 my %map = (
2045            lib      => [qw(lib perl5)],
2046            arch     => [('lib', 'perl5', $Config{archname})],
2047            bin      => [qw(bin)],
2048            man1dir  => [qw(man man1)],
2049            man3dir  => [qw(man man3)]
2050           );
2051 $map{script} = $map{bin};
2052
2053 sub init_INSTALL_from_INSTALL_BASE {
2054     my $self = shift;
2055
2056     @{$self}{qw(PREFIX VENDORPREFIX SITEPREFIX PERLPREFIX)} =
2057                                                          '$(INSTALL_BASE)';
2058
2059     my %install;
2060     foreach my $thing (keys %map) {
2061         foreach my $dir (('', 'SITE', 'VENDOR')) {
2062             my $uc_thing = uc $thing;
2063             my $key = "INSTALL".$dir.$uc_thing;
2064
2065             $install{$key} ||=
2066               $self->catdir('$(INSTALL_BASE)', @{$map{$thing}});
2067         }
2068     }
2069
2070     # Adjust for variable quirks.
2071     $install{INSTALLARCHLIB} ||= delete $install{INSTALLARCH};
2072     $install{INSTALLPRIVLIB} ||= delete $install{INSTALLLIB};
2073
2074     foreach my $key (keys %install) {
2075         $self->{$key} ||= $install{$key};
2076     }
2077
2078     return 1;
2079 }
2080
2081
2082 =head3 init_VERSION  I<Abstract>
2083
2084     $mm->init_VERSION
2085
2086 Initialize macros representing versions of MakeMaker and other tools
2087
2088 MAKEMAKER: path to the MakeMaker module.
2089
2090 MM_VERSION: ExtUtils::MakeMaker Version
2091
2092 MM_REVISION: ExtUtils::MakeMaker version control revision (for backwards
2093              compat)
2094
2095 VERSION: version of your module
2096
2097 VERSION_MACRO: which macro represents the version (usually 'VERSION')
2098
2099 VERSION_SYM: like version but safe for use as an RCS revision number
2100
2101 DEFINE_VERSION: -D line to set the module version when compiling
2102
2103 XS_VERSION: version in your .xs file.  Defaults to $(VERSION)
2104
2105 XS_VERSION_MACRO: which macro represents the XS version.
2106
2107 XS_DEFINE_VERSION: -D line to set the xs version when compiling.
2108
2109 Called by init_main.
2110
2111 =cut
2112
2113 sub init_VERSION {
2114     my($self) = shift;
2115
2116     $self->{MAKEMAKER}  = $ExtUtils::MakeMaker::Filename;
2117     $self->{MM_VERSION} = $ExtUtils::MakeMaker::VERSION;
2118     $self->{MM_REVISION}= $ExtUtils::MakeMaker::Revision;
2119     $self->{VERSION_FROM} ||= '';
2120
2121     if ($self->{VERSION_FROM}){
2122         $self->{VERSION} = $self->parse_version($self->{VERSION_FROM});
2123         if( $self->{VERSION} eq 'undef' ) {
2124             carp("WARNING: Setting VERSION via file ".
2125                  "'$self->{VERSION_FROM}' failed\n");
2126         }
2127     }
2128
2129     if (defined $self->{VERSION}) {
2130         if ( $self->{VERSION} !~ /^\s*v?[\d_\.]+\s*$/ ) {
2131           require version;
2132           my $normal = eval { version->new( $self->{VERSION} ) };
2133           $self->{VERSION} = $normal if defined $normal;
2134         }
2135         $self->{VERSION} =~ s/^\s+//;
2136         $self->{VERSION} =~ s/\s+$//;
2137     }
2138     else {
2139         $self->{VERSION} = '';
2140     }
2141
2142
2143     $self->{VERSION_MACRO}  = 'VERSION';
2144     ($self->{VERSION_SYM} = $self->{VERSION}) =~ s/\W/_/g;
2145     $self->{DEFINE_VERSION} = '-D$(VERSION_MACRO)=\"$(VERSION)\"';
2146
2147
2148     # Graham Barr and Paul Marquess had some ideas how to ensure
2149     # version compatibility between the *.pm file and the
2150     # corresponding *.xs file. The bottom line was, that we need an
2151     # XS_VERSION macro that defaults to VERSION:
2152     $self->{XS_VERSION} ||= $self->{VERSION};
2153
2154     $self->{XS_VERSION_MACRO}  = 'XS_VERSION';
2155     $self->{XS_DEFINE_VERSION} = '-D$(XS_VERSION_MACRO)=\"$(XS_VERSION)\"';
2156
2157 }
2158
2159
2160 =head3 init_tools
2161
2162     $MM->init_tools();
2163
2164 Initializes the simple macro definitions used by tools_other() and
2165 places them in the $MM object.  These use conservative cross platform
2166 versions and should be overridden with platform specific versions for
2167 performance.
2168
2169 Defines at least these macros.
2170
2171   Macro             Description
2172
2173   NOOP              Do nothing
2174   NOECHO            Tell make not to display the command itself
2175
2176   SHELL             Program used to run shell commands
2177
2178   ECHO              Print text adding a newline on the end
2179   RM_F              Remove a file
2180   RM_RF             Remove a directory
2181   TOUCH             Update a file's timestamp
2182   TEST_F            Test for a file's existence
2183   TEST_S            Test the size of a file
2184   CP                Copy a file
2185   CP_NONEMPTY       Copy a file if it is not empty
2186   MV                Move a file
2187   CHMOD             Change permissions on a file
2188   FALSE             Exit with non-zero
2189   TRUE              Exit with zero
2190
2191   UMASK_NULL        Nullify umask
2192   DEV_NULL          Suppress all command output
2193
2194 =cut
2195
2196 sub init_tools {
2197     my $self = shift;
2198
2199     $self->{ECHO}     ||= $self->oneliner('binmode STDOUT, qq{:raw}; print qq{@ARGV}', ['-l']);
2200     $self->{ECHO_N}   ||= $self->oneliner('print qq{@ARGV}');
2201
2202     $self->{TOUCH}    ||= $self->oneliner('touch', ["-MExtUtils::Command"]);
2203     $self->{CHMOD}    ||= $self->oneliner('chmod', ["-MExtUtils::Command"]);
2204     $self->{RM_F}     ||= $self->oneliner('rm_f',  ["-MExtUtils::Command"]);
2205     $self->{RM_RF}    ||= $self->oneliner('rm_rf', ["-MExtUtils::Command"]);
2206     $self->{TEST_F}   ||= $self->oneliner('test_f', ["-MExtUtils::Command"]);
2207     $self->{TEST_S}   ||= $self->oneliner('test_s', ["-MExtUtils::Command::MM"]);
2208     $self->{CP_NONEMPTY} ||= $self->oneliner('cp_nonempty', ["-MExtUtils::Command::MM"]);
2209     $self->{FALSE}    ||= $self->oneliner('exit 1');
2210     $self->{TRUE}     ||= $self->oneliner('exit 0');
2211
2212     $self->{MKPATH}   ||= $self->oneliner('mkpath', ["-MExtUtils::Command"]);
2213
2214     $self->{CP}       ||= $self->oneliner('cp', ["-MExtUtils::Command"]);
2215     $self->{MV}       ||= $self->oneliner('mv', ["-MExtUtils::Command"]);
2216
2217     $self->{MOD_INSTALL} ||=
2218       $self->oneliner(<<'CODE', ['-MExtUtils::Install']);
2219 install([ from_to => {@ARGV}, verbose => '$(VERBINST)', uninstall_shadows => '$(UNINST)', dir_mode => '$(PERM_DIR)' ]);
2220 CODE
2221     $self->{DOC_INSTALL} ||= $self->oneliner('perllocal_install', ["-MExtUtils::Command::MM"]);
2222     $self->{UNINSTALL}   ||= $self->oneliner('uninstall', ["-MExtUtils::Command::MM"]);
2223     $self->{WARN_IF_OLD_PACKLIST} ||=
2224       $self->oneliner('warn_if_old_packlist', ["-MExtUtils::Command::MM"]);
2225     $self->{FIXIN}       ||= $self->oneliner('MY->fixin(shift)', ["-MExtUtils::MY"]);
2226     $self->{EQUALIZE_TIMESTAMP} ||= $self->oneliner('eqtime', ["-MExtUtils::Command"]);
2227
2228     $self->{UNINST}     ||= 0;
2229     $self->{VERBINST}   ||= 0;
2230
2231     $self->{SHELL}              ||= $Config{sh};
2232
2233     # UMASK_NULL is not used by MakeMaker but some CPAN modules
2234     # make use of it.
2235     $self->{UMASK_NULL}         ||= "umask 0";
2236
2237     # Not the greatest default, but its something.
2238     $self->{DEV_NULL}           ||= "> /dev/null 2>&1";
2239
2240     $self->{NOOP}               ||= '$(TRUE)';
2241     $self->{NOECHO}             = '@' unless defined $self->{NOECHO};
2242
2243     $self->{FIRST_MAKEFILE}     ||= $self->{MAKEFILE} || 'Makefile';
2244     $self->{MAKEFILE}           ||= $self->{FIRST_MAKEFILE};
2245     $self->{MAKEFILE_OLD}       ||= $self->{MAKEFILE}.'.old';
2246     $self->{MAKE_APERL_FILE}    ||= $self->{MAKEFILE}.'.aperl';
2247
2248     # Not everybody uses -f to indicate "use this Makefile instead"
2249     $self->{USEMAKEFILE}        ||= '-f';
2250
2251     # Some makes require a wrapper around macros passed in on the command
2252     # line.
2253     $self->{MACROSTART}         ||= '';
2254     $self->{MACROEND}           ||= '';
2255
2256     return;
2257 }
2258
2259
2260 =head3 init_others
2261
2262     $MM->init_others();
2263
2264 Initializes the macro definitions having to do with compiling and
2265 linking used by tools_other() and places them in the $MM object.
2266
2267 If there is no description, its the same as the parameter to
2268 WriteMakefile() documented in ExtUtils::MakeMaker.
2269
2270 =cut
2271
2272 sub init_others {
2273     my $self = shift;
2274
2275     $self->{LD_RUN_PATH} = "";
2276
2277     $self->{LIBS} = $self->_fix_libs($self->{LIBS});
2278
2279     # Compute EXTRALIBS, BSLOADLIBS and LDLOADLIBS from $self->{LIBS}
2280     foreach my $libs ( @{$self->{LIBS}} ){
2281         $libs =~ s/^\s*(.*\S)\s*$/$1/; # remove leading and trailing whitespace
2282         my(@libs) = $self->extliblist($libs);
2283         if ($libs[0] or $libs[1] or $libs[2]){
2284             # LD_RUN_PATH now computed by ExtUtils::Liblist
2285             ($self->{EXTRALIBS},  $self->{BSLOADLIBS},
2286              $self->{LDLOADLIBS}, $self->{LD_RUN_PATH}) = @libs;
2287             last;
2288         }
2289     }
2290
2291     if ( $self->{OBJECT} ) {
2292         $self->{OBJECT} = join(" ", @{$self->{OBJECT}}) if ref $self->{OBJECT};
2293         $self->{OBJECT} =~ s!\.o(bj)?\b!\$(OBJ_EXT)!g;
2294     } elsif ( $self->{MAGICXS} && @{$self->{O_FILES}||[]} ) {
2295         $self->{OBJECT} = join(" ", @{$self->{O_FILES}});
2296         $self->{OBJECT} =~ s!\.o(bj)?\b!\$(OBJ_EXT)!g;
2297     } else {
2298         # init_dirscan should have found out, if we have C files
2299         $self->{OBJECT} = "";
2300         $self->{OBJECT} = '$(BASEEXT)$(OBJ_EXT)' if @{$self->{C}||[]};
2301     }
2302     $self->{OBJECT} =~ s/\n+/ \\\n\t/g;
2303
2304     $self->{BOOTDEP}  = (-f "$self->{BASEEXT}_BS") ? "$self->{BASEEXT}_BS" : "";
2305     $self->{PERLMAINCC} ||= '$(CC)';
2306     $self->{LDFROM} = '$(OBJECT)' unless $self->{LDFROM};
2307
2308     # Sanity check: don't define LINKTYPE = dynamic if we're skipping
2309     # the 'dynamic' section of MM.  We don't have this problem with
2310     # 'static', since we either must use it (%Config says we can't
2311     # use dynamic loading) or the caller asked for it explicitly.
2312     if (!$self->{LINKTYPE}) {
2313        $self->{LINKTYPE} = $self->{SKIPHASH}{'dynamic'}
2314                         ? 'static'
2315                         : ($Config{usedl} ? 'dynamic' : 'static');
2316     }
2317
2318     return;
2319 }
2320
2321
2322 # Lets look at $self->{LIBS} carefully: It may be an anon array, a string or
2323 # undefined. In any case we turn it into an anon array
2324 sub _fix_libs {
2325     my($self, $libs) = @_;
2326
2327     return !defined $libs       ? ['']          :
2328            !ref $libs           ? [$libs]       :
2329            !defined $libs->[0]  ? ['']          :
2330                                   $libs         ;
2331 }
2332
2333
2334 =head3 tools_other
2335
2336     my $make_frag = $MM->tools_other;
2337
2338 Returns a make fragment containing definitions for the macros init_others()
2339 initializes.
2340
2341 =cut
2342
2343 sub tools_other {
2344     my($self) = shift;
2345     my @m;
2346
2347     # We set PM_FILTER as late as possible so it can see all the earlier
2348     # on macro-order sensitive makes such as nmake.
2349     for my $tool (qw{ SHELL CHMOD CP MV NOOP NOECHO RM_F RM_RF TEST_F TOUCH
2350                       UMASK_NULL DEV_NULL MKPATH EQUALIZE_TIMESTAMP
2351                       FALSE TRUE
2352                       ECHO ECHO_N
2353                       UNINST VERBINST
2354                       MOD_INSTALL DOC_INSTALL UNINSTALL
2355                       WARN_IF_OLD_PACKLIST
2356                       MACROSTART MACROEND
2357                       USEMAKEFILE
2358                       PM_FILTER
2359                       FIXIN
2360                       CP_NONEMPTY
2361                     } )
2362     {
2363         next unless defined $self->{$tool};
2364         push @m, "$tool = $self->{$tool}\n";
2365     }
2366
2367     return join "", @m;
2368 }
2369
2370
2371 =head3 init_DIRFILESEP  I<Abstract>
2372
2373   $MM->init_DIRFILESEP;
2374   my $dirfilesep = $MM->{DIRFILESEP};
2375
2376 Initializes the DIRFILESEP macro which is the separator between the
2377 directory and filename in a filepath.  ie. / on Unix, \ on Win32 and
2378 nothing on VMS.
2379
2380 For example:
2381
2382     # instead of $(INST_ARCHAUTODIR)/extralibs.ld
2383     $(INST_ARCHAUTODIR)$(DIRFILESEP)extralibs.ld
2384
2385 Something of a hack but it prevents a lot of code duplication between
2386 MM_* variants.
2387
2388 Do not use this as a separator between directories.  Some operating
2389 systems use different separators between subdirectories as between
2390 directories and filenames (for example:  VOLUME:[dir1.dir2]file on VMS).
2391
2392 =head3 init_linker  I<Abstract>
2393
2394     $mm->init_linker;
2395
2396 Initialize macros which have to do with linking.
2397
2398 PERL_ARCHIVE: path to libperl.a equivalent to be linked to dynamic
2399 extensions.
2400
2401 PERL_ARCHIVE_AFTER: path to a library which should be put on the
2402 linker command line I<after> the external libraries to be linked to
2403 dynamic extensions.  This may be needed if the linker is one-pass, and
2404 Perl includes some overrides for C RTL functions, such as malloc().
2405
2406 EXPORT_LIST: name of a file that is passed to linker to define symbols
2407 to be exported.
2408
2409 Some OSes do not need these in which case leave it blank.
2410
2411
2412 =head3 init_platform
2413
2414     $mm->init_platform
2415
2416 Initialize any macros which are for platform specific use only.
2417
2418 A typical one is the version number of your OS specific module.
2419 (ie. MM_Unix_VERSION or MM_VMS_VERSION).
2420
2421 =cut
2422
2423 sub init_platform {
2424     return '';
2425 }
2426
2427
2428 =head3 init_MAKE
2429
2430     $mm->init_MAKE
2431
2432 Initialize MAKE from either a MAKE environment variable or $Config{make}.
2433
2434 =cut
2435
2436 sub init_MAKE {
2437     my $self = shift;
2438
2439     $self->{MAKE} ||= $ENV{MAKE} || $Config{make};
2440 }
2441
2442
2443 =head2 Tools
2444
2445 A grab bag of methods to generate specific macros and commands.
2446
2447
2448
2449 =head3 manifypods
2450
2451 Defines targets and routines to translate the pods into manpages and
2452 put them into the INST_* directories.
2453
2454 =cut
2455
2456 sub manifypods {
2457     my $self          = shift;
2458
2459     my $POD2MAN_macro = $self->POD2MAN_macro();
2460     my $manifypods_target = $self->manifypods_target();
2461
2462     return <<END_OF_TARGET;
2463
2464 $POD2MAN_macro
2465
2466 $manifypods_target
2467
2468 END_OF_TARGET
2469
2470 }
2471
2472
2473 =head3 POD2MAN_macro
2474
2475   my $pod2man_macro = $self->POD2MAN_macro
2476
2477 Returns a definition for the POD2MAN macro.  This is a program
2478 which emulates the pod2man utility.  You can add more switches to the
2479 command by simply appending them on the macro.
2480
2481 Typical usage:
2482
2483     $(POD2MAN) --section=3 --perm_rw=$(PERM_RW) podfile1 man_page1 ...
2484
2485 =cut
2486
2487 sub POD2MAN_macro {
2488     my $self = shift;
2489
2490 # Need the trailing '--' so perl stops gobbling arguments and - happens
2491 # to be an alternative end of line separator on VMS so we quote it
2492     return <<'END_OF_DEF';
2493 POD2MAN_EXE = $(PERLRUN) "-MExtUtils::Command::MM" -e pod2man "--"
2494 POD2MAN = $(POD2MAN_EXE)
2495 END_OF_DEF
2496 }
2497
2498
2499 =head3 test_via_harness
2500
2501   my $command = $mm->test_via_harness($perl, $tests);
2502
2503 Returns a $command line which runs the given set of $tests with
2504 Test::Harness and the given $perl.
2505
2506 Used on the t/*.t files.
2507
2508 =cut
2509
2510 sub test_via_harness {
2511     my($self, $perl, $tests) = @_;
2512
2513     return qq{\t$perl "-MExtUtils::Command::MM" "-MTest::Harness" }.
2514            qq{"-e" "undef *Test::Harness::Switches; test_harness(\$(TEST_VERBOSE), '\$(INST_LIB)', '\$(INST_ARCHLIB)')" $tests\n};
2515 }
2516
2517 =head3 test_via_script
2518
2519   my $command = $mm->test_via_script($perl, $script);
2520
2521 Returns a $command line which just runs a single test without
2522 Test::Harness.  No checks are done on the results, they're just
2523 printed.
2524
2525 Used for test.pl, since they don't always follow Test::Harness
2526 formatting.
2527
2528 =cut
2529
2530 sub test_via_script {
2531     my($self, $perl, $script) = @_;
2532     return qq{\t$perl "-I\$(INST_LIB)" "-I\$(INST_ARCHLIB)" $script\n};
2533 }
2534
2535
2536 =head3 tool_autosplit
2537
2538 Defines a simple perl call that runs autosplit. May be deprecated by
2539 pm_to_blib soon.
2540
2541 =cut
2542
2543 sub tool_autosplit {
2544     my($self, %attribs) = @_;
2545
2546     my $maxlen = $attribs{MAXLEN} ? '$$AutoSplit::Maxlen=$attribs{MAXLEN};'
2547                                   : '';
2548
2549     my $asplit = $self->oneliner(sprintf <<'PERL_CODE', $maxlen);
2550 use AutoSplit; %s autosplit($$ARGV[0], $$ARGV[1], 0, 1, 1)
2551 PERL_CODE
2552
2553     return sprintf <<'MAKE_FRAG', $asplit;
2554 # Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto
2555 AUTOSPLITFILE = %s
2556
2557 MAKE_FRAG
2558
2559 }
2560
2561
2562 =head3 arch_check
2563
2564     my $arch_ok = $mm->arch_check(
2565         $INC{"Config.pm"},
2566         File::Spec->catfile($Config{archlibexp}, "Config.pm")
2567     );
2568
2569 A sanity check that what Perl thinks the architecture is and what
2570 Config thinks the architecture is are the same.  If they're not it
2571 will return false and show a diagnostic message.
2572
2573 When building Perl it will always return true, as nothing is installed
2574 yet.
2575
2576 The interface is a bit odd because this is the result of a
2577 quick refactoring.  Don't rely on it.
2578
2579 =cut
2580
2581 sub arch_check {
2582     my $self = shift;
2583     my($pconfig, $cconfig) = @_;
2584
2585     return 1 if $self->{PERL_SRC};
2586
2587     my($pvol, $pthinks) = $self->splitpath($pconfig);
2588     my($cvol, $cthinks) = $self->splitpath($cconfig);
2589
2590     $pthinks = $self->canonpath($pthinks);
2591     $cthinks = $self->canonpath($cthinks);
2592
2593     my $ret = 1;
2594     if ($pthinks ne $cthinks) {
2595         print "Have $pthinks\n";
2596         print "Want $cthinks\n";
2597
2598         $ret = 0;
2599
2600         my $arch = (grep length, $self->splitdir($pthinks))[-1];
2601
2602         print <<END unless $self->{UNINSTALLED_PERL};
2603 Your perl and your Config.pm seem to have different ideas about the
2604 architecture they are running on.
2605 Perl thinks: [$arch]
2606 Config says: [$Config{archname}]
2607 This may or may not cause problems. Please check your installation of perl
2608 if you have problems building this extension.
2609 END
2610     }
2611
2612     return $ret;
2613 }
2614
2615
2616
2617 =head2 File::Spec wrappers
2618
2619 ExtUtils::MM_Any is a subclass of File::Spec.  The methods noted here
2620 override File::Spec.
2621
2622
2623
2624 =head3 catfile
2625
2626 File::Spec <= 0.83 has a bug where the file part of catfile is not
2627 canonicalized.  This override fixes that bug.
2628
2629 =cut
2630
2631 sub catfile {
2632     my $self = shift;
2633     return $self->canonpath($self->SUPER::catfile(@_));
2634 }
2635
2636
2637
2638 =head2 Misc
2639
2640 Methods I can't really figure out where they should go yet.
2641
2642
2643 =head3 find_tests
2644
2645   my $test = $mm->find_tests;
2646
2647 Returns a string suitable for feeding to the shell to return all
2648 tests in t/*.t.
2649
2650 =cut
2651
2652 sub find_tests {
2653     my($self) = shift;
2654     return -d 't' ? 't/*.t' : '';
2655 }
2656
2657 =head3 find_tests_recursive
2658
2659   my $tests = $mm->find_tests_recursive;
2660
2661 Returns a string suitable for feeding to the shell to return all
2662 tests in t/ but recursively.
2663
2664 =cut
2665
2666 sub find_tests_recursive {
2667     my($self) = shift;
2668     return '' unless -d 't';
2669
2670     require File::Find;
2671
2672     my %testfiles;
2673
2674     my $wanted = sub {
2675         return unless m!\.t$!;
2676         my ($volume,$directories,$file) =
2677             File::Spec->splitpath( $File::Find::name  );
2678         my @dirs = File::Spec->splitdir( $directories );
2679         for ( @dirs ) {
2680           next if $_ eq 't';
2681           unless ( $_ ) {
2682             $_ = '*.t';
2683             next;
2684           }
2685           $_ = '*';
2686         }
2687         my $testfile = join '/', @dirs;
2688         $testfiles{ $testfile } = 1;
2689     };
2690
2691     File::Find::find( $wanted, 't' );
2692
2693     return join ' ', sort keys %testfiles;
2694 }
2695
2696 =head3 extra_clean_files
2697
2698     my @files_to_clean = $MM->extra_clean_files;
2699
2700 Returns a list of OS specific files to be removed in the clean target in
2701 addition to the usual set.
2702
2703 =cut
2704
2705 # An empty method here tickled a perl 5.8.1 bug and would return its object.
2706 sub extra_clean_files {
2707     return;
2708 }
2709
2710
2711 =head3 installvars
2712
2713     my @installvars = $mm->installvars;
2714
2715 A list of all the INSTALL* variables without the INSTALL prefix.  Useful
2716 for iteration or building related variable sets.
2717
2718 =cut
2719
2720 sub installvars {
2721     return qw(PRIVLIB SITELIB  VENDORLIB
2722               ARCHLIB SITEARCH VENDORARCH
2723               BIN     SITEBIN  VENDORBIN
2724               SCRIPT  SITESCRIPT  VENDORSCRIPT
2725               MAN1DIR SITEMAN1DIR VENDORMAN1DIR
2726               MAN3DIR SITEMAN3DIR VENDORMAN3DIR
2727              );
2728 }
2729
2730
2731 =head3 libscan
2732
2733   my $wanted = $self->libscan($path);
2734
2735 Takes a path to a file or dir and returns an empty string if we don't
2736 want to include this file in the library.  Otherwise it returns the
2737 the $path unchanged.
2738
2739 Mainly used to exclude version control administrative directories from
2740 installation.
2741
2742 =cut
2743
2744 sub libscan {
2745     my($self,$path) = @_;
2746     my($dirs,$file) = ($self->splitpath($path))[1,2];
2747     return '' if grep /^(?:RCS|CVS|SCCS|\.svn|_darcs)$/,
2748                      $self->splitdir($dirs), $file;
2749
2750     return $path;
2751 }
2752
2753
2754 =head3 platform_constants
2755
2756     my $make_frag = $mm->platform_constants
2757
2758 Returns a make fragment defining all the macros initialized in
2759 init_platform() rather than put them in constants().
2760
2761 =cut
2762
2763 sub platform_constants {
2764     return '';
2765 }
2766
2767 =begin private
2768
2769 =head3 _PREREQ_PRINT
2770
2771     $self->_PREREQ_PRINT;
2772
2773 Implements PREREQ_PRINT.
2774
2775 Refactored out of MakeMaker->new().
2776
2777 =end private
2778
2779 =cut
2780
2781 sub _PREREQ_PRINT {
2782     my $self = shift;
2783
2784     require Data::Dumper;
2785     my @what = ('PREREQ_PM');
2786     push @what, 'MIN_PERL_VERSION' if $self->{MIN_PERL_VERSION};
2787     push @what, 'BUILD_REQUIRES'   if $self->{BUILD_REQUIRES};
2788     print Data::Dumper->Dump([@{$self}{@what}], \@what);
2789     exit 0;
2790 }
2791
2792
2793 =begin private
2794
2795 =head3 _PRINT_PREREQ
2796
2797   $mm->_PRINT_PREREQ;
2798
2799 Implements PRINT_PREREQ, a slightly different version of PREREQ_PRINT
2800 added by Redhat to, I think, support generating RPMs from Perl modules.
2801
2802 Should not include BUILD_REQUIRES as RPMs do not incluide them.
2803
2804 Refactored out of MakeMaker->new().
2805
2806 =end private
2807
2808 =cut
2809
2810 sub _PRINT_PREREQ {
2811     my $self = shift;
2812
2813     my $prereqs= $self->{PREREQ_PM};
2814     my @prereq = map { [$_, $prereqs->{$_}] } keys %$prereqs;
2815
2816     if ( $self->{MIN_PERL_VERSION} ) {
2817         push @prereq, ['perl' => $self->{MIN_PERL_VERSION}];
2818     }
2819
2820     print join(" ", map { "perl($_->[0])>=$_->[1] " }
2821                  sort { $a->[0] cmp $b->[0] } @prereq), "\n";
2822     exit 0;
2823 }
2824
2825
2826 =begin private
2827
2828 =head3 _all_prereqs
2829
2830   my $prereqs = $self->_all_prereqs;
2831
2832 Returns a hash ref of both PREREQ_PM and BUILD_REQUIRES.
2833
2834 =end private
2835
2836 =cut
2837
2838 sub _all_prereqs {
2839     my $self = shift;
2840
2841     return { %{$self->{PREREQ_PM}}, %{$self->{BUILD_REQUIRES}} };
2842 }
2843
2844 =begin private
2845
2846 =head3 _perl_header_files
2847
2848   my $perl_header_files= $self->_perl_header_files;
2849
2850 returns a sorted list of header files as found in PERL_SRC or $archlibexp/CORE.
2851
2852 Used by perldepend() in MM_Unix and MM_VMS via _perl_header_files_fragment()
2853
2854 =end private
2855
2856 =cut
2857
2858 sub _perl_header_files {
2859     my $self = shift;
2860
2861     my $header_dir = $self->{PERL_SRC} || $ENV{PERL_SRC} || $self->catdir($Config{archlibexp}, 'CORE');
2862     opendir my $dh, $header_dir
2863         or die "Failed to opendir '$header_dir' to find header files: $!";
2864
2865     # we need to use a temporary here as the sort in scalar context would have undefined results.
2866     my @perl_headers= sort grep { /\.h\z/ } readdir($dh);
2867
2868     closedir $dh;
2869
2870     return @perl_headers;
2871 }
2872
2873 =begin private
2874
2875 =head3 _perl_header_files_fragment ($o, $separator)
2876
2877   my $perl_header_files_fragment= $self->_perl_header_files_fragment("/");
2878
2879 return a Makefile fragment which holds the list of perl header files which
2880 XS code depends on $(PERL_INC), and sets up the dependency for the $(OBJECT) file.
2881
2882 The $separator argument defaults to "". MM_VMS will set it to "" and MM_UNIX to "/"
2883 in perldepend(). This reason child subclasses need to control this is that in
2884 VMS the $(PERL_INC) directory will already have delimiters in it, but in
2885 UNIX $(PERL_INC) will need a slash between it an the filename. Hypothetically
2886 win32 could use "\\" (but it doesn't need to).
2887
2888 =end private
2889
2890 =cut
2891
2892 sub _perl_header_files_fragment {
2893     my ($self, $separator)= @_;
2894     $separator ||= "";
2895     return join("\\\n",
2896                 "PERL_HDRS = ",
2897                 map {
2898                     sprintf( "        \$(PERL_INCDEP)%s%s            ", $separator, $_ )
2899                 } $self->_perl_header_files()
2900            ) . "\n\n"
2901            . "\$(OBJECT) : \$(PERL_HDRS)\n";
2902 }
2903
2904
2905 =head1 AUTHOR
2906
2907 Michael G Schwern <schwern@pobox.com> and the denizens of
2908 makemaker@perl.org with code from ExtUtils::MM_Unix and
2909 ExtUtils::MM_Win32.
2910
2911
2912 =cut
2913
2914 1;