Tuesday, September 23, 2008

Show Selectors

here is a simple perl script for parsing a project for css files. it will display occurrences of css id's and classes. this is useful if you need to display unused id's/classes.

show-selectors.pl


#!/usr/bin/perl
use File::List;
use CSS;

my $cssl = new File::List(".");
my @css = @{ $cssl->find("\.css\$") };
my $cssc = @css;
my $seen;
my @final;

for my $cssfile (@css){
my $css = CSS->new();
$css->read_file($cssfile);

for my $style ( @{ $css->{styles} }){
for my $selector ( @{ $style->{selectors}}){
my $name = $selector->{name};
my @multiple = split(/ /, $name);

foreach $multiple (@multiple){
if ($multiple =~ /.*(\.|\#)(.*)/){
my $sel = $1 . $2;
$seen{$sel}++;
next if $seen{$sel} > 1;
push(@final, $sel);
}
}
}
}
}

foreach $selector (@final){
if ($selector =~ /.(.*)/){
my $total = 0;
my $output = `grep -c '$1' . -R | grep -v -E '.svn|css'`;
foreach $line (split(/\n/, $output)){
if ($line =~ /(.*):(\d)/){
my $occ = eval($2);
$total += $occ;
}
}
print("$selector: $total\n");
}
}