Move Archive-Extract from ext/ to cpan/
[p5sagit/p5-mst-13.2.git] / make_ext.pl
1 #!./miniperl
2 use strict;
3 use warnings;
4 use Config;
5 BEGIN {
6     unshift @INC, $^O eq 'MSWin32' ? '../ext/Cwd' : 'ext/Cwd';
7 }
8 use Cwd;
9
10 # To clarify, this isn't the entire suite of modules considered "toolchain"
11 # It's not even all modules needed to build ext/
12 # It's just the source paths of the (minimum complete set of) modules in ext/
13 # needed to build the nonxs modules
14 # After which, all nonxs modules are in lib, which was always sufficient to
15 # allow miniperl to build everything else.
16
17 my @toolchain = qw(ext/constant/lib ext/Cwd ext/Cwd/lib ext/ExtUtils-Command/lib
18                    ext/ExtUtils-Install/lib ext/ExtUtils-MakeMaker/lib
19                    ext/ExtUtils-Manifest/lib ext/Text-ParseWords/lib
20        ext/File-Path/lib ext/AutoLoader/lib);
21
22 my @ext_dirs = qw(ext cpan);
23 my $ext_dirs_re = '(?:' . join('|', @ext_dirs) . ')';
24
25 # This script acts as a simple interface for building extensions.
26
27 # It's actually a cut and shut of the Unix version ext/utils/makeext and the
28 # Windows version win32/build_ext.pl hence the two invocation styles.
29
30 # On Unix, it primarily used by the perl Makefile one extention at a time:
31 #
32 # d_dummy $(dynamic_ext): miniperl preplibrary FORCE
33 #       @$(RUN) ./miniperl make_ext.pl --target=dynamic $@ MAKE=$(MAKE) LIBPERL_A=$(LIBPERL)
34 #
35 # On Windows or VMS,
36 # If '--static' is specified, static extensions will be built.
37 # If '--dynamic' is specified, dynamic extensions will be built.
38 # If '--nonxs' is specified, nonxs extensions will be built.
39 # If '--dynaloader' is specificied, DynaLoader will be built.
40 # If '--all' is specified, all extensions will be built.
41 #
42 #    make_ext.pl "MAKE=make [-make_opts]" --dir=directory [--target=target] [--static|--dynamic|--all] +ext2 !ext1
43 #
44 # E.g.
45
46 #     make_ext.pl "MAKE=nmake -nologo" --dir=..\ext
47
48 #     make_ext.pl "MAKE=nmake -nologo" --dir=..\ext --target=clean
49
50 #     make_ext.pl MAKE=dmake --dir=..\ext
51
52 #     make_ext.pl MAKE=dmake --dir=..\ext --target=clean
53
54 # Will skip building extensions which are marked with an '!' char.
55 # Mostly because they still not ported to specified platform.
56
57 # If any extensions are listed with a '+' char then only those
58 # extensions will be built, but only if they arent countermanded
59 # by an '!ext' and are appropriate to the type of building being done.
60
61 # It may be deleted in a later release of perl so try to
62 # avoid using it for other purposes.
63
64 my $is_Win32 = $^O eq 'MSWin32';
65 my $is_VMS = $^O eq 'VMS';
66 my $is_Unix = !$is_Win32 && !$is_VMS;
67
68 require FindExt if $is_Win32;
69
70 my (%excl, %incl, %opts, @extspec, @pass_through);
71
72 foreach (@ARGV) {
73     if (/^!(.*)$/) {
74         $excl{$1} = 1;
75     } elsif (/^\+(.*)$/) {
76         $incl{$1} = 1;
77     } elsif (/^--([\w\-]+)$/) {
78         $opts{$1} = 1;
79     } elsif (/^--([\w\-]+)=(.*)$/) {
80         push @{$opts{$1}}, $2;
81     } elsif (/=/) {
82         push @pass_through, $_;
83     } elsif (length) {
84         push @extspec, $_;
85     }
86 }
87
88 my $static = $opts{static} || $opts{all};
89 my $dynamic = $opts{dynamic} || $opts{all};
90 my $nonxs = $opts{nonxs} || $opts{all};
91 my $dynaloader = $opts{dynaloader} || $opts{all};
92
93 # The Perl Makefile.SH will expand all extensions to
94 #       lib/auto/X/X.a  (or lib/auto/X/Y/Y.a if nested)
95 # A user wishing to run make_ext might use
96 #       X (or X/Y or X::Y if nested)
97
98 # canonise into X/Y form (pname)
99
100 foreach (@extspec) {
101     if (s{^lib/auto/}{}) {
102         # Remove lib/auto prefix and /*.* suffix
103         s{/[^/]+\.[^/]+$}{};
104     } elsif (s{^$ext_dirs_re/}{}) {
105         # Remove ext/ prefix and /pm_to_blib suffix
106         s{/pm_to_blib$}{};
107         # Targets are given as files on disk, but the extension spec is still
108         # written using /s for each ::
109         tr!-!/!;
110     } elsif (s{::}{\/}g) {
111         # Convert :: to /
112     } else {
113         s/\..*o//;
114     }
115 }
116
117 my $makecmd  = shift @pass_through; # Should be something like MAKE=make
118 unshift @pass_through, 'PERL_CORE=1';
119
120 my @dirs  = @{$opts{dir} || ['ext', 'cpan']};
121 my $target   = $opts{target}[0];
122 $target = 'all' unless defined $target;
123
124 # Previously, $make was taken from config.sh.  However, the user might
125 # instead be running a possibly incompatible make.  This might happen if
126 # the user types "gmake" instead of a plain "make", for example.  The
127 # correct current value of MAKE will come through from the main perl
128 # makefile as MAKE=/whatever/make in $makecmd.  We'll be cautious in
129 # case third party users of this script (are there any?) don't have the
130 # MAKE=$(MAKE) argument, which was added after 5.004_03.
131 unless(defined $makecmd and $makecmd =~ /^MAKE=(.*)$/) {
132     die "$0:  WARNING:  Please include MAKE=\$(MAKE) in \@ARGV\n";
133 }
134
135 # This isn't going to cope with anything fancy, such as spaces inside command
136 # names, but neither did what it replaced. Once there is a use case that needs
137 # it, please supply patches. Until then, I'm sticking to KISS
138 my @make = split ' ', $1 || $Config{make} || $ENV{MAKE};
139 # Using an array of 0 or 1 elements makes the subsequent code simpler.
140 my @run = $Config{run};
141 @run = () if not defined $run[0] or $run[0] eq '';
142
143
144 if ($target eq '') {
145     die "make_ext: no make target specified (eg all or clean)\n";
146 } elsif ($target !~ /(?:^all|clean)$/) {
147     # for the time being we are strict about what make_ext is used for
148     die "$0: unknown make target '$target'\n";
149 }
150
151 if (!@extspec and !$static and !$dynamic and !$nonxs and !$dynaloader)  {
152     die "$0: no extension specified\n";
153 }
154
155 my $perl;
156 my %extra_passthrough;
157
158 if ($is_Win32) {
159     (my $here = getcwd()) =~ s{/}{\\}g;
160     $perl = $^X;
161     if ($perl =~ m#^\.\.#) {
162         $perl = "$here\\$perl";
163     }
164     (my $topdir = $perl) =~ s/\\[^\\]+$//;
165     # miniperl needs to find perlglob and pl2bat
166     $ENV{PATH} = "$topdir;$topdir\\win32\\bin;$ENV{PATH}";
167     my $pl2bat = "$topdir\\win32\\bin\\pl2bat";
168     unless (-f "$pl2bat.bat") {
169         my @args = ($perl, "-I$topdir\\lib", ("$pl2bat.pl") x 2);
170         print "@args\n";
171         system(@args) unless defined $::Cross::platform;
172     }
173
174     my $build = getcwd();
175     print "In $build";
176     foreach my $dir (@dirs) {
177         chdir($dir) or die "Cannot cd to $dir: $!\n";
178         (my $ext = getcwd()) =~ s{/}{\\}g;
179         FindExt::scan_ext($ext);
180         FindExt::set_static_extensions(split ' ', $Config{static_ext});
181
182         my @ext;
183         push @ext, FindExt::static_ext() if $static;
184         push @ext, FindExt::dynamic_ext() if $dynamic;
185         push @ext, FindExt::nonxs_ext() if $nonxs;
186         push @ext, 'DynaLoader' if $dynaloader;
187
188         foreach (sort @ext) {
189             if (%incl and !exists $incl{$_}) {
190                 #warn "Skipping extension $ext\\$_, not in inclusion list\n";
191                 next;
192             }
193             if (exists $excl{$_}) {
194                 warn "Skipping extension $ext\\$_, not ported to current platform";
195                 next;
196             }
197             push @extspec, $_;
198             if($_ eq 'DynaLoader') {
199                 # No, we don't know why nmake can't work out the dependency chain
200                 push @{$extra_passthrough{$_}}, 'DynaLoader.c';
201             } elsif(FindExt::is_static($_)) {
202                 push @{$extra_passthrough{$_}}, 'LINKTYPE=static';
203             }
204         }
205         chdir $build
206             or die "Couldn't chdir to '$build': $!"; # restore our start directory
207     }
208     chdir '..'
209         or die "Couldn't chdir to build directory: $!"; # now in the Perl build directory
210 }
211 elsif ($is_VMS) {
212     $perl = $^X;
213     push @extspec, (split ' ', $Config{static_ext}) if $static;
214     push @extspec, (split ' ', $Config{dynamic_ext}) if $dynamic;
215     push @extspec, (split ' ', $Config{nonxs_ext}) if $nonxs;
216     push @extspec, 'DynaLoader' if $dynaloader;
217 }
218
219 {
220     # Cwd needs to be built before Encode recurses into subdirectories.
221     # This seems to be the simplest way to ensure this ordering:
222     my (@first, @other);
223     foreach (@extspec) {
224         if ($_ eq 'Cwd') {
225             push @first, $_;
226         } else {
227             push @other, $_;
228         }
229     }
230     @extspec = (@first, @other);
231 }
232
233 foreach my $spec (@extspec)  {
234     my $mname = $spec;
235     $mname =~ s!/!::!g;
236     my $ext_pathname;
237     if (-d "ext/$spec") {
238         # Old style ext/Data/Dumper/
239         $ext_pathname = "ext/$spec";
240     } else {
241         # New style ext/Data-Dumper/
242         my $copy = $spec;
243         $copy =~ tr!/!-!;
244         foreach my $dir (@ext_dirs) {
245             if (-d "$dir/$copy") {
246                 $ext_pathname = "$dir/$copy";
247                 last;
248             }
249         }
250         if (!defined $ext_pathname) {
251             warn "Can't find extension $spec in any of @ext_dirs";
252             next;
253         }
254     }
255
256     if ($Config{osname} eq 'catamount') {
257         # Snowball's chance of building extensions.
258         die "This is $Config{osname}, not building $mname, sorry.\n";
259     }
260
261     print "\tMaking $mname ($target)\n";
262
263     build_extension($ext_pathname, $perl, $mname,
264                     [@pass_through, @{$extra_passthrough{$spec} || []}]);
265 }
266
267 sub build_extension {
268     my ($ext_dir, $perl, $mname, $pass_through) = @_;
269
270     my $up = $ext_dir;
271     $up =~ s![^/]+!..!g;
272
273     $perl ||= "$up/miniperl";
274     my $return_dir = $up;
275     my $lib_dir = "$up/lib";
276     # $lib_dir must be last, as we're copying files into it, and in a parallel
277     # make there's a race condition if one process tries to open a module that
278     # another process has half-written.
279     $ENV{PERL5LIB}
280         = join $Config{path_sep}, (map {"$up/$_"} @toolchain), $lib_dir;
281     $ENV{PERL_CORE} = 1;
282
283     unless (chdir "$ext_dir") {
284         warn "Cannot cd to $ext_dir: $!";
285         return;
286     }
287     my $makefile;
288     if ($is_VMS) {
289         $makefile = 'descrip.mms';
290         if ($target =~ /clean$/
291             && !-f $makefile
292             && -f "${makefile}_old") {
293             $makefile = "${makefile}_old";
294         }
295     } else {
296         $makefile = 'Makefile';
297     }
298     
299     if (!-f $makefile) {
300         if (!-f 'Makefile.PL') {
301             print "\nCreating Makefile.PL in $ext_dir for $mname\n";
302             # We need to cope well with various possible layouts
303             my @dirs = split /::/, $mname;
304             my $leaf = pop @dirs;
305             my $leafname = "$leaf.pm";
306             my $pathname = join '/', @dirs, $leafname;
307             my @locations = ($leafname, $pathname, "lib/$pathname");
308             my $fromname;
309             foreach (@locations) {
310                 if (-f $_) {
311                     $fromname = $_;
312                     last;
313                 }
314             }
315
316             unless ($fromname) {
317                 die "For $mname tried @locations in in $ext_dir but can't find source";
318             }
319             open my $fh, '>', 'Makefile.PL'
320                 or die "Can't open Makefile.PL for writing: $!";
321             print $fh <<"EOM";
322 #-*- buffer-read-only: t -*-
323
324 # This Makefile.PL was written by $0.
325 # It will be deleted automatically by make realclean
326
327 use strict;
328 use ExtUtils::MakeMaker;
329
330 WriteMakefile(
331     NAME          => '$mname',
332     VERSION_FROM  => '$fromname',
333     ABSTRACT_FROM => '$fromname',
334     realclean     => {FILES => 'Makefile.PL'},
335 );
336
337 # ex: set ro:
338 EOM
339             close $fh or die "Can't close Makefile.PL: $!";
340         }
341         print "\nRunning Makefile.PL in $ext_dir\n";
342
343         # Presumably this can be simplified
344         my @cross;
345         if (defined $::Cross::platform) {
346             # Inherited from win32/buildext.pl
347             @cross = "-MCross=$::Cross::platform";
348         } elsif ($opts{cross}) {
349             # Inherited from make_ext.pl
350             @cross = '-MCross';
351         }
352             
353         my @args = (@cross, 'Makefile.PL');
354         if ($is_VMS) {
355             my $libd = VMS::Filespec::vmspath($lib_dir);
356             push @args, "INST_LIB=$libd", "INST_ARCHLIB=$libd";
357         } else {
358             push @args, 'INSTALLDIRS=perl', 'INSTALLMAN1DIR=none',
359                 'INSTALLMAN3DIR=none';
360         }
361         push @args, @$pass_through;
362         _quote_args(\@args) if $is_VMS;
363         print join(' ', @run, $perl, @args), "\n";
364         my $code = system @run, $perl, @args;
365         warn "$code from $ext_dir\'s Makefile.PL" if $code;
366
367         # Right. The reason for this little hack is that we're sitting inside
368         # a program run by ./miniperl, but there are tasks we need to perform
369         # when the 'realclean', 'distclean' or 'veryclean' targets are run.
370         # Unfortunately, they can be run *after* 'clean', which deletes
371         # ./miniperl
372         # So we do our best to leave a set of instructions identical to what
373         # we would do if we are run directly as 'realclean' etc
374         # Whilst we're perfect, unfortunately the targets we call are not, as
375         # some of them rely on a $(PERL) for their own distclean targets.
376         # But this always used to be a problem with the old /bin/sh version of
377         # this.
378         if ($is_Unix) {
379             my $suffix = '.sh';
380             foreach my $clean_target ('realclean', 'veryclean') {
381                 my $file = "$return_dir/$clean_target$suffix";
382                 open my $fh, '>>', $file or die "open $file: $!";
383                 # Quite possible that we're being run in parallel here.
384                 # Can't use Fcntl this early to get the LOCK_EX
385                 flock $fh, 2 or warn "flock $file: $!";
386                 print $fh <<"EOS";
387 cd $ext_dir
388 if test ! -f Makefile -a -f Makefile.old; then
389     echo "Note: Using Makefile.old"
390     make -f Makefile.old $clean_target MAKE='@make' @pass_through
391 else
392     if test ! -f Makefile ; then
393         echo "Warning: No Makefile!"
394     fi
395     make $clean_target MAKE='@make' @pass_through
396 fi
397 cd $return_dir
398 EOS
399                 close $fh or die "close $file: $!";
400             }
401         }
402     }
403
404     if (not -f $makefile) {
405         print "Warning: No Makefile!\n";
406     }
407
408     if ($is_VMS) {
409         _macroify_passthrough($pass_through);
410         unshift @$pass_through, "/DESCRIPTION=$makefile";
411     }
412
413     if (!$target or $target !~ /clean$/) {
414         # Give makefile an opportunity to rewrite itself.
415         # reassure users that life goes on...
416         my @args = ('config', @$pass_through);
417         _quote_args(\@args) if $is_VMS;
418         system(@run, @make, @args) and print "@run @make @args failed, continuing anyway...\n";
419     }
420     my @targ = ($target, @$pass_through);
421     _quote_args(\@targ) if $is_VMS;
422     print "Making $target in $ext_dir\n@run @make @targ\n";
423     my $code = system(@run, @make, @targ);
424     die "Unsuccessful make($ext_dir): code=$code" if $code != 0;
425
426     chdir $return_dir || die "Cannot cd to $return_dir: $!";
427 }
428
429 sub _quote_args {
430     my $args = shift; # must be array reference
431
432     # Do not quote qualifiers that begin with '/'.
433     map { if (!/^\//) {
434           $_ =~ s/\"/""/g;     # escape C<"> by doubling
435           $_ = q(").$_.q(");
436         }
437     } @{$args}
438     ;
439 }
440
441 sub _macroify_passthrough {
442     my $passthrough = shift;
443     _quote_args($passthrough);
444     my $macro = '/MACRO=(' . join(',',@$passthrough) . ')';
445     @$passthrough = ();
446     @$passthrough[0] = $macro;  
447 }