Move AutoLoader 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 cpan/AutoLoader/lib);
21
22 my @ext_dirs = qw(cpan ext);
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_dirs};
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         # Temporary hack to cope with smokers that are not clearing directories:
239         && $spec =~ m!/!
240        ) {
241         # Old style ext/Data/Dumper/
242         $ext_pathname = "ext/$spec";
243     } else {
244         # New style ext/Data-Dumper/
245         my $copy = $spec;
246         $copy =~ tr!/!-!;
247         foreach my $dir (@ext_dirs) {
248             if (-d "$dir/$copy") {
249                 $ext_pathname = "$dir/$copy";
250                 last;
251             }
252         }
253         if (!defined $ext_pathname) {
254             warn "Can't find extension $spec in any of @ext_dirs";
255             next;
256         }
257     }
258
259     if ($Config{osname} eq 'catamount') {
260         # Snowball's chance of building extensions.
261         die "This is $Config{osname}, not building $mname, sorry.\n";
262     }
263
264     print "\tMaking $mname ($target)\n";
265
266     build_extension($ext_pathname, $perl, $mname,
267                     [@pass_through, @{$extra_passthrough{$spec} || []}]);
268 }
269
270 sub build_extension {
271     my ($ext_dir, $perl, $mname, $pass_through) = @_;
272
273     my $up = $ext_dir;
274     $up =~ s![^/]+!..!g;
275
276     $perl ||= "$up/miniperl";
277     my $return_dir = $up;
278     my $lib_dir = "$up/lib";
279     # $lib_dir must be last, as we're copying files into it, and in a parallel
280     # make there's a race condition if one process tries to open a module that
281     # another process has half-written.
282     $ENV{PERL5LIB}
283         = join $Config{path_sep}, (map {"$up/$_"} @toolchain), $lib_dir;
284     $ENV{PERL_CORE} = 1;
285
286     unless (chdir "$ext_dir") {
287         warn "Cannot cd to $ext_dir: $!";
288         return;
289     }
290     my $makefile;
291     if ($is_VMS) {
292         $makefile = 'descrip.mms';
293         if ($target =~ /clean$/
294             && !-f $makefile
295             && -f "${makefile}_old") {
296             $makefile = "${makefile}_old";
297         }
298     } else {
299         $makefile = 'Makefile';
300     }
301     
302     if (!-f $makefile) {
303         if (!-f 'Makefile.PL') {
304             print "\nCreating Makefile.PL in $ext_dir for $mname\n";
305             # We need to cope well with various possible layouts
306             my @dirs = split /::/, $mname;
307             my $leaf = pop @dirs;
308             my $leafname = "$leaf.pm";
309             my $pathname = join '/', @dirs, $leafname;
310             my @locations = ($leafname, $pathname, "lib/$pathname");
311             my $fromname;
312             foreach (@locations) {
313                 if (-f $_) {
314                     $fromname = $_;
315                     last;
316                 }
317             }
318
319             unless ($fromname) {
320                 die "For $mname tried @locations in in $ext_dir but can't find source";
321             }
322             open my $fh, '>', 'Makefile.PL'
323                 or die "Can't open Makefile.PL for writing: $!";
324             print $fh <<"EOM";
325 #-*- buffer-read-only: t -*-
326
327 # This Makefile.PL was written by $0.
328 # It will be deleted automatically by make realclean
329
330 use strict;
331 use ExtUtils::MakeMaker;
332
333 WriteMakefile(
334     NAME          => '$mname',
335     VERSION_FROM  => '$fromname',
336     ABSTRACT_FROM => '$fromname',
337     realclean     => {FILES => 'Makefile.PL'},
338 );
339
340 # ex: set ro:
341 EOM
342             close $fh or die "Can't close Makefile.PL: $!";
343         }
344         print "\nRunning Makefile.PL in $ext_dir\n";
345
346         # Presumably this can be simplified
347         my @cross;
348         if (defined $::Cross::platform) {
349             # Inherited from win32/buildext.pl
350             @cross = "-MCross=$::Cross::platform";
351         } elsif ($opts{cross}) {
352             # Inherited from make_ext.pl
353             @cross = '-MCross';
354         }
355             
356         my @args = (@cross, 'Makefile.PL');
357         if ($is_VMS) {
358             my $libd = VMS::Filespec::vmspath($lib_dir);
359             push @args, "INST_LIB=$libd", "INST_ARCHLIB=$libd";
360         } else {
361             push @args, 'INSTALLDIRS=perl', 'INSTALLMAN1DIR=none',
362                 'INSTALLMAN3DIR=none';
363         }
364         push @args, @$pass_through;
365         _quote_args(\@args) if $is_VMS;
366         print join(' ', @run, $perl, @args), "\n";
367         my $code = system @run, $perl, @args;
368         warn "$code from $ext_dir\'s Makefile.PL" if $code;
369
370         # Right. The reason for this little hack is that we're sitting inside
371         # a program run by ./miniperl, but there are tasks we need to perform
372         # when the 'realclean', 'distclean' or 'veryclean' targets are run.
373         # Unfortunately, they can be run *after* 'clean', which deletes
374         # ./miniperl
375         # So we do our best to leave a set of instructions identical to what
376         # we would do if we are run directly as 'realclean' etc
377         # Whilst we're perfect, unfortunately the targets we call are not, as
378         # some of them rely on a $(PERL) for their own distclean targets.
379         # But this always used to be a problem with the old /bin/sh version of
380         # this.
381         if ($is_Unix) {
382             my $suffix = '.sh';
383             foreach my $clean_target ('realclean', 'veryclean') {
384                 my $file = "$return_dir/$clean_target$suffix";
385                 open my $fh, '>>', $file or die "open $file: $!";
386                 # Quite possible that we're being run in parallel here.
387                 # Can't use Fcntl this early to get the LOCK_EX
388                 flock $fh, 2 or warn "flock $file: $!";
389                 print $fh <<"EOS";
390 cd $ext_dir
391 if test ! -f Makefile -a -f Makefile.old; then
392     echo "Note: Using Makefile.old"
393     make -f Makefile.old $clean_target MAKE='@make' @pass_through
394 else
395     if test ! -f Makefile ; then
396         echo "Warning: No Makefile!"
397     fi
398     make $clean_target MAKE='@make' @pass_through
399 fi
400 cd $return_dir
401 EOS
402                 close $fh or die "close $file: $!";
403             }
404         }
405     }
406
407     if (not -f $makefile) {
408         print "Warning: No Makefile!\n";
409     }
410
411     if ($is_VMS) {
412         _macroify_passthrough($pass_through);
413         unshift @$pass_through, "/DESCRIPTION=$makefile";
414     }
415
416     if (!$target or $target !~ /clean$/) {
417         # Give makefile an opportunity to rewrite itself.
418         # reassure users that life goes on...
419         my @args = ('config', @$pass_through);
420         _quote_args(\@args) if $is_VMS;
421         system(@run, @make, @args) and print "@run @make @args failed, continuing anyway...\n";
422     }
423     my @targ = ($target, @$pass_through);
424     _quote_args(\@targ) if $is_VMS;
425     print "Making $target in $ext_dir\n@run @make @targ\n";
426     my $code = system(@run, @make, @targ);
427     die "Unsuccessful make($ext_dir): code=$code" if $code != 0;
428
429     chdir $return_dir || die "Cannot cd to $return_dir: $!";
430 }
431
432 sub _quote_args {
433     my $args = shift; # must be array reference
434
435     # Do not quote qualifiers that begin with '/'.
436     map { if (!/^\//) {
437           $_ =~ s/\"/""/g;     # escape C<"> by doubling
438           $_ = q(").$_.q(");
439         }
440     } @{$args}
441     ;
442 }
443
444 sub _macroify_passthrough {
445     my $passthrough = shift;
446     _quote_args($passthrough);
447     my $macro = '/MACRO=(' . join(',',@$passthrough) . ')';
448     @$passthrough = ();
449     @$passthrough[0] = $macro;  
450 }