]> git.draconx.ca Git - dxcommon.git/blob - scripts/fix-gnulib.pl
954780f42eeaaa998322adf454faac48468966e2
[dxcommon.git] / scripts / fix-gnulib.pl
1 #!/usr/bin/env perl
2 #
3 # Copyright © 2011-2012 Nick Bowler
4 #
5 # Prepare the Gnulib tree for inclusion into a non-recursive automake build.
6 # While the output of gnulib-tool is "include"-able if the --makefile-name
7 # option is used, it is still not suitable for non-recursive use for a couple
8 # reasons; chief among them is that filenames are not relative to the top
9 # source directory.
10 #
11 # This script postprocesses the gnulib-tool output to produce something that
12 # is intended to be suitable for inclusion into such non-recursive build
13 # environments.  Since the integration involves both configure.ac and
14 # Makefile.am, the output must be included into _both_.  Supposing the output
15 # is written to lib/gnulib.mk, you would add:
16 #
17 #   m4_include([lib/gnulib.mk]) # to configure.ac, after any call to gl_INIT
18 #   include $(top_srcdir)/lib/gnulib.mk # to Makefile.am
19 #
20 # You must also arrange for the Gnulib-generated header files to be built
21 # before the object files which depend on them; the most robust way to do this
22 # is by explicit prerequisites, for example:
23 #
24 #   bin_PROGRAMS = foo
25 #   $(foo_OBJECTS): $(gnulib_headers)
26 #
27 # The $(gnulib_headers) variable will expand to GNU-make order-only
28 # prerequisites when available, avoiding spurious incremental rebuilds when
29 # unused headers are changed.  If this feature is not available, it will
30 # expand to ordinary prerequisites.  It is therefore only appropriate for use
31 # in target prerequisites; the $(gnulib_raw_headers) variable may be used in
32 # other contexts when only the list of header files is required.
33 #
34 # This script also provides machinery for Gnulib symbol renaming via the
35 # glconfig.mk Makefile.am snippet; use of this feature is optional.
36 #
37 # Most of the specific transformations are documented below.
38 #
39 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
40 # This is free software: you are free to do what the fuck you want to.
41 # There is NO WARRANTY, to the extent permitted by law.
42
43 use strict;
44 use List::Compare;
45 use Getopt::Long;
46
47 my $output   = undef;
48 my $input    = undef;
49
50 my $line     = 0;
51
52 Getopt::Long::Configure("gnu_getopt", "no_auto_abbrev");
53 GetOptions(
54         "o|output=s"   => \$output,
55         "i|input=s"    => \$input,
56 );
57
58 open STDOUT, ">", $output or die "$output: $!\n" if (defined $output);
59 open STDIN,  "<", $input  or die "$input: $!\n"  if (defined $input);
60
61 my $printed_header = 0;
62 my (%allvars, %sourcevars);
63 my @cleanfiles;
64
65 sub drop {
66         undef $_;
67         next;
68 }
69
70 sub basename {
71         my $file = shift;
72         $file =~ m|(?:.+/)?([^/]+)/?|;
73         return $1;
74 }
75
76 sub mangle_file {
77         my $word = shift;
78
79         if ($word =~ /^\$\(([[:word:].]+)\)$/) {
80                 # Don't touch variables now, but record them for later.
81                 $sourcevars{$1} = 1;
82         } elsif ($word =~ /^\$\((?:top_)?(?:srcdir|builddir)\)/) {
83                 # Do nothing.  Generic transformation will take care of
84                 # $(srcdir) and $(builddir).
85         } elsif ($word =~ /^[[:word:].+\/-]+$/) {
86                 # Mangle the filename.  Assume that all relevant files start
87                 # with a non-dot (so we don't transform suffix rules) and
88                 # contain at least one dot (so we don't transform phony rules).
89                 $word = "lib/$word" if ($word =~ /^[^.]+\./);
90         } else {
91                 print STDERR "$0:$line: warning: unrecognized source file: $word\n";
92         }
93
94         return "$word";
95 }
96
97 sub mangle_variable {
98         my $raw = shift;
99
100         $raw =~ /([^=]+=)[[:space:]]*(.*)/s;
101         my ($left, @right) = ($1, split(/[[:space:]]+/, $2));
102
103         return join(" ", ($left, map(mangle_file($_), @right))) . "\n";
104 }
105
106 sub mangle_target {
107         my $raw = shift;
108
109         $raw =~ /([^:]+):[[:space:]]*(.*)/s;
110         my @left  = split(/[[:space:]]+/, $1);
111         my @right = split(/[[:space:]]+/, $2);
112
113         @left  = map(mangle_file($_), @left);
114         @right = map(mangle_file($_), @right);
115
116         return join(" ", @left) . ": " . join(" ", @right) . "\n";
117 }
118
119 while (<STDIN>) {
120         $line++;
121
122         # Combine line splices.
123         while (s/\\$//) {
124                 $line++;
125                 $_ = $_ . <STDIN>
126         }
127
128         next if (/^#/);
129
130         if (!$printed_header) {
131                 print "# Postprocessed by ", basename($0), "\n\n";
132                 print <<'EOF';
133 # BEGIN AUTOMAKE/M4 POLYGLOT \
134 m4_unquote(m4_argn([2], [
135 .PHONY: # Automake code follows
136
137 # This trick should define gnulib_orderonly to | iff we're using GNU make.
138 gnulib_have_orderonly = $(findstring order-only,$(.FEATURES))
139 gnulib_orderonly = $(gnulib_have_orderonly:order-only=|)
140 gnulib_core_headers =
141 gnulib_raw_headers = $(gnulib_core_headers)
142 gnulib_headers = $(gnulib_orderonly) $(gnulib_raw_headers)
143
144 # Oddly, gnulib tries to add to MOSTLYCLEANDIRS (which is *not* an automake
145 # variable) without defining it.
146 MOSTLYCLEANDIRS =
147 EOF
148
149                 $printed_header = 1;
150                 drop;
151         }
152
153         # For some reason, gnulib-tool adds core dumps to "make mostlyclean".
154         # Since these files are (hopefully!) not created by make, they should
155         # not be cleaned.
156         drop if (/^MOSTLYCLEANFILES.*core/);
157
158         # Some modules set AM_CPPFLAGS/AM_CFLAGS/etc. in a manner that is not
159         # useful for non-recursive builds.  Strip them out.
160         drop if (/^(AM_CPPFLAGS|AM_CFLAGS)/);
161
162         # Library dependencies are added automatically to libgnu.la by
163         # gnulib-tool.  Unfortunately, this means that everything linking
164         # against libgnu.la is forced to pull in the same deps, even if they're
165         # unneeded.  Furthermore, a libtool linker flag reordering bug prevents
166         # --as-needed from stripping out the useless deps, so it's better to
167         # handle them all manually.
168         drop if (/LDFLAGS/);
169
170         # Current uses of SUFFIXES in gnulib are pointless since Automake will
171         # figure it out all on its own.  Strip it out.
172         drop if (/SUFFIXES/);
173
174         # Rewrite automake hook targets to be more generic.
175         if (s/^(.*)-local:/\1-gnulib:/) {
176                 print ".PHONY: $1-gnulib\n";
177                 print "$1-local: $1-gnulib\n";
178                 s/$1-generic//;
179         }
180
181         # We need to mangle filenames in make variables; prepending a lib/ on
182         # relative paths.  The following should catch all variable assignments
183         # that need mangling.
184         if (/^([[:word:]]+)[[:space:]]*\+?=/) {
185                 $allvars{$1} = 1;
186
187                 if (/_SOURCES|CLEANFILES|EXTRA_DIST|[[:upper:]]+_H/) {
188                         $_ = mangle_variable($_);
189                 }
190         }
191
192         # BUILT_SOURCES has similar problems to recursive make: inadequate
193         # dependencies lead to incorrect builds.  Collect them into an
194         # ordinary variable so we can deal with them later.
195         s/BUILT_SOURCES/gnulib_core_headers/;
196
197         # Targets are similar to variables: the target and its dependencies
198         # need to be mangled.
199         if (/^[^\t].*:/) {
200                 $_ = mangle_target($_);
201         }
202
203         # MKDIR_P commands need to be fixed up; in principle Gnulib could also
204         # be patched here to use $(@D) instead (and thus automatically benefit
205         # from the target being fixed up), but this will do for now.
206         s/^(\t.*\$\(MKDIR_P\)) ([[:alnum:]]+)$/\1 lib\/\2/;
207
208         # When using conditional-dependencies, *CLEANFILES can end up
209         # depending on the configuration.  This means that "make distclean"
210         # may not actually delete everything if the configuration changes
211         # after building the package.  Stash all the variables for later so
212         # they can be moved outside of any conditional.
213         if (/(CLEANFILES|CLEANDIRS)[[:space:]]*\+=/) {
214                 push(@cleanfiles, $_);
215                 drop;
216         }
217
218         # Change t-$@ to $@-t as the former will break if $@ has a directory
219         # component.
220         s/t-\$@/\$\@-t/g;
221
222         # Finally, references to $(srcdir) and $(builddir) need to be fixed up.
223         s:\$\(srcdir\):\$\(top_srcdir\)/lib:g;
224         s:\$\(builddir\):\$\(top_builddir\)/lib:g;
225 } continue { s/(\n.)/\\\1/g; print; };
226
227 print <<'EOF';
228 gnulib_lt_objects = $(libgnu_la_OBJECTS) $(gl_LTLIBOBJS)
229 $(gnulib_lt_objects): $(gnulib_headers)
230 EOF
231 print @cleanfiles;
232
233 # Some filenames are AC_SUBSTed by the Gnulib macros, and thus we need to
234 # prepend lib/ if and only if they're not empty.  Unfortunately, make is not
235 # powerful to do this, so we need to put this transformation into configure
236 # itself by defining a new autoconf macro.
237
238 my $lc = List::Compare->new('-u', '-a', \%sourcevars, \%allvars);
239 my @vars = $lc->get_unique;
240
241 print <<'EOF';
242 if FALSE
243 ], [dnl M4 code follows
244
245 AC_SUBST([GLSRC], [lib])
246 AC_CONFIG_LIBOBJ_DIR([lib])
247
248 AC_DEFUN_ONCE([DX_GLSYM_PREFIX], [dnl
249 AC_REQUIRE([DX_EXPORTED_SH])
250 AC_SUBST([GLSYM_PREFIX], [$1])
251 ])
252 AC_CONFIG_COMMANDS_PRE([DX_GLSYM_PREFIX([${PACKAGE}__])])
253
254 m4_foreach([gl_objvar], [[gl_LIBOBJS], [gl_LTLIBOBJS]], [dnl
255 set x $gl_objvar; shift
256 gl_objvar=
257 while test ${#} -gt 0; do
258         gl_objvar="$gl_objvar lib/${1}"; shift
259 done
260 ])
261 EOF
262
263 foreach (@vars) {
264         print "$_=\${$_:+lib/\$$_}\n";
265 }
266
267 print <<'EOF';
268 ], [
269 endif
270 # ]))dnl
271 # END AUTOMAKE/M4 POLYGLOT
272 EOF