Debian Codegraph @

lib/Autom4te/FileUtils.pm

raw
1 # Copyright (C) 2003-2025 Free Software Foundation, Inc.
2
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.
7
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.
12
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/>.
15
16 ##################################################################
17 # The master copy of this file is in Automake's source repository.
18 # Please send updates to [email protected].
19 ##################################################################
20
21 package Autom4te::FileUtils;
22
23 =head1 NAME
24
25 Autom4te::FileUtils - handling files
26
27 =head1 SYNOPSIS
28
29 use Autom4te::FileUtils
30
31 =head1 DESCRIPTION
32
33 This perl module provides various general purpose file handling functions.
34
35 =cut
36
37 use 5.006; use strict; use warnings;
38
39 BEGIN
40 {
41 require Exporter;
42 our @ISA = qw (Exporter);
43 our @EXPORT = qw (&contents
44 &find_file &mtime
45 &update_file
46 &xsystem &xsystem_hint &xqx
47 &dir_has_case_matching_file &reset_dir_cache
48 &set_dir_cache_file);
49 }
50
51 # Use sub-second resolution file timestamps if available, carry on
52 # with one-second resolution timestamps if Time::HiRes is not available.
53 #
54 # Unfortunately, even if Time::HiRes is available, we don't get
55 # timestamps to the full precision recorded by the operating system,
56 # because Time::HiRes converts timestamps to floating-point, and the
57 # rounding error is hundreds of nanoseconds for circa-2023 timestamps
58 # in IEEE double precision. But this is the best we can do without
59 # dropping down to C.
60 #
61 # $subsecond_mtime is not exported, but is intended for external
62 # consumption, as $Autom4te::FileUtils::subsecond_mtime.
63 BEGIN
64 {
65 our $subsecond_mtime = 0;
66 eval
67 {
68 require Time::HiRes;
69 import Time::HiRes qw(stat);
70 $subsecond_mtime = 1;
71 }
72 }
73
74 use IO::File;
75 use Autom4te::Channels;
76 use Autom4te::ChannelDefs;
77
78 =over 4
79
80 =item C<find_file ($file_name, @include)>
81
82 Return the first path for a C<$file_name> in the C<include>s.
83
84 We match exactly the behavior of GNU M4: first look in the current
85 directory (which includes the case of absolute file names), and then,
86 if the file name is not absolute, look in C<@include>.
87
88 If the file is flagged as optional (ends with C<?>), then return undef
89 if absent, otherwise exit with error.
90
91 =cut
92
93 # $FILE_NAME
94 # find_file ($FILE_NAME, @INCLUDE)
95 # --------------------------------
96 sub find_file ($@)
97 {
98 use File::Spec;
99
100 my ($file_name, @include) = @_;
101 my $optional = 0;
102
103 $optional = 1
104 if $file_name =~ s/\?$//;
105
106 return File::Spec->canonpath ($file_name)
107 if -e $file_name;
108
109 if (!File::Spec->file_name_is_absolute ($file_name))
110 {
111 foreach my $path (@include)
112 {
113 return File::Spec->canonpath (File::Spec->catfile ($path, $file_name))
114 if -e File::Spec->catfile ($path, $file_name)
115 }
116 }
117
118 fatal "$file_name: no such file or directory"
119 unless $optional;
120 return undef;
121 }
122
123 =item C<mtime ($file)>
124
125 Return the mtime of C<$file>. Missing files, or C<-> standing for
126 C<STDIN> or C<STDOUT> are "obsolete", i.e., as old as possible.
127
128 =cut
129
130 # $MTIME
131 # MTIME ($FILE)
132 # -------------
133 sub mtime ($)
134 {
135 my ($file) = @_;
136
137 return 0
138 if $file eq '-' || ! -f $file;
139
140 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
141 $atime,$mtime,$ctime,$blksize,$blocks) = stat ($file)
142 or fatal "cannot stat $file: $!";
143
144 return $mtime;
145 }
146
147
148 =item C<update_file ($from, $to, [$force])>
149
150 Rename C<$from> as C<$to>, preserving C<$to> timestamp if it has not
151 changed, unless C<$force> is true (defaults to false). Recognize
152 C<$to> = C<-> standing for C<STDIN>. C<$from> is always
153 removed/renamed.
154
155 =cut
156
157 # &update_file ($FROM, $TO; $FORCE)
158 # ---------------------------------
159 sub update_file ($$;$)
160 {
161 my ($from, $to, $force) = @_;
162 $force = 0
163 unless defined $force;
164 my $SIMPLE_BACKUP_SUFFIX = $ENV{'SIMPLE_BACKUP_SUFFIX'} || '~';
165 use File::Compare;
166 use File::Copy;
167
168 if ($to eq '-')
169 {
170 my $in = new IO::File $from, "<";
171 my $out = new IO::File (">-");
172 while ($_ = $in->getline)
173 {
174 print $out $_;
175 }
176 $in->close;
177 unlink ($from) || fatal "cannot remove $from: $!";
178 return;
179 }
180
181 if (!$force && -f "$to" && compare ("$from", "$to") == 0)
182 {
183 # File didn't change, so don't update its mod time.
184 msg 'note', "'$to' is unchanged";
185 unlink ($from)
186 or fatal "cannot remove $from: $!";
187 return
188 }
189
190 if (-f "$to")
191 {
192 # Back up and install the new one.
193 move ("$to", "$to$SIMPLE_BACKUP_SUFFIX")
194 or fatal "cannot backup $to: $!";
195 move ("$from", "$to")
196 or fatal "cannot rename $from as $to: $!";
197 msg 'note', "'$to' is updated";
198 }
199 else
200 {
201 move ("$from", "$to")
202 or fatal "cannot rename $from as $to: $!";
203 msg 'note', "'$to' is created";
204 }
205 }
206
207
208 =item C<handle_exec_errors ($command, [$expected_exit_code = 0], [$hint])>
209
210 Display an error message for C<$command>, based on the content of
211 C<$?> and C<$!>. Be quiet if the command exited normally
212 with C<$expected_exit_code>. If C<$hint> is given, display that as well
213 if the command failed to run at all.
214
215 =cut
216
217 sub handle_exec_errors ($;$$)
218 {
219 my ($command, $expected, $hint) = @_;
220 $expected = 0 unless defined $expected;
221 if (defined $hint)
222 {
223 $hint = "\n" . $hint;
224 }
225 else
226 {
227 $hint = '';
228 }
229
230 $command = (split (' ', $command))[0];
231 if ($!)
232 {
233 fatal "failed to run $command: $!" . $hint;
234 }
235 else
236 {
237 use POSIX qw (WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG);
238
239 if (WIFEXITED ($?))
240 {
241 my $status = WEXITSTATUS ($?);
242 # Propagate exit codes.
243 fatal ('',
244 "$command failed with exit status: $status",
245 exit_code => $status)
246 unless $status == $expected;
247 }
248 elsif (WIFSIGNALED ($?))
249 {
250 my $signal = WTERMSIG ($?);
251 fatal "$command terminated by signal: $signal";
252 }
253 else
254 {
255 fatal "$command exited abnormally";
256 }
257 }
258 }
259
260 =item C<xqx ($command)>
261
262 Same as C<qx> (but in scalar context), but fails on errors.
263
264 =cut
265
266 # xqx ($COMMAND)
267 # --------------
268 sub xqx ($)
269 {
270 my ($command) = @_;
271
272 verb "running: $command";
273
274 $! = 0;
275 my $res = `$command`;
276 handle_exec_errors $command
277 if $?;
278
279 return $res;
280 }
281
282
283 =item C<xsystem (@argv)>
284
285 Same as C<system>, but fails on errors, and reports the C<@argv>
286 in verbose mode.
287
288 =cut
289
290 sub xsystem (@)
291 {
292 my (@command) = @_;
293
294 verb "running: @command";
295
296 $! = 0;
297 handle_exec_errors "@command"
298 if system @command;
299 }
300
301
302 =item C<xsystem_hint ($msg, @argv)>
303
304 Same as C<xsystem>, but allows to pass a hint that will be displayed
305 in case the command failed to run at all.
306
307 =cut
308
309 sub xsystem_hint (@)
310 {
311 my ($hint, @command) = @_;
312
313 verb "running: @command";
314
315 $! = 0;
316 handle_exec_errors "@command", 0, $hint
317 if system @command;
318 }
319
320
321 =item C<contents ($file_name)>
322
323 Return the contents of C<$file_name>.
324
325 =cut
326
327 # contents ($FILE_NAME)
328 # ---------------------
329 sub contents ($)
330 {
331 my ($file) = @_;
332 verb "reading $file";
333 local $/; # Turn on slurp-mode.
334 my $f = new Autom4te::XFile $file, "<";
335 my $contents = $f->getline;
336 $f->close;
337 return $contents;
338 }
339
340
341 =item C<dir_has_case_matching_file ($DIRNAME, $FILE_NAME)>
342
343 Return true iff $DIR contains a file name that matches $FILE_NAME case
344 insensitively.
345
346 We need to be cautious on case-insensitive case-preserving file
347 systems (e.g. Mac OS X's HFS+). On such systems C<-f 'Foo'> and C<-f
348 'foO'> answer the same thing. Hence if a package distributes its own
349 F<CHANGELOG> file, but has no F<ChangeLog> file, automake would still
350 try to distribute F<ChangeLog> (because it thinks it exists) in
351 addition to F<CHANGELOG>, although it is impossible for these two
352 files to be in the same directory (the two file names designate the
353 same file).
354
355 =cut
356
357 our %_directory_cache;
358 sub dir_has_case_matching_file ($$)
359 {
360 # Note that print File::Spec->case_tolerant returns 0 even on MacOS
361 # X (with Perl v5.8.1-RC3 at least), so do not try to shortcut this
362 # function using that.
363
364 my ($dirname, $file_name) = @_;
365 return 0 unless -f "$dirname/$file_name";
366
367 # The file appears to exist, however it might be a mirage if the
368 # system is case insensitive. Let's browse the directory and check
369 # whether the file is really in. We maintain a cache of directories
370 # so Automake doesn't spend all its time reading the same directory
371 # again and again.
372 if (!exists $_directory_cache{$dirname})
373 {
374 error "failed to open directory '$dirname'"
375 unless opendir (DIR, $dirname);
376 $_directory_cache{$dirname} = { map { $_ => 1 } readdir (DIR) };
377 closedir (DIR);
378 }
379 return exists $_directory_cache{$dirname}{$file_name};
380 }
381
382 =item C<reset_dir_cache ($dirname)>
383
384 Clear C<dir_has_case_matching_file>'s cache for C<$dirname>.
385
386 =cut
387
388 sub reset_dir_cache ($)
389 {
390 delete $_directory_cache{$_[0]};
391 }
392
393 =item C<set_dir_cache_file ($dirname, $file_name)>
394
395 State that C<$dirname> contains C<$file_name> now.
396
397 =cut
398
399 sub set_dir_cache_file ($$)
400 {
401 my ($dirname, $file_name) = @_;
402 $_directory_cache{$dirname}{$file_name} = 1
403 if exists $_directory_cache{$dirname};
404 }
405
406 =back
407
408 =cut
409
410 1; # for require
411
412 ### Setup "GNU" style for perl-mode and cperl-mode.
413 ## Local Variables:
414 ## perl-indent-level: 2
415 ## perl-continued-statement-offset: 2
416 ## perl-continued-brace-offset: 0
417 ## perl-brace-offset: 0
418 ## perl-brace-imaginary-offset: 0
419 ## perl-label-offset: -2
420 ## cperl-indent-level: 2
421 ## cperl-brace-offset: 0
422 ## cperl-continued-brace-offset: 0
423 ## cperl-label-offset: -2
424 ## cperl-extra-newline-before-brace: t
425 ## cperl-merge-trailing-else: nil
426 ## cperl-continued-statement-offset: 2
427 ## End: