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