#!/usr/bin/env php -q * @copyright Copyright (c) 2005-2007 Arto Bendiken. All rights reserved. * @license http://www.opensource.org/licenses/mit-license.php MIT * @license http://www.opensource.org/licenses/gpl-license.php GPL * @version 0.1.1 (2007/07/25) */ function is_boring_file($path) { // Skip emacs backup files, documentation files (e.g. README, TODO, // CREDITS), and any non-code resources return ereg('~$', $path) || (strtoupper($path) === $path) || ereg('\.(info|txt|pot?|html?|ini|conf|swf|gif|png|jpg|ico|psd)$', $path); } function is_boring_dir($path) { // Skip CVS/SVN/Darcs directories return ereg('/(po|patches|icons|CVS|\.svn|_darcs)$', $path); } function count_loc($file) { $line_count = 0; $in_comment = FALSE; // Staggeringly inefficient, but who cares $lines = explode("\n", file_get_contents($file)); foreach ($lines as $line) { $line = trim($line); if (!EVERYTHING) { if (!WHITESPACE && strlen($line) == 0) continue; if (substr($line, 0, 2) == '//') continue; if (strpos($line, '/*') !== FALSE) $in_comment = TRUE; if (strpos($line, '*/') !== FALSE) $in_comment = FALSE; } if (!$in_comment) $line_count++; } return $line_count; } function count_dir($dir) { $sum_proc = create_function('$x, $y', 'return $x + $y;'); $files = $bytes = $lines = 0; foreach (glob("$dir/*") as $file) { if (is_link($file)) { continue; // Skip symbolic links } else if (is_dir($file) && !is_boring_dir($file)) { // Recurse into directories list($files, $bytes, $lines) = array_map($sum_proc, array($files, $bytes, $lines), count_dir($file)); } else if (!is_boring_file($file) && is_readable($file)) { $files++; list($l, $b) = array(count_loc($file), filesize($file)); if (VERBOSE) { print "$file: $b bytes, $l LOC.\n"; } $bytes += $b; $lines += $l; } } return array($files, $bytes, $lines); } function get_option(&$argv, $option, $default = FALSE) { if (($index = array_search($option, $argv)) !== FALSE) { unset($argv[$index]); return TRUE; } return $default; } function main($argv) { if (get_option($argv, '-?') || get_option($argv, '-h') || get_option($argv, '--help')) { die("Usage: sloccount.php [PATH] [-a] [-w] [-v]\n"); } define('EVERYTHING', get_option($argv, '-a')); define('WHITESPACE', get_option($argv, '-w')); define('VERBOSE', get_option($argv, '-v')); $paths = empty($argv) ? array(dirname(__FILE__)) : $argv; foreach ($paths as $path) { $path = realpath($path); print("Analyzing code directory $path...\n"); list($files, $bytes, $lines) = count_dir($path); printf("%d files (%s KB), containing %d lines of code.\n", $files, number_format($bytes / 1024.0, 0), $lines); } } main(array_slice($argv, 1));