checkincludes.pl 1.9 KB

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