checkincludes.pl 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env 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. my $dup_counter = 0;
  35. foreach my $file (@ARGV) {
  36. open(my $f, '<', $file)
  37. or die "Cannot open $file: $!.\n";
  38. my %includedfiles = ();
  39. my @file_lines = ();
  40. while (<$f>) {
  41. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  42. ++$includedfiles{$1};
  43. }
  44. push(@file_lines, $_);
  45. }
  46. close($f);
  47. if (!$remove) {
  48. foreach my $filename (keys %includedfiles) {
  49. if ($includedfiles{$filename} > 1) {
  50. print "$file: $filename is included more than once.\n";
  51. ++$dup_counter;
  52. }
  53. }
  54. next;
  55. }
  56. open($f, '>', $file)
  57. or die("Cannot write to $file: $!");
  58. my $dups = 0;
  59. foreach (@file_lines) {
  60. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  61. foreach my $filename (keys %includedfiles) {
  62. if ($1 eq $filename) {
  63. if ($includedfiles{$filename} > 1) {
  64. $includedfiles{$filename}--;
  65. $dups++;
  66. ++$dup_counter;
  67. } else {
  68. print {$f} $_;
  69. }
  70. }
  71. }
  72. } else {
  73. print {$f} $_;
  74. }
  75. }
  76. if ($dups > 0) {
  77. print "$file: removed $dups duplicate includes\n";
  78. }
  79. close($f);
  80. }
  81. if ($dup_counter == 0) {
  82. print "No duplicate includes found.\n";
  83. }