Filename globbing made perl-5.6.0 backward compatible.
[macros.git] / AutoGen.pm
1 #! /usr/bin/perl
2
3 # $Id$
4 # Module to generate all the initial makefiles etc.
5 # Copyright (C) 2002 Jan Kratochvil <project-macros@jankratochvil.net>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; exactly version 2 of June 1991 is required
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
21 package AutoGen;
22 require 5.6.0;  # at least 'use warnings;' but we need some 5.6.0+ modules anyway
23 use vars qw($VERSION);
24 $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
25 use strict;
26 use warnings;
27
28 BEGIN {
29         my @missing;
30         for (split "\n",<<'HERE') {
31                 use Carp qw(cluck confess);
32                 use Getopt::Long;       # &GetOptions, $Getopt::Long::*
33                 use File::Basename;     # &basename
34                 use File::Grep qw(fgrep);
35                 use File::HomeDir;      # &home
36                 use File::Remove qw(remove);
37                 use File::NCopy qw(copy);
38                 use File::chdir;        # $CWD
39                 use File::Touch;        # &touch
40                 use POSIX qw(WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG);
41 HERE
42                 eval "$_\n; 1;" or push @missing,(/^\s*use\s+([^ ;]+)/)[0];
43                 }
44         die "You are missing some modules - install them by:\n"
45                                         ."\tperl -MCPAN -e 'install qw(".join(" ",@missing).")'\n"
46                         if @missing;
47         }
48
49 our %Options;
50
51 sub _help
52 {
53         return '
54 Beware: '.basename($0).' is a tool only for maintainers!
55
56 Supported parameters:
57  --rpm       Build RPM packages locally (needs /usr/src/(redhat|packages)/ access)
58  --rpmtest   Build RPM like "rpm" but w/o gpg/pgp signing
59  --clean     Standard cleanup method
60  --fullclean Like clean but even the .cvsignore files are removed
61  --copy      Behave exactly like in default mode but copy all instead of symlinks
62  -h|--help   Print this help message.
63 '.($Options{"help"} || "");
64 }
65
66 sub _readfile
67 {
68 my($filename)=@_;
69
70         local $/=undef();
71         local *F;
72         open F,$filename or confess "Open \"$filename\": $!";
73         my $r=<F>;
74         close F or cluck "Close \"$filename\": $!";
75         return $r;
76 }
77
78 sub _writefile
79 {
80 my($filename,@content)=@_;
81
82         local *F;
83         open F,">".$filename or confess "rewrite \"$filename\": $!";
84         print F @content;
85         close F or cluck "close \"$filename\": $!";
86 }
87
88 my %_rpmeval_cache;
89 sub _rpmeval
90 {
91 my(@names)=@_;
92
93         my @r=map({
94                 my $name=$_;
95                 my $nameref=\$_rpmeval_cache{$name};
96                 $$nameref=_readfile('rpm --eval %'.$name.'|') if !defined $$nameref;
97                 chomp $$nameref;
98                 $$nameref;
99                 } @names);
100         return @r if wantarray();
101         confess "Scalar return for ".scalar(@r)." values" if 1!=@r;
102         return $r[0];
103 }
104
105 sub _system
106 {
107 my(@args)=@_;
108
109         system(@args) and confess join(" ",@args).": $?=".join(",",
110                         (!WIFEXITED($?)   ? () : ("EXITSTATUS(".WEXITSTATUS($?).")")),
111                         (!WIFSIGNALED($?) ? () : ("TERMSIG("   .WTERMSIG($?)   .")")),
112                         (!WIFSTOPPED($?)  ? () : ("STOPSIG("   .WSTOPSIG($?)   .")")),
113                         );
114 }
115
116 # Assumed wildcard pattern expansion to exactly one item if !$nocheck
117 sub _copy
118 {
119 my(@files)=@_;
120
121         my $nocheck=shift @files if $files[0] eq "nocheck";
122         my $dest=pop @files;
123         # expand pattern to properly match &copy resulting filenames count
124         @files=map({ glob $_; } @files);
125         @files==copy @files,$dest or $nocheck or confess "$!";
126 }
127
128 # Assumed wildcard pattern expansion to exactly one item if !$nocheck
129 sub _remove
130 {
131 my(@files)=@_;
132
133         my $nocheck=shift @files if $files[0] eq "nocheck";
134         my $flag=shift @files if ref $files[0];
135         # expand pattern to properly match &remove resulting filenames count
136         @files=map({ glob $_; } @files);
137         @files==remove((!$flag ? () : $flag),@files) or $nocheck or confess "$!";
138 }
139
140 # FIXME: File::NCopy exists but File::NMove doesn't
141 sub _move
142 {
143 my(@files)=@_;
144
145         my $dest=pop @files;
146         _copy @files,$dest;
147         _remove @files;
148 }
149
150 # $args{
151 #       "sign"=>bool,
152 #       },
153 sub _rpmbuild
154 {
155 my($class,%args)=@_;
156
157         my $name=$Options{"name"};
158         _remove "nocheck",\1,
159                         _rpmeval("_tmppath" )."/$name-*-root",
160                         _rpmeval("_builddir")."/$name-*";
161         my($specsrc)=map((-e $_ ? $_ : "$name.spec.in"),"$name.spec.m4.in");
162         my $spec=_readfile $specsrc;
163         $spec=~s/\\\n/ /gs;
164         $class->run(%Options,
165                         "ARGV"=>["--copy"],
166                         "configure_args"=>[split /\s+/,($spec=~/^[%]configure\b[ \t]*(.*)$/m)[0]],
167                         );
168         _remove "ChangeLog";    # force its rebuild by Makefile/rcs2log
169         _system "make dist $name.spec";
170         _copy "$name-*.tar.gz",_rpmeval("_sourcedir");
171         _system(join(" ","rpmbuild",
172                         "-ba",
173                         "--rmsource",   # _remove _rpmeval("_sourcedir")."/$name-*.tar.gz";
174                         "--clean",      # _remove _rpmeval("_builddir")."/$name-VERSION";
175                         (!$args{"sign"} ? () : "--sign"),
176                         "$name.spec",
177                         ));
178         _system "make dist-tarZ" if $Options{"dist-tarZ"};
179         _move _rpmeval("_srcrpmdir")."/$name-*.src.rpm",".";
180         _move _rpmeval("_rpmdir")."/"._rpmeval("_target_cpu")."/$name-*."._rpmeval("_target_cpu").".rpm",".";
181   _system "ls -l $name-*";
182         exit 0; # should never return
183 }
184
185 # WARNING: doesn't respect %Options change!
186 my @_cleanfiles_cache;
187 sub _cleanfiles
188 {
189         # maintainer-clean hack is not safe, please list all files for 'rm'.
190         # When the filename doesn't contain '/', it is applied to ALL directories.
191         # Please note that files exactly in root dir MUST have ./ in the front
192         #   (to not to be considered as ALL-directories files).
193
194         if (!@_cleanfiles_cache) {
195                 @_cleanfiles_cache=map({
196                                                 local $_=$_;    # Prevent: Modification of a read-only value attempted
197                                                 s/\Q<name>\E/$Options{"name"}/ego;
198                                                 s#/+#/#g;
199                                                 # "*xyzzy" basename -> "*xyzzy",".*xyzzy" for proper cleaning
200                                                 (!m#^((?:.*/)?)([*][^/]*)$# ? ($_) : ("$1$2","$1.$2"));
201                                                 }
202                                 (
203                                 ".#*",  # Possible attempt to put comments in qw() list
204                                 qw(
205                                                 *~
206                                                 *.orig *.rej
207                                                 core
208                                                 Makefile Makefile.in
209                                                 TAGS tags ID
210                                                 .deps .libs
211                                                 *.[oa] *.l[oa] *.l[oa]T
212                                                 .cvsignore
213
214                                                 ./errs*
215                                                 ./intl
216                                                 ./configure ./configure.scan
217                                                 ./config.guess ./config.status ./config.sub ./config.log ./config.cache
218                                                 ./config.h ./config.h.in
219                                                 ./confdefs.h ./conftest* ./autoh[0-9]* ./confcache
220                                                 ./config.rpath
221                                                 ./depcomp
222                                                 ./compile
223                                                 ./stamp-h ./stamp-h.in ./stamp-h1
224                                                 ./install-sh
225                                                 ./aclocal.m4
226                                                 ./autom4te.cache ./autom4te-*.cache
227                                                 ./m4
228                                                 ./missing
229                                                 ./mkinstalldirs
230                                                 ./libtool ./ltconfig ./ltmain.sh
231                                                 ./ChangeLog
232                                                 ./ABOUT-NLS
233                                                 ./<name>-[0-9]* ./<name>-devel-[0-9]*
234                                                 ./<name>.spec ./<name>.m4 ./<name>.spec.m4
235                                                 ./macros/macros.dep
236                                                 ./po/Makefile.in.in ./po/POTFILES* ./po/cat-id-tbl.c ./po/cat-id-tbl.tmp
237                                                 ./po/*.gmo ./po/*.mo ./po/stamp-cat-id ./po/<name>.pot ./po/ChangeLog
238                                                 ./po/Makevars ./po/Makevars.template ./po/Rules-quot ./po/*.sed ./po/*.sin ./po/*.header
239                                                 ),
240                                 map((!$_ ? () : do { my $dir=$_; map("$dir/$_",qw(
241                                                 *.stamp
242                                                 sgml*
243                                                 tmpl*
244                                                 html*
245                                                 *.txt
246                                                 *.txt.bak
247                                                 *.args
248                                                 *.hierarchy
249                                                 *.signals
250                                                 )); }),$Options{"gtk-doc-dir"}),
251                                 map((!$_ ? () : do { my $dir=$_; map("$dir/$_",qw(
252                                                 *.html
253                                                 *.info*
254                                                 *.txt
255                                                 *.tex
256                                                 *.sgml
257                                                 )); }),$Options{"docbook-lite-dir"}),
258                                 map((!$_ ? () : @$_),$Options{"clean"}),
259                                 ));
260                 # sanity check
261                 for (@_cleanfiles_cache) {
262                                 confess "dir-specific 'clean'-pattern must start with './': $_" if m#^(?!\Q./\E).*/#;
263                                 };
264                 }
265         return @_cleanfiles_cache;
266 }
267
268 sub _cleanfilesfordir
269 {
270 my($dir)=@_;
271
272         return map({
273                            if (m#^\Q$dir\E/([^/]+)$#) { # this-dir: "./this-dir/file-name.c"
274                                         ($1);
275                                         }
276                         elsif (m#^[^/]+$#) {    # all-dirs: "file-name.c"; the same as "./*/file-name.c"
277                                         ($&);
278                                         }
279                         elsif (do {     # all-subdirs: "./parent-of-this-dir/*/file-name.c"
280                                                         m#/[*]/([^/]+)$#;
281                                                         ($_=$1) && $dir=~m#^\Q$`\E(?:/|$)#;
282                                                         }) {
283                                         ($_);
284                                         }
285                         else {
286                                         ();
287                                         }
288                         } _cleanfiles());
289 }
290
291 sub _cvsdirs
292 {
293 my(@startdirs)=@_;
294
295         my @r=();
296         my @todo=(@startdirs);
297         while (defined(my $dir=shift @todo)) {
298                 local *ENTRIES;
299                 my $entries_filename="$dir/CVS/Entries";
300                 open ENTRIES,$entries_filename or (cluck "open \"$entries_filename\": $!" and next);
301                 push @r,$dir;
302                 local $/="\n";
303                 my %local=();
304                 local $_;
305                 while (<ENTRIES>) {
306                         chomp;
307                         next if !m#^D/([^/]+)/#;
308                         $local{$1}=1;
309                         }
310                 close ENTRIES or cluck "close \"$entries_filename\": $!";
311                 if (-e (my $entries_log_filename=$dir."/CVS/Entries.Log")) {
312                         local *ENTRIES_LOG;
313                         if (open ENTRIES_LOG,$entries_log_filename or cluck "open \"$entries_log_filename\": $!") {
314                                 local $_;
315                                 while (<ENTRIES_LOG>) {
316                                         chomp;
317                                                  if (m#^A D/([^/]*)/#) {
318                                                 $local{$1}=1;
319                                                 }
320                                         elsif (m#^R D/([^/]*)/#) {
321                                                 delete $local{$1};
322                                                 }
323                                         else {
324                                                 cluck "$entries_log_filename: Unrecognized line $.: $_";
325                                                 }
326                                         }
327                                 close ENTRIES_LOG or cluck "close \"$entries_log_filename\": $!";
328                                 }
329                         }
330                 push @todo,map(("$dir/$_"),keys(%local));
331                 }
332         return @r;
333 }
334
335 sub _expandclass
336 {
337 my($patt)=@_;
338
339         return $patt if $patt!~/\Q[\E(.*?)\Q]\E/;
340         my($pre,$range,$post)=($`,$1,$');       # FIXME: local($`,$1,$') doesn't work - why?
341         1 while $range=~s#(.)-(.)# join("",map(chr,(ord($1)..ord($2))));
342                         #ge;
343         return map({ _expandclass("$pre$_$post"); } split("",$range));
344 }
345
346 sub run
347 {
348 my($class,%options)=@_;
349
350         local %Options=%options;
351         do { require $_ if -e; } for (home()."/.".$Options{"name"}.".autogen.pl");
352         do { $$_=1 if !defined($$_) && fgrep { /^\s*AUTOMAKE_OPTIONS\s*=[^#]*\bdist-tarZ\b/m; } "Makefile.am"; }
353                         for (\$Options{"dist-tarZ"});
354         Getopt::Long::Configure('noignorecase','prefix_pattern=(--|-|\+|)');
355         local @ARGV=@{$Options{"ARGV"}};
356         print _help() and confess if !GetOptions(
357                           "rpm"      ,sub { $class->_rpmbuild("sign"=>1); },
358                           "rpmtest"  ,sub { $class->_rpmbuild("sign"=>0); },
359                           "dist"     ,\$Options{"ARGV_dist"},
360                           "copy!"    ,\$Options{"ARGV_copy"},
361                           "fullclean",\$Options{"ARGV_fullclean"},
362                           "clean"    ,\$Options{"ARGV_clean"},
363                         "h|help"     ,sub { print _help(); exit 0; },
364                         $Options{"GetOptions_args"},
365                         ) || @ARGV;
366
367         for my $subdir (map((!$_ ? () : @$_),$Options{"subdirs"})) {
368                 local $CWD=$subdir;
369                 _system "./autogen.pl",@{$Options{"ARGV"}},"--dist";    # use "--dist" just as fallback!
370                 }
371
372         for my $dir (_cvsdirs(".")) {
373                 my @cleanfilesfordir=_cleanfilesfordir $dir;
374                 _writefile $dir."/.cvsignore",map("$_\n",@cleanfilesfordir) if !$Options{"ARGV_fullclean"};
375                 _remove "nocheck",\1,map({ _expandclass("$dir/$_"); } grep({
376                                 $Options{"ARGV_fullclean"} or $_ ne ".cvsignore";
377                                 } @cleanfilesfordir));
378                 }
379         return if $Options{"ARGV_clean"} || $Options{"ARGV_fullclean"};
380
381         $Options{"aclocal_args"}=[qw(-I macros),map((!$_ ? () : @$_),$Options{"aclocal_args"})];
382         my $configure_in=_readfile("configure.in");
383         do { $$_=1 if !defined($$_) && $configure_in=~/^AM_GNU_GETTEXT\b/m; }
384                         for (\$Options{"want-gettextize"});
385         do { $$_=1 if !defined($$_) && $configure_in=~/^AM_GLIB_GNU_GETTEXT\b/m; }
386                         for (\$Options{"want-glib-gettextize"});
387         do { $$_=1 if !defined($$_) && $configure_in=~/^AM_PROG_LIBTOOL\b/m; }
388                         for (\$Options{"want-libtoolize"}); 
389         do { $$_=1 if !defined($$_) && $configure_in=~/^A[CM]_CONFIG_HEADER\b/m; }
390                         for (\$Options{"want-autoheader"});
391         my @copy_arg=(!$Options{"ARGV_copy"} ? () : "--copy");
392
393         do { &$_ if $_; } for ($Options{"prep"});
394         touch "po/POTFILES.in" if -d "po";
395         if ($Options{"want-gettextize"}) {
396                 # don't use multi-arg system() here as it would reject "</dev/null" redirection etc.
397                 for ("expect -c '"
398                                 .'spawn gettextize --intl --no-changelog '.join(" ",@copy_arg).';'
399                                 .'expect -timeout -1 "Press Return to acknowledge" {send "\r";exp_continue;} eof;'
400                                 ."'") {
401                         _system $_ and confess $_;
402                         }
403                 for ("configure.in","Makefile.am") {
404                         STDERR->printflush("gettextize recovery rename \"$_~\"->\"$_\"... ");
405                         rename "$_~","$_" or confess "$!";
406                         STDERR->printflush("ok\n");
407                         }
408                 if (!-e "po/Makevars") {
409                         my $Makevars_template="po/Makevars.template";
410                         my $makevars=_readfile $Makevars_template;
411                         $makevars=~s/^(COPYRIGHT_HOLDER)\b.*$/"$1=".$Options{"COPYRIGHT_HOLDER"}/meg
412                                         or confess "COPYRIGHT_HOLDER not found in $Makevars_template";
413                         _writefile "po/Makevars",$makevars;
414                         }
415                 # Prevent updating of contents during touch of any source file;
416                 # change the .po contents only when some data get updated
417                 for my $Makefile_in_in ("po/Makefile.in.in") {
418                         my $file=_readfile $Makefile_in_in;
419                         $file=~s%(\$\Q(MSGMERGE_UPDATE)\E) (\$\$\Q{lang}.po \E\$\Q(DOMAIN).pot\E)$%
420                                         $1.q< --backup=simple --suffix="~" >.$2.q<;>
421                                                         .q< if test `diff -u $${lang}.po~ $${lang}.po>
422                                                                                         .q< | sed>
423                                                                                                         .q< -e '1,/^@@.*@@$$/d'>
424                                                                                                         .q< -e '/^[+-]"POT-Creation-Date:/d'>
425                                                                                                         .q< -e '/^[^+-]/d'>
426                                                                                                         .q< -e '/^[+-]#/d'>
427                                                                                         .q< | wc -l` -eq 0;then>
428                                                                         .q< touch --reference=$${lang}.po $${lang}.po~;>
429                                                                                         .q< mv -f $${lang}.po~ $${lang}.po;>
430                                                         .q< else>
431                                                                         .q< rm -f $${lang}.po~;>
432                                                         .q< fi>
433                                         %me or confess;
434                         unlink $Makefile_in_in or confess "$!";
435                         _writefile $Makefile_in_in,$file;
436                         }
437                 }
438         if ($Options{"want-glib-gettextize"}) {
439                 _system "glib-gettextize",@copy_arg;
440                 # "po/ChangeLog" is somehow missing at this point
441                 File::Touch->new("atime_only"=>1)->touch("po/ChangeLog");
442                 }
443         _system "aclocal",map((!$_ ? () : @$_),$Options{"aclocal_args"});
444         _system qw(libtoolize),@copy_arg if $Options{"want-libtoolize"};
445         _system qw(autoheader) if $Options{"want-autoheader"};
446         # "ChangeLog" is reqd by automake(1)
447         # Don't remove it afterwards as it may still be needed during automatic automake Makefile rebuilds
448         File::Touch->new("atime_only"=>1)->touch("ChangeLog");
449         _system qw(automake --add-missing),@copy_arg;
450         _system qw(autoconf);
451         # Why it is left there after RedHat autoconf-2.53-8 ?
452         _remove "nocheck",\1,"autom4te-*.cache";
453
454         return if $Options{"ARGV_dist"};
455
456         # 'configure' defaults to CFLAGS '-g -O2' but our --enable-maintainer-mode
457         # should force '-ggdb3'
458         $ENV{"CFLAGS"}||="";
459         # shared/static switching cannot be based on maintainer-mode in configure
460         _system(qw(./configure --enable-maintainer-mode),
461                         (!$Options{"want-libtoolize"} ? () : qw(--enable-shared --disable-static)),
462                         map((!$_ ? () : @$_),$Options{"configure_args"}),
463                         );
464 }
465
466 1;
467 __END__
468
469 Tested with:
470         RedHat autoconf-2.53-8
471         RedHat automake-1.6.3-1
472         RedHat gettext-0.11.4-3
473         RedHat libtool-1.4.2-12
474         RedHat perl-5.8.0-48