| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 |
|
| 15 | use strict;
|
| 16 |
|
| 17 | sub usage {
|
| 18 | print "Usage: checkincludes.pl [-r]\n";
|
| 19 | print "By default we just warn of duplicates\n";
|
| 20 | print "To remove duplicated includes in place use -r\n";
|
| 21 | exit 1;
|
| 22 | }
|
| 23 |
|
| 24 | my $remove = 0;
|
| 25 |
|
| 26 | if ($#ARGV < 0) {
|
| 27 | usage();
|
| 28 | }
|
| 29 |
|
| 30 | if ($#ARGV >= 1) {
|
| 31 | if ($ARGV[0] =~ /^-/) {
|
| 32 | if ($ARGV[0] eq "-r") {
|
| 33 | $remove = 1;
|
| 34 | shift;
|
| 35 | } else {
|
| 36 | usage();
|
| 37 | }
|
| 38 | }
|
| 39 | }
|
| 40 |
|
| 41 | my $dup_counter = 0;
|
| 42 |
|
| 43 | foreach my $file (@ARGV) {
|
| 44 | open(my $f, '<', $file)
|
| 45 | or die "Cannot open $file: $!.\n";
|
| 46 |
|
| 47 | my %includedfiles = ();
|
| 48 | my @file_lines = ();
|
| 49 |
|
| 50 | while (<$f>) {
|
| 51 | if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
|
| 52 | ++$includedfiles{$1};
|
| 53 | }
|
| 54 | push(@file_lines, $_);
|
| 55 | }
|
| 56 |
|
| 57 | close($f);
|
| 58 |
|
| 59 | if (!$remove) {
|
| 60 | foreach my $filename (keys %includedfiles) {
|
| 61 | if ($includedfiles{$filename} > 1) {
|
| 62 | print "$file: $filename is included more than once.\n";
|
| 63 | ++$dup_counter;
|
| 64 | }
|
| 65 | }
|
| 66 | next;
|
| 67 | }
|
| 68 |
|
| 69 | open($f, '>', $file)
|
| 70 | or die("Cannot write to $file: $!");
|
| 71 |
|
| 72 | my $dups = 0;
|
| 73 | foreach (@file_lines) {
|
| 74 | if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
|
| 75 | foreach my $filename (keys %includedfiles) {
|
| 76 | if ($1 eq $filename) {
|
| 77 | if ($includedfiles{$filename} > 1) {
|
| 78 | $includedfiles{$filename}--;
|
| 79 | $dups++;
|
| 80 | ++$dup_counter;
|
| 81 | } else {
|
| 82 | print {$f} $_;
|
| 83 | }
|
| 84 | }
|
| 85 | }
|
| 86 | } else {
|
| 87 | print {$f} $_;
|
| 88 | }
|
| 89 | }
|
| 90 | if ($dups > 0) {
|
| 91 | print "$file: removed $dups duplicate includes\n";
|
| 92 | }
|
| 93 | close($f);
|
| 94 | }
|
| 95 |
|
| 96 | if ($dup_counter == 0) {
|
| 97 | print "No duplicate includes found.\n";
|
| 98 | }
|