| 1 |
#!/usr/bin/perl |
| 2 |
|
| 3 |
use v5.36; |
| 4 |
use autodie; |
| 5 |
use warnings; |
| 6 |
|
| 7 |
use File::Basename qw(dirname); |
| 8 |
use File::Spec(); |
| 9 |
use Getopt::Long; |
| 10 |
|
| 11 |
my $opt_includes = 1; |
| 12 |
|
| 13 |
GetOptions( |
| 14 |
'includes!' => \$opt_includes, |
| 15 |
) or exit 1; |
| 16 |
|
| 17 |
if (@ARGV) { |
| 18 |
dump_file($_) for @ARGV; |
| 19 |
} |
| 20 |
else { |
| 21 |
dump_handle(\*STDIN); |
| 22 |
} |
| 23 |
|
| 24 |
my %file_seen; |
| 25 |
my $current_file; |
| 26 |
|
| 27 |
sub dump_file { |
| 28 |
my $file = shift; |
| 29 |
|
| 30 |
if ($file_seen{$file}++) { |
| 31 |
print "# file '$file' already seen\n"; |
| 32 |
return; |
| 33 |
} |
| 34 |
|
| 35 |
my $save_current_file = $current_file; |
| 36 |
$current_file = $file; |
| 37 |
open my $fh, '<', $file; |
| 38 |
print "# $file start\n"; |
| 39 |
dump_handle($fh); |
| 40 |
print "# $file end\n"; |
| 41 |
|
| 42 |
$current_file = $save_current_file; |
| 43 |
} |
| 44 |
|
| 45 |
sub dump_handle { |
| 46 |
my $fh = shift; |
| 47 |
my $line_no = 0; |
| 48 |
while (defined(my $line = <$fh>)) { |
| 49 |
$line_no++; |
| 50 |
|
| 51 |
if ($opt_includes and $line =~ /^\s*include\s+(.+?)\s*$/) { |
| 52 |
my $new_file = $1; |
| 53 |
if (File::Spec->file_name_is_absolute($new_file)) { |
| 54 |
my @matches = glob($new_file); |
| 55 |
die "line $line_no: no matches for '$new_file'\n" unless @matches; |
| 56 |
dump_file($_) for @matches; |
| 57 |
} |
| 58 |
else { |
| 59 |
die |
| 60 |
"line $line_no: can't include a relative file name when processing a stream\n" |
| 61 |
unless $current_file; |
| 62 |
|
| 63 |
my @matches = |
| 64 |
glob File::Spec->catfile(dirname($current_file), $new_file); |
| 65 |
die "line $line_no: no matches for '$new_file'\n" unless @matches; |
| 66 |
dump_file($_) for @matches; |
| 67 |
} |
| 68 |
} |
| 69 |
else { |
| 70 |
print $line; |
| 71 |
} |
| 72 |
} |
| 73 |
} |