checkincludes.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/perl
  2. #
  3. # checkincludes: find/remove files included more than once
  4. #
  5. # Copyright abandoned, 2000, Niels Kristian Bech Jensen <nkbj@image.dk>.
  6. # Copyright 2009 Luis R. Rodriguez <mcgrof@gmail.com>
  7. #
  8. # This script checks for duplicate includes. It also has support
  9. # to remove them in place. Note that this will not take into
  10. # consideration macros so you should run this only if you know
  11. # you do have real dups and do not have them under #ifdef's. You
  12. # could also just review the results.
  13. use strict;
  14. sub usage {
  15. print "Usage: checkincludes.pl [-r]\n";
  16. print "By default we just warn of duplicates\n";
  17. print "To remove duplicated includes in place use -r\n";
  18. exit 1;
  19. }
  20. my $remove = 0;
  21. if ($#ARGV < 0) {
  22. usage();
  23. }
  24. if ($#ARGV >= 1) {
  25. if ($ARGV[0] =~ /^-/) {
  26. if ($ARGV[0] eq "-r") {
  27. $remove = 1;
  28. shift;
  29. } else {
  30. usage();
  31. }
  32. }
  33. }
  34. foreach my $file (@ARGV) {
  35. open(my $f, '<', $file)
  36. or die "Cannot open $file: $!.\n";
  37. my %includedfiles = ();
  38. my @file_lines = ();
  39. while (<$f>) {
  40. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  41. ++$includedfiles{$1};
  42. }
  43. push(@file_lines, $_);
  44. }
  45. close($f);
  46. if (!$remove) {
  47. foreach my $filename (keys %includedfiles) {
  48. if ($includedfiles{$filename} > 1) {
  49. print "$file: $filename is included more than once.\n";
  50. }
  51. }
  52. next;
  53. }
  54. open($f, '>', $file)
  55. or die("Cannot write to $file: $!");
  56. my $dups = 0;
  57. foreach (@file_lines) {
  58. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  59. foreach my $filename (keys %includedfiles) {
  60. if ($1 eq $filename) {
  61. if ($includedfiles{$filename} > 1) {
  62. $includedfiles{$filename}--;
  63. $dups++;
  64. } else {
  65. print {$f} $_;
  66. }
  67. }
  68. }
  69. } else {
  70. print {$f} $_;
  71. }
  72. }
  73. if ($dups > 0) {
  74. print "$file: removed $dups duplicate includes\n";
  75. }
  76. close($f);
  77. }