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