Back to home page

OSCL-LXR

 
 

    


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