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