f0feb2dd08c15bc696dee1ee1e270bd318f5308b
[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] *.l[oa]T
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                                                 ./compile
216                                                 ./stamp-h ./stamp-h.in ./stamp-h1
217                                                 ./install-sh
218                                                 ./aclocal.m4
219                                                 ./autom4te-*.cache
220                                                 ./m4
221                                                 ./missing
222                                                 ./mkinstalldirs
223                                                 ./libtool ./ltconfig ./ltmain.sh
224                                                 ./ChangeLog
225                                                 ./ABOUT-NLS
226                                                 ./<name>-[0-9]* ./<name>-devel-[0-9]*
227                                                 ./<name>.spec ./<name>.m4 ./<name>.spec.m4
228                                                 ./macros/macros.dep
229                                                 ./po/Makefile.in.in ./po/POTFILES* ./po/cat-id-tbl.c ./po/cat-id-tbl.tmp
230                                                 ./po/*.gmo ./po/*.mo ./po/stamp-cat-id ./po/<name>.pot ./po/ChangeLog
231                                                 ./po/Makevars ./po/Makevars.template ./po/Rules-quot ./po/*.sed ./po/*.sin ./po/*.header
232                                                 ),
233                                 map((!$_ ? () : do { my $dir=$_; map("$dir/$_",qw(
234                                                 *.stamp
235                                                 sgml*
236                                                 tmpl*
237                                                 html*
238                                                 *.txt
239                                                 *.txt.bak
240                                                 *.args
241                                                 *.hierarchy
242                                                 *.signals
243                                                 )); }),$Options{"gtk-doc-dir"}),
244                                 map((!$_ ? () : do { my $dir=$_; map("$dir/$_",qw(
245                                                 *.html
246                                                 *.info*
247                                                 *.txt
248                                                 *.tex
249                                                 *.sgml
250                                                 )); }),$Options{"docbook-lite-dir"}),
251                                 map((!$_ ? () : @$_),$Options{"clean"}),
252                                 ));
253                 # sanity check
254                 for (@_cleanfiles_cache) {
255                                 confess "dir-specific 'clean'-pattern must start with './': $_" if m#^(?!\Q./\E).*/#;
256                                 };
257                 }
258         return @_cleanfiles_cache;
259 }
260
261 sub _cleanfilesfordir
262 {
263 my($dir)=@_;
264
265         return map({
266                            if (m#^\Q$dir\E/([^/]+)$#) { # this-dir: "./this-dir/file-name.c"
267                                         ($1);
268                                         }
269                         elsif (m#^[^/]+$#) {    # all-dirs: "file-name.c"; the same as "./*/file-name.c"
270                                         ($&);
271                                         }
272                         elsif (do {     # all-subdirs: "./parent-of-this-dir/*/file-name.c"
273                                                         m#/[*]/([^/]+)$#;
274                                                         ($_=$1) && $dir=~m#^\Q$`\E(?:/|$)#;
275                                                         }) {
276                                         ($_);
277                                         }
278                         else {
279                                         ();
280                                         }
281                         } _cleanfiles());
282 }
283
284 sub _cvsdirs
285 {
286 my(@startdirs)=@_;
287
288         my @r=();
289         my @todo=(@startdirs);
290         while (defined(my $dir=shift @todo)) {
291                 local *ENTRIES;
292                 my $entries_filename="$dir/CVS/Entries";
293                 open ENTRIES,$entries_filename or (cluck "open \"$entries_filename\": $!" and next);
294                 push @r,$dir;
295                 local $/="\n";
296                 my %local=();
297                 local $_;
298                 while (<ENTRIES>) {
299                         chomp;
300                         next if !m#^D/([^/]+)/#;
301                         $local{$1}=1;
302                         }
303                 close ENTRIES or cluck "close \"$entries_filename\": $!";
304                 if (-e (my $entries_log_filename=$dir."/CVS/Entries.Log")) {
305                         local *ENTRIES_LOG;
306                         if (open ENTRIES_LOG,$entries_log_filename or cluck "open \"$entries_log_filename\": $!") {
307                                 local $_;
308                                 while (<ENTRIES_LOG>) {
309                                         chomp;
310                                                  if (m#^A D/([^/]*)/#) {
311                                                 $local{$1}=1;
312                                                 }
313                                         elsif (m#^R D/([^/]*)/#) {
314                                                 delete $local{$1};
315                                                 }
316                                         else {
317                                                 cluck "$entries_log_filename: Unrecognized line $.: $_";
318                                                 }
319                                         }
320                                 close ENTRIES_LOG or cluck "close \"$entries_log_filename\": $!";
321                                 }
322                         }
323                 push @todo,map(("$dir/$_"),keys(%local));
324                 }
325         return @r;
326 }
327
328 sub _expandclass
329 {
330 my($patt)=@_;
331
332         return $patt if $patt!~/\Q[\E(.*?)\Q]\E/;
333         my($pre,$post)=($`,$'); # FIXME: local($`,$') doesn't work - why?
334         return map({ _expandclass("$pre$_$post"); } split("",$1));
335 }
336
337 sub run
338 {
339 my($class,%options)=@_;
340
341         local %Options=%options;
342         do { require $_ if -e; } for (home()."/.".$Options{"name"}.".autogen.pl");
343         do { $$_=1 if !defined($$_) && fgrep { /^\s*AUTOMAKE_OPTIONS\s*=[^#]*\bdist-tarZ\b/m; } "Makefile.am"; }
344                         for (\$Options{"dist-tarZ"});
345         Getopt::Long::Configure('noignorecase','prefix_pattern=(--|-|\+|)');
346         local @ARGV=@{$Options{"ARGV"}};
347         print _help() and confess if !GetOptions(
348                           "rpm"      ,sub { $class->_rpmbuild("sign"=>1); return; },
349                           "rpmtest"  ,sub { $class->_rpmbuild("sign"=>0); return; },
350                           "dist"     ,\$Options{"ARGV_dist"},
351                           "copy!"    ,\$Options{"ARGV_copy"},
352                           "fullclean",\$Options{"ARGV_fullclean"},
353                           "clean"    ,\$Options{"ARGV_clean"},
354                         "h|help"     ,sub { print _help(); exit 0; },
355                         $Options{"GetOptions_args"},
356                         ) || @ARGV;
357
358         for my $subdir (map((!$_ ? () : @$_),$Options{"subdirs"})) {
359                 local $CWD=$subdir;
360                 _system "./autogen.pl",@{$Options{"ARGV"}},"--dist";    # use "--dist" just as fallback!
361                 }
362
363         for my $dir (_cvsdirs(".")) {
364                 my @cleanfilesfordir=_cleanfilesfordir $dir;
365                 _writefile $dir."/.cvsignore",map("$_\n",@cleanfilesfordir) if !$Options{"ARGV_fullclean"};
366                 _remove "nocheck",\1,map({ _expandclass("$dir/$_"); } grep({
367                                 $Options{"ARGV_fullclean"} or $_ ne ".cvsignore";
368                                 } @cleanfilesfordir));
369                 }
370         return if $Options{"ARGV_clean"} || $Options{"ARGV_fullclean"};
371
372         $Options{"aclocal_args"}=[qw(-I macros),map((!$_ ? () : @$_),$Options{"aclocal_args"})];
373         my $configure_in=_readfile("configure.in");
374         do { $$_=1 if !defined($$_) && $configure_in=~/^AM_GNU_GETTEXT\b/m; }
375                         for (\$Options{"want-gettextize"});
376         do { $$_=1 if !defined($$_) && $configure_in=~/^AM_PROG_LIBTOOL\b/m; }
377                         for (\$Options{"want-libtoolize"}); 
378         do { $$_=1 if !defined($$_) && $configure_in=~/^A[CM]_CONFIG_HEADER\b/m; }
379                         for (\$Options{"want-autoheader"});
380         my @copy_arg=(!$Options{"ARGV_copy"} ? () : "--copy");
381
382         do { &$_ if $_; } for ($Options{"prep"});
383         touch "po/POTFILES.in" if -d "po";
384         if ($Options{"want-gettextize"}) {
385                 # don't use multi-arg system() here as it would reject "</dev/null" redirection etc.
386                 for ("expect -c '"
387                                 .'spawn gettextize --intl --no-changelog '.join(" ",@copy_arg).';'
388                                 .'expect -timeout -1 "Press Return to acknowledge" {send "\r";exp_continue;} eof;'
389                                 ."'") {
390                         _system $_ and confess $_;
391                         }
392                 for ("configure.in","Makefile.am") {
393                         STDERR->printflush("gettextize recovery rename \"$_~\"->\"$_\"... ");
394                         rename "$_~","$_" or confess "$!";
395                         STDERR->printflush("ok\n");
396                         }
397                 if (!-e "po/Makevars") {
398                         my $Makevars_template="po/Makevars.template";
399                         my $makevars=_readfile $Makevars_template;
400                         $makevars=~s/^(COPYRIGHT_HOLDER)\b.*$/"$1=".$Options{"COPYRIGHT_HOLDER"}/meg
401                                         or confess "COPYRIGHT_HOLDER not found in $Makevars_template";
402                         _writefile "po/Makevars",$makevars;
403                         }
404                 # Prevent updating of contents during touch of any source file;
405                 # change the .po contents only when some data get updated
406                 for my $Makefile_in_in ("po/Makefile.in.in") {
407                         my $file=_readfile $Makefile_in_in;
408                         $file=~s%(\$\Q(MSGMERGE_UPDATE)\E) (\$\$\Q{lang}.po \E\$\Q(DOMAIN).pot\E)$%
409                                         $1.q< --backup=simple --suffix="~" >.$2.q<;>
410                                                         .q< if test `diff -u $${lang}.po~ $${lang}.po>
411                                                                                         .q< | sed>
412                                                                                                         .q< -e '1,/^@@.*@@$$/d'>
413                                                                                                         .q< -e '/^[+-]"POT-Creation-Date:/d'>
414                                                                                                         .q< -e '/^[^+-]/d'>
415                                                                                                         .q< -e '/^[+-]#/d'>
416                                                                                         .q< | wc -l` -eq 0;then>
417                                                                         .q< touch --reference=$${lang}.po $${lang}.po~;>
418                                                                                         .q< mv -f $${lang}.po~ $${lang}.po;>
419                                                         .q< else>
420                                                                         .q< rm -f $${lang}.po~;>
421                                                         .q< fi>
422                                         %me or confess;
423                         unlink $Makefile_in_in or confess "$!";
424                         _writefile $Makefile_in_in,$file;
425                         }
426                 }
427         _system "aclocal",map((!$_ ? () : @$_),$Options{"aclocal_args"});
428         _system qw(libtoolize),@copy_arg if $Options{"want-libtoolize"};
429         _system qw(autoheader) if $Options{"want-autoheader"};
430         # "ChangeLog" is reqd by automake(1)
431         # Don't remove it afterwards as it may still be needed during automatic automake Makefile rebuilds
432         File::Touch->new("atime_only"=>1)->touch("ChangeLog");
433         _system qw(automake --add-missing),@copy_arg;
434         _system qw(autoconf);
435         # Why it is left there after RedHat autoconf-2.53-8 ?
436         _remove "nocheck",\1,"autom4te-*.cache";
437
438         return if $Options{"ARGV_dist"};
439
440         # shared/static switching cannot be based on maintainer-mode in configure
441         _system(qw(./configure --enable-maintainer-mode),
442                         ($Options{"want-libtoolize"} && qw(--enable-shared --disable-static)),
443                         map((!$_ ? () : @$_),$Options{"configure_args"}),
444                         );
445 }
446
447 1;
448 __END__
449
450 Tested with:
451         RedHat autoconf-2.53-8
452         RedHat automake-1.6.3-1
453         RedHat gettext-0.11.4-3
454         RedHat libtool-1.4.2-12
455         RedHat perl-5.8.0-48