]> git.draconx.ca Git - dxcommon.git/blob - scripts/fix-gnulib.pl
a59e4a6e3d66b1eab748754fc33b6d5eba3349f8
[dxcommon.git] / scripts / fix-gnulib.pl
1 #!/usr/bin/env perl
2 #
3 # Copyright © 2011-2014, 2020-2021 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
12 # that is intended to be suitable for inclusion into such non-recursive
13 # build environments.  Since the integration involves both configure.ac
14 # and Makefile.am, the output must be included into _both_.  Supposing
15 # the output 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
22 # this 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
31 # use in target prerequisites; the $(gnulib_raw_headers) variable may be
32 # used in 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 Getopt::Long;
45
46 my $output   = undef;
47 my $input    = undef;
48
49 my $use_libtool = undef;
50 my $for_library = undef;
51
52 my $line     = 0;
53
54 Getopt::Long::Configure("gnu_getopt", "no_auto_abbrev");
55 GetOptions(
56         "o|output=s"   => \$output,
57         "i|input=s"    => \$input,
58         "library"      => sub { $for_library = 1; },
59         "program"      => sub { $for_library = 0; },
60 );
61
62 open STDOUT, ">", $output or die "$output: $!\n" if (defined $output);
63 open STDIN,  "<", $input  or die "$input: $!\n"  if (defined $input);
64
65 my $printed_header = 0;
66 my @cleanfiles;
67
68 # Hashes to record make variables used in the automake source.  The allvars
69 # hash contains variables actually assigned in the Makefile, sourcevars
70 # contains variables used as filenames.  Keys are the variable name, and
71 # the value is always set to 1.
72 my (%allvars, %sourcevars);
73
74 sub drop {
75         undef $_;
76         next;
77 }
78
79 sub basename {
80         my $file = shift;
81         $file =~ m|(?:.+/)?([^/]+)/?|;
82         return $1;
83 }
84
85 sub mangle_file {
86         my $word = shift;
87
88         if ($word =~ /^\$\(([[:word:].]+)\)$/) {
89                 # Don't touch variables now, but record them for later.
90                 $sourcevars{$1} = 1;
91         } elsif ($word =~ /^\$\((?:top_)?(?:srcdir|builddir)\)/) {
92                 # Do nothing.  Generic transformation will take care of
93                 # $(srcdir) and $(builddir).
94         } elsif ($word =~ /^[[:word:].+\/-]+$/) {
95                 # Mangle the filename.  Assume that all relevant files start
96                 # with a non-dot (so we don't transform suffix rules) and
97                 # contain at least one dot (so we don't transform phony rules).
98                 $word = "lib/$word" if ($word =~ /^[^.]+\./);
99         } else {
100                 print STDERR "$0:$line: warning: unrecognized source file: $word\n";
101         }
102
103         return "$word";
104 }
105
106 sub mangle_variable {
107         my $raw = shift;
108
109         $raw =~ /([^=]+=)[[:space:]]*(.*)/s;
110         my ($left, @right) = ($1, split(/[[:space:]]+/, $2));
111
112         return join(" ", ($left, map(mangle_file($_), @right))) . "\n";
113 }
114
115 sub mangle_target {
116         my $raw = shift;
117
118         $raw =~ /([^:]+):[[:space:]]*(.*)/s;
119         my @left  = split(/[[:space:]]+/, $1);
120         my @right = split(/[[:space:]]+/, $2);
121
122         @left  = map(mangle_file($_), @left);
123         @right = map(mangle_file($_), @right);
124
125         return join(" ", @left) . ": " . join(" ", @right) . "\n";
126 }
127
128 while (<STDIN>) {
129         $line++;
130
131         # Combine line splices.
132         while (s/\\$//) {
133                 $line++;
134                 $_ = $_ . <STDIN>
135         }
136
137         next if (/^#/);
138
139         if (!$printed_header) {
140                 print "# Postprocessed by ", basename($0), "\n\n";
141                 print <<'EOF';
142 # BEGIN AUTOMAKE/M4 POLYGLOT \
143 m4_unquote(m4_argn([2], [
144 .PHONY: # Automake code follows
145
146 # This trick should define gnulib_orderonly to | iff we're using GNU make.
147 gnulib_make_features = $(.FEATURES)
148 gnulib_have_orderonly = $(findstring order-only,$(gnulib_make_features))
149 gnulib_orderonly = $(gnulib_have_orderonly:order-only=|)
150 gnulib_core_headers =
151 gnulib_raw_headers = $(gnulib_core_headers)
152 gnulib_headers = $(gnulib_orderonly) $(gnulib_raw_headers)
153
154 # Oddly, gnulib tries to add to MOSTLYCLEANDIRS (which is *not* an automake
155 # variable) without defining it.
156 MOSTLYCLEANDIRS =
157 EOF
158
159                 $printed_header = 1;
160                 drop;
161         }
162
163         # Locate the libgnu definition to determine whether or not the user is
164         # using libtool mode in gnulib-tool.  Default to program mode if they
165         # are not, which will avoid pulling in the glsym dependencies.
166         #
167         # Convert noinst to EXTRA, that way libgnu will not be built unless
168         # something actually depends on it (which is typically the case).
169         if (/^noinst_LIBRARIES.*libgnu.a/) {
170                 s/^noinst/EXTRA/;
171                 $for_library //= 0;
172                 $use_libtool = 0;
173         }
174         if (/^noinst_LTLIBRARIES.*libgnu.la/) {
175                 s/^noinst/EXTRA/;
176                 $for_library //= 1;
177                 $use_libtool = 1;
178         }
179
180         # For some reason, gnulib-tool adds core dumps to "make mostlyclean".
181         # Since these files are (hopefully!) not created by make, they should
182         # not be cleaned.
183         drop if (/^MOSTLYCLEANFILES.*core/);
184
185         # Some modules set AM_CPPFLAGS/AM_CFLAGS/etc. in a manner that is not
186         # useful for non-recursive builds.  Strip them out.
187         drop if (/^(AM_CPPFLAGS|AM_CFLAGS)/);
188
189         # Library dependencies are added automatically to libgnu.la by
190         # gnulib-tool.  Unfortunately, this means that everything linking
191         # against libgnu.la is forced to pull in the same deps, even if they're
192         # unneeded.  Furthermore, a libtool linker flag reordering bug prevents
193         # --as-needed from stripping out the useless deps, so it's better to
194         # handle them all manually.
195         drop if (/LDFLAGS/);
196
197         # Current uses of SUFFIXES in gnulib are pointless since Automake will
198         # figure it out all on its own.  Strip it out.
199         drop if (/SUFFIXES/);
200
201         # Rewrite automake hook targets to be more generic.
202         if (s/^(.*)-local:/\1-gnulib:/) {
203                 print ".PHONY: $1-gnulib\n";
204                 print "$1-local: $1-gnulib\n";
205                 s/$1-generic//;
206         }
207
208         # We need to mangle filenames in make variables; prepending a lib/ on
209         # relative paths.  The following should catch all variable assignments
210         # that need mangling.
211         if (/^([[:word:]]+)[[:space:]]*\+?=/) {
212                 $allvars{$1} = 1;
213
214                 if (/_SOURCES|CLEANFILES|EXTRA_DIST|[[:upper:]]+_H/) {
215                         $_ = mangle_variable($_);
216                 }
217         }
218
219         # BUILT_SOURCES has similar problems to recursive make: inadequate
220         # dependencies lead to incorrect builds.  Collect them into an
221         # ordinary variable so we can deal with them later.
222         s/BUILT_SOURCES/gnulib_core_headers/;
223
224         # Targets are similar to variables: the target and its dependencies
225         # need to be mangled.
226         if (/^[^\t].*:/) {
227                 $_ = mangle_target($_);
228         }
229
230         # MKDIR_P commands need to be fixed up; in principle Gnulib could also
231         # be patched here to use $(@D) instead (and thus automatically benefit
232         # from the target being fixed up), but this will do for now.
233         s/^(\t.*\$\(MKDIR_P\)) ([[:alnum:]]+)$/\1 lib\/\2/;
234
235         # When using conditional-dependencies, *CLEANFILES can end up
236         # depending on the configuration.  This means that "make distclean"
237         # may not actually delete everything if the configuration changes
238         # after building the package.  Stash all the variables for later so
239         # they can be moved outside of any conditional.
240         if (/(CLEANFILES|CLEANDIRS)[[:space:]]*\+=/) {
241                 push(@cleanfiles, $_);
242                 drop;
243         }
244
245         # Change t-$@ to $@-t as the former will break if $@ has a directory
246         # component.
247         s/t-\$@/\$\@-t/g;
248
249         # Finally, references to $(srcdir) and $(builddir) need to be fixed up.
250         s:\$\(srcdir\):\$\(top_srcdir\)/lib:g;
251         s:\$\(builddir\):\$\(top_builddir\)/lib:g;
252 } continue { s/(\n.)/\\\1/g; print; };
253
254 print <<'EOF' if ($use_libtool);
255 gnulib_lt_objects = $(libgnu_la_OBJECTS) $(gl_LTLIBOBJS)
256 gnulib_objects = $(gnulib_lt_objects)
257 $(gnulib_objects): $(gnulib_headers)
258 EOF
259 print <<'EOF' if (!$use_libtool);
260 gnulib_objects = $(libgnu_a_OBJECTS) $(gl_LIBOBJS)
261 $(gnulib_objects): $(gnulib_headers)
262 EOF
263
264 print @cleanfiles;
265
266 print <<'EOF';
267 if FALSE
268 ], [dnl M4 code follows
269
270 AC_SUBST([GLSRC], [lib])
271 AC_CONFIG_LIBOBJ_DIR([lib])
272
273 AC_DEFUN_ONCE([DX_GLSYM_PREFIX], [dnl
274 AC_REQUIRE([DX_EXPORTED_SH])
275 AC_SUBST([GLSYM_PREFIX], [$1])
276 ])
277 EOF
278
279 print <<'EOF' if ($for_library);
280 AC_CONFIG_COMMANDS_PRE([DX_GLSYM_PREFIX([${PACKAGE}__])])
281 EOF
282
283 print <<'EOF';
284 m4_foreach([gl_objvar], [[gl_LIBOBJS], [gl_LTLIBOBJS]], [dnl
285 set x $gl_objvar; shift
286 gl_objvar=
287 while test ${#} -gt 0; do
288         gl_objvar="$gl_objvar lib/${1}"; shift
289 done
290 ])
291 EOF
292
293 # Some filenames are AC_SUBSTed by the Gnulib macros, and thus we need to
294 # prepend lib/ if and only if they're not empty.  Unfortunately, make is not
295 # powerful to do this, so we need to put this transformation into configure
296 # itself by defining a new autoconf macro.
297
298 foreach (keys %sourcevars) {
299         print "$_=\${$_:+lib/\$$_}\n" unless $allvars{$_};
300 }
301
302 print <<'EOF';
303 ], [
304 endif
305 # ]))dnl
306 # END AUTOMAKE/M4 POLYGLOT
307 EOF