Created
July 10, 2012 15:57
-
-
Save oranj/3084307 to your computer and use it in GitHub Desktop.
Javascript Function Pruner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (count($argv) < 2) { | |
die("Please enter a filename"); | |
} | |
$filename = $argv[1]; | |
$funcNameRegex = '(?P<func>[a-zA-Z0-9_$]+)'; | |
$contents = file_get_contents($filename); | |
if (! $contents) { | |
die("No data for file \"$filename\""); | |
} | |
$funcNameRegexes = Array( | |
'/[\'"]?'.$funcNameRegex.'[\'"]\s*:\s*function/i', | |
'/function\s+'.$funcNameRegex.'\s*\(/i', | |
'/var\s+'.$funcNameRegex.'\s*=\s*function/i' | |
); | |
$nameLocations = array(); | |
$useLocations = array(); | |
foreach ($funcNameRegexes as $regex) { | |
if (preg_match_all($regex, $contents, $output, PREG_OFFSET_CAPTURE)) { | |
foreach ($output['func'] as $out) { | |
$nameLocations[$out[0]] []= $out[1]; | |
} | |
} | |
} | |
$funcUseRegexes = Array( | |
'/that\.'.$funcNameRegex.'\(/i', | |
'/this\.'.$funcNameRegex.'\(/i', | |
'/\b'.$funcNameRegex.'\(/i', | |
'/[\(,]\s*'.$funcNameRegex.'\s*[\),]/i' | |
); | |
foreach ($funcUseRegexes as $regex) { | |
if (preg_match_all($regex, $contents, $output, PREG_OFFSET_CAPTURE)) { | |
foreach ($output['func'] as $out) { | |
$useLocations[$out[0]] []= $out[1]; | |
} | |
} | |
} | |
$output = array(); | |
$notUsed = array(); | |
foreach ($nameLocations as $name => $defined) { | |
$output [$name] = array( | |
'defined' => $defined, | |
'used' => array() | |
); | |
if (! isset($useLocations[$name])) { | |
$notUsed [$name] = $defined; | |
} else { | |
$output[$name]['used'] = $useLocations[$name]; | |
} | |
} | |
foreach ($notUsed as $name => $defined_locations) { | |
echo "\033[44m\033[1;37m function $name \033[0m\n"; | |
echo " Defined at\n - line "; | |
echo join("\n - line ", $defined_locations); | |
echo "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script will detect unused functions within a single javascript file.