Back to home page

LXR

 
 

    


0001 #!/usr/bin/perl
0002 #
0003 # checkincludes: find/remove files included more than once
0004 #
0005 # Copyright abandoned, 2000, Niels Kristian Bech Jensen <nkbj@image.dk>.
0006 # Copyright 2009 Luis R. Rodriguez <mcgrof@gmail.com>
0007 #
0008 # This script checks for duplicate includes. It also has support
0009 # to remove them in place. Note that this will not take into
0010 # consideration macros so you should run this only if you know
0011 # you do have real dups and do not have them under #ifdef's. You
0012 # could also just review the results.
0013 
0014 use strict;
0015 
0016 sub usage {
0017     print "Usage: checkincludes.pl [-r]\n";
0018     print "By default we just warn of duplicates\n";
0019     print "To remove duplicated includes in place use -r\n";
0020     exit 1;
0021 }
0022 
0023 my $remove = 0;
0024 
0025 if ($#ARGV < 0) {
0026     usage();
0027 }
0028 
0029 if ($#ARGV >= 1) {
0030     if ($ARGV[0] =~ /^-/) {
0031         if ($ARGV[0] eq "-r") {
0032             $remove = 1;
0033             shift;
0034         } else {
0035             usage();
0036         }
0037     }
0038 }
0039 
0040 foreach my $file (@ARGV) {
0041     open(my $f, '<', $file)
0042         or die "Cannot open $file: $!.\n";
0043 
0044     my %includedfiles = ();
0045     my @file_lines = ();
0046 
0047     while (<$f>) {
0048         if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
0049             ++$includedfiles{$1};
0050         }
0051         push(@file_lines, $_);
0052     }
0053 
0054     close($f);
0055 
0056     if (!$remove) {
0057         foreach my $filename (keys %includedfiles) {
0058             if ($includedfiles{$filename} > 1) {
0059                 print "$file: $filename is included more than once.\n";
0060             }
0061         }
0062         next;
0063     }
0064 
0065     open($f, '>', $file)
0066         or die("Cannot write to $file: $!");
0067 
0068     my $dups = 0;
0069     foreach (@file_lines) {
0070         if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
0071             foreach my $filename (keys %includedfiles) {
0072                 if ($1 eq $filename) {
0073                     if ($includedfiles{$filename} > 1) {
0074                         $includedfiles{$filename}--;
0075                         $dups++;
0076                     } else {
0077                         print {$f} $_;
0078                     }
0079                 }
0080             }
0081         } else {
0082             print {$f} $_;
0083         }
0084     }
0085     if ($dups > 0) {
0086         print "$file: removed $dups duplicate includes\n";
0087     }
0088     close($f);
0089 }