checkincludes.pl 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. sub usage {
  14. print "Usage: checkincludes.pl [-r]\n";
  15. print "By default we just warn of duplicates\n";
  16. print "To remove duplicated includes in place use -r\n";
  17. exit 1;
  18. }
  19. my $remove = 0;
  20. if ($#ARGV < 0) {
  21. usage();
  22. }
  23. if ($#ARGV >= 1) {
  24. if ($ARGV[0] =~ /^-/) {
  25. if ($ARGV[0] eq "-r") {
  26. $remove = 1;
  27. shift;
  28. } else {
  29. usage();
  30. }
  31. }
  32. }
  33. foreach $file (@ARGV) {
  34. open(FILE, $file) or die "Cannot open $file: $!.\n";
  35. my %includedfiles = ();
  36. my @file_lines = ();
  37. while (<FILE>) {
  38. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  39. ++$includedfiles{$1};
  40. }
  41. push(@file_lines, $_);
  42. }
  43. close(FILE);
  44. if (!$remove) {
  45. foreach $filename (keys %includedfiles) {
  46. if ($includedfiles{$filename} > 1) {
  47. print "$file: $filename is included more than once.\n";
  48. }
  49. }
  50. next;
  51. }
  52. open(FILE,">$file") || die("Cannot write to $file: $!");
  53. my $dups = 0;
  54. foreach (@file_lines) {
  55. if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
  56. foreach $filename (keys %includedfiles) {
  57. if ($1 eq $filename) {
  58. if ($includedfiles{$filename} > 1) {
  59. $includedfiles{$filename}--;
  60. $dups++;
  61. } else {
  62. print FILE $_;
  63. }
  64. }
  65. }
  66. } else {
  67. print FILE $_;
  68. }
  69. }
  70. if ($dups > 0) {
  71. print "$file: removed $dups duplicate includes\n";
  72. }
  73. close(FILE);
  74. }