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