lib: fix update_file timestamps
[autoconf.git] / lib / Autom4te / FileUtils.pm
blob16b2de97efdbf4a1c23d7b93c5e9fe4f521d3217
1 # Copyright (C) 2003-2017 Free Software Foundation, Inc.
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <https://www.gnu.org/licenses/>.
16 ###############################################################
17 # The main copy of this file is in Automake's git repository. #
18 # Updates should be sent to automake-patches@gnu.org. #
19 ###############################################################
21 package Autom4te::FileUtils;
23 =head1 NAME
25 Autom4te::FileUtils - handling files
27 =head1 SYNOPSIS
29 use Autom4te::FileUtils
31 =head1 DESCRIPTION
33 This perl module provides various general purpose file handling functions.
35 =cut
37 use 5.006;
38 use strict;
39 use Exporter;
40 use File::stat;
41 use IO::File;
42 use Autom4te::Channels;
43 use Autom4te::ChannelDefs;
45 use vars qw (@ISA @EXPORT);
47 @ISA = qw (Exporter);
48 @EXPORT = qw (&contents
49 &find_file &mtime
50 &update_file &up_to_date_p
51 &xsystem &xsystem_hint &xqx
52 &dir_has_case_matching_file &reset_dir_cache
53 &set_dir_cache_file);
55 =item C<find_file ($file_name, @include)>
57 Return the first path for a C<$file_name> in the C<include>s.
59 We match exactly the behavior of GNU M4: first look in the current
60 directory (which includes the case of absolute file names), and then,
61 if the file name is not absolute, look in C<@include>.
63 If the file is flagged as optional (ends with C<?>), then return undef
64 if absent, otherwise exit with error.
66 =cut
68 # $FILE_NAME
69 # find_file ($FILE_NAME, @INCLUDE)
70 # --------------------------------
71 sub find_file ($@)
73 use File::Spec;
75 my ($file_name, @include) = @_;
76 my $optional = 0;
78 $optional = 1
79 if $file_name =~ s/\?$//;
81 return File::Spec->canonpath ($file_name)
82 if -e $file_name;
84 if (!File::Spec->file_name_is_absolute ($file_name))
86 foreach my $path (@include)
88 return File::Spec->canonpath (File::Spec->catfile ($path, $file_name))
89 if -e File::Spec->catfile ($path, $file_name)
93 fatal "$file_name: no such file or directory"
94 unless $optional;
95 return undef;
98 =item C<mtime ($file)>
100 Return the mtime of C<$file>. Missing files, or C<-> standing for
101 C<STDIN> or C<STDOUT> are "obsolete", i.e., as old as possible.
103 =cut
105 # $MTIME
106 # MTIME ($FILE)
107 # -------------
108 sub mtime ($)
110 my ($file) = @_;
112 return 0
113 if $file eq '-' || ! -f $file;
115 my $stat = stat ($file)
116 or fatal "cannot stat $file: $!";
118 return $stat->mtime;
122 =item C<update_file ($from, $to, [$force])>
124 Rename C<$from> as C<$to>, preserving C<$to> timestamp if it has not
125 changed, unless C<$force> is true (defaults to false). Recognize
126 C<$to> = C<-> standing for C<STDIN>. C<$from> is always
127 removed/renamed.
129 =cut
131 # &update_file ($FROM, $TO; $FORCE)
132 # ---------------------------------
133 sub update_file ($$;$)
135 my ($from, $to, $force) = @_;
136 $force = 0
137 unless defined $force;
138 my $SIMPLE_BACKUP_SUFFIX = $ENV{'SIMPLE_BACKUP_SUFFIX'} || '~';
139 use File::Compare;
140 use File::Copy;
142 if ($to eq '-')
144 my $in = new IO::File $from, "<";
145 my $out = new IO::File (">-");
146 while ($_ = $in->getline)
148 print $out $_;
150 $in->close;
151 unlink ($from) || fatal "cannot remove $from: $!";
152 return;
155 if (!$force && -f "$to" && compare ("$from", "$to") == 0)
157 # File didn't change, so don't update its mod time.
158 msg 'note', "'$to' is unchanged";
159 unlink ($from)
160 or fatal "cannot remove $from: $!";
161 return
164 my $exists = (-f "$to");
165 if ($exists)
167 # Back up any existing destination.
168 move ("$to", "$to$SIMPLE_BACKUP_SUFFIX")
169 or fatal "cannot backup $to: $!";
172 # Do not use move ("$from", "$to"), as it truncates file timestamps.
173 rename ("$from", "$to")
174 or system ("mv", "$from", "$to") == 0
175 or fatal "cannot rename $from as $to: $!";
177 msg 'note', ($exists ? "'$to' is updated" : "'$to is created")
181 =item C<up_to_date_p ($file, @dep)>
183 Is C<$file> more recent than C<@dep>?
185 =cut
187 # $BOOLEAN
188 # &up_to_date_p ($FILE, @DEP)
189 # ---------------------------
190 sub up_to_date_p ($@)
192 my ($file, @dep) = @_;
193 my $mtime = mtime ($file);
195 foreach my $dep (@dep)
197 if ($mtime < mtime ($dep))
199 verb "up_to_date ($file): outdated: $dep";
200 return 0;
204 verb "up_to_date ($file): up to date";
205 return 1;
209 =item C<handle_exec_errors ($command, [$expected_exit_code = 0], [$hint])>
211 Display an error message for C<$command>, based on the content of
212 C<$?> and C<$!>. Be quiet if the command exited normally
213 with C<$expected_exit_code>. If C<$hint> is given, display that as well
214 if the command failed to run at all.
216 =cut
218 sub handle_exec_errors ($;$$)
220 my ($command, $expected, $hint) = @_;
221 $expected = 0 unless defined $expected;
222 if (defined $hint)
224 $hint = "\n" . $hint;
226 else
228 $hint = '';
231 $command = (split (' ', $command))[0];
232 if ($!)
234 fatal "failed to run $command: $!" . $hint;
236 else
238 use POSIX qw (WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG);
240 if (WIFEXITED ($?))
242 my $status = WEXITSTATUS ($?);
243 # Propagate exit codes.
244 fatal ('',
245 "$command failed with exit status: $status",
246 exit_code => $status)
247 unless $status == $expected;
249 elsif (WIFSIGNALED ($?))
251 my $signal = WTERMSIG ($?);
252 fatal "$command terminated by signal: $signal";
254 else
256 fatal "$command exited abnormally";
261 =item C<xqx ($command)>
263 Same as C<qx> (but in scalar context), but fails on errors.
265 =cut
267 # xqx ($COMMAND)
268 # --------------
269 sub xqx ($)
271 my ($command) = @_;
273 verb "running: $command";
275 $! = 0;
276 my $res = `$command`;
277 handle_exec_errors $command
278 if $?;
280 return $res;
284 =item C<xsystem (@argv)>
286 Same as C<system>, but fails on errors, and reports the C<@argv>
287 in verbose mode.
289 =cut
291 sub xsystem (@)
293 my (@command) = @_;
295 verb "running: @command";
297 $! = 0;
298 handle_exec_errors "@command"
299 if system @command;
303 =item C<xsystem_hint ($msg, @argv)>
305 Same as C<xsystem>, but allows to pass a hint that will be displayed
306 in case the command failed to run at all.
308 =cut
310 sub xsystem_hint (@)
312 my ($hint, @command) = @_;
314 verb "running: @command";
316 $! = 0;
317 handle_exec_errors "@command", 0, $hint
318 if system @command;
322 =item C<contents ($file_name)>
324 Return the contents of C<$file_name>.
326 =cut
328 # contents ($FILE_NAME)
329 # ---------------------
330 sub contents ($)
332 my ($file) = @_;
333 verb "reading $file";
334 local $/; # Turn on slurp-mode.
335 my $f = new Autom4te::XFile $file, "<";
336 my $contents = $f->getline;
337 $f->close;
338 return $contents;
342 =item C<dir_has_case_matching_file ($DIRNAME, $FILE_NAME)>
344 Return true iff $DIR contains a file name that matches $FILE_NAME case
345 insensitively.
347 We need to be cautious on case-insensitive case-preserving file
348 systems (e.g. Mac OS X's HFS+). On such systems C<-f 'Foo'> and C<-f
349 'foO'> answer the same thing. Hence if a package distributes its own
350 F<CHANGELOG> file, but has no F<ChangeLog> file, automake would still
351 try to distribute F<ChangeLog> (because it thinks it exists) in
352 addition to F<CHANGELOG>, although it is impossible for these two
353 files to be in the same directory (the two file names designate the
354 same file).
356 =cut
358 use vars '%_directory_cache';
359 sub dir_has_case_matching_file ($$)
361 # Note that print File::Spec->case_tolerant returns 0 even on MacOS
362 # X (with Perl v5.8.1-RC3 at least), so do not try to shortcut this
363 # function using that.
365 my ($dirname, $file_name) = @_;
366 return 0 unless -f "$dirname/$file_name";
368 # The file appears to exist, however it might be a mirage if the
369 # system is case insensitive. Let's browse the directory and check
370 # whether the file is really in. We maintain a cache of directories
371 # so Automake doesn't spend all its time reading the same directory
372 # again and again.
373 if (!exists $_directory_cache{$dirname})
375 error "failed to open directory '$dirname'"
376 unless opendir (DIR, $dirname);
377 $_directory_cache{$dirname} = { map { $_ => 1 } readdir (DIR) };
378 closedir (DIR);
380 return exists $_directory_cache{$dirname}{$file_name};
383 =item C<reset_dir_cache ($dirname)>
385 Clear C<dir_has_case_matching_file>'s cache for C<$dirname>.
387 =cut
389 sub reset_dir_cache ($)
391 delete $_directory_cache{$_[0]};
394 =item C<set_dir_cache_file ($dirname, $file_name)>
396 State that C<$dirname> contains C<$file_name> now.
398 =cut
400 sub set_dir_cache_file ($$)
402 my ($dirname, $file_name) = @_;
403 $_directory_cache{$dirname}{$file_name} = 1
404 if exists $_directory_cache{$dirname};
407 1; # for require