summaryrefslogtreecommitdiff
path: root/lib/Automake/Utils.pm
blob: 8f1c8c4af1c84e3128f1b4bc80227924c1956545 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# Copyright (C) 2018  Free Software Foundation, Inc.

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package Automake::Utils;

use 5.006;
use strict;

use Automake::Channels;
use Automake::ConfVars;
use Automake::Global;
use Automake::Location;
use Automake::Options;
use Automake::XFile;
use Automake::ChannelDefs;
use Automake::Variable 'var';
use Automake::Rule;
use Exporter 'import';
use File::Basename;

use vars qw (@EXPORT);

@EXPORT = qw ($config_aux_dir $am_config_aux_dir
    $config_aux_dir_set_in_configure_ac $relative_dir
    &var_SUFFIXES_trigger &locate_aux_dir &subst &flatten
    &canonicalize &push_dist_common &is_make_dir &backname &transform
    &get_number_of_threads &locate_am &prepend_srcdir
    &rewrite_inputs_into_dependencies &substitute_ac_subst_variables
    &check_directory);

# Directory to search for configure-required files.  This
# will be computed by locate_aux_dir() and can be set using
# AC_CONFIG_AUX_DIR in configure.ac.
# $CONFIG_AUX_DIR is the 'raw' directory, valid only in the source-tree.
our $config_aux_dir = '';

# $AM_CONFIG_AUX_DIR is prefixed with $(top_srcdir), so it can be used
# in Makefiles.
our $am_config_aux_dir;

our $config_aux_dir_set_in_configure_ac = 0;

# Relative dir of the output makefile.
our $relative_dir;

# var_SUFFIXES_trigger ($TYPE, $VALUE)
# ------------------------------------
# This is called by Automake::Variable::define() when SUFFIXES
# is defined ($TYPE eq '') or appended ($TYPE eq '+').
# The work here needs to be performed as a side-effect of the
# macro_define() call because SUFFIXES definitions impact
# on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
# the input am file.
sub var_SUFFIXES_trigger
{
    my ($type, $value) = @_;
    accept_extensions (split (' ', $value));
}


