checkincludes.pl 1.77 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2
#!/usr/bin/perl
#
3 4
# checkincludes: find/remove files included more than once
#
Linus Torvalds's avatar
Linus Torvalds committed
5
# Copyright abandoned, 2000, Niels Kristian Bech Jensen <nkbj@image.dk>.
6 7 8 9 10 11 12
# Copyright 2009 Luis R. Rodriguez <mcgrof@gmail.com>
#
# This script checks for duplicate includes. It also has support
# to remove them in place. Note that this will not take into
# consideration macros so you should run this only if you know
# you do have real dups and do not have them under #ifdef's. You
# could also just review the results.
Linus Torvalds's avatar
Linus Torvalds committed
13

14 15
use strict;

16
sub usage {
17 18 19
	print "Usage: checkincludes.pl [-r]\n";
	print "By default we just warn of duplicates\n";
	print "To remove duplicated includes in place use -r\n";
20 21 22
	exit 1;
}

23 24
my $remove = 0;

25
if ($#ARGV < 0) {
26 27 28 29 30 31 32 33 34 35 36 37
	usage();
}

if ($#ARGV >= 1) {
	if ($ARGV[0] =~ /^-/) {
		if ($ARGV[0] eq "-r") {
			$remove = 1;
			shift;
		} else {
			usage();
		}
	}
38 39
}

40 41 42
foreach my $file (@ARGV) {
	open(my $f, '<', $file)
	    or die "Cannot open $file: $!.\n";
Linus Torvalds's avatar
Linus Torvalds committed
43 44

	my %includedfiles = ();
45
	my @file_lines = ();
Linus Torvalds's avatar
Linus Torvalds committed
46

47
	while (<$f>) {
Linus Torvalds's avatar
Linus Torvalds committed
48 49 50
		if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
			++$includedfiles{$1};
		}
51
		push(@file_lines, $_);
Linus Torvalds's avatar
Linus Torvalds committed
52
	}
53

54
	close($f);
55 56

	if (!$remove) {
57
		foreach my $filename (keys %includedfiles) {
58 59 60
			if ($includedfiles{$filename} > 1) {
				print "$file: $filename is included more than once.\n";
			}
Linus Torvalds's avatar
Linus Torvalds committed
61
		}
62
		next;
Linus Torvalds's avatar
Linus Torvalds committed
63
	}
64

65 66
	open($f, '>', $file)
	    or die("Cannot write to $file: $!");
67 68 69 70

	my $dups = 0;
	foreach (@file_lines) {
		if (m/^\s*#\s*include\s*[<"](\S*)[>"]/o) {
71
			foreach my $filename (keys %includedfiles) {
72 73 74 75 76
				if ($1 eq $filename) {
					if ($includedfiles{$filename} > 1) {
						$includedfiles{$filename}--;
						$dups++;
					} else {
77
						print {$f} $_;
78 79 80 81
					}
				}
			}
		} else {
82
			print {$f} $_;
83 84 85 86 87
		}
	}
	if ($dups > 0) {
		print "$file: removed $dups duplicate includes\n";
	}
88
	close($f);
Linus Torvalds's avatar
Linus Torvalds committed
89
}