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