# Find the aux dir.  This should match the algorithm used by
# ./configure. (See the Autoconf documentation for for
# AC_CONFIG_AUX_DIR.)
sub locate_aux_dir
{
  if (! $config_aux_dir_set_in_configure_ac)
    {
      # The default auxiliary directory is the first
      # of ., .., or ../.. that contains install-sh.
      # Assume . if install-sh doesn't exist yet.
      for my $dir (qw (. .. ../..))
	{
	  if (-f "$dir/install-sh")
	    {
	      $config_aux_dir = $dir;
	      last;
	    }
	}
      $config_aux_dir = '.' unless $config_aux_dir;
    }
  # Avoid unsightly '/.'s.
  $am_config_aux_dir =
    '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
  $am_config_aux_dir =~ s,/*$,,;
}


# subst ($TEXT)
# -------------
# Return a configure-style substitution using the indicated text.
# We do this to avoid having the substitutions directly in automake.in;
# when we do that they are sometimes removed and this causes confusion
# and bugs.
sub subst ($)
{
    my ($text) = @_;
    return '@' . $text . '@';
}


# transform_token ($TOKEN, \%PAIRS, $KEY)
# ---------------------------------------
# Return the value associated to $KEY in %PAIRS, as used on $TOKEN
# (which should be ?KEY? or any of the special %% requests)..
sub transform_token ($\%$)
{
  my ($token, $transform, $key) = @_;
  my $res = $transform->{$key};
  prog_error "Unknown key '$key' in '$token'" unless defined $res;
  return $res;
}


# transform ($TOKEN, \%PAIRS)
# ---------------------------
# If ($TOKEN, $VAL) is in %PAIRS:
#   - replaces %KEY% with $VAL,
#   - enables/disables ?KEY? and ?!KEY?,
#   - replaces %?KEY% with TRUE or FALSE.
sub transform ($\%)
{
  my ($token, $transform) = @_;

  # %KEY%.
  # Must be before the following pattern to exclude the case
  # when there is neither IFTRUE nor IFFALSE.
  if ($token =~ /^%([\w\-]+)%$/)
    {
      return transform_token ($token, %$transform, $1);
    }
  # %?KEY%.
  elsif ($token =~ /^%\?([\w\-]+)%$/)
    {
      return transform_token ($token, %$transform, $1) ? 'TRUE' : 'FALSE';
    }
  # ?KEY? and ?!KEY?.
  elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
    {
      my $neg = ($1 eq '!') ? 1 : 0;
      my $val = transform_token ($token, %$transform, $2);
      return (!!$val == $neg) ? '##%' : '';
    }
  else
    {
      prog_error "Unknown request format: $token";
    }
}


# $STRING
# flatten ($ORIGINAL_STRING)
# --------------------------
sub flatten
{
  $_ = shift;

  s/\\\n//somg;
  s/\s+/ /g;
  s/^ //;
  s/ $//;

  return $_;
}


# Canonicalize the input parameter.
sub canonicalize
{
    my ($string) = @_;
    $string =~ tr/A-Za-z0-9_\@/_/c;
    return $string;
}


# Push a list of files onto '@dist_common'.
sub push_dist_common
{
  prog_error "push_dist_common run after handle_dist"
    if $handle_dist_run;
  push @dist_common, @_;
}

# Each key in this hash is the name of a directory holding a
# Makefile.in.  These variables are local to 'is_make_dir'.
my %make_dirs = ();
my $make_dirs_set = 0;

# is_make_dir ($DIRECTORY)
# ------------------------
sub is_make_dir
{
    my ($dir) = @_;
    if (! $make_dirs_set)
    {
	foreach my $iter (@configure_input_files)
	{
	    $make_dirs{dirname ($iter)} = 1;
	}
	# We also want to notice Makefile.in's.
	foreach my $iter (@other_input_files)
	{
	    if ($iter =~ /Makefile\.in$/)
	    {
		$make_dirs{dirname ($iter)} = 1;
	    }
	}
	$make_dirs_set = 1;
    }
    return defined $make_dirs{$dir};
}


# $BACKPATH
# backname ($RELDIR)
# -------------------
# If I "cd $RELDIR", then to come back, I should "cd $BACKPATH".
# For instance 'src/foo' => '../..'.
# Works with non strictly increasing paths, i.e., 'src/../lib' => '..'.
sub backname
{
    my ($file) = @_;
    my @res;
    foreach (split (/\//, $file))
    {
	next if $_ eq '.' || $_ eq '';
	if ($_ eq '..')
	{
	    pop @res
	      or prog_error ("trying to reverse path '$file' pointing outside tree");
	}
	else
	{
	    push (@res, '..');
	}
    }
    return join ('/', @res) || '.';
}


# Logic for deciding how many worker threads to use.
sub get_number_of_threads ()
{
  my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;

  $nthreads = 0
    unless $nthreads =~ /^[0-9]+$/;

  # It doesn't make sense to use more threads than makefiles,
  my $max_threads = @input_files;

  if ($nthreads > $max_threads)
    {
      $nthreads = $max_threads;
    }
  return $nthreads;
}



# $input
# locate_am (@POSSIBLE_SOURCES)
# -----------------------------
# AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
# This functions returns the first *.in file for which a *.am exists.
# It returns undef otherwise.
sub locate_am
{
  my (@rest) = @_;
  my $input;
  foreach my $file (@rest)
    {
      if (($file =~ /^(.*)\.in$/) && -f "$1.am")
	{
	  $input = $file;
	  last;
	}
    }
  return $input;
}


# @DEPENDENCIES
# prepend_srcdir (@INPUTS)
# ------------------------
# Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
# if an input file has a directory part the same as the current
# directory, then the directory part is simply replaced by $(srcdir).
# But if the directory part is different, then $(top_srcdir) is
# prepended.
sub prepend_srcdir
{
  my (@inputs) = @_;
  my @newinputs;

  foreach my $single (@inputs)
    {
      if (dirname ($single) eq $relative_dir)
	{
	  push (@newinputs, '$(srcdir)/' . basename ($single));
	}
      else
	{
	  push (@newinputs, '$(top_srcdir)/' . $single);
	}
    }
  return @newinputs;
}


# Helper function for 'substitute_ac_subst_variables'.
sub substitute_ac_subst_variables_worker
{
  my ($token) = @_;
  return "\@$token\@" if var $token;
  return "\${$token\}";
}


# substitute_ac_subst_variables ($TEXT)
# -------------------------------------
# Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
# variable.
sub substitute_ac_subst_variables
{
  my ($text) = @_;
  $text =~ s/\$[{]([^ \t=:+{}]+)}/substitute_ac_subst_variables_worker ($1)/ge;
  return $text;
}


# @DEPENDENCIES
# rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
# ---------------------------------------------------
# Compute a list of dependencies appropriate for the rebuild
# rule of
#   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
# Also distribute $INPUTs which are not built by another AC_CONFIG_FOOs.
sub rewrite_inputs_into_dependencies
{
  my ($file, @inputs) = @_;
  my @res = ();

  for my $i (@inputs)
    {
      # We cannot create dependencies on shell variables.
      next if (substitute_ac_subst_variables $i) =~ /\$/;

      if (exists $ac_config_files_location{$i} && $i ne $file)
	{
	  my $di = dirname $i;
	  if ($di eq $relative_dir)
	    {
	      $i = basename $i;
	    }
	  # In the top-level Makefile we do not use $(top_builddir), because
	  # we are already there, and since the targets are built without
	  # a $(top_builddir), it helps BSD Make to match them with
	  # dependencies.
	  elsif ($relative_dir ne '.')
	    {
	      $i = '$(top_builddir)/' . $i;
	    }
	}
      else
	{
	  msg ('error', $ac_config_files_location{$file},
	       "required file '$i' not found")
	    unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
	  ($i) = prepend_srcdir ($i);
	  push_dist_common ($i);
	}
      push @res, $i;
    }
  return @res;
}


# check_directory ($NAME, $WHERE [, $RELATIVE_DIR = "."])
# -------------------------------------------------------
# Ensure $NAME is a directory (in $RELATIVE_DIR), and that it uses a sane
# name.  Use $WHERE as a location in the diagnostic, if any.
sub check_directory
{
  my ($dir, $where, $reldir) = @_;
  $reldir = '.' unless defined $reldir;

  error $where, "required directory $reldir/$dir does not exist"
    unless -d "$reldir/$dir";

  # If an 'obj/' directory exists, BSD make will enter it before
  # reading 'Makefile'.  Hence the 'Makefile' in the current directory
  # will not be read.
  #
  #  % cat Makefile
  #  all:
  #          echo Hello
  #  % cat obj/Makefile
  #  all:
  #          echo World
  #  % make      # GNU make
  #  echo Hello
  #  Hello
  #  % pmake     # BSD make
  #  echo World
  #  World
  msg ('portability', $where,
       "naming a subdirectory 'obj' causes troubles with BSD make")
    if $dir eq 'obj';

  # 'aux' is probably the most important of the following forbidden name,
  # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
  msg ('portability', $where,
       "name '$dir' is reserved on W32 and DOS platforms")
    if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
}


1;