checkincludes.pl 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. }